bpf: Add cookie support to programs attached with kprobe multi link
[linux-2.6-block.git] / tools / lib / bpf / libbpf.c
CommitLineData
1bc38b8f 1// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
6061a3d6 2
1b76c13e
WN
3/*
4 * Common eBPF ELF object loading operations.
5 *
6 * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7 * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2015 Huawei Inc.
f367540c 9 * Copyright (C) 2017 Nicira, Inc.
d859900c 10 * Copyright (C) 2019 Isovalent, Inc.
1b76c13e
WN
11 */
12
b4269954 13#ifndef _GNU_SOURCE
531b014e 14#define _GNU_SOURCE
b4269954 15#endif
1b76c13e 16#include <stdlib.h>
b3f59d66
WN
17#include <stdio.h>
18#include <stdarg.h>
f367540c 19#include <libgen.h>
34090915 20#include <inttypes.h>
8ab9da57 21#include <limits.h>
b3f59d66 22#include <string.h>
1b76c13e 23#include <unistd.h>
cdb2f920 24#include <endian.h>
1a5e3fb1
WN
25#include <fcntl.h>
26#include <errno.h>
113e6b7e 27#include <ctype.h>
1b76c13e 28#include <asm/unistd.h>
e28ff1a8 29#include <linux/err.h>
cb1e5e96 30#include <linux/kernel.h>
1b76c13e 31#include <linux/bpf.h>
38d5d3b3 32#include <linux/btf.h>
47eff617 33#include <linux/filter.h>
9a208eff 34#include <linux/list.h>
f367540c 35#include <linux/limits.h>
438363c0 36#include <linux/perf_event.h>
a64af0ef 37#include <linux/ring_buffer.h>
5e61f270 38#include <linux/version.h>
fb84b822 39#include <sys/epoll.h>
63f2f5ee 40#include <sys/ioctl.h>
fb84b822 41#include <sys/mman.h>
f367540c
JS
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/vfs.h>
ddc7c304 45#include <sys/utsname.h>
dc3a2d25 46#include <sys/resource.h>
1a5e3fb1
WN
47#include <libelf.h>
48#include <gelf.h>
166750bc 49#include <zlib.h>
1b76c13e
WN
50
51#include "libbpf.h"
52d3352e 52#include "bpf.h"
8a138aed 53#include "btf.h"
6d41907c 54#include "str_error.h"
d7c4b398 55#include "libbpf_internal.h"
ddc7c304 56#include "hashmap.h"
67234743 57#include "bpf_gen_internal.h"
b3f59d66 58
f367540c
JS
59#ifndef BPF_FS_MAGIC
60#define BPF_FS_MAGIC 0xcafe4a11
61#endif
62
9c0f8cbd
AN
63#define BPF_INSN_SZ (sizeof(struct bpf_insn))
64
ff466b58
AI
65/* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
67 */
68#pragma GCC diagnostic ignored "-Wformat-nonliteral"
69
b3f59d66
WN
70#define __printf(a, b) __attribute__((format(printf, a, b)))
71
590a0088 72static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
aea28a60 73static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
590a0088 74
a8a1f7d0
SF
75static int __base_pr(enum libbpf_print_level level, const char *format,
76 va_list args)
b3f59d66 77{
6f1ae8b6
YS
78 if (level == LIBBPF_DEBUG)
79 return 0;
80
a8a1f7d0 81 return vfprintf(stderr, format, args);
b3f59d66
WN
82}
83
a8a1f7d0 84static libbpf_print_fn_t __libbpf_pr = __base_pr;
b3f59d66 85
e87fd8ba 86libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
b3f59d66 87{
e87fd8ba
AN
88 libbpf_print_fn_t old_print_fn = __libbpf_pr;
89
6f1ae8b6 90 __libbpf_pr = fn;
e87fd8ba 91 return old_print_fn;
b3f59d66 92}
1a5e3fb1 93
8461ef8b
YS
94__printf(2, 3)
95void libbpf_print(enum libbpf_print_level level, const char *format, ...)
96{
97 va_list args;
98
6f1ae8b6
YS
99 if (!__libbpf_pr)
100 return;
101
8461ef8b 102 va_start(args, format);
6f1ae8b6 103 __libbpf_pr(level, format, args);
8461ef8b
YS
104 va_end(args);
105}
106
dc3a2d25
THJ
107static void pr_perm_msg(int err)
108{
109 struct rlimit limit;
110 char buf[100];
111
112 if (err != -EPERM || geteuid() != 0)
113 return;
114
115 err = getrlimit(RLIMIT_MEMLOCK, &limit);
116 if (err)
117 return;
118
119 if (limit.rlim_cur == RLIM_INFINITY)
120 return;
121
122 if (limit.rlim_cur < 1024)
b5c7d0d0 123 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
dc3a2d25
THJ
124 else if (limit.rlim_cur < 1024*1024)
125 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
126 else
127 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
128
129 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
130 buf);
131}
132
6371ca3b
WN
133#define STRERR_BUFSIZE 128
134
1a5e3fb1
WN
135/* Copied from tools/perf/util/util.h */
136#ifndef zfree
137# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
138#endif
139
140#ifndef zclose
141# define zclose(fd) ({ \
142 int ___err = 0; \
143 if ((fd) >= 0) \
144 ___err = close((fd)); \
145 fd = -1; \
146 ___err; })
147#endif
148
34be1646
SL
149static inline __u64 ptr_to_u64(const void *ptr)
150{
151 return (__u64) (unsigned long) ptr;
152}
153
5981881d
AN
154/* this goes away in libbpf 1.0 */
155enum libbpf_strict_mode libbpf_mode = LIBBPF_STRICT_NONE;
156
157int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
158{
5981881d
AN
159 libbpf_mode = mode;
160 return 0;
161}
162
7615209f
AN
163__u32 libbpf_major_version(void)
164{
165 return LIBBPF_MAJOR_VERSION;
166}
167
168__u32 libbpf_minor_version(void)
169{
170 return LIBBPF_MINOR_VERSION;
171}
172
173const char *libbpf_version_string(void)
174{
175#define __S(X) #X
176#define _S(X) __S(X)
177 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
178#undef _S
179#undef __S
180}
181
166750bc
AN
182enum reloc_type {
183 RELO_LD64,
184 RELO_CALL,
185 RELO_DATA,
0c091e5c 186 RELO_EXTERN_VAR,
5bd022ec 187 RELO_EXTERN_FUNC,
53eddb5e 188 RELO_SUBPROG_ADDR,
d0e92887 189 RELO_CORE,
166750bc
AN
190};
191
192struct reloc_desc {
193 enum reloc_type type;
194 int insn_idx;
d0e92887
AS
195 union {
196 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
197 struct {
198 int map_idx;
199 int sym_off;
200 };
201 };
166750bc
AN
202};
203
15ea31fa
AN
204/* stored as sec_def->cookie for all libbpf-supported SEC()s */
205enum sec_def_flags {
206 SEC_NONE = 0,
207 /* expected_attach_type is optional, if kernel doesn't support that */
208 SEC_EXP_ATTACH_OPT = 1,
209 /* legacy, only used by libbpf_get_type_names() and
210 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
211 * This used to be associated with cgroup (and few other) BPF programs
212 * that were attachable through BPF_PROG_ATTACH command. Pretty
213 * meaningless nowadays, though.
214 */
215 SEC_ATTACHABLE = 2,
216 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
217 /* attachment target is specified through BTF ID in either kernel or
218 * other BPF program's BTF object */
219 SEC_ATTACH_BTF = 4,
220 /* BPF program type allows sleeping/blocking in kernel */
221 SEC_SLEEPABLE = 8,
dd94d45c
AN
222 /* allow non-strict prefix matching */
223 SEC_SLOPPY_PFX = 16,
082c4bfb
LB
224 /* BPF program support non-linear XDP buffer */
225 SEC_XDP_FRAGS = 32,
4a4d4cee
LB
226 /* deprecated sec definitions not supposed to be used */
227 SEC_DEPRECATED = 64,
15ea31fa
AN
228};
229
25498a19 230struct bpf_sec_def {
697f104d 231 char *sec;
25498a19
AN
232 enum bpf_prog_type prog_type;
233 enum bpf_attach_type expected_attach_type;
15ea31fa 234 long cookie;
697f104d 235 int handler_id;
12d9466d 236
4fa5bcfe
AN
237 libbpf_prog_setup_fn_t prog_setup_fn;
238 libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
239 libbpf_prog_attach_fn_t prog_attach_fn;
25498a19
AN
240};
241
a5b8bd47
WN
242/*
243 * bpf_prog should be a better name but it has been used in
244 * linux/filter.h.
245 */
246struct bpf_program {
25498a19 247 const struct bpf_sec_def *sec_def;
52109584 248 char *sec_name;
c1122392
AN
249 size_t sec_idx;
250 /* this program's instruction offset (in number of instructions)
251 * within its containing ELF section
252 */
253 size_t sec_insn_off;
254 /* number of original instructions in ELF section belonging to this
255 * program, not taking into account subprogram instructions possible
256 * appended later during relocation
257 */
258 size_t sec_insn_cnt;
259 /* Offset (in number of instructions) of the start of instruction
260 * belonging to this BPF program within its containing main BPF
261 * program. For the entry-point (main) BPF program, this is always
262 * zero. For a sub-program, this gets reset before each of main BPF
263 * programs are processed and relocated and is used to determined
264 * whether sub-program was already appended to the main program, and
265 * if yes, at which instruction offset.
266 */
267 size_t sub_insn_off;
268
269 char *name;
a77f879b 270 /* name with / replaced by _; makes recursive pinning
33a2c75c
SF
271 * in bpf_object__pin_programs easier
272 */
273 char *pin_name;
c1122392
AN
274
275 /* instructions that belong to BPF program; insns[0] is located at
276 * sec_insn_off instruction within its ELF section in ELF file, so
277 * when mapping ELF file instruction index to the local instruction,
278 * one needs to subtract sec_insn_off; and vice versa.
279 */
a5b8bd47 280 struct bpf_insn *insns;
c1122392
AN
281 /* actual number of instruction in this BPF program's image; for
282 * entry-point BPF programs this includes the size of main program
283 * itself plus all the used sub-programs, appended at the end
284 */
c3c55696 285 size_t insns_cnt;
34090915 286
166750bc 287 struct reloc_desc *reloc_desc;
34090915 288 int nr_reloc;
b3ce9079
AN
289
290 /* BPF verifier log settings */
291 char *log_buf;
292 size_t log_size;
293 __u32 log_level;
55cffde2 294
b580563e
WN
295 struct {
296 int nr;
297 int *fds;
298 } instances;
299 bpf_program_prep_t preprocessor;
aa9b1ac3
WN
300
301 struct bpf_object *obj;
302 void *priv;
303 bpf_program_clear_priv_t clear_priv;
d7be143b 304
c1122392 305 bool load;
aea28a60 306 bool mark_btf_static;
c1122392 307 enum bpf_prog_type type;
d7be143b 308 enum bpf_attach_type expected_attach_type;
c1122392 309 int prog_ifindex;
91abb4a6 310 __u32 attach_btf_obj_fd;
12a8654b 311 __u32 attach_btf_id;
e7bf94db 312 __u32 attach_prog_fd;
2993e051
YS
313 void *func_info;
314 __u32 func_info_rec_size;
f0187f0b 315 __u32 func_info_cnt;
47eff617 316
3d650141
MKL
317 void *line_info;
318 __u32 line_info_rec_size;
319 __u32 line_info_cnt;
04656198 320 __u32 prog_flags;
a5b8bd47
WN
321};
322
590a0088
MKL
323struct bpf_struct_ops {
324 const char *tname;
325 const struct btf_type *type;
326 struct bpf_program **progs;
327 __u32 *kern_func_off;
328 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
329 void *data;
330 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
331 * btf_vmlinux's format.
332 * struct bpf_struct_ops_tcp_congestion_ops {
333 * [... some other kernel fields ...]
334 * struct tcp_congestion_ops data;
335 * }
336 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
337 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
338 * from "data".
339 */
340 void *kern_vdata;
341 __u32 type_id;
342};
343
ac9d1389
AN
344#define DATA_SEC ".data"
345#define BSS_SEC ".bss"
346#define RODATA_SEC ".rodata"
81bfdd08 347#define KCONFIG_SEC ".kconfig"
1c0c7074 348#define KSYMS_SEC ".ksyms"
590a0088 349#define STRUCT_OPS_SEC ".struct_ops"
ac9d1389 350
d859900c
DB
351enum libbpf_map_type {
352 LIBBPF_MAP_UNSPEC,
353 LIBBPF_MAP_DATA,
354 LIBBPF_MAP_BSS,
355 LIBBPF_MAP_RODATA,
81bfdd08 356 LIBBPF_MAP_KCONFIG,
d859900c
DB
357};
358
9d759a9b 359struct bpf_map {
561bbcca 360 char *name;
aed65917
AN
361 /* real_name is defined for special internal maps (.rodata*,
362 * .data*, .bss, .kconfig) and preserves their original ELF section
363 * name. This is important to be be able to find corresponding BTF
364 * DATASEC information.
365 */
366 char *real_name;
01af3bf0 367 int fd;
db48814b
AN
368 int sec_idx;
369 size_t sec_offset;
f0307a7e 370 int map_ifindex;
addb9fc9 371 int inner_map_fd;
9d759a9b 372 struct bpf_map_def def;
1bdb6c9a 373 __u32 numa_node;
646f02ff 374 __u32 btf_var_idx;
5b891af7
MKL
375 __u32 btf_key_type_id;
376 __u32 btf_value_type_id;
590a0088 377 __u32 btf_vmlinux_value_type_id;
9d759a9b
WN
378 void *priv;
379 bpf_map_clear_priv_t clear_priv;
d859900c 380 enum libbpf_map_type libbpf_type;
eba9c5f4 381 void *mmaped;
590a0088 382 struct bpf_struct_ops *st_ops;
646f02ff
AN
383 struct bpf_map *inner_map;
384 void **init_slots;
385 int init_slots_sz;
4580b25f
THJ
386 char *pin_path;
387 bool pinned;
ec6d5f47 388 bool reused;
229fae38 389 bool skipped;
47512102 390 __u64 map_extra;
d859900c
DB
391};
392
166750bc
AN
393enum extern_type {
394 EXT_UNKNOWN,
2e33efe3 395 EXT_KCFG,
1c0c7074 396 EXT_KSYM,
2e33efe3
AN
397};
398
399enum kcfg_type {
400 KCFG_UNKNOWN,
401 KCFG_CHAR,
402 KCFG_BOOL,
403 KCFG_INT,
404 KCFG_TRISTATE,
405 KCFG_CHAR_ARR,
166750bc
AN
406};
407
408struct extern_desc {
2e33efe3 409 enum extern_type type;
166750bc
AN
410 int sym_idx;
411 int btf_id;
2e33efe3
AN
412 int sec_btf_id;
413 const char *name;
166750bc 414 bool is_set;
2e33efe3
AN
415 bool is_weak;
416 union {
417 struct {
418 enum kcfg_type type;
419 int sz;
420 int align;
421 int data_off;
422 bool is_signed;
423 } kcfg;
1c0c7074
AN
424 struct {
425 unsigned long long addr;
d370bbe1
HL
426
427 /* target btf_id of the corresponding kernel var. */
284d2587
AN
428 int kernel_btf_obj_fd;
429 int kernel_btf_id;
d370bbe1
HL
430
431 /* local btf_id of the ksym extern's type. */
432 __u32 type_id;
9dbe6015
KKD
433 /* BTF fd index to be patched in for insn->off, this is
434 * 0 for vmlinux BTF, index in obj->fd_array for module
435 * BTF
436 */
437 __s16 btf_fd_idx;
1c0c7074 438 } ksym;
2e33efe3 439 };
166750bc
AN
440};
441
9a208eff
WN
442static LIST_HEAD(bpf_objects_list);
443
4f33a53d
AN
444struct module_btf {
445 struct btf *btf;
446 char *name;
447 __u32 id;
91abb4a6 448 int fd;
9dbe6015 449 int fd_array_idx;
4f33a53d
AN
450};
451
25bbbd7a
AN
452enum sec_type {
453 SEC_UNUSED = 0,
454 SEC_RELO,
455 SEC_BSS,
456 SEC_DATA,
457 SEC_RODATA,
458};
459
460struct elf_sec_desc {
461 enum sec_type sec_type;
462 Elf64_Shdr *shdr;
463 Elf_Data *data;
464};
465
29a30ff5
AN
466struct elf_state {
467 int fd;
468 const void *obj_buf;
469 size_t obj_buf_sz;
470 Elf *elf;
ad23b723 471 Elf64_Ehdr *ehdr;
29a30ff5 472 Elf_Data *symbols;
29a30ff5
AN
473 Elf_Data *st_ops_data;
474 size_t shstrndx; /* section index for section name strings */
475 size_t strtabidx;
25bbbd7a
AN
476 struct elf_sec_desc *secs;
477 int sec_cnt;
29a30ff5
AN
478 int maps_shndx;
479 int btf_maps_shndx;
480 __u32 btf_maps_sec_btf_id;
481 int text_shndx;
482 int symbols_shndx;
29a30ff5 483 int st_ops_shndx;
4f33a53d
AN
484};
485
1a5e3fb1 486struct bpf_object {
d859900c 487 char name[BPF_OBJ_NAME_LEN];
cb1e5e96 488 char license[64];
438363c0 489 __u32 kern_version;
0b3d1efa 490
a5b8bd47
WN
491 struct bpf_program *programs;
492 size_t nr_programs;
9d759a9b
WN
493 struct bpf_map *maps;
494 size_t nr_maps;
bf829271 495 size_t maps_cap;
9d759a9b 496
8601fd42 497 char *kconfig;
166750bc
AN
498 struct extern_desc *externs;
499 int nr_extern;
81bfdd08 500 int kconfig_map_idx;
166750bc 501
52d3352e 502 bool loaded;
c3c55696 503 bool has_subcalls;
25bbbd7a 504 bool has_rodata;
a5b8bd47 505
e2fa0156
AS
506 struct bpf_gen *gen_loader;
507
29a30ff5
AN
508 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
509 struct elf_state efile;
1a5e3fb1 510 /*
29a30ff5 511 * All loaded bpf_object are linked in a list, which is
9a208eff
WN
512 * hidden to caller. bpf_objects__<func> handlers deal with
513 * all objects.
514 */
515 struct list_head list;
10931d24 516
8a138aed 517 struct btf *btf;
0f7515ca
AN
518 struct btf_ext *btf_ext;
519
a6ed02ca
KS
520 /* Parse and load BTF vmlinux if any of the programs in the object need
521 * it at load time.
522 */
523 struct btf *btf_vmlinux;
1373ff59
SC
524 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
525 * override for vmlinux BTF.
526 */
527 char *btf_custom_path;
0f7515ca
AN
528 /* vmlinux BTF override for CO-RE relocations */
529 struct btf *btf_vmlinux_override;
4f33a53d
AN
530 /* Lazily initialized kernel module BTFs */
531 struct module_btf *btf_modules;
532 bool btf_modules_loaded;
533 size_t btf_module_cnt;
534 size_t btf_module_cap;
8a138aed 535
e0e3ea88
AN
536 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
537 char *log_buf;
538 size_t log_size;
539 __u32 log_level;
540
10931d24
WN
541 void *priv;
542 bpf_object_clear_priv_t clear_priv;
543
9dbe6015
KKD
544 int *fd_array;
545 size_t fd_array_cap;
546 size_t fd_array_cnt;
547
1a5e3fb1
WN
548 char path[];
549};
1a5e3fb1 550
88a82120
AN
551static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
552static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
553static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
554static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
ad23b723 555static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
88a82120
AN
556static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
557static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
ad23b723
AN
558static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
559static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
88a82120 560
29cd77f4 561void bpf_program__unload(struct bpf_program *prog)
55cffde2 562{
b580563e
WN
563 int i;
564
55cffde2
WN
565 if (!prog)
566 return;
567
b580563e
WN
568 /*
569 * If the object is opened but the program was never loaded,
570 * it is possible that prog->instances.nr == -1.
571 */
572 if (prog->instances.nr > 0) {
573 for (i = 0; i < prog->instances.nr; i++)
574 zclose(prog->instances.fds[i]);
575 } else if (prog->instances.nr != -1) {
be18010e
KW
576 pr_warn("Internal error: instances.nr is %d\n",
577 prog->instances.nr);
b580563e
WN
578 }
579
580 prog->instances.nr = -1;
581 zfree(&prog->instances.fds);
2993e051 582
2993e051 583 zfree(&prog->func_info);
07a09d1b 584 zfree(&prog->line_info);
55cffde2
WN
585}
586
a5b8bd47
WN
587static void bpf_program__exit(struct bpf_program *prog)
588{
589 if (!prog)
590 return;
591
aa9b1ac3
WN
592 if (prog->clear_priv)
593 prog->clear_priv(prog, prog->priv);
594
595 prog->priv = NULL;
596 prog->clear_priv = NULL;
597
55cffde2 598 bpf_program__unload(prog);
88cda1c9 599 zfree(&prog->name);
52109584 600 zfree(&prog->sec_name);
33a2c75c 601 zfree(&prog->pin_name);
a5b8bd47 602 zfree(&prog->insns);
34090915
WN
603 zfree(&prog->reloc_desc);
604
605 prog->nr_reloc = 0;
a5b8bd47 606 prog->insns_cnt = 0;
c1122392 607 prog->sec_idx = -1;
a5b8bd47
WN
608}
609
33a2c75c
SF
610static char *__bpf_program__pin_name(struct bpf_program *prog)
611{
612 char *name, *p;
613
a77f879b
SF
614 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
615 name = strdup(prog->name);
616 else
617 name = strdup(prog->sec_name);
618
619 if (!name)
620 return NULL;
621
622 p = name;
623
33a2c75c
SF
624 while ((p = strchr(p, '/')))
625 *p = '_';
626
627 return name;
628}
629
c3c55696
AN
630static bool insn_is_subprog_call(const struct bpf_insn *insn)
631{
632 return BPF_CLASS(insn->code) == BPF_JMP &&
633 BPF_OP(insn->code) == BPF_CALL &&
634 BPF_SRC(insn->code) == BPF_K &&
635 insn->src_reg == BPF_PSEUDO_CALL &&
636 insn->dst_reg == 0 &&
637 insn->off == 0;
638}
639
aa0b8d43
MKL
640static bool is_call_insn(const struct bpf_insn *insn)
641{
642 return insn->code == (BPF_JMP | BPF_CALL);
643}
644
53eddb5e
YS
645static bool insn_is_pseudo_func(struct bpf_insn *insn)
646{
aa0b8d43 647 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
53eddb5e
YS
648}
649
a5b8bd47 650static int
c3c55696
AN
651bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
652 const char *name, size_t sec_idx, const char *sec_name,
653 size_t sec_off, void *insn_data, size_t insn_data_sz)
a5b8bd47 654{
c1122392
AN
655 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
656 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
657 sec_name, name, sec_off, insn_data_sz);
a5b8bd47
WN
658 return -EINVAL;
659 }
660
1ad9cbb8 661 memset(prog, 0, sizeof(*prog));
c3c55696
AN
662 prog->obj = obj;
663
c1122392
AN
664 prog->sec_idx = sec_idx;
665 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
666 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
667 /* insns_cnt can later be increased by appending used subprograms */
668 prog->insns_cnt = prog->sec_insn_cnt;
a5b8bd47 669
c1122392
AN
670 prog->type = BPF_PROG_TYPE_UNSPEC;
671 prog->load = true;
a5b8bd47 672
c1122392
AN
673 prog->instances.fds = NULL;
674 prog->instances.nr = -1;
675
b3ce9079
AN
676 /* inherit object's log_level */
677 prog->log_level = obj->log_level;
678
52109584
AN
679 prog->sec_name = strdup(sec_name);
680 if (!prog->sec_name)
c1122392
AN
681 goto errout;
682
683 prog->name = strdup(name);
684 if (!prog->name)
a5b8bd47 685 goto errout;
a5b8bd47 686
33a2c75c 687 prog->pin_name = __bpf_program__pin_name(prog);
c1122392 688 if (!prog->pin_name)
33a2c75c 689 goto errout;
33a2c75c 690
c1122392
AN
691 prog->insns = malloc(insn_data_sz);
692 if (!prog->insns)
a5b8bd47 693 goto errout;
c1122392 694 memcpy(prog->insns, insn_data, insn_data_sz);
a5b8bd47
WN
695
696 return 0;
697errout:
c1122392 698 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
a5b8bd47
WN
699 bpf_program__exit(prog);
700 return -ENOMEM;
701}
702
703static int
c1122392
AN
704bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
705 const char *sec_name, int sec_idx)
a5b8bd47 706{
6245947c 707 Elf_Data *symbols = obj->efile.symbols;
c1122392
AN
708 struct bpf_program *prog, *progs;
709 void *data = sec_data->d_buf;
6245947c
AN
710 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
711 int nr_progs, err, i;
c1122392 712 const char *name;
ad23b723 713 Elf64_Sym *sym;
a5b8bd47
WN
714
715 progs = obj->programs;
716 nr_progs = obj->nr_programs;
ad23b723 717 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
c1122392 718 sec_off = 0;
a5b8bd47 719
6245947c 720 for (i = 0; i < nr_syms; i++) {
ad23b723
AN
721 sym = elf_sym_by_idx(obj, i);
722
723 if (sym->st_shndx != sec_idx)
6245947c 724 continue;
ad23b723 725 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
6245947c 726 continue;
88cda1c9 727
ad23b723
AN
728 prog_sz = sym->st_size;
729 sec_off = sym->st_value;
88cda1c9 730
ad23b723 731 name = elf_sym_str(obj, sym->st_name);
c1122392
AN
732 if (!name) {
733 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
734 sec_name, sec_off);
735 return -LIBBPF_ERRNO__FORMAT;
736 }
88cda1c9 737
c1122392
AN
738 if (sec_off + prog_sz > sec_sz) {
739 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
740 sec_name, sec_off);
741 return -LIBBPF_ERRNO__FORMAT;
742 }
88cda1c9 743
ad23b723 744 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
513f485c
AN
745 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
746 return -ENOTSUP;
747 }
748
c3c55696
AN
749 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
750 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
88cda1c9 751
c3c55696 752 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
c1122392
AN
753 if (!progs) {
754 /*
755 * In this case the original obj->programs
756 * is still valid, so don't need special treat for
757 * bpf_close_object().
758 */
759 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
760 sec_name, name);
761 return -ENOMEM;
88cda1c9 762 }
c1122392 763 obj->programs = progs;
88cda1c9 764
c1122392 765 prog = &progs[nr_progs];
9a94f277 766
c3c55696
AN
767 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
768 sec_off, data + sec_off, prog_sz);
c1122392
AN
769 if (err)
770 return err;
9a94f277 771
e5670fa0
AN
772 /* if function is a global/weak symbol, but has restricted
773 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
774 * as static to enable more permissive BPF verification mode
775 * with more outside context available to BPF verifier
aea28a60 776 */
ad23b723
AN
777 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
778 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
779 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
aea28a60
AN
780 prog->mark_btf_static = true;
781
c1122392
AN
782 nr_progs++;
783 obj->nr_programs = nr_progs;
88cda1c9
MKL
784 }
785
786 return 0;
787}
788
5b3d7298 789__u32 get_kernel_version(void)
5e61f270 790{
5b3d7298
AN
791 /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
792 * but Ubuntu provides /proc/version_signature file, as described at
793 * https://ubuntu.com/kernel, with an example contents below, which we
794 * can use to get a proper LINUX_VERSION_CODE.
795 *
796 * Ubuntu 5.4.0-12.15-generic 5.4.8
797 *
798 * In the above, 5.4.8 is what kernel is actually expecting, while
799 * uname() call will return 5.4.0 in info.release.
800 */
801 const char *ubuntu_kver_file = "/proc/version_signature";
5e61f270
AN
802 __u32 major, minor, patch;
803 struct utsname info;
804
5b3d7298
AN
805 if (access(ubuntu_kver_file, R_OK) == 0) {
806 FILE *f;
807
808 f = fopen(ubuntu_kver_file, "r");
809 if (f) {
810 if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
811 fclose(f);
812 return KERNEL_VERSION(major, minor, patch);
813 }
814 fclose(f);
815 }
816 /* something went wrong, fall back to uname() approach */
817 }
818
5e61f270
AN
819 uname(&info);
820 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
821 return 0;
822 return KERNEL_VERSION(major, minor, patch);
823}
824
590a0088
MKL
825static const struct btf_member *
826find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
827{
828 struct btf_member *m;
829 int i;
830
831 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
832 if (btf_member_bit_offset(t, i) == bit_offset)
833 return m;
834 }
835
836 return NULL;
837}
838
839static const struct btf_member *
840find_member_by_name(const struct btf *btf, const struct btf_type *t,
841 const char *name)
842{
843 struct btf_member *m;
844 int i;
845
846 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
847 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
848 return m;
849 }
850
851 return NULL;
852}
853
854#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
a6ed02ca
KS
855static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
856 const char *name, __u32 kind);
590a0088
MKL
857
858static int
859find_struct_ops_kern_types(const struct btf *btf, const char *tname,
860 const struct btf_type **type, __u32 *type_id,
861 const struct btf_type **vtype, __u32 *vtype_id,
862 const struct btf_member **data_member)
863{
864 const struct btf_type *kern_type, *kern_vtype;
865 const struct btf_member *kern_data_member;
866 __s32 kern_vtype_id, kern_type_id;
590a0088
MKL
867 __u32 i;
868
869 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
870 if (kern_type_id < 0) {
871 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
872 tname);
873 return kern_type_id;
874 }
875 kern_type = btf__type_by_id(btf, kern_type_id);
876
877 /* Find the corresponding "map_value" type that will be used
878 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
879 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
880 * btf_vmlinux.
881 */
a6ed02ca
KS
882 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
883 tname, BTF_KIND_STRUCT);
590a0088 884 if (kern_vtype_id < 0) {
a6ed02ca
KS
885 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
886 STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
887 return kern_vtype_id;
888 }
889 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
890
891 /* Find "struct tcp_congestion_ops" from
892 * struct bpf_struct_ops_tcp_congestion_ops {
893 * [ ... ]
894 * struct tcp_congestion_ops data;
895 * }
896 */
897 kern_data_member = btf_members(kern_vtype);
898 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
899 if (kern_data_member->type == kern_type_id)
900 break;
901 }
902 if (i == btf_vlen(kern_vtype)) {
a6ed02ca
KS
903 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
904 tname, STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
905 return -EINVAL;
906 }
907
908 *type = kern_type;
909 *type_id = kern_type_id;
910 *vtype = kern_vtype;
911 *vtype_id = kern_vtype_id;
912 *data_member = kern_data_member;
913
914 return 0;
915}
916
917static bool bpf_map__is_struct_ops(const struct bpf_map *map)
918{
919 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
920}
921
922/* Init the map's fields that depend on kern_btf */
923static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
924 const struct btf *btf,
925 const struct btf *kern_btf)
926{
927 const struct btf_member *member, *kern_member, *kern_data_member;
928 const struct btf_type *type, *kern_type, *kern_vtype;
929 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
930 struct bpf_struct_ops *st_ops;
931 void *data, *kern_data;
932 const char *tname;
933 int err;
934
935 st_ops = map->st_ops;
936 type = st_ops->type;
937 tname = st_ops->tname;
938 err = find_struct_ops_kern_types(kern_btf, tname,
939 &kern_type, &kern_type_id,
940 &kern_vtype, &kern_vtype_id,
941 &kern_data_member);
942 if (err)
943 return err;
944
945 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
946 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
947
948 map->def.value_size = kern_vtype->size;
949 map->btf_vmlinux_value_type_id = kern_vtype_id;
950
951 st_ops->kern_vdata = calloc(1, kern_vtype->size);
952 if (!st_ops->kern_vdata)
953 return -ENOMEM;
954
955 data = st_ops->data;
956 kern_data_off = kern_data_member->offset / 8;
957 kern_data = st_ops->kern_vdata + kern_data_off;
958
959 member = btf_members(type);
960 for (i = 0; i < btf_vlen(type); i++, member++) {
961 const struct btf_type *mtype, *kern_mtype;
962 __u32 mtype_id, kern_mtype_id;
963 void *mdata, *kern_mdata;
964 __s64 msize, kern_msize;
965 __u32 moff, kern_moff;
966 __u32 kern_member_idx;
967 const char *mname;
968
969 mname = btf__name_by_offset(btf, member->name_off);
970 kern_member = find_member_by_name(kern_btf, kern_type, mname);
971 if (!kern_member) {
972 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
973 map->name, mname);
974 return -ENOTSUP;
975 }
976
977 kern_member_idx = kern_member - btf_members(kern_type);
978 if (btf_member_bitfield_size(type, i) ||
979 btf_member_bitfield_size(kern_type, kern_member_idx)) {
980 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
981 map->name, mname);
982 return -ENOTSUP;
983 }
984
985 moff = member->offset / 8;
986 kern_moff = kern_member->offset / 8;
987
988 mdata = data + moff;
989 kern_mdata = kern_data + kern_moff;
990
991 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
992 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
993 &kern_mtype_id);
994 if (BTF_INFO_KIND(mtype->info) !=
995 BTF_INFO_KIND(kern_mtype->info)) {
996 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
997 map->name, mname, BTF_INFO_KIND(mtype->info),
998 BTF_INFO_KIND(kern_mtype->info));
999 return -ENOTSUP;
1000 }
1001
1002 if (btf_is_ptr(mtype)) {
1003 struct bpf_program *prog;
1004
d2836ddd
MKL
1005 prog = st_ops->progs[i];
1006 if (!prog)
1007 continue;
1008
590a0088
MKL
1009 kern_mtype = skip_mods_and_typedefs(kern_btf,
1010 kern_mtype->type,
1011 &kern_mtype_id);
d2836ddd
MKL
1012
1013 /* mtype->type must be a func_proto which was
1014 * guaranteed in bpf_object__collect_st_ops_relos(),
1015 * so only check kern_mtype for func_proto here.
1016 */
1017 if (!btf_is_func_proto(kern_mtype)) {
1018 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
590a0088
MKL
1019 map->name, mname);
1020 return -ENOTSUP;
1021 }
1022
590a0088
MKL
1023 prog->attach_btf_id = kern_type_id;
1024 prog->expected_attach_type = kern_member_idx;
1025
1026 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1027
1028 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1029 map->name, mname, prog->name, moff,
1030 kern_moff);
1031
1032 continue;
1033 }
1034
1035 msize = btf__resolve_size(btf, mtype_id);
1036 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1037 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1038 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1039 map->name, mname, (ssize_t)msize,
1040 (ssize_t)kern_msize);
1041 return -ENOTSUP;
1042 }
1043
1044 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1045 map->name, mname, (unsigned int)msize,
1046 moff, kern_moff);
1047 memcpy(kern_mdata, mdata, msize);
1048 }
1049
1050 return 0;
1051}
1052
1053static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1054{
590a0088
MKL
1055 struct bpf_map *map;
1056 size_t i;
1057 int err;
1058
1059 for (i = 0; i < obj->nr_maps; i++) {
1060 map = &obj->maps[i];
1061
1062 if (!bpf_map__is_struct_ops(map))
1063 continue;
1064
a6ed02ca
KS
1065 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1066 obj->btf_vmlinux);
1067 if (err)
590a0088 1068 return err;
590a0088
MKL
1069 }
1070
590a0088
MKL
1071 return 0;
1072}
1073
1074static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1075{
1076 const struct btf_type *type, *datasec;
1077 const struct btf_var_secinfo *vsi;
1078 struct bpf_struct_ops *st_ops;
1079 const char *tname, *var_name;
1080 __s32 type_id, datasec_id;
1081 const struct btf *btf;
1082 struct bpf_map *map;
1083 __u32 i;
1084
1085 if (obj->efile.st_ops_shndx == -1)
1086 return 0;
1087
1088 btf = obj->btf;
1089 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1090 BTF_KIND_DATASEC);
1091 if (datasec_id < 0) {
1092 pr_warn("struct_ops init: DATASEC %s not found\n",
1093 STRUCT_OPS_SEC);
1094 return -EINVAL;
1095 }
1096
1097 datasec = btf__type_by_id(btf, datasec_id);
1098 vsi = btf_var_secinfos(datasec);
1099 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1100 type = btf__type_by_id(obj->btf, vsi->type);
1101 var_name = btf__name_by_offset(obj->btf, type->name_off);
1102
1103 type_id = btf__resolve_type(obj->btf, vsi->type);
1104 if (type_id < 0) {
1105 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1106 vsi->type, STRUCT_OPS_SEC);
1107 return -EINVAL;
1108 }
1109
1110 type = btf__type_by_id(obj->btf, type_id);
1111 tname = btf__name_by_offset(obj->btf, type->name_off);
1112 if (!tname[0]) {
1113 pr_warn("struct_ops init: anonymous type is not supported\n");
1114 return -ENOTSUP;
1115 }
1116 if (!btf_is_struct(type)) {
1117 pr_warn("struct_ops init: %s is not a struct\n", tname);
1118 return -EINVAL;
1119 }
1120
1121 map = bpf_object__add_map(obj);
1122 if (IS_ERR(map))
1123 return PTR_ERR(map);
1124
1125 map->sec_idx = obj->efile.st_ops_shndx;
1126 map->sec_offset = vsi->offset;
1127 map->name = strdup(var_name);
1128 if (!map->name)
1129 return -ENOMEM;
1130
1131 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1132 map->def.key_size = sizeof(int);
1133 map->def.value_size = type->size;
1134 map->def.max_entries = 1;
1135
1136 map->st_ops = calloc(1, sizeof(*map->st_ops));
1137 if (!map->st_ops)
1138 return -ENOMEM;
1139 st_ops = map->st_ops;
1140 st_ops->data = malloc(type->size);
1141 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1142 st_ops->kern_func_off = malloc(btf_vlen(type) *
1143 sizeof(*st_ops->kern_func_off));
1144 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1145 return -ENOMEM;
1146
1147 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1148 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1149 var_name, STRUCT_OPS_SEC);
1150 return -EINVAL;
1151 }
1152
1153 memcpy(st_ops->data,
1154 obj->efile.st_ops_data->d_buf + vsi->offset,
1155 type->size);
1156 st_ops->tname = tname;
1157 st_ops->type = type;
1158 st_ops->type_id = type_id;
1159
1160 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1161 tname, type_id, var_name, vsi->offset);
1162 }
1163
1164 return 0;
1165}
1166
6c956392 1167static struct bpf_object *bpf_object__new(const char *path,
5e61f270 1168 const void *obj_buf,
2ce8450e
AN
1169 size_t obj_buf_sz,
1170 const char *obj_name)
1a5e3fb1 1171{
689624f0 1172 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1a5e3fb1 1173 struct bpf_object *obj;
d859900c 1174 char *end;
1a5e3fb1
WN
1175
1176 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1177 if (!obj) {
be18010e 1178 pr_warn("alloc memory failed for %s\n", path);
6371ca3b 1179 return ERR_PTR(-ENOMEM);
1a5e3fb1
WN
1180 }
1181
1182 strcpy(obj->path, path);
2ce8450e 1183 if (obj_name) {
9fc205b4 1184 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
2ce8450e
AN
1185 } else {
1186 /* Using basename() GNU version which doesn't modify arg. */
9fc205b4 1187 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
2ce8450e
AN
1188 end = strchr(obj->name, '.');
1189 if (end)
1190 *end = 0;
1191 }
6c956392 1192
d859900c 1193 obj->efile.fd = -1;
6c956392 1194 /*
76e1022b 1195 * Caller of this function should also call
6c956392
WN
1196 * bpf_object__elf_finish() after data collection to return
1197 * obj_buf to user. If not, we should duplicate the buffer to
1198 * avoid user freeing them before elf finish.
1199 */
1200 obj->efile.obj_buf = obj_buf;
1201 obj->efile.obj_buf_sz = obj_buf_sz;
666810e8 1202 obj->efile.maps_shndx = -1;
abd29c93 1203 obj->efile.btf_maps_shndx = -1;
590a0088 1204 obj->efile.st_ops_shndx = -1;
81bfdd08 1205 obj->kconfig_map_idx = -1;
6c956392 1206
5e61f270 1207 obj->kern_version = get_kernel_version();
52d3352e 1208 obj->loaded = false;
9a208eff
WN
1209
1210 INIT_LIST_HEAD(&obj->list);
689624f0
JB
1211 if (!strict)
1212 list_add(&obj->list, &bpf_objects_list);
1a5e3fb1
WN
1213 return obj;
1214}
1215
1216static void bpf_object__elf_finish(struct bpf_object *obj)
1217{
29a30ff5 1218 if (!obj->efile.elf)
1a5e3fb1
WN
1219 return;
1220
1221 if (obj->efile.elf) {
1222 elf_end(obj->efile.elf);
1223 obj->efile.elf = NULL;
1224 }
bec7d68c 1225 obj->efile.symbols = NULL;
590a0088 1226 obj->efile.st_ops_data = NULL;
b62f06e8 1227
25bbbd7a
AN
1228 zfree(&obj->efile.secs);
1229 obj->efile.sec_cnt = 0;
1a5e3fb1 1230 zclose(obj->efile.fd);
6c956392
WN
1231 obj->efile.obj_buf = NULL;
1232 obj->efile.obj_buf_sz = 0;
1a5e3fb1
WN
1233}
1234
1235static int bpf_object__elf_init(struct bpf_object *obj)
1236{
ad23b723 1237 Elf64_Ehdr *ehdr;
1a5e3fb1 1238 int err = 0;
ad23b723 1239 Elf *elf;
1a5e3fb1 1240
29a30ff5 1241 if (obj->efile.elf) {
88a82120 1242 pr_warn("elf: init internal error\n");
6371ca3b 1243 return -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1244 }
1245
6c956392
WN
1246 if (obj->efile.obj_buf_sz > 0) {
1247 /*
1248 * obj_buf should have been validated by
1249 * bpf_object__open_buffer().
1250 */
ad23b723 1251 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
6c956392 1252 } else {
92274e24 1253 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
6c956392 1254 if (obj->efile.fd < 0) {
be5c5d4e 1255 char errmsg[STRERR_BUFSIZE], *cp;
1ce6a9fc 1256
be5c5d4e
AN
1257 err = -errno;
1258 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
88a82120 1259 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
be5c5d4e 1260 return err;
6c956392
WN
1261 }
1262
ad23b723 1263 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1a5e3fb1
WN
1264 }
1265
ad23b723 1266 if (!elf) {
88a82120 1267 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1268 err = -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1269 goto errout;
1270 }
1271
ad23b723
AN
1272 obj->efile.elf = elf;
1273
1274 if (elf_kind(elf) != ELF_K_ELF) {
1275 err = -LIBBPF_ERRNO__FORMAT;
1276 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1277 goto errout;
1278 }
1279
1280 if (gelf_getclass(elf) != ELFCLASS64) {
1281 err = -LIBBPF_ERRNO__FORMAT;
1282 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1283 goto errout;
1284 }
1285
1286 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1287 if (!obj->efile.ehdr) {
88a82120 1288 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1289 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1290 goto errout;
1291 }
1a5e3fb1 1292
ad23b723 1293 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
88a82120
AN
1294 pr_warn("elf: failed to get section names section index for %s: %s\n",
1295 obj->path, elf_errmsg(-1));
1296 err = -LIBBPF_ERRNO__FORMAT;
1297 goto errout;
1298 }
1299
1300 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
ad23b723 1301 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
88a82120
AN
1302 pr_warn("elf: failed to get section names strings from %s: %s\n",
1303 obj->path, elf_errmsg(-1));
8f3f5792
NK
1304 err = -LIBBPF_ERRNO__FORMAT;
1305 goto errout;
88a82120
AN
1306 }
1307
9b16137a 1308 /* Old LLVM set e_machine to EM_NONE */
ad23b723 1309 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
88a82120 1310 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
6371ca3b 1311 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1312 goto errout;
1313 }
1314
1315 return 0;
1316errout:
1317 bpf_object__elf_finish(obj);
1318 return err;
1319}
1320
12ef5634 1321static int bpf_object__check_endianness(struct bpf_object *obj)
cc4228d5 1322{
3930198d 1323#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
ad23b723 1324 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
12ef5634 1325 return 0;
3930198d 1326#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
ad23b723 1327 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
12ef5634
AN
1328 return 0;
1329#else
1330# error "Unrecognized __BYTE_ORDER__"
1331#endif
88a82120 1332 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
6371ca3b 1333 return -LIBBPF_ERRNO__ENDIAN;
cc4228d5
WN
1334}
1335
cb1e5e96 1336static int
399dc65e 1337bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
cb1e5e96 1338{
f9798239
AN
1339 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1340 * go over allowed ELF data section buffer
1341 */
1342 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
cb1e5e96
WN
1343 pr_debug("license of %s is %s\n", obj->path, obj->license);
1344 return 0;
1345}
1346
54b8625c
JF
1347static int
1348bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1349{
1350 __u32 kver;
1351
1352 if (size != sizeof(kver)) {
be18010e 1353 pr_warn("invalid kver section in %s\n", obj->path);
54b8625c
JF
1354 return -LIBBPF_ERRNO__FORMAT;
1355 }
1356 memcpy(&kver, data, sizeof(kver));
1357 obj->kern_version = kver;
1358 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1359 return 0;
1360}
1361
addb9fc9
NS
1362static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1363{
1364 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1365 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1366 return true;
1367 return false;
1368}
1369
b96c07f3 1370static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1713d68b 1371{
25bbbd7a
AN
1372 Elf_Data *data;
1373 Elf_Scn *scn;
1713d68b 1374
25bbbd7a 1375 if (!name)
1713d68b 1376 return -EINVAL;
88a82120 1377
25bbbd7a
AN
1378 scn = elf_sec_by_name(obj, name);
1379 data = elf_sec_data(obj, scn);
1380 if (data) {
25bbbd7a 1381 *size = data->d_size;
08894d9c 1382 return 0; /* found it */
1713d68b
DB
1383 }
1384
08894d9c 1385 return -ENOENT;
1713d68b
DB
1386}
1387
b96c07f3 1388static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1713d68b
DB
1389{
1390 Elf_Data *symbols = obj->efile.symbols;
1391 const char *sname;
1392 size_t si;
1393
1394 if (!name || !off)
1395 return -EINVAL;
1396
ad23b723
AN
1397 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1398 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1713d68b 1399
ad23b723
AN
1400 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL ||
1401 ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1713d68b
DB
1402 continue;
1403
ad23b723 1404 sname = elf_sym_str(obj, sym->st_name);
1713d68b 1405 if (!sname) {
ad23b723 1406 pr_warn("failed to get sym name string for var %s\n", name);
1713d68b
DB
1407 return -EIO;
1408 }
1409 if (strcmp(name, sname) == 0) {
ad23b723 1410 *off = sym->st_value;
1713d68b
DB
1411 return 0;
1412 }
1413 }
1414
1415 return -ENOENT;
1416}
1417
bf829271 1418static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
d859900c 1419{
bf829271
AN
1420 struct bpf_map *new_maps;
1421 size_t new_cap;
1422 int i;
1423
1424 if (obj->nr_maps < obj->maps_cap)
1425 return &obj->maps[obj->nr_maps++];
1426
95064979 1427 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
029258d7 1428 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
bf829271 1429 if (!new_maps) {
be18010e 1430 pr_warn("alloc maps for object failed\n");
bf829271
AN
1431 return ERR_PTR(-ENOMEM);
1432 }
1433
1434 obj->maps_cap = new_cap;
1435 obj->maps = new_maps;
1436
1437 /* zero out new maps */
1438 memset(obj->maps + obj->nr_maps, 0,
1439 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1440 /*
1441 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1442 * when failure (zclose won't close negative fd)).
1443 */
1444 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1445 obj->maps[i].fd = -1;
1446 obj->maps[i].inner_map_fd = -1;
1447 }
1448
1449 return &obj->maps[obj->nr_maps++];
d859900c
DB
1450}
1451
eba9c5f4
AN
1452static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1453{
1454 long page_sz = sysconf(_SC_PAGE_SIZE);
1455 size_t map_sz;
1456
c701917e 1457 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
eba9c5f4
AN
1458 map_sz = roundup(map_sz, page_sz);
1459 return map_sz;
1460}
1461
aed65917 1462static char *internal_map_name(struct bpf_object *obj, const char *real_name)
81bfdd08 1463{
113e6b7e 1464 char map_name[BPF_OBJ_NAME_LEN], *p;
aed65917
AN
1465 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1466
1467 /* This is one of the more confusing parts of libbpf for various
1468 * reasons, some of which are historical. The original idea for naming
1469 * internal names was to include as much of BPF object name prefix as
1470 * possible, so that it can be distinguished from similar internal
1471 * maps of a different BPF object.
1472 * As an example, let's say we have bpf_object named 'my_object_name'
1473 * and internal map corresponding to '.rodata' ELF section. The final
1474 * map name advertised to user and to the kernel will be
1475 * 'my_objec.rodata', taking first 8 characters of object name and
1476 * entire 7 characters of '.rodata'.
1477 * Somewhat confusingly, if internal map ELF section name is shorter
1478 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1479 * for the suffix, even though we only have 4 actual characters, and
1480 * resulting map will be called 'my_objec.bss', not even using all 15
1481 * characters allowed by the kernel. Oh well, at least the truncated
1482 * object name is somewhat consistent in this case. But if the map
1483 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1484 * (8 chars) and thus will be left with only first 7 characters of the
1485 * object name ('my_obje'). Happy guessing, user, that the final map
1486 * name will be "my_obje.kconfig".
1487 * Now, with libbpf starting to support arbitrarily named .rodata.*
1488 * and .data.* data sections, it's possible that ELF section name is
1489 * longer than allowed 15 chars, so we now need to be careful to take
1490 * only up to 15 first characters of ELF name, taking no BPF object
1491 * name characters at all. So '.rodata.abracadabra' will result in
1492 * '.rodata.abracad' kernel and user-visible name.
1493 * We need to keep this convoluted logic intact for .data, .bss and
1494 * .rodata maps, but for new custom .data.custom and .rodata.custom
1495 * maps we use their ELF names as is, not prepending bpf_object name
1496 * in front. We still need to truncate them to 15 characters for the
1497 * kernel. Full name can be recovered for such maps by using DATASEC
1498 * BTF type associated with such map's value type, though.
1499 */
1500 if (sfx_len >= BPF_OBJ_NAME_LEN)
1501 sfx_len = BPF_OBJ_NAME_LEN - 1;
1502
1503 /* if there are two or more dots in map name, it's a custom dot map */
1504 if (strchr(real_name + 1, '.') != NULL)
1505 pfx_len = 0;
1506 else
1507 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
81bfdd08
AN
1508
1509 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
aed65917 1510 sfx_len, real_name);
81bfdd08 1511
113e6b7e
THJ
1512 /* sanitise map name to characters allowed by kernel */
1513 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1514 if (!isalnum(*p) && *p != '_' && *p != '.')
1515 *p = '_';
1516
81bfdd08
AN
1517 return strdup(map_name);
1518}
1519
d859900c 1520static int
bf829271 1521bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
aed65917 1522 const char *real_name, int sec_idx, void *data, size_t data_sz)
d859900c 1523{
bf829271
AN
1524 struct bpf_map_def *def;
1525 struct bpf_map *map;
eba9c5f4 1526 int err;
bf829271
AN
1527
1528 map = bpf_object__add_map(obj);
1529 if (IS_ERR(map))
1530 return PTR_ERR(map);
d859900c
DB
1531
1532 map->libbpf_type = type;
db48814b
AN
1533 map->sec_idx = sec_idx;
1534 map->sec_offset = 0;
aed65917
AN
1535 map->real_name = strdup(real_name);
1536 map->name = internal_map_name(obj, real_name);
1537 if (!map->real_name || !map->name) {
1538 zfree(&map->real_name);
1539 zfree(&map->name);
d859900c
DB
1540 return -ENOMEM;
1541 }
1542
bf829271 1543 def = &map->def;
d859900c
DB
1544 def->type = BPF_MAP_TYPE_ARRAY;
1545 def->key_size = sizeof(int);
eba9c5f4 1546 def->value_size = data_sz;
d859900c 1547 def->max_entries = 1;
81bfdd08 1548 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
166750bc 1549 ? BPF_F_RDONLY_PROG : 0;
0d13bfce 1550 def->map_flags |= BPF_F_MMAPABLE;
7fe74b43
AN
1551
1552 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
81bfdd08 1553 map->name, map->sec_idx, map->sec_offset, def->map_flags);
7fe74b43 1554
eba9c5f4
AN
1555 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1556 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1557 if (map->mmaped == MAP_FAILED) {
1558 err = -errno;
1559 map->mmaped = NULL;
1560 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1561 map->name, err);
aed65917 1562 zfree(&map->real_name);
eba9c5f4
AN
1563 zfree(&map->name);
1564 return err;
d859900c
DB
1565 }
1566
166750bc 1567 if (data)
eba9c5f4
AN
1568 memcpy(map->mmaped, data, data_sz);
1569
e1d1dc46 1570 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
d859900c
DB
1571 return 0;
1572}
1573
bf829271
AN
1574static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1575{
25bbbd7a 1576 struct elf_sec_desc *sec_desc;
aed65917 1577 const char *sec_name;
25bbbd7a 1578 int err = 0, sec_idx;
bf829271 1579
bf829271
AN
1580 /*
1581 * Populate obj->maps with libbpf internal maps.
1582 */
25bbbd7a
AN
1583 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1584 sec_desc = &obj->efile.secs[sec_idx];
1585
1586 switch (sec_desc->sec_type) {
1587 case SEC_DATA:
aed65917 1588 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1589 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
aed65917 1590 sec_name, sec_idx,
25bbbd7a
AN
1591 sec_desc->data->d_buf,
1592 sec_desc->data->d_size);
1593 break;
1594 case SEC_RODATA:
1595 obj->has_rodata = true;
aed65917 1596 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1597 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
aed65917 1598 sec_name, sec_idx,
25bbbd7a
AN
1599 sec_desc->data->d_buf,
1600 sec_desc->data->d_size);
1601 break;
1602 case SEC_BSS:
aed65917 1603 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1604 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
aed65917 1605 sec_name, sec_idx,
25bbbd7a
AN
1606 NULL,
1607 sec_desc->data->d_size);
1608 break;
1609 default:
1610 /* skip */
1611 break;
1612 }
bf829271
AN
1613 if (err)
1614 return err;
1615 }
1616 return 0;
1617}
1618
166750bc
AN
1619
1620static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1621 const void *name)
1622{
1623 int i;
1624
1625 for (i = 0; i < obj->nr_extern; i++) {
1626 if (strcmp(obj->externs[i].name, name) == 0)
1627 return &obj->externs[i];
1628 }
1629 return NULL;
1630}
1631
2e33efe3
AN
1632static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1633 char value)
166750bc 1634{
2e33efe3
AN
1635 switch (ext->kcfg.type) {
1636 case KCFG_BOOL:
166750bc 1637 if (value == 'm') {
2e33efe3 1638 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
166750bc
AN
1639 ext->name, value);
1640 return -EINVAL;
1641 }
1642 *(bool *)ext_val = value == 'y' ? true : false;
1643 break;
2e33efe3 1644 case KCFG_TRISTATE:
166750bc
AN
1645 if (value == 'y')
1646 *(enum libbpf_tristate *)ext_val = TRI_YES;
1647 else if (value == 'm')
1648 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1649 else /* value == 'n' */
1650 *(enum libbpf_tristate *)ext_val = TRI_NO;
1651 break;
2e33efe3 1652 case KCFG_CHAR:
166750bc
AN
1653 *(char *)ext_val = value;
1654 break;
2e33efe3
AN
1655 case KCFG_UNKNOWN:
1656 case KCFG_INT:
1657 case KCFG_CHAR_ARR:
166750bc 1658 default:
2e33efe3 1659 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
166750bc
AN
1660 ext->name, value);
1661 return -EINVAL;
1662 }
1663 ext->is_set = true;
1664 return 0;
1665}
1666
2e33efe3
AN
1667static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1668 const char *value)
166750bc
AN
1669{
1670 size_t len;
1671
2e33efe3
AN
1672 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1673 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
166750bc
AN
1674 return -EINVAL;
1675 }
1676
1677 len = strlen(value);
1678 if (value[len - 1] != '"') {
2e33efe3 1679 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
166750bc
AN
1680 ext->name, value);
1681 return -EINVAL;
1682 }
1683
1684 /* strip quotes */
1685 len -= 2;
2e33efe3
AN
1686 if (len >= ext->kcfg.sz) {
1687 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1688 ext->name, value, len, ext->kcfg.sz - 1);
1689 len = ext->kcfg.sz - 1;
166750bc
AN
1690 }
1691 memcpy(ext_val, value + 1, len);
1692 ext_val[len] = '\0';
1693 ext->is_set = true;
1694 return 0;
1695}
1696
1697static int parse_u64(const char *value, __u64 *res)
1698{
1699 char *value_end;
1700 int err;
1701
1702 errno = 0;
1703 *res = strtoull(value, &value_end, 0);
1704 if (errno) {
1705 err = -errno;
1706 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1707 return err;
1708 }
1709 if (*value_end) {
1710 pr_warn("failed to parse '%s' as integer completely\n", value);
1711 return -EINVAL;
1712 }
1713 return 0;
1714}
1715
2e33efe3 1716static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
166750bc 1717{
2e33efe3 1718 int bit_sz = ext->kcfg.sz * 8;
166750bc 1719
2e33efe3 1720 if (ext->kcfg.sz == 8)
166750bc
AN
1721 return true;
1722
1723 /* Validate that value stored in u64 fits in integer of `ext->sz`
1724 * bytes size without any loss of information. If the target integer
1725 * is signed, we rely on the following limits of integer type of
1726 * Y bits and subsequent transformation:
1727 *
1728 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1729 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1730 * 0 <= X + 2^(Y-1) < 2^Y
1731 *
1732 * For unsigned target integer, check that all the (64 - Y) bits are
1733 * zero.
1734 */
2e33efe3 1735 if (ext->kcfg.is_signed)
166750bc
AN
1736 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1737 else
1738 return (v >> bit_sz) == 0;
1739}
1740
2e33efe3
AN
1741static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1742 __u64 value)
166750bc 1743{
2e33efe3
AN
1744 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1745 pr_warn("extern (kcfg) %s=%llu should be integer\n",
7745ff98 1746 ext->name, (unsigned long long)value);
166750bc
AN
1747 return -EINVAL;
1748 }
2e33efe3
AN
1749 if (!is_kcfg_value_in_range(ext, value)) {
1750 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1751 ext->name, (unsigned long long)value, ext->kcfg.sz);
166750bc
AN
1752 return -ERANGE;
1753 }
2e33efe3 1754 switch (ext->kcfg.sz) {
166750bc
AN
1755 case 1: *(__u8 *)ext_val = value; break;
1756 case 2: *(__u16 *)ext_val = value; break;
1757 case 4: *(__u32 *)ext_val = value; break;
1758 case 8: *(__u64 *)ext_val = value; break;
1759 default:
1760 return -EINVAL;
1761 }
1762 ext->is_set = true;
1763 return 0;
1764}
1765
8601fd42
AN
1766static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1767 char *buf, void *data)
166750bc 1768{
166750bc 1769 struct extern_desc *ext;
8601fd42 1770 char *sep, *value;
166750bc
AN
1771 int len, err = 0;
1772 void *ext_val;
1773 __u64 num;
166750bc 1774
13d35a0c 1775 if (!str_has_pfx(buf, "CONFIG_"))
8601fd42 1776 return 0;
166750bc 1777
8601fd42
AN
1778 sep = strchr(buf, '=');
1779 if (!sep) {
1780 pr_warn("failed to parse '%s': no separator\n", buf);
1781 return -EINVAL;
1782 }
1783
1784 /* Trim ending '\n' */
1785 len = strlen(buf);
1786 if (buf[len - 1] == '\n')
1787 buf[len - 1] = '\0';
1788 /* Split on '=' and ensure that a value is present. */
1789 *sep = '\0';
1790 if (!sep[1]) {
1791 *sep = '=';
1792 pr_warn("failed to parse '%s': no value\n", buf);
1793 return -EINVAL;
1794 }
1795
1796 ext = find_extern_by_name(obj, buf);
1797 if (!ext || ext->is_set)
1798 return 0;
1799
2e33efe3 1800 ext_val = data + ext->kcfg.data_off;
8601fd42
AN
1801 value = sep + 1;
1802
1803 switch (*value) {
1804 case 'y': case 'n': case 'm':
2e33efe3 1805 err = set_kcfg_value_tri(ext, ext_val, *value);
8601fd42
AN
1806 break;
1807 case '"':
2e33efe3 1808 err = set_kcfg_value_str(ext, ext_val, value);
8601fd42
AN
1809 break;
1810 default:
1811 /* assume integer */
1812 err = parse_u64(value, &num);
1813 if (err) {
2e33efe3 1814 pr_warn("extern (kcfg) %s=%s should be integer\n",
8601fd42
AN
1815 ext->name, value);
1816 return err;
1817 }
2e33efe3 1818 err = set_kcfg_value_num(ext, ext_val, num);
8601fd42 1819 break;
166750bc 1820 }
8601fd42
AN
1821 if (err)
1822 return err;
2e33efe3 1823 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
8601fd42
AN
1824 return 0;
1825}
1826
1827static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1828{
1829 char buf[PATH_MAX];
1830 struct utsname uts;
1831 int len, err = 0;
1832 gzFile file;
1833
1834 uname(&uts);
1835 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1836 if (len < 0)
1837 return -EINVAL;
1838 else if (len >= PATH_MAX)
1839 return -ENAMETOOLONG;
1840
1841 /* gzopen also accepts uncompressed files. */
1842 file = gzopen(buf, "r");
1843 if (!file)
1844 file = gzopen("/proc/config.gz", "r");
1845
166750bc 1846 if (!file) {
8601fd42 1847 pr_warn("failed to open system Kconfig\n");
166750bc
AN
1848 return -ENOENT;
1849 }
1850
1851 while (gzgets(file, buf, sizeof(buf))) {
8601fd42
AN
1852 err = bpf_object__process_kconfig_line(obj, buf, data);
1853 if (err) {
1854 pr_warn("error parsing system Kconfig line '%s': %d\n",
1855 buf, err);
166750bc
AN
1856 goto out;
1857 }
8601fd42 1858 }
166750bc 1859
8601fd42
AN
1860out:
1861 gzclose(file);
1862 return err;
1863}
166750bc 1864
8601fd42
AN
1865static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1866 const char *config, void *data)
1867{
1868 char buf[PATH_MAX];
1869 int err = 0;
1870 FILE *file;
166750bc 1871
8601fd42
AN
1872 file = fmemopen((void *)config, strlen(config), "r");
1873 if (!file) {
1874 err = -errno;
1875 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1876 return err;
1877 }
1878
1879 while (fgets(buf, sizeof(buf), file)) {
1880 err = bpf_object__process_kconfig_line(obj, buf, data);
1881 if (err) {
1882 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1883 buf, err);
166750bc
AN
1884 break;
1885 }
166750bc
AN
1886 }
1887
8601fd42 1888 fclose(file);
166750bc
AN
1889 return err;
1890}
1891
81bfdd08 1892static int bpf_object__init_kconfig_map(struct bpf_object *obj)
166750bc 1893{
2e33efe3 1894 struct extern_desc *last_ext = NULL, *ext;
166750bc 1895 size_t map_sz;
2e33efe3 1896 int i, err;
166750bc 1897
2e33efe3
AN
1898 for (i = 0; i < obj->nr_extern; i++) {
1899 ext = &obj->externs[i];
1900 if (ext->type == EXT_KCFG)
1901 last_ext = ext;
1902 }
166750bc 1903
2e33efe3
AN
1904 if (!last_ext)
1905 return 0;
166750bc 1906
2e33efe3 1907 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
81bfdd08 1908 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
aed65917 1909 ".kconfig", obj->efile.symbols_shndx,
166750bc
AN
1910 NULL, map_sz);
1911 if (err)
1912 return err;
1913
81bfdd08 1914 obj->kconfig_map_idx = obj->nr_maps - 1;
166750bc
AN
1915
1916 return 0;
1917}
1918
bf829271 1919static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
561bbcca 1920{
561bbcca 1921 Elf_Data *symbols = obj->efile.symbols;
bf829271 1922 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
d859900c 1923 Elf_Data *data = NULL;
bf829271
AN
1924 Elf_Scn *scn;
1925
1926 if (obj->efile.maps_shndx < 0)
1927 return 0;
561bbcca 1928
93b8952d
AN
1929 if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
1930 pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
1931 return -EOPNOTSUPP;
1932 }
1933
4708bbda
EL
1934 if (!symbols)
1935 return -EINVAL;
1936
88a82120
AN
1937 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1938 data = elf_sec_data(obj, scn);
bf829271 1939 if (!scn || !data) {
88a82120
AN
1940 pr_warn("elf: failed to get legacy map definitions for %s\n",
1941 obj->path);
bf829271 1942 return -EINVAL;
4708bbda 1943 }
561bbcca 1944
4708bbda
EL
1945 /*
1946 * Count number of maps. Each map has a name.
1947 * Array of maps is not supported: only the first element is
1948 * considered.
1949 *
1950 * TODO: Detect array of map and report error.
1951 */
ad23b723 1952 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
bf829271 1953 for (i = 0; i < nr_syms; i++) {
ad23b723 1954 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4708bbda 1955
ad23b723 1956 if (sym->st_shndx != obj->efile.maps_shndx)
4708bbda 1957 continue;
ad23b723 1958 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
161ecd53 1959 continue;
4708bbda
EL
1960 nr_maps++;
1961 }
b13c5c14 1962 /* Assume equally sized map definitions */
88a82120
AN
1963 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1964 nr_maps, data->d_size, obj->path);
bf829271 1965
98e527af 1966 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
88a82120
AN
1967 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1968 obj->path);
bf829271 1969 return -EINVAL;
addb9fc9 1970 }
98e527af 1971 map_def_sz = data->d_size / nr_maps;
4708bbda 1972
bf829271
AN
1973 /* Fill obj->maps using data in "maps" section. */
1974 for (i = 0; i < nr_syms; i++) {
ad23b723 1975 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
561bbcca 1976 const char *map_name;
4708bbda 1977 struct bpf_map_def *def;
bf829271 1978 struct bpf_map *map;
561bbcca 1979
ad23b723 1980 if (sym->st_shndx != obj->efile.maps_shndx)
561bbcca 1981 continue;
ad23b723 1982 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
c3e8c44a 1983 continue;
561bbcca 1984
bf829271
AN
1985 map = bpf_object__add_map(obj);
1986 if (IS_ERR(map))
1987 return PTR_ERR(map);
1988
ad23b723 1989 map_name = elf_sym_str(obj, sym->st_name);
c51829bb 1990 if (!map_name) {
be18010e
KW
1991 pr_warn("failed to get map #%d name sym string for obj %s\n",
1992 i, obj->path);
c51829bb
AN
1993 return -LIBBPF_ERRNO__FORMAT;
1994 }
d859900c 1995
93b8952d
AN
1996 pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
1997
ad23b723 1998 if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
c1cccec9
AN
1999 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2000 return -ENOTSUP;
2001 }
2002
bf829271 2003 map->libbpf_type = LIBBPF_MAP_UNSPEC;
ad23b723
AN
2004 map->sec_idx = sym->st_shndx;
2005 map->sec_offset = sym->st_value;
db48814b
AN
2006 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2007 map_name, map->sec_idx, map->sec_offset);
ad23b723 2008 if (sym->st_value + map_def_sz > data->d_size) {
be18010e
KW
2009 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2010 obj->path, map_name);
4708bbda 2011 return -EINVAL;
561bbcca 2012 }
4708bbda 2013
bf829271
AN
2014 map->name = strdup(map_name);
2015 if (!map->name) {
aed65917 2016 pr_warn("map '%s': failed to alloc map name\n", map_name);
973170e6
WN
2017 return -ENOMEM;
2018 }
bf829271 2019 pr_debug("map %d is \"%s\"\n", i, map->name);
ad23b723 2020 def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
b13c5c14
CG
2021 /*
2022 * If the definition of the map in the object file fits in
2023 * bpf_map_def, copy it. Any extra fields in our version
2024 * of bpf_map_def will default to zero as a result of the
2025 * calloc above.
2026 */
2027 if (map_def_sz <= sizeof(struct bpf_map_def)) {
bf829271 2028 memcpy(&map->def, def, map_def_sz);
b13c5c14
CG
2029 } else {
2030 /*
2031 * Here the map structure being read is bigger than what
2032 * we expect, truncate if the excess bits are all zero.
2033 * If they are not zero, reject this map as
2034 * incompatible.
2035 */
2036 char *b;
8983b731 2037
b13c5c14
CG
2038 for (b = ((char *)def) + sizeof(struct bpf_map_def);
2039 b < ((char *)def) + map_def_sz; b++) {
2040 if (*b != 0) {
8983b731 2041 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
be18010e 2042 obj->path, map_name);
c034a177
JF
2043 if (strict)
2044 return -EINVAL;
b13c5c14
CG
2045 }
2046 }
bf829271 2047 memcpy(&map->def, def, sizeof(struct bpf_map_def));
b13c5c14 2048 }
561bbcca 2049 }
bf829271
AN
2050 return 0;
2051}
4708bbda 2052
42869d28 2053const struct btf_type *
ddc7c304 2054skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
abd29c93
AN
2055{
2056 const struct btf_type *t = btf__type_by_id(btf, id);
8837fe5d 2057
ddc7c304
AN
2058 if (res_id)
2059 *res_id = id;
2060
2061 while (btf_is_mod(t) || btf_is_typedef(t)) {
2062 if (res_id)
2063 *res_id = t->type;
2064 t = btf__type_by_id(btf, t->type);
abd29c93 2065 }
ddc7c304
AN
2066
2067 return t;
abd29c93
AN
2068}
2069
590a0088
MKL
2070static const struct btf_type *
2071resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2072{
2073 const struct btf_type *t;
2074
2075 t = skip_mods_and_typedefs(btf, id, NULL);
2076 if (!btf_is_ptr(t))
2077 return NULL;
2078
2079 t = skip_mods_and_typedefs(btf, t->type, res_id);
2080
2081 return btf_is_func_proto(t) ? t : NULL;
2082}
2083
774e132e 2084static const char *__btf_kind_str(__u16 kind)
81ba0889 2085{
774e132e 2086 switch (kind) {
81ba0889
AN
2087 case BTF_KIND_UNKN: return "void";
2088 case BTF_KIND_INT: return "int";
2089 case BTF_KIND_PTR: return "ptr";
2090 case BTF_KIND_ARRAY: return "array";
2091 case BTF_KIND_STRUCT: return "struct";
2092 case BTF_KIND_UNION: return "union";
2093 case BTF_KIND_ENUM: return "enum";
2094 case BTF_KIND_FWD: return "fwd";
2095 case BTF_KIND_TYPEDEF: return "typedef";
2096 case BTF_KIND_VOLATILE: return "volatile";
2097 case BTF_KIND_CONST: return "const";
2098 case BTF_KIND_RESTRICT: return "restrict";
2099 case BTF_KIND_FUNC: return "func";
2100 case BTF_KIND_FUNC_PROTO: return "func_proto";
2101 case BTF_KIND_VAR: return "var";
2102 case BTF_KIND_DATASEC: return "datasec";
22541a9e 2103 case BTF_KIND_FLOAT: return "float";
223f903e 2104 case BTF_KIND_DECL_TAG: return "decl_tag";
2dc1e488 2105 case BTF_KIND_TYPE_TAG: return "type_tag";
81ba0889
AN
2106 default: return "unknown";
2107 }
2108}
2109
42869d28 2110const char *btf_kind_str(const struct btf_type *t)
774e132e
MKL
2111{
2112 return __btf_kind_str(btf_kind(t));
2113}
2114
ef99b02b
AN
2115/*
2116 * Fetch integer attribute of BTF map definition. Such attributes are
2117 * represented using a pointer to an array, in which dimensionality of array
2118 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2119 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2120 * type definition, while using only sizeof(void *) space in ELF data section.
2121 */
2122static bool get_map_field_int(const char *map_name, const struct btf *btf,
8983b731
AN
2123 const struct btf_member *m, __u32 *res)
2124{
ddc7c304 2125 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
abd29c93 2126 const char *name = btf__name_by_offset(btf, m->name_off);
ef99b02b
AN
2127 const struct btf_array *arr_info;
2128 const struct btf_type *arr_t;
abd29c93 2129
b03bc685 2130 if (!btf_is_ptr(t)) {
81ba0889
AN
2131 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2132 map_name, name, btf_kind_str(t));
abd29c93
AN
2133 return false;
2134 }
ef99b02b
AN
2135
2136 arr_t = btf__type_by_id(btf, t->type);
2137 if (!arr_t) {
be18010e
KW
2138 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2139 map_name, name, t->type);
abd29c93
AN
2140 return false;
2141 }
b03bc685 2142 if (!btf_is_array(arr_t)) {
81ba0889
AN
2143 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2144 map_name, name, btf_kind_str(arr_t));
abd29c93
AN
2145 return false;
2146 }
b03bc685 2147 arr_info = btf_array(arr_t);
ef99b02b 2148 *res = arr_info->nelems;
abd29c93
AN
2149 return true;
2150}
2151
57a00f41
THJ
2152static int build_map_pin_path(struct bpf_map *map, const char *path)
2153{
2154 char buf[PATH_MAX];
6e9cab2e 2155 int len;
57a00f41
THJ
2156
2157 if (!path)
2158 path = "/sys/fs/bpf";
2159
2160 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2161 if (len < 0)
2162 return -EINVAL;
2163 else if (len >= PATH_MAX)
2164 return -ENAMETOOLONG;
2165
6e9cab2e 2166 return bpf_map__set_pin_path(map, buf);
57a00f41
THJ
2167}
2168
c7ef5ec9
AN
2169int parse_btf_map_def(const char *map_name, struct btf *btf,
2170 const struct btf_type *def_t, bool strict,
2171 struct btf_map_def *map_def, struct btf_map_def *inner_def)
abd29c93 2172{
41017e56 2173 const struct btf_type *t;
abd29c93 2174 const struct btf_member *m;
c7ef5ec9 2175 bool is_inner = inner_def == NULL;
abd29c93
AN
2176 int vlen, i;
2177
c7ef5ec9
AN
2178 vlen = btf_vlen(def_t);
2179 m = btf_members(def_t);
abd29c93 2180 for (i = 0; i < vlen; i++, m++) {
c7ef5ec9 2181 const char *name = btf__name_by_offset(btf, m->name_off);
abd29c93
AN
2182
2183 if (!name) {
c7ef5ec9 2184 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
abd29c93
AN
2185 return -EINVAL;
2186 }
2187 if (strcmp(name, "type") == 0) {
c7ef5ec9 2188 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
abd29c93 2189 return -EINVAL;
c7ef5ec9 2190 map_def->parts |= MAP_DEF_MAP_TYPE;
abd29c93 2191 } else if (strcmp(name, "max_entries") == 0) {
c7ef5ec9 2192 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
abd29c93 2193 return -EINVAL;
c7ef5ec9 2194 map_def->parts |= MAP_DEF_MAX_ENTRIES;
abd29c93 2195 } else if (strcmp(name, "map_flags") == 0) {
c7ef5ec9 2196 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
abd29c93 2197 return -EINVAL;
c7ef5ec9 2198 map_def->parts |= MAP_DEF_MAP_FLAGS;
1bdb6c9a 2199 } else if (strcmp(name, "numa_node") == 0) {
c7ef5ec9 2200 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
1bdb6c9a 2201 return -EINVAL;
c7ef5ec9 2202 map_def->parts |= MAP_DEF_NUMA_NODE;
abd29c93
AN
2203 } else if (strcmp(name, "key_size") == 0) {
2204 __u32 sz;
2205
c7ef5ec9 2206 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2207 return -EINVAL;
c7ef5ec9 2208 if (map_def->key_size && map_def->key_size != sz) {
be18010e 2209 pr_warn("map '%s': conflicting key size %u != %u.\n",
c7ef5ec9 2210 map_name, map_def->key_size, sz);
abd29c93
AN
2211 return -EINVAL;
2212 }
c7ef5ec9
AN
2213 map_def->key_size = sz;
2214 map_def->parts |= MAP_DEF_KEY_SIZE;
abd29c93
AN
2215 } else if (strcmp(name, "key") == 0) {
2216 __s64 sz;
2217
c7ef5ec9 2218 t = btf__type_by_id(btf, m->type);
abd29c93 2219 if (!t) {
be18010e 2220 pr_warn("map '%s': key type [%d] not found.\n",
c7ef5ec9 2221 map_name, m->type);
abd29c93
AN
2222 return -EINVAL;
2223 }
b03bc685 2224 if (!btf_is_ptr(t)) {
81ba0889 2225 pr_warn("map '%s': key spec is not PTR: %s.\n",
c7ef5ec9 2226 map_name, btf_kind_str(t));
abd29c93
AN
2227 return -EINVAL;
2228 }
c7ef5ec9 2229 sz = btf__resolve_size(btf, t->type);
abd29c93 2230 if (sz < 0) {
679152d3 2231 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
c7ef5ec9 2232 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2233 return sz;
2234 }
c7ef5ec9 2235 if (map_def->key_size && map_def->key_size != sz) {
679152d3 2236 pr_warn("map '%s': conflicting key size %u != %zd.\n",
c7ef5ec9 2237 map_name, map_def->key_size, (ssize_t)sz);
abd29c93
AN
2238 return -EINVAL;
2239 }
c7ef5ec9
AN
2240 map_def->key_size = sz;
2241 map_def->key_type_id = t->type;
2242 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
abd29c93
AN
2243 } else if (strcmp(name, "value_size") == 0) {
2244 __u32 sz;
2245
c7ef5ec9 2246 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2247 return -EINVAL;
c7ef5ec9 2248 if (map_def->value_size && map_def->value_size != sz) {
be18010e 2249 pr_warn("map '%s': conflicting value size %u != %u.\n",
c7ef5ec9 2250 map_name, map_def->value_size, sz);
abd29c93
AN
2251 return -EINVAL;
2252 }
c7ef5ec9
AN
2253 map_def->value_size = sz;
2254 map_def->parts |= MAP_DEF_VALUE_SIZE;
abd29c93
AN
2255 } else if (strcmp(name, "value") == 0) {
2256 __s64 sz;
2257
c7ef5ec9 2258 t = btf__type_by_id(btf, m->type);
abd29c93 2259 if (!t) {
be18010e 2260 pr_warn("map '%s': value type [%d] not found.\n",
c7ef5ec9 2261 map_name, m->type);
abd29c93
AN
2262 return -EINVAL;
2263 }
b03bc685 2264 if (!btf_is_ptr(t)) {
81ba0889 2265 pr_warn("map '%s': value spec is not PTR: %s.\n",
c7ef5ec9 2266 map_name, btf_kind_str(t));
abd29c93
AN
2267 return -EINVAL;
2268 }
c7ef5ec9 2269 sz = btf__resolve_size(btf, t->type);
abd29c93 2270 if (sz < 0) {
679152d3 2271 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
c7ef5ec9 2272 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2273 return sz;
2274 }
c7ef5ec9 2275 if (map_def->value_size && map_def->value_size != sz) {
679152d3 2276 pr_warn("map '%s': conflicting value size %u != %zd.\n",
c7ef5ec9 2277 map_name, map_def->value_size, (ssize_t)sz);
abd29c93
AN
2278 return -EINVAL;
2279 }
c7ef5ec9
AN
2280 map_def->value_size = sz;
2281 map_def->value_type_id = t->type;
2282 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
646f02ff
AN
2283 }
2284 else if (strcmp(name, "values") == 0) {
341ac5ff
HC
2285 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2286 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2287 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
c7ef5ec9 2288 char inner_map_name[128];
646f02ff
AN
2289 int err;
2290
2291 if (is_inner) {
2292 pr_warn("map '%s': multi-level inner maps not supported.\n",
c7ef5ec9 2293 map_name);
646f02ff
AN
2294 return -ENOTSUP;
2295 }
2296 if (i != vlen - 1) {
2297 pr_warn("map '%s': '%s' member should be last.\n",
c7ef5ec9 2298 map_name, name);
646f02ff
AN
2299 return -EINVAL;
2300 }
341ac5ff
HC
2301 if (!is_map_in_map && !is_prog_array) {
2302 pr_warn("map '%s': should be map-in-map or prog-array.\n",
c7ef5ec9 2303 map_name);
646f02ff
AN
2304 return -ENOTSUP;
2305 }
c7ef5ec9 2306 if (map_def->value_size && map_def->value_size != 4) {
646f02ff 2307 pr_warn("map '%s': conflicting value size %u != 4.\n",
c7ef5ec9 2308 map_name, map_def->value_size);
646f02ff
AN
2309 return -EINVAL;
2310 }
c7ef5ec9
AN
2311 map_def->value_size = 4;
2312 t = btf__type_by_id(btf, m->type);
646f02ff 2313 if (!t) {
341ac5ff
HC
2314 pr_warn("map '%s': %s type [%d] not found.\n",
2315 map_name, desc, m->type);
646f02ff
AN
2316 return -EINVAL;
2317 }
2318 if (!btf_is_array(t) || btf_array(t)->nelems) {
341ac5ff
HC
2319 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2320 map_name, desc);
646f02ff
AN
2321 return -EINVAL;
2322 }
c7ef5ec9 2323 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
646f02ff 2324 if (!btf_is_ptr(t)) {
341ac5ff
HC
2325 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2326 map_name, desc, btf_kind_str(t));
646f02ff
AN
2327 return -EINVAL;
2328 }
c7ef5ec9 2329 t = skip_mods_and_typedefs(btf, t->type, NULL);
341ac5ff
HC
2330 if (is_prog_array) {
2331 if (!btf_is_func_proto(t)) {
2332 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2333 map_name, btf_kind_str(t));
2334 return -EINVAL;
2335 }
2336 continue;
2337 }
646f02ff 2338 if (!btf_is_struct(t)) {
81ba0889 2339 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
c7ef5ec9 2340 map_name, btf_kind_str(t));
646f02ff
AN
2341 return -EINVAL;
2342 }
2343
c7ef5ec9
AN
2344 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2345 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
646f02ff
AN
2346 if (err)
2347 return err;
c7ef5ec9
AN
2348
2349 map_def->parts |= MAP_DEF_INNER_MAP;
57a00f41
THJ
2350 } else if (strcmp(name, "pinning") == 0) {
2351 __u32 val;
57a00f41 2352
646f02ff 2353 if (is_inner) {
c7ef5ec9 2354 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
646f02ff
AN
2355 return -EINVAL;
2356 }
c7ef5ec9 2357 if (!get_map_field_int(map_name, btf, m, &val))
57a00f41 2358 return -EINVAL;
c7ef5ec9 2359 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
57a00f41 2360 pr_warn("map '%s': invalid pinning value %u.\n",
c7ef5ec9 2361 map_name, val);
57a00f41
THJ
2362 return -EINVAL;
2363 }
c7ef5ec9
AN
2364 map_def->pinning = val;
2365 map_def->parts |= MAP_DEF_PINNING;
47512102
JK
2366 } else if (strcmp(name, "map_extra") == 0) {
2367 __u32 map_extra;
2368
2369 if (!get_map_field_int(map_name, btf, m, &map_extra))
2370 return -EINVAL;
2371 map_def->map_extra = map_extra;
2372 map_def->parts |= MAP_DEF_MAP_EXTRA;
abd29c93
AN
2373 } else {
2374 if (strict) {
c7ef5ec9 2375 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
abd29c93
AN
2376 return -ENOTSUP;
2377 }
c7ef5ec9 2378 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
abd29c93
AN
2379 }
2380 }
2381
c7ef5ec9
AN
2382 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2383 pr_warn("map '%s': map type isn't specified.\n", map_name);
abd29c93
AN
2384 return -EINVAL;
2385 }
2386
2387 return 0;
2388}
2389
c7ef5ec9
AN
2390static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2391{
2392 map->def.type = def->map_type;
2393 map->def.key_size = def->key_size;
2394 map->def.value_size = def->value_size;
2395 map->def.max_entries = def->max_entries;
2396 map->def.map_flags = def->map_flags;
47512102 2397 map->map_extra = def->map_extra;
c7ef5ec9
AN
2398
2399 map->numa_node = def->numa_node;
2400 map->btf_key_type_id = def->key_type_id;
2401 map->btf_value_type_id = def->value_type_id;
2402
2403 if (def->parts & MAP_DEF_MAP_TYPE)
2404 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2405
2406 if (def->parts & MAP_DEF_KEY_TYPE)
2407 pr_debug("map '%s': found key [%u], sz = %u.\n",
2408 map->name, def->key_type_id, def->key_size);
2409 else if (def->parts & MAP_DEF_KEY_SIZE)
2410 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2411
2412 if (def->parts & MAP_DEF_VALUE_TYPE)
2413 pr_debug("map '%s': found value [%u], sz = %u.\n",
2414 map->name, def->value_type_id, def->value_size);
2415 else if (def->parts & MAP_DEF_VALUE_SIZE)
2416 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2417
2418 if (def->parts & MAP_DEF_MAX_ENTRIES)
2419 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2420 if (def->parts & MAP_DEF_MAP_FLAGS)
47512102
JK
2421 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2422 if (def->parts & MAP_DEF_MAP_EXTRA)
2423 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2424 (unsigned long long)def->map_extra);
c7ef5ec9
AN
2425 if (def->parts & MAP_DEF_PINNING)
2426 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2427 if (def->parts & MAP_DEF_NUMA_NODE)
2428 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2429
2430 if (def->parts & MAP_DEF_INNER_MAP)
2431 pr_debug("map '%s': found inner map definition.\n", map->name);
2432}
2433
c1cccec9
AN
2434static const char *btf_var_linkage_str(__u32 linkage)
2435{
2436 switch (linkage) {
2437 case BTF_VAR_STATIC: return "static";
2438 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2439 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2440 default: return "unknown";
2441 }
2442}
2443
41017e56
AN
2444static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2445 const struct btf_type *sec,
2446 int var_idx, int sec_idx,
2447 const Elf_Data *data, bool strict,
2448 const char *pin_root_path)
2449{
c7ef5ec9 2450 struct btf_map_def map_def = {}, inner_def = {};
41017e56
AN
2451 const struct btf_type *var, *def;
2452 const struct btf_var_secinfo *vi;
2453 const struct btf_var *var_extra;
2454 const char *map_name;
2455 struct bpf_map *map;
c7ef5ec9 2456 int err;
41017e56
AN
2457
2458 vi = btf_var_secinfos(sec) + var_idx;
2459 var = btf__type_by_id(obj->btf, vi->type);
2460 var_extra = btf_var(var);
2461 map_name = btf__name_by_offset(obj->btf, var->name_off);
2462
2463 if (map_name == NULL || map_name[0] == '\0') {
2464 pr_warn("map #%d: empty name.\n", var_idx);
2465 return -EINVAL;
2466 }
2467 if ((__u64)vi->offset + vi->size > data->d_size) {
2468 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2469 return -EINVAL;
2470 }
2471 if (!btf_is_var(var)) {
81ba0889
AN
2472 pr_warn("map '%s': unexpected var kind %s.\n",
2473 map_name, btf_kind_str(var));
41017e56
AN
2474 return -EINVAL;
2475 }
c1cccec9
AN
2476 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2477 pr_warn("map '%s': unsupported map linkage %s.\n",
2478 map_name, btf_var_linkage_str(var_extra->linkage));
41017e56
AN
2479 return -EOPNOTSUPP;
2480 }
2481
2482 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2483 if (!btf_is_struct(def)) {
81ba0889
AN
2484 pr_warn("map '%s': unexpected def kind %s.\n",
2485 map_name, btf_kind_str(var));
41017e56
AN
2486 return -EINVAL;
2487 }
2488 if (def->size > vi->size) {
2489 pr_warn("map '%s': invalid def size.\n", map_name);
2490 return -EINVAL;
2491 }
2492
2493 map = bpf_object__add_map(obj);
2494 if (IS_ERR(map))
2495 return PTR_ERR(map);
2496 map->name = strdup(map_name);
2497 if (!map->name) {
2498 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2499 return -ENOMEM;
2500 }
2501 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2502 map->def.type = BPF_MAP_TYPE_UNSPEC;
2503 map->sec_idx = sec_idx;
2504 map->sec_offset = vi->offset;
646f02ff 2505 map->btf_var_idx = var_idx;
41017e56
AN
2506 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2507 map_name, map->sec_idx, map->sec_offset);
2508
c7ef5ec9
AN
2509 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2510 if (err)
2511 return err;
2512
2513 fill_map_from_def(map, &map_def);
2514
2515 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2516 err = build_map_pin_path(map, pin_root_path);
2517 if (err) {
2518 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2519 return err;
2520 }
2521 }
2522
2523 if (map_def.parts & MAP_DEF_INNER_MAP) {
2524 map->inner_map = calloc(1, sizeof(*map->inner_map));
2525 if (!map->inner_map)
2526 return -ENOMEM;
2527 map->inner_map->fd = -1;
2528 map->inner_map->sec_idx = sec_idx;
2529 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2530 if (!map->inner_map->name)
2531 return -ENOMEM;
2532 sprintf(map->inner_map->name, "%s.inner", map_name);
2533
2534 fill_map_from_def(map->inner_map, &inner_def);
2535 }
2536
2537 return 0;
41017e56
AN
2538}
2539
57a00f41
THJ
2540static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2541 const char *pin_root_path)
abd29c93
AN
2542{
2543 const struct btf_type *sec = NULL;
2544 int nr_types, i, vlen, err;
2545 const struct btf_type *t;
2546 const char *name;
2547 Elf_Data *data;
2548 Elf_Scn *scn;
2549
2550 if (obj->efile.btf_maps_shndx < 0)
2551 return 0;
2552
88a82120
AN
2553 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2554 data = elf_sec_data(obj, scn);
abd29c93 2555 if (!scn || !data) {
88a82120
AN
2556 pr_warn("elf: failed to get %s map definitions for %s\n",
2557 MAPS_ELF_SEC, obj->path);
abd29c93
AN
2558 return -EINVAL;
2559 }
2560
6a886de0
HC
2561 nr_types = btf__type_cnt(obj->btf);
2562 for (i = 1; i < nr_types; i++) {
abd29c93 2563 t = btf__type_by_id(obj->btf, i);
b03bc685 2564 if (!btf_is_datasec(t))
abd29c93
AN
2565 continue;
2566 name = btf__name_by_offset(obj->btf, t->name_off);
2567 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2568 sec = t;
646f02ff 2569 obj->efile.btf_maps_sec_btf_id = i;
abd29c93
AN
2570 break;
2571 }
2572 }
2573
2574 if (!sec) {
be18010e 2575 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
abd29c93
AN
2576 return -ENOENT;
2577 }
2578
b03bc685 2579 vlen = btf_vlen(sec);
abd29c93
AN
2580 for (i = 0; i < vlen; i++) {
2581 err = bpf_object__init_user_btf_map(obj, sec, i,
2582 obj->efile.btf_maps_shndx,
8983b731
AN
2583 data, strict,
2584 pin_root_path);
abd29c93
AN
2585 if (err)
2586 return err;
2587 }
2588
2589 return 0;
2590}
2591
0d13bfce 2592static int bpf_object__init_maps(struct bpf_object *obj,
01af3bf0 2593 const struct bpf_object_open_opts *opts)
bf829271 2594{
166750bc
AN
2595 const char *pin_root_path;
2596 bool strict;
bf829271 2597 int err;
8837fe5d 2598
166750bc
AN
2599 strict = !OPTS_GET(opts, relaxed_maps, false);
2600 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
bf829271 2601
166750bc
AN
2602 err = bpf_object__init_user_maps(obj, strict);
2603 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2604 err = err ?: bpf_object__init_global_data_maps(obj);
81bfdd08 2605 err = err ?: bpf_object__init_kconfig_map(obj);
590a0088 2606 err = err ?: bpf_object__init_struct_ops_maps(obj);
bf829271 2607
3b3af91c 2608 return err;
561bbcca
WN
2609}
2610
e3d91b0c
JDB
2611static bool section_have_execinstr(struct bpf_object *obj, int idx)
2612{
ad23b723 2613 Elf64_Shdr *sh;
e3d91b0c 2614
ad23b723
AN
2615 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2616 if (!sh)
e3d91b0c
JDB
2617 return false;
2618
ad23b723 2619 return sh->sh_flags & SHF_EXECINSTR;
e3d91b0c
JDB
2620}
2621
0f0e55d8
AN
2622static bool btf_needs_sanitization(struct bpf_object *obj)
2623{
9ca1f56a
AS
2624 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2625 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2626 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2627 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2628 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2629 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
0f0e55d8 2630
2dc1e488
YS
2631 return !has_func || !has_datasec || !has_func_global || !has_float ||
2632 !has_decl_tag || !has_type_tag;
0f0e55d8
AN
2633}
2634
2635static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
d7c4b398 2636{
9ca1f56a
AS
2637 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2638 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2639 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2640 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2641 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2642 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
d7c4b398
AN
2643 struct btf_type *t;
2644 int i, j, vlen;
d7c4b398 2645
6a886de0 2646 for (i = 1; i < btf__type_cnt(btf); i++) {
d7c4b398 2647 t = (struct btf_type *)btf__type_by_id(btf, i);
d7c4b398 2648
223f903e
YS
2649 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2650 /* replace VAR/DECL_TAG with INT */
d7c4b398 2651 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1d4126c4
AN
2652 /*
2653 * using size = 1 is the safest choice, 4 will be too
2654 * big and cause kernel BTF validation failure if
2655 * original variable took less than 4 bytes
2656 */
2657 t->size = 1;
708852dc 2658 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
b03bc685 2659 } else if (!has_datasec && btf_is_datasec(t)) {
d7c4b398 2660 /* replace DATASEC with STRUCT */
b03bc685
AN
2661 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2662 struct btf_member *m = btf_members(t);
d7c4b398
AN
2663 struct btf_type *vt;
2664 char *name;
2665
2666 name = (char *)btf__name_by_offset(btf, t->name_off);
2667 while (*name) {
2668 if (*name == '.')
2669 *name = '_';
2670 name++;
2671 }
2672
b03bc685 2673 vlen = btf_vlen(t);
d7c4b398
AN
2674 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2675 for (j = 0; j < vlen; j++, v++, m++) {
2676 /* order of field assignments is important */
2677 m->offset = v->offset * 8;
2678 m->type = v->type;
2679 /* preserve variable name as member name */
2680 vt = (void *)btf__type_by_id(btf, v->type);
2681 m->name_off = vt->name_off;
2682 }
b03bc685 2683 } else if (!has_func && btf_is_func_proto(t)) {
d7c4b398 2684 /* replace FUNC_PROTO with ENUM */
b03bc685 2685 vlen = btf_vlen(t);
d7c4b398
AN
2686 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2687 t->size = sizeof(__u32); /* kernel enforced */
b03bc685 2688 } else if (!has_func && btf_is_func(t)) {
d7c4b398
AN
2689 /* replace FUNC with TYPEDEF */
2690 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2d3eb67f
AS
2691 } else if (!has_func_global && btf_is_func(t)) {
2692 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2693 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
22541a9e
IL
2694 } else if (!has_float && btf_is_float(t)) {
2695 /* replace FLOAT with an equally-sized empty STRUCT;
2696 * since C compilers do not accept e.g. "float" as a
2697 * valid struct name, make it anonymous
2698 */
2699 t->name_off = 0;
2700 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2dc1e488
YS
2701 } else if (!has_type_tag && btf_is_type_tag(t)) {
2702 /* replace TYPE_TAG with a CONST */
2703 t->name_off = 0;
2704 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
d7c4b398
AN
2705 }
2706 }
2707}
2708
b35f14f4 2709static bool libbpf_needs_btf(const struct bpf_object *obj)
abd29c93 2710{
b35f14f4
AN
2711 return obj->efile.btf_maps_shndx >= 0 ||
2712 obj->efile.st_ops_shndx >= 0 ||
2713 obj->nr_extern > 0;
2714}
2715
2716static bool kernel_needs_btf(const struct bpf_object *obj)
2717{
2718 return obj->efile.st_ops_shndx >= 0;
abd29c93
AN
2719}
2720
063183bf 2721static int bpf_object__init_btf(struct bpf_object *obj,
9c6660d0
AN
2722 Elf_Data *btf_data,
2723 Elf_Data *btf_ext_data)
2724{
b7d7f3e1 2725 int err = -ENOENT;
9c6660d0
AN
2726
2727 if (btf_data) {
2728 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
e9fc3ce9
AN
2729 err = libbpf_get_error(obj->btf);
2730 if (err) {
b7d7f3e1 2731 obj->btf = NULL;
e9fc3ce9 2732 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
9c6660d0
AN
2733 goto out;
2734 }
4c01925f
AN
2735 /* enforce 8-byte pointers for BPF-targeted BTFs */
2736 btf__set_pointer_size(obj->btf, 8);
9c6660d0
AN
2737 }
2738 if (btf_ext_data) {
2739 if (!obj->btf) {
2740 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2741 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2742 goto out;
2743 }
e9fc3ce9
AN
2744 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2745 err = libbpf_get_error(obj->btf_ext);
2746 if (err) {
2747 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2748 BTF_EXT_ELF_SEC, err);
9c6660d0
AN
2749 obj->btf_ext = NULL;
2750 goto out;
2751 }
9c6660d0
AN
2752 }
2753out:
b35f14f4 2754 if (err && libbpf_needs_btf(obj)) {
be18010e 2755 pr_warn("BTF is required, but is missing or corrupted.\n");
b7d7f3e1 2756 return err;
abd29c93 2757 }
9c6660d0
AN
2758 return 0;
2759}
2760
b96c07f3
AN
2761static int compare_vsi_off(const void *_a, const void *_b)
2762{
2763 const struct btf_var_secinfo *a = _a;
2764 const struct btf_var_secinfo *b = _b;
2765
2766 return a->offset - b->offset;
2767}
2768
2769static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2770 struct btf_type *t)
2771{
2772 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2773 const char *name = btf__name_by_offset(btf, t->name_off);
2774 const struct btf_type *t_var;
2775 struct btf_var_secinfo *vsi;
2776 const struct btf_var *var;
2777 int ret;
2778
2779 if (!name) {
2780 pr_debug("No name found in string section for DATASEC kind.\n");
2781 return -ENOENT;
2782 }
2783
2784 /* .extern datasec size and var offsets were set correctly during
2785 * extern collection step, so just skip straight to sorting variables
2786 */
2787 if (t->size)
2788 goto sort_vars;
2789
2790 ret = find_elf_sec_sz(obj, name, &size);
6966d4c4 2791 if (ret || !size) {
b96c07f3
AN
2792 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2793 return -ENOENT;
2794 }
2795
2796 t->size = size;
2797
2798 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2799 t_var = btf__type_by_id(btf, vsi->type);
88918dc1 2800 if (!t_var || !btf_is_var(t_var)) {
b96c07f3
AN
2801 pr_debug("Non-VAR type seen in section %s\n", name);
2802 return -EINVAL;
2803 }
2804
88918dc1 2805 var = btf_var(t_var);
b96c07f3
AN
2806 if (var->linkage == BTF_VAR_STATIC)
2807 continue;
2808
2809 name = btf__name_by_offset(btf, t_var->name_off);
2810 if (!name) {
2811 pr_debug("No name found in string section for VAR kind\n");
2812 return -ENOENT;
2813 }
2814
2815 ret = find_elf_var_offset(obj, name, &off);
2816 if (ret) {
2817 pr_debug("No offset found in symbol table for VAR %s\n",
2818 name);
2819 return -ENOENT;
2820 }
2821
2822 vsi->offset = off;
2823 }
2824
2825sort_vars:
2826 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2827 return 0;
2828}
2829
2830static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2831{
2832 int err = 0;
6a886de0 2833 __u32 i, n = btf__type_cnt(btf);
b96c07f3 2834
6a886de0 2835 for (i = 1; i < n; i++) {
b96c07f3
AN
2836 struct btf_type *t = btf_type_by_id(btf, i);
2837
2838 /* Loader needs to fix up some of the things compiler
2839 * couldn't get its hands on while emitting BTF. This
2840 * is section size and global variable offset. We use
2841 * the info from the ELF itself for this purpose.
2842 */
2843 if (btf_is_datasec(t)) {
2844 err = btf_fixup_datasec(obj, btf, t);
2845 if (err)
2846 break;
2847 }
2848 }
2849
2850 return libbpf_err(err);
2851}
2852
2853int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2854{
2855 return btf_finalize_data(obj, btf);
2856}
2857
166750bc
AN
2858static int bpf_object__finalize_btf(struct bpf_object *obj)
2859{
2860 int err;
2861
2862 if (!obj->btf)
2863 return 0;
2864
b96c07f3 2865 err = btf_finalize_data(obj, obj->btf);
bfc96656
AN
2866 if (err) {
2867 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2868 return err;
166750bc 2869 }
bfc96656 2870
166750bc
AN
2871 return 0;
2872}
2873
fe62de31 2874static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
a6ed02ca 2875{
1e092a03
KS
2876 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2877 prog->type == BPF_PROG_TYPE_LSM)
a6ed02ca
KS
2878 return true;
2879
2880 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2881 * also need vmlinux BTF
2882 */
2883 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2884 return true;
2885
2886 return false;
2887}
2888
fe62de31 2889static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
a6ed02ca
KS
2890{
2891 struct bpf_program *prog;
fe62de31 2892 int i;
a6ed02ca 2893
1373ff59
SC
2894 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2895 * is not specified
2896 */
2897 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
fe62de31 2898 return true;
192b6638 2899
d370bbe1
HL
2900 /* Support for typed ksyms needs kernel BTF */
2901 for (i = 0; i < obj->nr_extern; i++) {
2902 const struct extern_desc *ext;
2903
2904 ext = &obj->externs[i];
fe62de31
AN
2905 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2906 return true;
d370bbe1
HL
2907 }
2908
a6ed02ca 2909 bpf_object__for_each_program(prog, obj) {
d9297581
AN
2910 if (!prog->load)
2911 continue;
fe62de31
AN
2912 if (prog_needs_vmlinux_btf(prog))
2913 return true;
a6ed02ca
KS
2914 }
2915
fe62de31
AN
2916 return false;
2917}
2918
2919static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2920{
2921 int err;
2922
2923 /* btf_vmlinux could be loaded earlier */
67234743 2924 if (obj->btf_vmlinux || obj->gen_loader)
fe62de31
AN
2925 return 0;
2926
2927 if (!force && !obj_needs_vmlinux_btf(obj))
192b6638
AN
2928 return 0;
2929
a710eed3 2930 obj->btf_vmlinux = btf__load_vmlinux_btf();
e9fc3ce9
AN
2931 err = libbpf_get_error(obj->btf_vmlinux);
2932 if (err) {
192b6638
AN
2933 pr_warn("Error loading vmlinux BTF: %d\n", err);
2934 obj->btf_vmlinux = NULL;
2935 return err;
2936 }
a6ed02ca
KS
2937 return 0;
2938}
2939
063183bf
AN
2940static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2941{
0f0e55d8
AN
2942 struct btf *kern_btf = obj->btf;
2943 bool btf_mandatory, sanitize;
aea28a60 2944 int i, err = 0;
063183bf
AN
2945
2946 if (!obj->btf)
2947 return 0;
2948
9ca1f56a 2949 if (!kernel_supports(obj, FEAT_BTF)) {
68b08647
AN
2950 if (kernel_needs_btf(obj)) {
2951 err = -EOPNOTSUPP;
2952 goto report;
2953 }
2954 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2955 return 0;
2956 }
2957
aea28a60
AN
2958 /* Even though some subprogs are global/weak, user might prefer more
2959 * permissive BPF verification process that BPF verifier performs for
2960 * static functions, taking into account more context from the caller
2961 * functions. In such case, they need to mark such subprogs with
2962 * __attribute__((visibility("hidden"))) and libbpf will adjust
2963 * corresponding FUNC BTF type to be marked as static and trigger more
2964 * involved BPF verification process.
2965 */
2966 for (i = 0; i < obj->nr_programs; i++) {
2967 struct bpf_program *prog = &obj->programs[i];
2968 struct btf_type *t;
2969 const char *name;
2970 int j, n;
2971
2972 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2973 continue;
2974
6a886de0
HC
2975 n = btf__type_cnt(obj->btf);
2976 for (j = 1; j < n; j++) {
aea28a60
AN
2977 t = btf_type_by_id(obj->btf, j);
2978 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2979 continue;
2980
2981 name = btf__str_by_offset(obj->btf, t->name_off);
2982 if (strcmp(name, prog->name) != 0)
2983 continue;
2984
2985 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2986 break;
2987 }
2988 }
2989
0f0e55d8
AN
2990 sanitize = btf_needs_sanitization(obj);
2991 if (sanitize) {
5c3320d7 2992 const void *raw_data;
0f0e55d8 2993 __u32 sz;
063183bf 2994
0f0e55d8 2995 /* clone BTF to sanitize a copy and leave the original intact */
6a886de0 2996 raw_data = btf__raw_data(obj->btf, &sz);
5c3320d7 2997 kern_btf = btf__new(raw_data, sz);
e9fc3ce9
AN
2998 err = libbpf_get_error(kern_btf);
2999 if (err)
3000 return err;
04efe591 3001
4c01925f
AN
3002 /* enforce 8-byte pointers for BPF-targeted BTFs */
3003 btf__set_pointer_size(obj->btf, 8);
0f0e55d8 3004 bpf_object__sanitize_btf(obj, kern_btf);
063183bf 3005 }
0f0e55d8 3006
67234743
AS
3007 if (obj->gen_loader) {
3008 __u32 raw_size = 0;
6a886de0 3009 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
67234743
AS
3010
3011 if (!raw_data)
3012 return -ENOMEM;
3013 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3014 /* Pretend to have valid FD to pass various fd >= 0 checks.
3015 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3016 */
3017 btf__set_fd(kern_btf, 0);
3018 } else {
e0e3ea88
AN
3019 /* currently BPF_BTF_LOAD only supports log_level 1 */
3020 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3021 obj->log_level ? 1 : 0);
67234743 3022 }
0f0e55d8
AN
3023 if (sanitize) {
3024 if (!err) {
3025 /* move fd to libbpf's BTF */
3026 btf__set_fd(obj->btf, btf__fd(kern_btf));
3027 btf__set_fd(kern_btf, -1);
3028 }
3029 btf__free(kern_btf);
3030 }
68b08647 3031report:
0f0e55d8
AN
3032 if (err) {
3033 btf_mandatory = kernel_needs_btf(obj);
3034 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3035 btf_mandatory ? "BTF is mandatory, can't proceed."
3036 : "BTF is optional, ignoring.");
3037 if (!btf_mandatory)
3038 err = 0;
3039 }
3040 return err;
063183bf
AN
3041}
3042
88a82120
AN
3043static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3044{
3045 const char *name;
3046
3047 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3048 if (!name) {
3049 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3050 off, obj->path, elf_errmsg(-1));
3051 return NULL;
3052 }
3053
3054 return name;
3055}
3056
3057static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3058{
3059 const char *name;
3060
3061 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3062 if (!name) {
3063 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3064 off, obj->path, elf_errmsg(-1));
3065 return NULL;
3066 }
3067
3068 return name;
3069}
3070
3071static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3072{
3073 Elf_Scn *scn;
3074
3075 scn = elf_getscn(obj->efile.elf, idx);
3076 if (!scn) {
3077 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3078 idx, obj->path, elf_errmsg(-1));
3079 return NULL;
3080 }
3081 return scn;
3082}
3083
3084static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3085{
3086 Elf_Scn *scn = NULL;
3087 Elf *elf = obj->efile.elf;
3088 const char *sec_name;
3089
3090 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3091 sec_name = elf_sec_name(obj, scn);
3092 if (!sec_name)
3093 return NULL;
3094
3095 if (strcmp(sec_name, name) != 0)
3096 continue;
3097
3098 return scn;
3099 }
3100 return NULL;
3101}
3102
ad23b723 3103static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
88a82120 3104{
ad23b723
AN
3105 Elf64_Shdr *shdr;
3106
88a82120 3107 if (!scn)
ad23b723 3108 return NULL;
88a82120 3109
ad23b723
AN
3110 shdr = elf64_getshdr(scn);
3111 if (!shdr) {
88a82120
AN
3112 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3113 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
ad23b723 3114 return NULL;
88a82120
AN
3115 }
3116
ad23b723 3117 return shdr;
88a82120
AN
3118}
3119
3120static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3121{
3122 const char *name;
ad23b723 3123 Elf64_Shdr *sh;
88a82120
AN
3124
3125 if (!scn)
3126 return NULL;
3127
ad23b723
AN
3128 sh = elf_sec_hdr(obj, scn);
3129 if (!sh)
88a82120
AN
3130 return NULL;
3131
ad23b723 3132 name = elf_sec_str(obj, sh->sh_name);
88a82120
AN
3133 if (!name) {
3134 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3135 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3136 return NULL;
3137 }
3138
3139 return name;
3140}
3141
3142static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3143{
3144 Elf_Data *data;
3145
3146 if (!scn)
3147 return NULL;
3148
3149 data = elf_getdata(scn, 0);
3150 if (!data) {
3151 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3152 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3153 obj->path, elf_errmsg(-1));
3154 return NULL;
3155 }
3156
3157 return data;
3158}
3159
ad23b723
AN
3160static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3161{
3162 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3163 return NULL;
3164
3165 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3166}
3167
3168static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3169{
3170 if (idx >= data->d_size / sizeof(Elf64_Rel))
3171 return NULL;
3172
3173 return (Elf64_Rel *)data->d_buf + idx;
3174}
3175
50e09460
AN
3176static bool is_sec_name_dwarf(const char *name)
3177{
3178 /* approximation, but the actual list is too long */
13d35a0c 3179 return str_has_pfx(name, ".debug_");
50e09460
AN
3180}
3181
ad23b723 3182static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
50e09460
AN
3183{
3184 /* no special handling of .strtab */
3185 if (hdr->sh_type == SHT_STRTAB)
3186 return true;
3187
3188 /* ignore .llvm_addrsig section as well */
faf6ed32 3189 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
50e09460
AN
3190 return true;
3191
3192 /* no subprograms will lead to an empty .text section, ignore it */
3193 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3194 strcmp(name, ".text") == 0)
3195 return true;
3196
3197 /* DWARF sections */
3198 if (is_sec_name_dwarf(name))
3199 return true;
3200
13d35a0c 3201 if (str_has_pfx(name, ".rel")) {
50e09460
AN
3202 name += sizeof(".rel") - 1;
3203 /* DWARF section relocations */
3204 if (is_sec_name_dwarf(name))
3205 return true;
3206
3207 /* .BTF and .BTF.ext don't need relocations */
3208 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3209 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3210 return true;
3211 }
3212
3213 return false;
3214}
3215
db2b8b06
AN
3216static int cmp_progs(const void *_a, const void *_b)
3217{
3218 const struct bpf_program *a = _a;
3219 const struct bpf_program *b = _b;
3220
3221 if (a->sec_idx != b->sec_idx)
3222 return a->sec_idx < b->sec_idx ? -1 : 1;
3223
3224 /* sec_insn_off can't be the same within the section */
3225 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3226}
3227
0d13bfce 3228static int bpf_object__elf_collect(struct bpf_object *obj)
29603665 3229{
25bbbd7a 3230 struct elf_sec_desc *sec_desc;
29603665 3231 Elf *elf = obj->efile.elf;
f0187f0b 3232 Elf_Data *btf_ext_data = NULL;
1713d68b 3233 Elf_Data *btf_data = NULL;
666810e8 3234 int idx = 0, err = 0;
0201c575
AN
3235 const char *name;
3236 Elf_Data *data;
3237 Elf_Scn *scn;
ad23b723 3238 Elf64_Shdr *sh;
29603665 3239
0d6988e1
AN
3240 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3241 * section. e_shnum does include sec #0, so e_shnum is the necessary
3242 * size of an array to keep all the sections.
25bbbd7a 3243 */
0d6988e1 3244 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
25bbbd7a
AN
3245 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3246 if (!obj->efile.secs)
3247 return -ENOMEM;
29603665 3248
0201c575
AN
3249 /* a bunch of ELF parsing functionality depends on processing symbols,
3250 * so do the first pass and find the symbol table
3251 */
3252 scn = NULL;
29603665 3253 while ((scn = elf_nextscn(elf, scn)) != NULL) {
ad23b723
AN
3254 sh = elf_sec_hdr(obj, scn);
3255 if (!sh)
0201c575
AN
3256 return -LIBBPF_ERRNO__FORMAT;
3257
ad23b723 3258 if (sh->sh_type == SHT_SYMTAB) {
0201c575
AN
3259 if (obj->efile.symbols) {
3260 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3261 return -LIBBPF_ERRNO__FORMAT;
3262 }
29603665 3263
0201c575
AN
3264 data = elf_sec_data(obj, scn);
3265 if (!data)
3266 return -LIBBPF_ERRNO__FORMAT;
3267
25bbbd7a
AN
3268 idx = elf_ndxscn(scn);
3269
0201c575 3270 obj->efile.symbols = data;
25bbbd7a 3271 obj->efile.symbols_shndx = idx;
ad23b723 3272 obj->efile.strtabidx = sh->sh_link;
0201c575
AN
3273 }
3274 }
3275
03e601f4
THJ
3276 if (!obj->efile.symbols) {
3277 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3278 obj->path);
3279 return -ENOENT;
3280 }
3281
0201c575
AN
3282 scn = NULL;
3283 while ((scn = elf_nextscn(elf, scn)) != NULL) {
25bbbd7a
AN
3284 idx = elf_ndxscn(scn);
3285 sec_desc = &obj->efile.secs[idx];
88a82120 3286
ad23b723
AN
3287 sh = elf_sec_hdr(obj, scn);
3288 if (!sh)
01b29d1d 3289 return -LIBBPF_ERRNO__FORMAT;
29603665 3290
ad23b723 3291 name = elf_sec_str(obj, sh->sh_name);
88a82120 3292 if (!name)
01b29d1d 3293 return -LIBBPF_ERRNO__FORMAT;
29603665 3294
ad23b723 3295 if (ignore_elf_section(sh, name))
50e09460
AN
3296 continue;
3297
88a82120
AN
3298 data = elf_sec_data(obj, scn);
3299 if (!data)
01b29d1d 3300 return -LIBBPF_ERRNO__FORMAT;
88a82120
AN
3301
3302 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
077c066a 3303 idx, name, (unsigned long)data->d_size,
ad23b723
AN
3304 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3305 (int)sh->sh_type);
cb1e5e96 3306
1713d68b 3307 if (strcmp(name, "license") == 0) {
88a82120 3308 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
01b29d1d
AN
3309 if (err)
3310 return err;
1713d68b 3311 } else if (strcmp(name, "version") == 0) {
88a82120 3312 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
54b8625c
JF
3313 if (err)
3314 return err;
1713d68b 3315 } else if (strcmp(name, "maps") == 0) {
666810e8 3316 obj->efile.maps_shndx = idx;
abd29c93
AN
3317 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3318 obj->efile.btf_maps_shndx = idx;
1713d68b 3319 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
62554d52
AN
3320 if (sh->sh_type != SHT_PROGBITS)
3321 return -LIBBPF_ERRNO__FORMAT;
1713d68b 3322 btf_data = data;
2993e051 3323 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
62554d52
AN
3324 if (sh->sh_type != SHT_PROGBITS)
3325 return -LIBBPF_ERRNO__FORMAT;
f0187f0b 3326 btf_ext_data = data;
ad23b723 3327 } else if (sh->sh_type == SHT_SYMTAB) {
0201c575 3328 /* already processed during the first pass above */
ad23b723
AN
3329 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3330 if (sh->sh_flags & SHF_EXECINSTR) {
f8c7a4d4
JS
3331 if (strcmp(name, ".text") == 0)
3332 obj->efile.text_shndx = idx;
c1122392 3333 err = bpf_object__add_programs(obj, data, name, idx);
88a82120 3334 if (err)
01b29d1d 3335 return err;
aed65917
AN
3336 } else if (strcmp(name, DATA_SEC) == 0 ||
3337 str_has_pfx(name, DATA_SEC ".")) {
25bbbd7a
AN
3338 sec_desc->sec_type = SEC_DATA;
3339 sec_desc->shdr = sh;
3340 sec_desc->data = data;
aed65917
AN
3341 } else if (strcmp(name, RODATA_SEC) == 0 ||
3342 str_has_pfx(name, RODATA_SEC ".")) {
25bbbd7a
AN
3343 sec_desc->sec_type = SEC_RODATA;
3344 sec_desc->shdr = sh;
3345 sec_desc->data = data;
590a0088
MKL
3346 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3347 obj->efile.st_ops_data = data;
3348 obj->efile.st_ops_shndx = idx;
d859900c 3349 } else {
50e09460
AN
3350 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3351 idx, name);
a5b8bd47 3352 }
ad23b723 3353 } else if (sh->sh_type == SHT_REL) {
25bbbd7a 3354 int targ_sec_idx = sh->sh_info; /* points to other section */
e3d91b0c 3355
b7332d28
AN
3356 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3357 targ_sec_idx >= obj->efile.sec_cnt)
3358 return -LIBBPF_ERRNO__FORMAT;
3359
e3d91b0c 3360 /* Only do relo for section with exec instructions */
25bbbd7a 3361 if (!section_have_execinstr(obj, targ_sec_idx) &&
646f02ff
AN
3362 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3363 strcmp(name, ".rel" MAPS_ELF_SEC)) {
50e09460 3364 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
25bbbd7a
AN
3365 idx, name, targ_sec_idx,
3366 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
e3d91b0c
JDB
3367 continue;
3368 }
b62f06e8 3369
25bbbd7a
AN
3370 sec_desc->sec_type = SEC_RELO;
3371 sec_desc->shdr = sh;
3372 sec_desc->data = data;
ad23b723 3373 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
25bbbd7a
AN
3374 sec_desc->sec_type = SEC_BSS;
3375 sec_desc->shdr = sh;
3376 sec_desc->data = data;
077c066a 3377 } else {
2e80be60 3378 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
ad23b723 3379 (size_t)sh->sh_size);
bec7d68c 3380 }
29603665 3381 }
561bbcca 3382
d3a3aa0c 3383 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
88a82120 3384 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
f102154d 3385 return -LIBBPF_ERRNO__FORMAT;
77ba9a5b 3386 }
db2b8b06
AN
3387
3388 /* sort BPF programs by section name and in-section instruction offset
3389 * for faster search */
2a6a9bf2
AN
3390 if (obj->nr_programs)
3391 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
db2b8b06 3392
0d13bfce 3393 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
29603665
WN
3394}
3395
ad23b723 3396static bool sym_is_extern(const Elf64_Sym *sym)
166750bc 3397{
ad23b723 3398 int bind = ELF64_ST_BIND(sym->st_info);
166750bc
AN
3399 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3400 return sym->st_shndx == SHN_UNDEF &&
3401 (bind == STB_GLOBAL || bind == STB_WEAK) &&
ad23b723 3402 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
166750bc
AN
3403}
3404
ad23b723 3405static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
53eddb5e 3406{
ad23b723
AN
3407 int bind = ELF64_ST_BIND(sym->st_info);
3408 int type = ELF64_ST_TYPE(sym->st_info);
53eddb5e
YS
3409
3410 /* in .text section */
3411 if (sym->st_shndx != text_shndx)
3412 return false;
3413
3414 /* local function */
3415 if (bind == STB_LOCAL && type == STT_SECTION)
3416 return true;
3417
3418 /* global function */
3419 return bind == STB_GLOBAL && type == STT_FUNC;
3420}
3421
166750bc
AN
3422static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3423{
3424 const struct btf_type *t;
5bd022ec 3425 const char *tname;
166750bc
AN
3426 int i, n;
3427
3428 if (!btf)
3429 return -ESRCH;
3430
6a886de0
HC
3431 n = btf__type_cnt(btf);
3432 for (i = 1; i < n; i++) {
166750bc
AN
3433 t = btf__type_by_id(btf, i);
3434
5bd022ec 3435 if (!btf_is_var(t) && !btf_is_func(t))
166750bc
AN
3436 continue;
3437
5bd022ec
MKL
3438 tname = btf__name_by_offset(btf, t->name_off);
3439 if (strcmp(tname, ext_name))
166750bc
AN
3440 continue;
3441
5bd022ec
MKL
3442 if (btf_is_var(t) &&
3443 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3444 return -EINVAL;
3445
3446 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
166750bc
AN
3447 return -EINVAL;
3448
3449 return i;
3450 }
3451
3452 return -ENOENT;
3453}
3454
2e33efe3
AN
3455static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3456 const struct btf_var_secinfo *vs;
3457 const struct btf_type *t;
3458 int i, j, n;
3459
3460 if (!btf)
3461 return -ESRCH;
3462
6a886de0
HC
3463 n = btf__type_cnt(btf);
3464 for (i = 1; i < n; i++) {
2e33efe3
AN
3465 t = btf__type_by_id(btf, i);
3466
3467 if (!btf_is_datasec(t))
3468 continue;
3469
3470 vs = btf_var_secinfos(t);
3471 for (j = 0; j < btf_vlen(t); j++, vs++) {
3472 if (vs->type == ext_btf_id)
3473 return i;
3474 }
3475 }
3476
3477 return -ENOENT;
3478}
3479
3480static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3481 bool *is_signed)
166750bc
AN
3482{
3483 const struct btf_type *t;
3484 const char *name;
3485
3486 t = skip_mods_and_typedefs(btf, id, NULL);
3487 name = btf__name_by_offset(btf, t->name_off);
3488
3489 if (is_signed)
3490 *is_signed = false;
3491 switch (btf_kind(t)) {
3492 case BTF_KIND_INT: {
3493 int enc = btf_int_encoding(t);
3494
3495 if (enc & BTF_INT_BOOL)
2e33efe3 3496 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
166750bc
AN
3497 if (is_signed)
3498 *is_signed = enc & BTF_INT_SIGNED;
3499 if (t->size == 1)
2e33efe3 3500 return KCFG_CHAR;
166750bc 3501 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2e33efe3
AN
3502 return KCFG_UNKNOWN;
3503 return KCFG_INT;
166750bc
AN
3504 }
3505 case BTF_KIND_ENUM:
3506 if (t->size != 4)
2e33efe3 3507 return KCFG_UNKNOWN;
166750bc 3508 if (strcmp(name, "libbpf_tristate"))
2e33efe3
AN
3509 return KCFG_UNKNOWN;
3510 return KCFG_TRISTATE;
166750bc
AN
3511 case BTF_KIND_ARRAY:
3512 if (btf_array(t)->nelems == 0)
2e33efe3
AN
3513 return KCFG_UNKNOWN;
3514 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3515 return KCFG_UNKNOWN;
3516 return KCFG_CHAR_ARR;
166750bc 3517 default:
2e33efe3 3518 return KCFG_UNKNOWN;
166750bc
AN
3519 }
3520}
3521
3522static int cmp_externs(const void *_a, const void *_b)
3523{
3524 const struct extern_desc *a = _a;
3525 const struct extern_desc *b = _b;
3526
2e33efe3
AN
3527 if (a->type != b->type)
3528 return a->type < b->type ? -1 : 1;
3529
3530 if (a->type == EXT_KCFG) {
3531 /* descending order by alignment requirements */
3532 if (a->kcfg.align != b->kcfg.align)
3533 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3534 /* ascending order by size, within same alignment class */
3535 if (a->kcfg.sz != b->kcfg.sz)
3536 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3537 }
3538
166750bc
AN
3539 /* resolve ties by name */
3540 return strcmp(a->name, b->name);
3541}
3542
1c0c7074
AN
3543static int find_int_btf_id(const struct btf *btf)
3544{
3545 const struct btf_type *t;
3546 int i, n;
3547
6a886de0
HC
3548 n = btf__type_cnt(btf);
3549 for (i = 1; i < n; i++) {
1c0c7074
AN
3550 t = btf__type_by_id(btf, i);
3551
3552 if (btf_is_int(t) && btf_int_bits(t) == 32)
3553 return i;
3554 }
3555
3556 return 0;
3557}
3558
5bd022ec
MKL
3559static int add_dummy_ksym_var(struct btf *btf)
3560{
3561 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3562 const struct btf_var_secinfo *vs;
3563 const struct btf_type *sec;
3564
9683e577
IR
3565 if (!btf)
3566 return 0;
3567
5bd022ec
MKL
3568 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3569 BTF_KIND_DATASEC);
3570 if (sec_btf_id < 0)
3571 return 0;
3572
3573 sec = btf__type_by_id(btf, sec_btf_id);
3574 vs = btf_var_secinfos(sec);
3575 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3576 const struct btf_type *vt;
3577
3578 vt = btf__type_by_id(btf, vs->type);
3579 if (btf_is_func(vt))
3580 break;
3581 }
3582
3583 /* No func in ksyms sec. No need to add dummy var. */
3584 if (i == btf_vlen(sec))
3585 return 0;
3586
3587 int_btf_id = find_int_btf_id(btf);
3588 dummy_var_btf_id = btf__add_var(btf,
3589 "dummy_ksym",
3590 BTF_VAR_GLOBAL_ALLOCATED,
3591 int_btf_id);
3592 if (dummy_var_btf_id < 0)
3593 pr_warn("cannot create a dummy_ksym var\n");
3594
3595 return dummy_var_btf_id;
3596}
3597
166750bc
AN
3598static int bpf_object__collect_externs(struct bpf_object *obj)
3599{
1c0c7074 3600 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
166750bc
AN
3601 const struct btf_type *t;
3602 struct extern_desc *ext;
5bd022ec 3603 int i, n, off, dummy_var_btf_id;
2e33efe3 3604 const char *ext_name, *sec_name;
166750bc 3605 Elf_Scn *scn;
ad23b723 3606 Elf64_Shdr *sh;
166750bc
AN
3607
3608 if (!obj->efile.symbols)
3609 return 0;
3610
88a82120 3611 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
ad23b723 3612 sh = elf_sec_hdr(obj, scn);
83390787 3613 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
166750bc 3614 return -LIBBPF_ERRNO__FORMAT;
166750bc 3615
5bd022ec
MKL
3616 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3617 if (dummy_var_btf_id < 0)
3618 return dummy_var_btf_id;
3619
ad23b723 3620 n = sh->sh_size / sh->sh_entsize;
166750bc 3621 pr_debug("looking for externs among %d symbols...\n", n);
88a82120 3622
166750bc 3623 for (i = 0; i < n; i++) {
ad23b723 3624 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
166750bc 3625
ad23b723 3626 if (!sym)
166750bc 3627 return -LIBBPF_ERRNO__FORMAT;
ad23b723 3628 if (!sym_is_extern(sym))
166750bc 3629 continue;
ad23b723 3630 ext_name = elf_sym_str(obj, sym->st_name);
166750bc
AN
3631 if (!ext_name || !ext_name[0])
3632 continue;
3633
3634 ext = obj->externs;
029258d7 3635 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
166750bc
AN
3636 if (!ext)
3637 return -ENOMEM;
3638 obj->externs = ext;
3639 ext = &ext[obj->nr_extern];
3640 memset(ext, 0, sizeof(*ext));
3641 obj->nr_extern++;
3642
3643 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3644 if (ext->btf_id <= 0) {
3645 pr_warn("failed to find BTF for extern '%s': %d\n",
3646 ext_name, ext->btf_id);
3647 return ext->btf_id;
3648 }
3649 t = btf__type_by_id(obj->btf, ext->btf_id);
3650 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3651 ext->sym_idx = i;
ad23b723 3652 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
2e33efe3
AN
3653
3654 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3655 if (ext->sec_btf_id <= 0) {
3656 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3657 ext_name, ext->btf_id, ext->sec_btf_id);
3658 return ext->sec_btf_id;
166750bc 3659 }
2e33efe3
AN
3660 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3661 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3662
3663 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
5bd022ec
MKL
3664 if (btf_is_func(t)) {
3665 pr_warn("extern function %s is unsupported under %s section\n",
3666 ext->name, KCONFIG_SEC);
3667 return -ENOTSUP;
3668 }
2e33efe3
AN
3669 kcfg_sec = sec;
3670 ext->type = EXT_KCFG;
3671 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3672 if (ext->kcfg.sz <= 0) {
3673 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3674 ext_name, ext->kcfg.sz);
3675 return ext->kcfg.sz;
3676 }
3677 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3678 if (ext->kcfg.align <= 0) {
3679 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3680 ext_name, ext->kcfg.align);
3681 return -EINVAL;
3682 }
3683 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3684 &ext->kcfg.is_signed);
3685 if (ext->kcfg.type == KCFG_UNKNOWN) {
3686 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3687 return -ENOTSUP;
3688 }
1c0c7074 3689 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
1c0c7074
AN
3690 ksym_sec = sec;
3691 ext->type = EXT_KSYM;
d370bbe1
HL
3692 skip_mods_and_typedefs(obj->btf, t->type,
3693 &ext->ksym.type_id);
2e33efe3
AN
3694 } else {
3695 pr_warn("unrecognized extern section '%s'\n", sec_name);
166750bc
AN
3696 return -ENOTSUP;
3697 }
3698 }
3699 pr_debug("collected %d externs total\n", obj->nr_extern);
3700
3701 if (!obj->nr_extern)
3702 return 0;
3703
2e33efe3 3704 /* sort externs by type, for kcfg ones also by (align, size, name) */
166750bc 3705 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
166750bc 3706
1c0c7074
AN
3707 /* for .ksyms section, we need to turn all externs into allocated
3708 * variables in BTF to pass kernel verification; we do this by
3709 * pretending that each extern is a 8-byte variable
3710 */
3711 if (ksym_sec) {
3712 /* find existing 4-byte integer type in BTF to use for fake
3713 * extern variables in DATASEC
3714 */
3715 int int_btf_id = find_int_btf_id(obj->btf);
5bd022ec
MKL
3716 /* For extern function, a dummy_var added earlier
3717 * will be used to replace the vs->type and
3718 * its name string will be used to refill
3719 * the missing param's name.
3720 */
3721 const struct btf_type *dummy_var;
1c0c7074 3722
5bd022ec 3723 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
1c0c7074
AN
3724 for (i = 0; i < obj->nr_extern; i++) {
3725 ext = &obj->externs[i];
3726 if (ext->type != EXT_KSYM)
3727 continue;
3728 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3729 i, ext->sym_idx, ext->name);
3730 }
3731
3732 sec = ksym_sec;
3733 n = btf_vlen(sec);
3734 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3735 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3736 struct btf_type *vt;
3737
3738 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3739 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3740 ext = find_extern_by_name(obj, ext_name);
3741 if (!ext) {
5bd022ec
MKL
3742 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3743 btf_kind_str(vt), ext_name);
1c0c7074
AN
3744 return -ESRCH;
3745 }
5bd022ec
MKL
3746 if (btf_is_func(vt)) {
3747 const struct btf_type *func_proto;
3748 struct btf_param *param;
3749 int j;
3750
3751 func_proto = btf__type_by_id(obj->btf,
3752 vt->type);
3753 param = btf_params(func_proto);
3754 /* Reuse the dummy_var string if the
3755 * func proto does not have param name.
3756 */
3757 for (j = 0; j < btf_vlen(func_proto); j++)
3758 if (param[j].type && !param[j].name_off)
3759 param[j].name_off =
3760 dummy_var->name_off;
3761 vs->type = dummy_var_btf_id;
3762 vt->info &= ~0xffff;
3763 vt->info |= BTF_FUNC_GLOBAL;
3764 } else {
3765 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3766 vt->type = int_btf_id;
3767 }
1c0c7074
AN
3768 vs->offset = off;
3769 vs->size = sizeof(int);
3770 }
3771 sec->size = off;
3772 }
3773
2e33efe3
AN
3774 if (kcfg_sec) {
3775 sec = kcfg_sec;
3776 /* for kcfg externs calculate their offsets within a .kconfig map */
3777 off = 0;
3778 for (i = 0; i < obj->nr_extern; i++) {
3779 ext = &obj->externs[i];
3780 if (ext->type != EXT_KCFG)
3781 continue;
166750bc 3782
2e33efe3
AN
3783 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3784 off = ext->kcfg.data_off + ext->kcfg.sz;
1c0c7074 3785 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
2e33efe3
AN
3786 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3787 }
3788 sec->size = off;
3789 n = btf_vlen(sec);
3790 for (i = 0; i < n; i++) {
3791 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3792
3793 t = btf__type_by_id(obj->btf, vs->type);
3794 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3795 ext = find_extern_by_name(obj, ext_name);
3796 if (!ext) {
3797 pr_warn("failed to find extern definition for BTF var '%s'\n",
3798 ext_name);
3799 return -ESRCH;
3800 }
3801 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3802 vs->offset = ext->kcfg.data_off;
166750bc 3803 }
166750bc 3804 }
166750bc
AN
3805 return 0;
3806}
3807
6d4b198b 3808struct bpf_program *
a324aae3
AN
3809bpf_object__find_program_by_title(const struct bpf_object *obj,
3810 const char *title)
6d4b198b
JK
3811{
3812 struct bpf_program *pos;
3813
3814 bpf_object__for_each_program(pos, obj) {
52109584 3815 if (pos->sec_name && !strcmp(pos->sec_name, title))
6d4b198b
JK
3816 return pos;
3817 }
e9fc3ce9 3818 return errno = ENOENT, NULL;
6d4b198b
JK
3819}
3820
c3c55696
AN
3821static bool prog_is_subprog(const struct bpf_object *obj,
3822 const struct bpf_program *prog)
3823{
197afc63
AN
3824 /* For legacy reasons, libbpf supports an entry-point BPF programs
3825 * without SEC() attribute, i.e., those in the .text section. But if
3826 * there are 2 or more such programs in the .text section, they all
3827 * must be subprograms called from entry-point BPF programs in
3828 * designated SEC()'tions, otherwise there is no way to distinguish
3829 * which of those programs should be loaded vs which are a subprogram.
3830 * Similarly, if there is a function/program in .text and at least one
3831 * other BPF program with custom SEC() attribute, then we just assume
3832 * .text programs are subprograms (even if they are not called from
3833 * other programs), because libbpf never explicitly supported mixing
3834 * SEC()-designated BPF programs and .text entry-point BPF programs.
3835 */
3836 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
c3c55696
AN
3837}
3838
01af3bf0
AN
3839struct bpf_program *
3840bpf_object__find_program_by_name(const struct bpf_object *obj,
3841 const char *name)
3842{
3843 struct bpf_program *prog;
3844
3845 bpf_object__for_each_program(prog, obj) {
c3c55696
AN
3846 if (prog_is_subprog(obj, prog))
3847 continue;
01af3bf0
AN
3848 if (!strcmp(prog->name, name))
3849 return prog;
3850 }
e9fc3ce9 3851 return errno = ENOENT, NULL;
01af3bf0
AN
3852}
3853
d859900c
DB
3854static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3855 int shndx)
3856{
25bbbd7a
AN
3857 switch (obj->efile.secs[shndx].sec_type) {
3858 case SEC_BSS:
3859 case SEC_DATA:
3860 case SEC_RODATA:
3861 return true;
3862 default:
3863 return false;
3864 }
d859900c
DB
3865}
3866
3867static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3868 int shndx)
3869{
abd29c93
AN
3870 return shndx == obj->efile.maps_shndx ||
3871 shndx == obj->efile.btf_maps_shndx;
d859900c
DB
3872}
3873
d859900c
DB
3874static enum libbpf_map_type
3875bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3876{
25bbbd7a
AN
3877 if (shndx == obj->efile.symbols_shndx)
3878 return LIBBPF_MAP_KCONFIG;
3879
3880 switch (obj->efile.secs[shndx].sec_type) {
3881 case SEC_BSS:
d859900c 3882 return LIBBPF_MAP_BSS;
25bbbd7a
AN
3883 case SEC_DATA:
3884 return LIBBPF_MAP_DATA;
3885 case SEC_RODATA:
d859900c 3886 return LIBBPF_MAP_RODATA;
25bbbd7a 3887 default:
d859900c 3888 return LIBBPF_MAP_UNSPEC;
25bbbd7a 3889 }
d859900c
DB
3890}
3891
1f8e2bcb
AN
3892static int bpf_program__record_reloc(struct bpf_program *prog,
3893 struct reloc_desc *reloc_desc,
9c0f8cbd 3894 __u32 insn_idx, const char *sym_name,
ad23b723 3895 const Elf64_Sym *sym, const Elf64_Rel *rel)
1f8e2bcb
AN
3896{
3897 struct bpf_insn *insn = &prog->insns[insn_idx];
3898 size_t map_idx, nr_maps = prog->obj->nr_maps;
3899 struct bpf_object *obj = prog->obj;
3900 __u32 shdr_idx = sym->st_shndx;
3901 enum libbpf_map_type type;
9c0f8cbd 3902 const char *sym_sec_name;
1f8e2bcb
AN
3903 struct bpf_map *map;
3904
aa0b8d43 3905 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
9c0f8cbd
AN
3906 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3907 prog->name, sym_name, insn_idx, insn->code);
1f8e2bcb
AN
3908 return -LIBBPF_ERRNO__RELOC;
3909 }
166750bc
AN
3910
3911 if (sym_is_extern(sym)) {
ad23b723 3912 int sym_idx = ELF64_R_SYM(rel->r_info);
166750bc
AN
3913 int i, n = obj->nr_extern;
3914 struct extern_desc *ext;
3915
3916 for (i = 0; i < n; i++) {
3917 ext = &obj->externs[i];
3918 if (ext->sym_idx == sym_idx)
3919 break;
3920 }
3921 if (i >= n) {
9c0f8cbd
AN
3922 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3923 prog->name, sym_name, sym_idx);
166750bc
AN
3924 return -LIBBPF_ERRNO__RELOC;
3925 }
9c0f8cbd
AN
3926 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3927 prog->name, i, ext->name, ext->sym_idx, insn_idx);
5bd022ec
MKL
3928 if (insn->code == (BPF_JMP | BPF_CALL))
3929 reloc_desc->type = RELO_EXTERN_FUNC;
3930 else
3931 reloc_desc->type = RELO_EXTERN_VAR;
166750bc 3932 reloc_desc->insn_idx = insn_idx;
2e33efe3 3933 reloc_desc->sym_off = i; /* sym_off stores extern index */
166750bc
AN
3934 return 0;
3935 }
3936
aa0b8d43
MKL
3937 /* sub-program call relocation */
3938 if (is_call_insn(insn)) {
3939 if (insn->src_reg != BPF_PSEUDO_CALL) {
3940 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3941 return -LIBBPF_ERRNO__RELOC;
3942 }
3943 /* text_shndx can be 0, if no default "main" program exists */
3944 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3945 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3946 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3947 prog->name, sym_name, sym_sec_name);
3948 return -LIBBPF_ERRNO__RELOC;
3949 }
3950 if (sym->st_value % BPF_INSN_SZ) {
3951 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3952 prog->name, sym_name, (size_t)sym->st_value);
3953 return -LIBBPF_ERRNO__RELOC;
3954 }
3955 reloc_desc->type = RELO_CALL;
3956 reloc_desc->insn_idx = insn_idx;
3957 reloc_desc->sym_off = sym->st_value;
3958 return 0;
3959 }
3960
1f8e2bcb 3961 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
9c0f8cbd
AN
3962 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3963 prog->name, sym_name, shdr_idx);
1f8e2bcb
AN
3964 return -LIBBPF_ERRNO__RELOC;
3965 }
3966
53eddb5e
YS
3967 /* loading subprog addresses */
3968 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3969 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3970 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3971 */
3972 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3973 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3974 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3975 return -LIBBPF_ERRNO__RELOC;
3976 }
3977
3978 reloc_desc->type = RELO_SUBPROG_ADDR;
3979 reloc_desc->insn_idx = insn_idx;
3980 reloc_desc->sym_off = sym->st_value;
3981 return 0;
3982 }
3983
1f8e2bcb 3984 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
9c0f8cbd 3985 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
1f8e2bcb
AN
3986
3987 /* generic map reference relocation */
3988 if (type == LIBBPF_MAP_UNSPEC) {
3989 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
9c0f8cbd
AN
3990 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3991 prog->name, sym_name, sym_sec_name);
1f8e2bcb
AN
3992 return -LIBBPF_ERRNO__RELOC;
3993 }
3994 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3995 map = &obj->maps[map_idx];
3996 if (map->libbpf_type != type ||
3997 map->sec_idx != sym->st_shndx ||
3998 map->sec_offset != sym->st_value)
3999 continue;
9c0f8cbd
AN
4000 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4001 prog->name, map_idx, map->name, map->sec_idx,
1f8e2bcb
AN
4002 map->sec_offset, insn_idx);
4003 break;
4004 }
4005 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4006 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4007 prog->name, sym_sec_name, (size_t)sym->st_value);
1f8e2bcb
AN
4008 return -LIBBPF_ERRNO__RELOC;
4009 }
4010 reloc_desc->type = RELO_LD64;
4011 reloc_desc->insn_idx = insn_idx;
4012 reloc_desc->map_idx = map_idx;
53f8dd43 4013 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1f8e2bcb
AN
4014 return 0;
4015 }
4016
4017 /* global data map relocation */
4018 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
9c0f8cbd
AN
4019 pr_warn("prog '%s': bad data relo against section '%s'\n",
4020 prog->name, sym_sec_name);
1f8e2bcb 4021 return -LIBBPF_ERRNO__RELOC;
1f8e2bcb 4022 }
1f8e2bcb
AN
4023 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4024 map = &obj->maps[map_idx];
25bbbd7a 4025 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
1f8e2bcb 4026 continue;
9c0f8cbd
AN
4027 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4028 prog->name, map_idx, map->name, map->sec_idx,
4029 map->sec_offset, insn_idx);
1f8e2bcb
AN
4030 break;
4031 }
4032 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4033 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4034 prog->name, sym_sec_name);
1f8e2bcb
AN
4035 return -LIBBPF_ERRNO__RELOC;
4036 }
4037
4038 reloc_desc->type = RELO_DATA;
4039 reloc_desc->insn_idx = insn_idx;
4040 reloc_desc->map_idx = map_idx;
53f8dd43 4041 reloc_desc->sym_off = sym->st_value;
1f8e2bcb
AN
4042 return 0;
4043}
4044
db2b8b06
AN
4045static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4046{
4047 return insn_idx >= prog->sec_insn_off &&
4048 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4049}
4050
4051static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4052 size_t sec_idx, size_t insn_idx)
4053{
4054 int l = 0, r = obj->nr_programs - 1, m;
4055 struct bpf_program *prog;
4056
4057 while (l < r) {
4058 m = l + (r - l + 1) / 2;
4059 prog = &obj->programs[m];
4060
4061 if (prog->sec_idx < sec_idx ||
4062 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4063 l = m;
4064 else
4065 r = m - 1;
4066 }
4067 /* matching program could be at index l, but it still might be the
4068 * wrong one, so we need to double check conditions for the last time
4069 */
4070 prog = &obj->programs[l];
4071 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4072 return prog;
4073 return NULL;
4074}
4075
34090915 4076static int
ad23b723 4077bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
34090915 4078{
9c0f8cbd 4079 const char *relo_sec_name, *sec_name;
b7332d28 4080 size_t sec_idx = shdr->sh_info, sym_idx;
c3c55696
AN
4081 struct bpf_program *prog;
4082 struct reloc_desc *relos;
1f8e2bcb 4083 int err, i, nrels;
c3c55696
AN
4084 const char *sym_name;
4085 __u32 insn_idx;
6245947c
AN
4086 Elf_Scn *scn;
4087 Elf_Data *scn_data;
ad23b723
AN
4088 Elf64_Sym *sym;
4089 Elf64_Rel *rel;
34090915 4090
b7332d28
AN
4091 if (sec_idx >= obj->efile.sec_cnt)
4092 return -EINVAL;
4093
6245947c
AN
4094 scn = elf_sec_by_idx(obj, sec_idx);
4095 scn_data = elf_sec_data(obj, scn);
4096
9c0f8cbd 4097 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
6245947c 4098 sec_name = elf_sec_name(obj, scn);
9c0f8cbd
AN
4099 if (!relo_sec_name || !sec_name)
4100 return -EINVAL;
4101
4102 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4103 relo_sec_name, sec_idx, sec_name);
34090915
WN
4104 nrels = shdr->sh_size / shdr->sh_entsize;
4105
34090915 4106 for (i = 0; i < nrels; i++) {
ad23b723
AN
4107 rel = elf_rel_by_idx(data, i);
4108 if (!rel) {
9c0f8cbd 4109 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
6371ca3b 4110 return -LIBBPF_ERRNO__FORMAT;
34090915 4111 }
ad23b723 4112
b7332d28
AN
4113 sym_idx = ELF64_R_SYM(rel->r_info);
4114 sym = elf_sym_by_idx(obj, sym_idx);
ad23b723 4115 if (!sym) {
b7332d28
AN
4116 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4117 relo_sec_name, sym_idx, i);
4118 return -LIBBPF_ERRNO__FORMAT;
4119 }
4120
4121 if (sym->st_shndx >= obj->efile.sec_cnt) {
4122 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4123 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
6371ca3b 4124 return -LIBBPF_ERRNO__FORMAT;
34090915 4125 }
6245947c 4126
ad23b723 4127 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
9c0f8cbd 4128 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
b7332d28 4129 relo_sec_name, (size_t)rel->r_offset, i);
1f8e2bcb 4130 return -LIBBPF_ERRNO__FORMAT;
9c0f8cbd 4131 }
d859900c 4132
ad23b723 4133 insn_idx = rel->r_offset / BPF_INSN_SZ;
c3c55696
AN
4134 /* relocations against static functions are recorded as
4135 * relocations against the section that contains a function;
4136 * in such case, symbol will be STT_SECTION and sym.st_name
4137 * will point to empty string (0), so fetch section name
4138 * instead
4139 */
ad23b723
AN
4140 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4141 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
c3c55696 4142 else
ad23b723 4143 sym_name = elf_sym_str(obj, sym->st_name);
c3c55696 4144 sym_name = sym_name ?: "<?";
d859900c 4145
9c0f8cbd
AN
4146 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4147 relo_sec_name, i, insn_idx, sym_name);
666810e8 4148
c3c55696
AN
4149 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4150 if (!prog) {
6245947c 4151 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
c3c55696 4152 relo_sec_name, i, sec_name, insn_idx);
6245947c 4153 continue;
c3c55696
AN
4154 }
4155
4156 relos = libbpf_reallocarray(prog->reloc_desc,
4157 prog->nr_reloc + 1, sizeof(*relos));
4158 if (!relos)
4159 return -ENOMEM;
4160 prog->reloc_desc = relos;
4161
4162 /* adjust insn_idx to local BPF program frame of reference */
4163 insn_idx -= prog->sec_insn_off;
4164 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
ad23b723 4165 insn_idx, sym_name, sym, rel);
1f8e2bcb
AN
4166 if (err)
4167 return err;
c3c55696
AN
4168
4169 prog->nr_reloc++;
34090915
WN
4170 }
4171 return 0;
4172}
4173
abd29c93 4174static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
8a138aed
MKL
4175{
4176 struct bpf_map_def *def = &map->def;
d859900c 4177 __u32 key_type_id = 0, value_type_id = 0;
96408c43 4178 int ret;
8a138aed 4179
590a0088
MKL
4180 /* if it's BTF-defined map, we don't need to search for type IDs.
4181 * For struct_ops map, it does not need btf_key_type_id and
4182 * btf_value_type_id.
4183 */
4184 if (map->sec_idx == obj->efile.btf_maps_shndx ||
4185 bpf_map__is_struct_ops(map))
abd29c93
AN
4186 return 0;
4187
d859900c 4188 if (!bpf_map__is_internal(map)) {
93b8952d 4189 pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
227a0713
AN
4190#pragma GCC diagnostic push
4191#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
abd29c93 4192 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
d859900c
DB
4193 def->value_size, &key_type_id,
4194 &value_type_id);
227a0713 4195#pragma GCC diagnostic pop
d859900c
DB
4196 } else {
4197 /*
4198 * LLVM annotates global data differently in BTF, that is,
4199 * only as '.data', '.bss' or '.rodata'.
4200 */
aed65917 4201 ret = btf__find_by_name(obj->btf, map->real_name);
d859900c
DB
4202 }
4203 if (ret < 0)
96408c43 4204 return ret;
8a138aed 4205
96408c43 4206 map->btf_key_type_id = key_type_id;
d859900c
DB
4207 map->btf_value_type_id = bpf_map__is_internal(map) ?
4208 ret : value_type_id;
8a138aed
MKL
4209 return 0;
4210}
4211
97eb3138
MP
4212static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4213{
4214 char file[PATH_MAX], buff[4096];
4215 FILE *fp;
4216 __u32 val;
4217 int err;
4218
4219 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4220 memset(info, 0, sizeof(*info));
4221
4222 fp = fopen(file, "r");
4223 if (!fp) {
4224 err = -errno;
4225 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4226 err);
4227 return err;
4228 }
4229
4230 while (fgets(buff, sizeof(buff), fp)) {
4231 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4232 info->type = val;
4233 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4234 info->key_size = val;
4235 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4236 info->value_size = val;
4237 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4238 info->max_entries = val;
4239 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4240 info->map_flags = val;
4241 }
4242
4243 fclose(fp);
4244
4245 return 0;
4246}
4247
26736eb9
JK
4248int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4249{
4250 struct bpf_map_info info = {};
4251 __u32 len = sizeof(info);
4252 int new_fd, err;
4253 char *new_name;
4254
4255 err = bpf_obj_get_info_by_fd(fd, &info, &len);
97eb3138
MP
4256 if (err && errno == EINVAL)
4257 err = bpf_get_map_info_from_fdinfo(fd, &info);
26736eb9 4258 if (err)
e9fc3ce9 4259 return libbpf_err(err);
26736eb9
JK
4260
4261 new_name = strdup(info.name);
4262 if (!new_name)
e9fc3ce9 4263 return libbpf_err(-errno);
26736eb9
JK
4264
4265 new_fd = open("/", O_RDONLY | O_CLOEXEC);
d1b4574a
THJ
4266 if (new_fd < 0) {
4267 err = -errno;
26736eb9 4268 goto err_free_new_name;
d1b4574a 4269 }
26736eb9
JK
4270
4271 new_fd = dup3(fd, new_fd, O_CLOEXEC);
d1b4574a
THJ
4272 if (new_fd < 0) {
4273 err = -errno;
26736eb9 4274 goto err_close_new_fd;
d1b4574a 4275 }
26736eb9
JK
4276
4277 err = zclose(map->fd);
d1b4574a
THJ
4278 if (err) {
4279 err = -errno;
26736eb9 4280 goto err_close_new_fd;
d1b4574a 4281 }
26736eb9
JK
4282 free(map->name);
4283
4284 map->fd = new_fd;
4285 map->name = new_name;
4286 map->def.type = info.type;
4287 map->def.key_size = info.key_size;
4288 map->def.value_size = info.value_size;
4289 map->def.max_entries = info.max_entries;
4290 map->def.map_flags = info.map_flags;
4291 map->btf_key_type_id = info.btf_key_type_id;
4292 map->btf_value_type_id = info.btf_value_type_id;
ec6d5f47 4293 map->reused = true;
47512102 4294 map->map_extra = info.map_extra;
26736eb9
JK
4295
4296 return 0;
4297
4298err_close_new_fd:
4299 close(new_fd);
4300err_free_new_name:
4301 free(new_name);
e9fc3ce9 4302 return libbpf_err(err);
26736eb9
JK
4303}
4304
1bdb6c9a 4305__u32 bpf_map__max_entries(const struct bpf_map *map)
1a11a4c7 4306{
1bdb6c9a
AN
4307 return map->def.max_entries;
4308}
1a11a4c7 4309
b3278099
AN
4310struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4311{
4312 if (!bpf_map_type__is_map_in_map(map->def.type))
e9fc3ce9 4313 return errno = EINVAL, NULL;
b3278099
AN
4314
4315 return map->inner_map;
4316}
4317
1bdb6c9a
AN
4318int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4319{
1a11a4c7 4320 if (map->fd >= 0)
e9fc3ce9 4321 return libbpf_err(-EBUSY);
1a11a4c7 4322 map->def.max_entries = max_entries;
1a11a4c7
AI
4323 return 0;
4324}
4325
1bdb6c9a
AN
4326int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4327{
4328 if (!map || !max_entries)
e9fc3ce9 4329 return libbpf_err(-EINVAL);
1bdb6c9a
AN
4330
4331 return bpf_map__set_max_entries(map, max_entries);
4332}
4333
47eff617 4334static int
fd9eef1a 4335bpf_object__probe_loading(struct bpf_object *obj)
47eff617 4336{
47eff617
SF
4337 char *cp, errmsg[STRERR_BUFSIZE];
4338 struct bpf_insn insns[] = {
4339 BPF_MOV64_IMM(BPF_REG_0, 0),
4340 BPF_EXIT_INSN(),
4341 };
e32660ac 4342 int ret, insn_cnt = ARRAY_SIZE(insns);
47eff617 4343
f9bceaa5
SF
4344 if (obj->gen_loader)
4345 return 0;
4346
e542f2c4
AN
4347 ret = bump_rlimit_memlock();
4348 if (ret)
4349 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4350
47eff617 4351 /* make sure basic loading works */
e32660ac
AN
4352 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4353 if (ret < 0)
4354 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
47eff617 4355 if (ret < 0) {
fd9eef1a
EC
4356 ret = errno;
4357 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4358 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4359 "program. Make sure your kernel supports BPF "
4360 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4361 "set to big enough value.\n", __func__, cp, ret);
4362 return -ret;
47eff617
SF
4363 }
4364 close(ret);
4365
fd9eef1a
EC
4366 return 0;
4367}
4368
bb180fb2
AN
4369static int probe_fd(int fd)
4370{
4371 if (fd >= 0)
4372 close(fd);
4373 return fd >= 0;
4374}
4375
47b6cb4d 4376static int probe_kern_prog_name(void)
fd9eef1a 4377{
fd9eef1a
EC
4378 struct bpf_insn insns[] = {
4379 BPF_MOV64_IMM(BPF_REG_0, 0),
4380 BPF_EXIT_INSN(),
4381 };
e32660ac 4382 int ret, insn_cnt = ARRAY_SIZE(insns);
fd9eef1a
EC
4383
4384 /* make sure loading with name works */
e32660ac 4385 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
bb180fb2 4386 return probe_fd(ret);
47eff617
SF
4387}
4388
47b6cb4d 4389static int probe_kern_global_data(void)
8837fe5d 4390{
8837fe5d
DB
4391 char *cp, errmsg[STRERR_BUFSIZE];
4392 struct bpf_insn insns[] = {
4393 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4394 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4395 BPF_MOV64_IMM(BPF_REG_0, 0),
4396 BPF_EXIT_INSN(),
4397 };
e32660ac 4398 int ret, map, insn_cnt = ARRAY_SIZE(insns);
8837fe5d 4399
a9606f40 4400 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
8837fe5d 4401 if (map < 0) {
23ab656b
THJ
4402 ret = -errno;
4403 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
be18010e 4404 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
23ab656b
THJ
4405 __func__, cp, -ret);
4406 return ret;
8837fe5d
DB
4407 }
4408
4409 insns[0].imm = map;
4410
e32660ac 4411 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
47b6cb4d 4412 close(map);
bb180fb2 4413 return probe_fd(ret);
8837fe5d
DB
4414}
4415
68b08647
AN
4416static int probe_kern_btf(void)
4417{
4418 static const char strs[] = "\0int";
4419 __u32 types[] = {
4420 /* int */
4421 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4422 };
4423
4424 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4425 strs, sizeof(strs)));
4426}
4427
47b6cb4d 4428static int probe_kern_btf_func(void)
d7c4b398 4429{
8983b731 4430 static const char strs[] = "\0int\0x\0a";
d7c4b398
AN
4431 /* void x(int a) {} */
4432 __u32 types[] = {
4433 /* int */
4434 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4435 /* FUNC_PROTO */ /* [2] */
4436 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4437 BTF_PARAM_ENC(7, 1),
4438 /* FUNC x */ /* [3] */
4439 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4440 };
d7c4b398 4441
bb180fb2
AN
4442 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4443 strs, sizeof(strs)));
d7c4b398
AN
4444}
4445
47b6cb4d 4446static int probe_kern_btf_func_global(void)
2d3eb67f
AS
4447{
4448 static const char strs[] = "\0int\0x\0a";
4449 /* static void x(int a) {} */
4450 __u32 types[] = {
4451 /* int */
4452 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4453 /* FUNC_PROTO */ /* [2] */
4454 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4455 BTF_PARAM_ENC(7, 1),
4456 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4457 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4458 };
2d3eb67f 4459
bb180fb2
AN
4460 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4461 strs, sizeof(strs)));
2d3eb67f
AS
4462}
4463
47b6cb4d 4464static int probe_kern_btf_datasec(void)
d7c4b398 4465{
8983b731 4466 static const char strs[] = "\0x\0.data";
d7c4b398
AN
4467 /* static int a; */
4468 __u32 types[] = {
4469 /* int */
4470 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4471 /* VAR x */ /* [2] */
4472 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4473 BTF_VAR_STATIC,
4474 /* DATASEC val */ /* [3] */
4475 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4476 BTF_VAR_SECINFO_ENC(2, 0, 4),
4477 };
cfd49210 4478
bb180fb2
AN
4479 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4480 strs, sizeof(strs)));
d7c4b398
AN
4481}
4482
22541a9e
IL
4483static int probe_kern_btf_float(void)
4484{
4485 static const char strs[] = "\0float";
4486 __u32 types[] = {
4487 /* float */
4488 BTF_TYPE_FLOAT_ENC(1, 4),
4489 };
4490
4491 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4492 strs, sizeof(strs)));
4493}
4494
223f903e 4495static int probe_kern_btf_decl_tag(void)
5b84bd10
YS
4496{
4497 static const char strs[] = "\0tag";
4498 __u32 types[] = {
4499 /* int */
4500 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4501 /* VAR x */ /* [2] */
4502 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4503 BTF_VAR_STATIC,
4504 /* attr */
223f903e 4505 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
5b84bd10
YS
4506 };
4507
4508 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4509 strs, sizeof(strs)));
4510}
4511
2dc1e488
YS
4512static int probe_kern_btf_type_tag(void)
4513{
4514 static const char strs[] = "\0tag";
4515 __u32 types[] = {
4516 /* int */
4517 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4518 /* attr */
4519 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4520 /* ptr */
4521 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4522 };
4523
4524 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4525 strs, sizeof(strs)));
4526}
4527
47b6cb4d 4528static int probe_kern_array_mmap(void)
7fe74b43 4529{
a9606f40
AN
4530 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4531 int fd;
7fe74b43 4532
a9606f40
AN
4533 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4534 return probe_fd(fd);
7fe74b43
AN
4535}
4536
47b6cb4d 4537static int probe_kern_exp_attach_type(void)
25498a19 4538{
e32660ac 4539 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
25498a19
AN
4540 struct bpf_insn insns[] = {
4541 BPF_MOV64_IMM(BPF_REG_0, 0),
4542 BPF_EXIT_INSN(),
4543 };
e32660ac 4544 int fd, insn_cnt = ARRAY_SIZE(insns);
25498a19 4545
25498a19
AN
4546 /* use any valid combination of program type and (optional)
4547 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4548 * to see if kernel supports expected_attach_type field for
4549 * BPF_PROG_LOAD command
4550 */
e32660ac
AN
4551 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4552 return probe_fd(fd);
25498a19
AN
4553}
4554
109cea5a
AN
4555static int probe_kern_probe_read_kernel(void)
4556{
109cea5a
AN
4557 struct bpf_insn insns[] = {
4558 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4559 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4560 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4561 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4562 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4563 BPF_EXIT_INSN(),
4564 };
e32660ac 4565 int fd, insn_cnt = ARRAY_SIZE(insns);
109cea5a 4566
e32660ac
AN
4567 fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4568 return probe_fd(fd);
109cea5a
AN
4569}
4570
5d23328d
YZ
4571static int probe_prog_bind_map(void)
4572{
5d23328d
YZ
4573 char *cp, errmsg[STRERR_BUFSIZE];
4574 struct bpf_insn insns[] = {
4575 BPF_MOV64_IMM(BPF_REG_0, 0),
4576 BPF_EXIT_INSN(),
4577 };
e32660ac 4578 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
5d23328d 4579
a9606f40 4580 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
5d23328d
YZ
4581 if (map < 0) {
4582 ret = -errno;
4583 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4584 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4585 __func__, cp, -ret);
4586 return ret;
4587 }
4588
e32660ac 4589 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5d23328d
YZ
4590 if (prog < 0) {
4591 close(map);
4592 return 0;
4593 }
4594
4595 ret = bpf_prog_bind_map(prog, map, NULL);
4596
4597 close(map);
4598 close(prog);
4599
4600 return ret >= 0;
4601}
4602
4f33a53d
AN
4603static int probe_module_btf(void)
4604{
4605 static const char strs[] = "\0int";
4606 __u32 types[] = {
4607 /* int */
4608 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4609 };
4610 struct bpf_btf_info info;
4611 __u32 len = sizeof(info);
4612 char name[16];
4613 int fd, err;
4614
4615 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4616 if (fd < 0)
4617 return 0; /* BTF not supported at all */
4618
4619 memset(&info, 0, sizeof(info));
4620 info.name = ptr_to_u64(name);
4621 info.name_len = sizeof(name);
4622
4623 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4624 * kernel's module BTF support coincides with support for
4625 * name/name_len fields in struct bpf_btf_info.
4626 */
4627 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4628 close(fd);
4629 return !err;
4630}
4631
668ace0e
AN
4632static int probe_perf_link(void)
4633{
668ace0e
AN
4634 struct bpf_insn insns[] = {
4635 BPF_MOV64_IMM(BPF_REG_0, 0),
4636 BPF_EXIT_INSN(),
4637 };
4638 int prog_fd, link_fd, err;
4639
e32660ac
AN
4640 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4641 insns, ARRAY_SIZE(insns), NULL);
668ace0e
AN
4642 if (prog_fd < 0)
4643 return -errno;
4644
4645 /* use invalid perf_event FD to get EBADF, if link is supported;
4646 * otherwise EINVAL should be returned
4647 */
4648 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4649 err = -errno; /* close() can clobber errno */
4650
4651 if (link_fd >= 0)
4652 close(link_fd);
4653 close(prog_fd);
4654
4655 return link_fd < 0 && err == -EBADF;
4656}
4657
47b6cb4d
AN
4658enum kern_feature_result {
4659 FEAT_UNKNOWN = 0,
4660 FEAT_SUPPORTED = 1,
4661 FEAT_MISSING = 2,
4662};
4663
4664typedef int (*feature_probe_fn)(void);
4665
4666static struct kern_feature_desc {
4667 const char *desc;
4668 feature_probe_fn probe;
4669 enum kern_feature_result res;
4670} feature_probes[__FEAT_CNT] = {
4671 [FEAT_PROG_NAME] = {
4672 "BPF program name", probe_kern_prog_name,
4673 },
4674 [FEAT_GLOBAL_DATA] = {
4675 "global variables", probe_kern_global_data,
4676 },
68b08647
AN
4677 [FEAT_BTF] = {
4678 "minimal BTF", probe_kern_btf,
4679 },
47b6cb4d
AN
4680 [FEAT_BTF_FUNC] = {
4681 "BTF functions", probe_kern_btf_func,
4682 },
4683 [FEAT_BTF_GLOBAL_FUNC] = {
4684 "BTF global function", probe_kern_btf_func_global,
4685 },
4686 [FEAT_BTF_DATASEC] = {
4687 "BTF data section and variable", probe_kern_btf_datasec,
4688 },
4689 [FEAT_ARRAY_MMAP] = {
4690 "ARRAY map mmap()", probe_kern_array_mmap,
4691 },
4692 [FEAT_EXP_ATTACH_TYPE] = {
4693 "BPF_PROG_LOAD expected_attach_type attribute",
4694 probe_kern_exp_attach_type,
4695 },
109cea5a
AN
4696 [FEAT_PROBE_READ_KERN] = {
4697 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5d23328d
YZ
4698 },
4699 [FEAT_PROG_BIND_MAP] = {
4700 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4f33a53d
AN
4701 },
4702 [FEAT_MODULE_BTF] = {
4703 "module BTF support", probe_module_btf,
4704 },
22541a9e
IL
4705 [FEAT_BTF_FLOAT] = {
4706 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4707 },
668ace0e
AN
4708 [FEAT_PERF_LINK] = {
4709 "BPF perf link support", probe_perf_link,
4710 },
223f903e
YS
4711 [FEAT_BTF_DECL_TAG] = {
4712 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5b84bd10 4713 },
2dc1e488
YS
4714 [FEAT_BTF_TYPE_TAG] = {
4715 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4716 },
e542f2c4
AN
4717 [FEAT_MEMCG_ACCOUNT] = {
4718 "memcg-based memory accounting", probe_memcg_account,
4719 },
47b6cb4d 4720};
8837fe5d 4721
e542f2c4 4722bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
47b6cb4d
AN
4723{
4724 struct kern_feature_desc *feat = &feature_probes[feat_id];
4725 int ret;
4726
e542f2c4 4727 if (obj && obj->gen_loader)
67234743
AS
4728 /* To generate loader program assume the latest kernel
4729 * to avoid doing extra prog_load, map_create syscalls.
4730 */
4731 return true;
4732
47b6cb4d
AN
4733 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4734 ret = feat->probe();
4735 if (ret > 0) {
4736 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4737 } else if (ret == 0) {
4738 WRITE_ONCE(feat->res, FEAT_MISSING);
4739 } else {
4740 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4741 WRITE_ONCE(feat->res, FEAT_MISSING);
4742 }
8837fe5d
DB
4743 }
4744
47b6cb4d 4745 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
47eff617
SF
4746}
4747
57a00f41
THJ
4748static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4749{
4750 struct bpf_map_info map_info = {};
4751 char msg[STRERR_BUFSIZE];
4752 __u32 map_info_len;
97eb3138 4753 int err;
57a00f41
THJ
4754
4755 map_info_len = sizeof(map_info);
4756
97eb3138
MP
4757 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4758 if (err && errno == EINVAL)
4759 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4760 if (err) {
4761 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4762 libbpf_strerror_r(errno, msg, sizeof(msg)));
57a00f41
THJ
4763 return false;
4764 }
4765
4766 return (map_info.type == map->def.type &&
4767 map_info.key_size == map->def.key_size &&
4768 map_info.value_size == map->def.value_size &&
4769 map_info.max_entries == map->def.max_entries &&
47512102
JK
4770 map_info.map_flags == map->def.map_flags &&
4771 map_info.map_extra == map->map_extra);
57a00f41
THJ
4772}
4773
4774static int
4775bpf_object__reuse_map(struct bpf_map *map)
4776{
4777 char *cp, errmsg[STRERR_BUFSIZE];
4778 int err, pin_fd;
4779
4780 pin_fd = bpf_obj_get(map->pin_path);
4781 if (pin_fd < 0) {
4782 err = -errno;
4783 if (err == -ENOENT) {
4784 pr_debug("found no pinned map to reuse at '%s'\n",
4785 map->pin_path);
4786 return 0;
4787 }
4788
4789 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4790 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4791 map->pin_path, cp);
4792 return err;
4793 }
4794
4795 if (!map_is_reuse_compat(map, pin_fd)) {
4796 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4797 map->pin_path);
4798 close(pin_fd);
4799 return -EINVAL;
4800 }
4801
4802 err = bpf_map__reuse_fd(map, pin_fd);
4803 if (err) {
4804 close(pin_fd);
4805 return err;
4806 }
4807 map->pinned = true;
4808 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4809
4810 return 0;
4811}
4812
d859900c
DB
4813static int
4814bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4815{
166750bc 4816 enum libbpf_map_type map_type = map->libbpf_type;
d859900c
DB
4817 char *cp, errmsg[STRERR_BUFSIZE];
4818 int err, zero = 0;
d859900c 4819
67234743
AS
4820 if (obj->gen_loader) {
4821 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4822 map->mmaped, map->def.value_size);
4823 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4824 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4825 return 0;
4826 }
eba9c5f4
AN
4827 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4828 if (err) {
4829 err = -errno;
4830 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4831 pr_warn("Error setting initial map(%s) contents: %s\n",
4832 map->name, cp);
4833 return err;
4834 }
d859900c 4835
81bfdd08
AN
4836 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4837 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
d859900c
DB
4838 err = bpf_map_freeze(map->fd);
4839 if (err) {
eba9c5f4
AN
4840 err = -errno;
4841 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e
KW
4842 pr_warn("Error freezing map(%s) as read-only: %s\n",
4843 map->name, cp);
eba9c5f4 4844 return err;
d859900c
DB
4845 }
4846 }
eba9c5f4 4847 return 0;
d859900c
DB
4848}
4849
2d39d7c5
AN
4850static void bpf_map__destroy(struct bpf_map *map);
4851
67234743 4852static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
2d39d7c5 4853{
992c4225 4854 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
2d39d7c5 4855 struct bpf_map_def *def = &map->def;
992c4225 4856 const char *map_name = NULL;
a21ab4c5 4857 int err = 0;
2d39d7c5 4858
9ca1f56a 4859 if (kernel_supports(obj, FEAT_PROG_NAME))
992c4225 4860 map_name = map->name;
2d39d7c5 4861 create_attr.map_ifindex = map->map_ifindex;
2d39d7c5 4862 create_attr.map_flags = def->map_flags;
1bdb6c9a 4863 create_attr.numa_node = map->numa_node;
47512102 4864 create_attr.map_extra = map->map_extra;
2d39d7c5 4865
2d39d7c5 4866 if (bpf_map__is_struct_ops(map))
992c4225 4867 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
2d39d7c5 4868
0f0e55d8 4869 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
2d39d7c5
AN
4870 create_attr.btf_fd = btf__fd(obj->btf);
4871 create_attr.btf_key_type_id = map->btf_key_type_id;
4872 create_attr.btf_value_type_id = map->btf_value_type_id;
4873 }
4874
646f02ff
AN
4875 if (bpf_map_type__is_map_in_map(def->type)) {
4876 if (map->inner_map) {
67234743 4877 err = bpf_object__create_map(obj, map->inner_map, true);
646f02ff
AN
4878 if (err) {
4879 pr_warn("map '%s': failed to create inner map: %d\n",
4880 map->name, err);
4881 return err;
4882 }
4883 map->inner_map_fd = bpf_map__fd(map->inner_map);
4884 }
4885 if (map->inner_map_fd >= 0)
4886 create_attr.inner_map_fd = map->inner_map_fd;
4887 }
4888
f7310523
HC
4889 switch (def->type) {
4890 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4891 case BPF_MAP_TYPE_CGROUP_ARRAY:
4892 case BPF_MAP_TYPE_STACK_TRACE:
4893 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4894 case BPF_MAP_TYPE_HASH_OF_MAPS:
4895 case BPF_MAP_TYPE_DEVMAP:
4896 case BPF_MAP_TYPE_DEVMAP_HASH:
4897 case BPF_MAP_TYPE_CPUMAP:
4898 case BPF_MAP_TYPE_XSKMAP:
4899 case BPF_MAP_TYPE_SOCKMAP:
4900 case BPF_MAP_TYPE_SOCKHASH:
4901 case BPF_MAP_TYPE_QUEUE:
4902 case BPF_MAP_TYPE_STACK:
4903 case BPF_MAP_TYPE_RINGBUF:
4904 create_attr.btf_fd = 0;
4905 create_attr.btf_key_type_id = 0;
4906 create_attr.btf_value_type_id = 0;
4907 map->btf_key_type_id = 0;
4908 map->btf_value_type_id = 0;
4909 default:
4910 break;
4911 }
4912
67234743 4913 if (obj->gen_loader) {
992c4225 4914 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
a4fbfdd7 4915 def->key_size, def->value_size, def->max_entries,
992c4225 4916 &create_attr, is_inner ? -1 : map - obj->maps);
67234743
AS
4917 /* Pretend to have valid FD to pass various fd >= 0 checks.
4918 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4919 */
4920 map->fd = 0;
4921 } else {
992c4225
AN
4922 map->fd = bpf_map_create(def->type, map_name,
4923 def->key_size, def->value_size,
a4fbfdd7 4924 def->max_entries, &create_attr);
67234743 4925 }
2d39d7c5
AN
4926 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4927 create_attr.btf_value_type_id)) {
4928 char *cp, errmsg[STRERR_BUFSIZE];
2d39d7c5 4929
a21ab4c5 4930 err = -errno;
2d39d7c5
AN
4931 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4932 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4933 map->name, cp, err);
4934 create_attr.btf_fd = 0;
4935 create_attr.btf_key_type_id = 0;
4936 create_attr.btf_value_type_id = 0;
4937 map->btf_key_type_id = 0;
4938 map->btf_value_type_id = 0;
992c4225
AN
4939 map->fd = bpf_map_create(def->type, map_name,
4940 def->key_size, def->value_size,
a4fbfdd7 4941 def->max_entries, &create_attr);
2d39d7c5
AN
4942 }
4943
a21ab4c5 4944 err = map->fd < 0 ? -errno : 0;
2d39d7c5 4945
646f02ff 4946 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
67234743
AS
4947 if (obj->gen_loader)
4948 map->inner_map->fd = -1;
646f02ff
AN
4949 bpf_map__destroy(map->inner_map);
4950 zfree(&map->inner_map);
4951 }
4952
a21ab4c5 4953 return err;
2d39d7c5
AN
4954}
4955
341ac5ff 4956static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
a0f2b7ac
HL
4957{
4958 const struct bpf_map *targ_map;
4959 unsigned int i;
67234743 4960 int fd, err = 0;
a0f2b7ac
HL
4961
4962 for (i = 0; i < map->init_slots_sz; i++) {
4963 if (!map->init_slots[i])
4964 continue;
4965
4966 targ_map = map->init_slots[i];
4967 fd = bpf_map__fd(targ_map);
341ac5ff 4968
67234743 4969 if (obj->gen_loader) {
be05c944
AS
4970 bpf_gen__populate_outer_map(obj->gen_loader,
4971 map - obj->maps, i,
4972 targ_map - obj->maps);
67234743
AS
4973 } else {
4974 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4975 }
a0f2b7ac
HL
4976 if (err) {
4977 err = -errno;
4978 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
341ac5ff 4979 map->name, i, targ_map->name, fd, err);
a0f2b7ac
HL
4980 return err;
4981 }
4982 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4983 map->name, i, targ_map->name, fd);
4984 }
4985
4986 zfree(&map->init_slots);
4987 map->init_slots_sz = 0;
4988
4989 return 0;
4990}
4991
341ac5ff
HC
4992static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
4993{
4994 const struct bpf_program *targ_prog;
4995 unsigned int i;
4996 int fd, err;
4997
4998 if (obj->gen_loader)
4999 return -ENOTSUP;
5000
5001 for (i = 0; i < map->init_slots_sz; i++) {
5002 if (!map->init_slots[i])
5003 continue;
5004
5005 targ_prog = map->init_slots[i];
5006 fd = bpf_program__fd(targ_prog);
5007
5008 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5009 if (err) {
5010 err = -errno;
5011 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5012 map->name, i, targ_prog->name, fd, err);
5013 return err;
5014 }
5015 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5016 map->name, i, targ_prog->name, fd);
5017 }
5018
5019 zfree(&map->init_slots);
5020 map->init_slots_sz = 0;
5021
5022 return 0;
5023}
5024
5025static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5026{
5027 struct bpf_map *map;
5028 int i, err;
5029
5030 for (i = 0; i < obj->nr_maps; i++) {
5031 map = &obj->maps[i];
5032
5033 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5034 continue;
5035
5036 err = init_prog_array_slots(obj, map);
5037 if (err < 0) {
5038 zclose(map->fd);
5039 return err;
5040 }
5041 }
5042 return 0;
5043}
5044
a4fbfdd7
ST
5045static int map_set_def_max_entries(struct bpf_map *map)
5046{
5047 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5048 int nr_cpus;
5049
5050 nr_cpus = libbpf_num_possible_cpus();
5051 if (nr_cpus < 0) {
5052 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5053 map->name, nr_cpus);
5054 return nr_cpus;
5055 }
5056 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5057 map->def.max_entries = nr_cpus;
5058 }
5059
5060 return 0;
5061}
5062
52d3352e
WN
5063static int
5064bpf_object__create_maps(struct bpf_object *obj)
5065{
2d39d7c5
AN
5066 struct bpf_map *map;
5067 char *cp, errmsg[STRERR_BUFSIZE];
5068 unsigned int i, j;
8a138aed 5069 int err;
043c5bb3 5070 bool retried;
52d3352e 5071
9d759a9b 5072 for (i = 0; i < obj->nr_maps; i++) {
2d39d7c5 5073 map = &obj->maps[i];
8a138aed 5074
16e0c35c
AN
5075 /* To support old kernels, we skip creating global data maps
5076 * (.rodata, .data, .kconfig, etc); later on, during program
5077 * loading, if we detect that at least one of the to-be-loaded
5078 * programs is referencing any global data map, we'll error
5079 * out with program name and relocation index logged.
5080 * This approach allows to accommodate Clang emitting
5081 * unnecessary .rodata.str1.1 sections for string literals,
5082 * but also it allows to have CO-RE applications that use
5083 * global variables in some of BPF programs, but not others.
5084 * If those global variable-using programs are not loaded at
5085 * runtime due to bpf_program__set_autoload(prog, false),
5086 * bpf_object loading will succeed just fine even on old
5087 * kernels.
5088 */
5089 if (bpf_map__is_internal(map) &&
229fae38
SC
5090 !kernel_supports(obj, FEAT_GLOBAL_DATA)) {
5091 map->skipped = true;
16e0c35c 5092 continue;
229fae38 5093 }
16e0c35c 5094
a4fbfdd7
ST
5095 err = map_set_def_max_entries(map);
5096 if (err)
5097 goto err_out;
5098
043c5bb3
MP
5099 retried = false;
5100retry:
57a00f41
THJ
5101 if (map->pin_path) {
5102 err = bpf_object__reuse_map(map);
5103 if (err) {
2d39d7c5 5104 pr_warn("map '%s': error reusing pinned map\n",
57a00f41 5105 map->name);
2d39d7c5 5106 goto err_out;
57a00f41 5107 }
043c5bb3
MP
5108 if (retried && map->fd < 0) {
5109 pr_warn("map '%s': cannot find pinned map\n",
5110 map->name);
5111 err = -ENOENT;
5112 goto err_out;
5113 }
57a00f41
THJ
5114 }
5115
26736eb9 5116 if (map->fd >= 0) {
2d39d7c5 5117 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
26736eb9 5118 map->name, map->fd);
2c193d32 5119 } else {
67234743 5120 err = bpf_object__create_map(obj, map, false);
2c193d32 5121 if (err)
d859900c 5122 goto err_out;
d859900c 5123
2c193d32
HL
5124 pr_debug("map '%s': created successfully, fd=%d\n",
5125 map->name, map->fd);
646f02ff 5126
2c193d32
HL
5127 if (bpf_map__is_internal(map)) {
5128 err = bpf_object__populate_internal_map(obj, map);
5129 if (err < 0) {
5130 zclose(map->fd);
5131 goto err_out;
5132 }
d859900c 5133 }
646f02ff 5134
341ac5ff
HC
5135 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5136 err = init_map_in_map_slots(obj, map);
2c193d32
HL
5137 if (err < 0) {
5138 zclose(map->fd);
646f02ff
AN
5139 goto err_out;
5140 }
646f02ff 5141 }
646f02ff
AN
5142 }
5143
57a00f41
THJ
5144 if (map->pin_path && !map->pinned) {
5145 err = bpf_map__pin(map, NULL);
5146 if (err) {
043c5bb3
MP
5147 zclose(map->fd);
5148 if (!retried && err == -EEXIST) {
5149 retried = true;
5150 goto retry;
5151 }
2d39d7c5
AN
5152 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5153 map->name, map->pin_path, err);
2d39d7c5 5154 goto err_out;
57a00f41
THJ
5155 }
5156 }
52d3352e
WN
5157 }
5158
52d3352e 5159 return 0;
2d39d7c5
AN
5160
5161err_out:
5162 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5163 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5164 pr_perm_msg(err);
5165 for (j = 0; j < i; j++)
5166 zclose(obj->maps[j].fd);
5167 return err;
52d3352e
WN
5168}
5169
ddc7c304
AN
5170static bool bpf_core_is_flavor_sep(const char *s)
5171{
5172 /* check X___Y name pattern, where X and Y are not underscores */
5173 return s[0] != '_' && /* X */
5174 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5175 s[4] != '_'; /* Y */
5176}
5177
5178/* Given 'some_struct_name___with_flavor' return the length of a name prefix
5179 * before last triple underscore. Struct name part after last triple
5180 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5181 */
b0588390 5182size_t bpf_core_essential_name_len(const char *name)
ddc7c304
AN
5183{
5184 size_t n = strlen(name);
5185 int i;
5186
5187 for (i = n - 5; i >= 0; i--) {
5188 if (bpf_core_is_flavor_sep(name + i))
5189 return i + 1;
5190 }
5191 return n;
5192}
5193
8de6cae4 5194void bpf_core_free_cands(struct bpf_core_cand_list *cands)
ddc7c304 5195{
8de6cae4
MV
5196 if (!cands)
5197 return;
5198
0f7515ca
AN
5199 free(cands->cands);
5200 free(cands);
ddc7c304
AN
5201}
5202
8de6cae4
MV
5203int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5204 size_t local_essent_len,
5205 const struct btf *targ_btf,
5206 const char *targ_btf_name,
5207 int targ_start_id,
5208 struct bpf_core_cand_list *cands)
ddc7c304 5209{
301ba4d7 5210 struct bpf_core_cand *new_cands, *cand;
03d5b991
AN
5211 const struct btf_type *t, *local_t;
5212 const char *targ_name, *local_name;
0f7515ca
AN
5213 size_t targ_essent_len;
5214 int n, i;
ddc7c304 5215
03d5b991
AN
5216 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5217 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5218
6a886de0
HC
5219 n = btf__type_cnt(targ_btf);
5220 for (i = targ_start_id; i < n; i++) {
ddc7c304 5221 t = btf__type_by_id(targ_btf, i);
03d5b991 5222 if (btf_kind(t) != btf_kind(local_t))
ddc7c304
AN
5223 continue;
5224
3fc32f40
AN
5225 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5226 if (str_is_empty(targ_name))
d121e1d3
AN
5227 continue;
5228
ddc7c304
AN
5229 targ_essent_len = bpf_core_essential_name_len(targ_name);
5230 if (targ_essent_len != local_essent_len)
5231 continue;
5232
03d5b991 5233 if (strncmp(local_name, targ_name, local_essent_len) != 0)
0f7515ca
AN
5234 continue;
5235
5236 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
03d5b991
AN
5237 local_cand->id, btf_kind_str(local_t),
5238 local_name, i, btf_kind_str(t), targ_name,
0f7515ca
AN
5239 targ_btf_name);
5240 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5241 sizeof(*cands->cands));
5242 if (!new_cands)
5243 return -ENOMEM;
5244
5245 cand = &new_cands[cands->len];
5246 cand->btf = targ_btf;
0f7515ca
AN
5247 cand->id = i;
5248
5249 cands->cands = new_cands;
5250 cands->len++;
ddc7c304 5251 }
0f7515ca
AN
5252 return 0;
5253}
5254
4f33a53d
AN
5255static int load_module_btfs(struct bpf_object *obj)
5256{
5257 struct bpf_btf_info info;
5258 struct module_btf *mod_btf;
5259 struct btf *btf;
5260 char name[64];
5261 __u32 id = 0, len;
5262 int err, fd;
5263
5264 if (obj->btf_modules_loaded)
5265 return 0;
5266
67234743
AS
5267 if (obj->gen_loader)
5268 return 0;
5269
4f33a53d
AN
5270 /* don't do this again, even if we find no module BTFs */
5271 obj->btf_modules_loaded = true;
5272
5273 /* kernel too old to support module BTFs */
9ca1f56a 5274 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4f33a53d
AN
5275 return 0;
5276
5277 while (true) {
5278 err = bpf_btf_get_next_id(id, &id);
5279 if (err && errno == ENOENT)
5280 return 0;
5281 if (err) {
5282 err = -errno;
5283 pr_warn("failed to iterate BTF objects: %d\n", err);
5284 return err;
ddc7c304 5285 }
4f33a53d
AN
5286
5287 fd = bpf_btf_get_fd_by_id(id);
5288 if (fd < 0) {
5289 if (errno == ENOENT)
5290 continue; /* expected race: BTF was unloaded */
5291 err = -errno;
5292 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5293 return err;
5294 }
5295
5296 len = sizeof(info);
5297 memset(&info, 0, sizeof(info));
5298 info.name = ptr_to_u64(name);
5299 info.name_len = sizeof(name);
5300
5301 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5302 if (err) {
5303 err = -errno;
5304 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
91abb4a6 5305 goto err_out;
4f33a53d
AN
5306 }
5307
5308 /* ignore non-module BTFs */
5309 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5310 close(fd);
5311 continue;
5312 }
5313
5314 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
e9fc3ce9
AN
5315 err = libbpf_get_error(btf);
5316 if (err) {
5317 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5318 name, id, err);
91abb4a6 5319 goto err_out;
4f33a53d
AN
5320 }
5321
3b029e06
AN
5322 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5323 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4f33a53d 5324 if (err)
91abb4a6 5325 goto err_out;
4f33a53d
AN
5326
5327 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5328
5329 mod_btf->btf = btf;
5330 mod_btf->id = id;
91abb4a6 5331 mod_btf->fd = fd;
4f33a53d 5332 mod_btf->name = strdup(name);
91abb4a6
AN
5333 if (!mod_btf->name) {
5334 err = -ENOMEM;
5335 goto err_out;
5336 }
5337 continue;
5338
5339err_out:
5340 close(fd);
5341 return err;
ddc7c304 5342 }
4f33a53d
AN
5343
5344 return 0;
5345}
5346
301ba4d7 5347static struct bpf_core_cand_list *
0f7515ca
AN
5348bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5349{
301ba4d7
AS
5350 struct bpf_core_cand local_cand = {};
5351 struct bpf_core_cand_list *cands;
4f33a53d 5352 const struct btf *main_btf;
03d5b991
AN
5353 const struct btf_type *local_t;
5354 const char *local_name;
0f7515ca 5355 size_t local_essent_len;
4f33a53d 5356 int err, i;
0f7515ca
AN
5357
5358 local_cand.btf = local_btf;
03d5b991
AN
5359 local_cand.id = local_type_id;
5360 local_t = btf__type_by_id(local_btf, local_type_id);
5361 if (!local_t)
0f7515ca
AN
5362 return ERR_PTR(-EINVAL);
5363
03d5b991
AN
5364 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5365 if (str_is_empty(local_name))
0f7515ca 5366 return ERR_PTR(-EINVAL);
03d5b991 5367 local_essent_len = bpf_core_essential_name_len(local_name);
0f7515ca
AN
5368
5369 cands = calloc(1, sizeof(*cands));
5370 if (!cands)
5371 return ERR_PTR(-ENOMEM);
5372
5373 /* Attempt to find target candidates in vmlinux BTF first */
4f33a53d
AN
5374 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5375 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5376 if (err)
5377 goto err_out;
5378
5379 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5380 if (cands->len)
5381 return cands;
5382
5383 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5384 if (obj->btf_vmlinux_override)
5385 return cands;
5386
5387 /* now look through module BTFs, trying to still find candidates */
5388 err = load_module_btfs(obj);
5389 if (err)
5390 goto err_out;
5391
5392 for (i = 0; i < obj->btf_module_cnt; i++) {
5393 err = bpf_core_add_cands(&local_cand, local_essent_len,
5394 obj->btf_modules[i].btf,
5395 obj->btf_modules[i].name,
6a886de0 5396 btf__type_cnt(obj->btf_vmlinux),
4f33a53d
AN
5397 cands);
5398 if (err)
5399 goto err_out;
0f7515ca
AN
5400 }
5401
5402 return cands;
ddc7c304 5403err_out:
4f33a53d 5404 bpf_core_free_cands(cands);
ddc7c304
AN
5405 return ERR_PTR(err);
5406}
5407
3fc32f40
AN
5408/* Check local and target types for compatibility. This check is used for
5409 * type-based CO-RE relocations and follow slightly different rules than
5410 * field-based relocations. This function assumes that root types were already
5411 * checked for name match. Beyond that initial root-level name check, names
5412 * are completely ignored. Compatibility rules are as follows:
5413 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5414 * kind should match for local and target types (i.e., STRUCT is not
5415 * compatible with UNION);
5416 * - for ENUMs, the size is ignored;
5417 * - for INT, size and signedness are ignored;
5418 * - for ARRAY, dimensionality is ignored, element types are checked for
5419 * compatibility recursively;
5420 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5421 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5422 * - FUNC_PROTOs are compatible if they have compatible signature: same
5423 * number of input args and compatible return and argument types.
5424 * These rules are not set in stone and probably will be adjusted as we get
5425 * more experience with using BPF CO-RE relocations.
5426 */
b0588390
AS
5427int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5428 const struct btf *targ_btf, __u32 targ_id)
3fc32f40
AN
5429{
5430 const struct btf_type *local_type, *targ_type;
5431 int depth = 32; /* max recursion depth */
5432
5433 /* caller made sure that names match (ignoring flavor suffix) */
5434 local_type = btf__type_by_id(local_btf, local_id);
f872e4bc 5435 targ_type = btf__type_by_id(targ_btf, targ_id);
3fc32f40
AN
5436 if (btf_kind(local_type) != btf_kind(targ_type))
5437 return 0;
5438
5439recur:
5440 depth--;
5441 if (depth < 0)
5442 return -EINVAL;
5443
5444 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5445 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5446 if (!local_type || !targ_type)
5447 return -EINVAL;
5448
5449 if (btf_kind(local_type) != btf_kind(targ_type))
5450 return 0;
5451
5452 switch (btf_kind(local_type)) {
5453 case BTF_KIND_UNKN:
5454 case BTF_KIND_STRUCT:
5455 case BTF_KIND_UNION:
5456 case BTF_KIND_ENUM:
5457 case BTF_KIND_FWD:
5458 return 1;
5459 case BTF_KIND_INT:
5460 /* just reject deprecated bitfield-like integers; all other
5461 * integers are by default compatible between each other
5462 */
5463 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5464 case BTF_KIND_PTR:
5465 local_id = local_type->type;
5466 targ_id = targ_type->type;
5467 goto recur;
5468 case BTF_KIND_ARRAY:
5469 local_id = btf_array(local_type)->type;
5470 targ_id = btf_array(targ_type)->type;
5471 goto recur;
5472 case BTF_KIND_FUNC_PROTO: {
5473 struct btf_param *local_p = btf_params(local_type);
5474 struct btf_param *targ_p = btf_params(targ_type);
5475 __u16 local_vlen = btf_vlen(local_type);
5476 __u16 targ_vlen = btf_vlen(targ_type);
5477 int i, err;
5478
5479 if (local_vlen != targ_vlen)
5480 return 0;
5481
5482 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5483 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5484 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5485 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5486 if (err <= 0)
5487 return err;
5488 }
5489
5490 /* tail recurse for return type check */
5491 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5492 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5493 goto recur;
5494 }
5495 default:
5496 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5497 btf_kind_str(local_type), local_id, targ_id);
5498 return 0;
5499 }
5500}
5501
ddc7c304
AN
5502static size_t bpf_core_hash_fn(const void *key, void *ctx)
5503{
5504 return (size_t)key;
5505}
5506
5507static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5508{
5509 return k1 == k2;
5510}
5511
5512static void *u32_as_hash_key(__u32 x)
5513{
5514 return (void *)(uintptr_t)x;
5515}
5516
d0e92887
AS
5517static int record_relo_core(struct bpf_program *prog,
5518 const struct bpf_core_relo *core_relo, int insn_idx)
5519{
5520 struct reloc_desc *relos, *relo;
5521
5522 relos = libbpf_reallocarray(prog->reloc_desc,
5523 prog->nr_reloc + 1, sizeof(*relos));
5524 if (!relos)
5525 return -ENOMEM;
5526 relo = &relos[prog->nr_reloc];
5527 relo->type = RELO_CORE;
5528 relo->insn_idx = insn_idx;
5529 relo->core_relo = core_relo;
5530 prog->reloc_desc = relos;
5531 prog->nr_reloc++;
5532 return 0;
5533}
5534
adb8fa19
MV
5535static int bpf_core_resolve_relo(struct bpf_program *prog,
5536 const struct bpf_core_relo *relo,
5537 int relo_idx,
5538 const struct btf *local_btf,
5539 struct hashmap *cand_cache,
5540 struct bpf_core_relo_res *targ_res)
3ee4f533 5541{
78c1f8d0 5542 struct bpf_core_spec specs_scratch[3] = {};
3ee4f533 5543 const void *type_key = u32_as_hash_key(relo->type_id);
301ba4d7 5544 struct bpf_core_cand_list *cands = NULL;
3ee4f533
AS
5545 const char *prog_name = prog->name;
5546 const struct btf_type *local_type;
5547 const char *local_name;
5548 __u32 local_id = relo->type_id;
adb8fa19 5549 int err;
3ee4f533
AS
5550
5551 local_type = btf__type_by_id(local_btf, local_id);
5552 if (!local_type)
5553 return -EINVAL;
5554
5555 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5556 if (!local_name)
5557 return -EINVAL;
5558
46334a0c 5559 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
3ee4f533
AS
5560 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5561 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5562 if (IS_ERR(cands)) {
5563 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5564 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5565 local_name, PTR_ERR(cands));
5566 return PTR_ERR(cands);
5567 }
5568 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5569 if (err) {
5570 bpf_core_free_cands(cands);
5571 return err;
5572 }
5573 }
5574
adb8fa19
MV
5575 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5576 targ_res);
3ee4f533
AS
5577}
5578
ddc7c304 5579static int
28b93c64 5580bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
ddc7c304
AN
5581{
5582 const struct btf_ext_info_sec *sec;
adb8fa19 5583 struct bpf_core_relo_res targ_res;
28b93c64 5584 const struct bpf_core_relo *rec;
ddc7c304
AN
5585 const struct btf_ext_info *seg;
5586 struct hashmap_entry *entry;
5587 struct hashmap *cand_cache = NULL;
5588 struct bpf_program *prog;
adb8fa19 5589 struct bpf_insn *insn;
ddc7c304 5590 const char *sec_name;
db2b8b06 5591 int i, err = 0, insn_idx, sec_idx;
ddc7c304 5592
28b93c64
AN
5593 if (obj->btf_ext->core_relo_info.len == 0)
5594 return 0;
5595
0f7515ca
AN
5596 if (targ_btf_path) {
5597 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
e9fc3ce9
AN
5598 err = libbpf_get_error(obj->btf_vmlinux_override);
5599 if (err) {
0f7515ca
AN
5600 pr_warn("failed to parse target BTF: %d\n", err);
5601 return err;
5602 }
ddc7c304
AN
5603 }
5604
5605 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5606 if (IS_ERR(cand_cache)) {
5607 err = PTR_ERR(cand_cache);
5608 goto out;
5609 }
5610
28b93c64 5611 seg = &obj->btf_ext->core_relo_info;
ddc7c304
AN
5612 for_each_btf_ext_sec(seg, sec) {
5613 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5614 if (str_is_empty(sec_name)) {
5615 err = -EINVAL;
5616 goto out;
5617 }
db2b8b06
AN
5618 /* bpf_object's ELF is gone by now so it's not easy to find
5619 * section index by section name, but we can find *any*
5620 * bpf_program within desired section name and use it's
5621 * prog->sec_idx to do a proper search by section index and
5622 * instruction offset
5623 */
9c82a63c
AN
5624 prog = NULL;
5625 for (i = 0; i < obj->nr_programs; i++) {
db2b8b06 5626 prog = &obj->programs[i];
52109584 5627 if (strcmp(prog->sec_name, sec_name) == 0)
9c82a63c 5628 break;
9c82a63c 5629 }
ddc7c304 5630 if (!prog) {
db2b8b06
AN
5631 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5632 return -ENOENT;
ddc7c304 5633 }
db2b8b06 5634 sec_idx = prog->sec_idx;
ddc7c304 5635
9c0f8cbd 5636 pr_debug("sec '%s': found %d CO-RE relocations\n",
ddc7c304
AN
5637 sec_name, sec->num_info);
5638
5639 for_each_btf_ext_rec(seg, sec, i, rec) {
adb8fa19
MV
5640 if (rec->insn_off % BPF_INSN_SZ)
5641 return -EINVAL;
db2b8b06
AN
5642 insn_idx = rec->insn_off / BPF_INSN_SZ;
5643 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5644 if (!prog) {
5645 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5646 sec_name, insn_idx, i);
5647 err = -EINVAL;
5648 goto out;
5649 }
47f7cf63
AN
5650 /* no need to apply CO-RE relocation if the program is
5651 * not going to be loaded
5652 */
5653 if (!prog->load)
5654 continue;
db2b8b06 5655
adb8fa19
MV
5656 /* adjust insn_idx from section frame of reference to the local
5657 * program's frame of reference; (sub-)program code is not yet
5658 * relocated, so it's enough to just subtract in-section offset
5659 */
5660 insn_idx = insn_idx - prog->sec_insn_off;
5661 if (insn_idx >= prog->insns_cnt)
5662 return -EINVAL;
5663 insn = &prog->insns[insn_idx];
5664
5665 if (prog->obj->gen_loader) {
5666 err = record_relo_core(prog, rec, insn_idx);
5667 if (err) {
5668 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5669 prog->name, i, err);
5670 goto out;
5671 }
5672 continue;
5673 }
5674
5675 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
ddc7c304 5676 if (err) {
be18010e 5677 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
9c0f8cbd 5678 prog->name, i, err);
ddc7c304
AN
5679 goto out;
5680 }
adb8fa19
MV
5681
5682 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5683 if (err) {
5684 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5685 prog->name, i, insn_idx, err);
5686 goto out;
5687 }
ddc7c304
AN
5688 }
5689 }
5690
5691out:
4f33a53d 5692 /* obj->btf_vmlinux and module BTFs are freed after object load */
0f7515ca
AN
5693 btf__free(obj->btf_vmlinux_override);
5694 obj->btf_vmlinux_override = NULL;
5695
ddc7c304
AN
5696 if (!IS_ERR_OR_NULL(cand_cache)) {
5697 hashmap__for_each_entry(cand_cache, entry, i) {
5698 bpf_core_free_cands(entry->value);
5699 }
5700 hashmap__free(cand_cache);
5701 }
5702 return err;
5703}
5704
c3c55696
AN
5705/* Relocate data references within program code:
5706 * - map references;
5707 * - global variable references;
5708 * - extern references.
5709 */
48cca7e4 5710static int
c3c55696 5711bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
8a47a6c5 5712{
c3c55696 5713 int i;
8a47a6c5
WN
5714
5715 for (i = 0; i < prog->nr_reloc; i++) {
53f8dd43 5716 struct reloc_desc *relo = &prog->reloc_desc[i];
166750bc 5717 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
2e33efe3 5718 struct extern_desc *ext;
8a47a6c5 5719
166750bc
AN
5720 switch (relo->type) {
5721 case RELO_LD64:
e2fa0156
AS
5722 if (obj->gen_loader) {
5723 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5724 insn[0].imm = relo->map_idx;
5725 } else {
5726 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5727 insn[0].imm = obj->maps[relo->map_idx].fd;
5728 }
166750bc
AN
5729 break;
5730 case RELO_DATA:
166750bc 5731 insn[1].imm = insn[0].imm + relo->sym_off;
e2fa0156
AS
5732 if (obj->gen_loader) {
5733 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5734 insn[0].imm = relo->map_idx;
5735 } else {
16e0c35c
AN
5736 const struct bpf_map *map = &obj->maps[relo->map_idx];
5737
229fae38 5738 if (map->skipped) {
16e0c35c
AN
5739 pr_warn("prog '%s': relo #%d: kernel doesn't support global data\n",
5740 prog->name, i);
5741 return -ENOTSUP;
5742 }
e2fa0156
AS
5743 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5744 insn[0].imm = obj->maps[relo->map_idx].fd;
5745 }
166750bc 5746 break;
0c091e5c 5747 case RELO_EXTERN_VAR:
2e33efe3 5748 ext = &obj->externs[relo->sym_off];
1c0c7074 5749 if (ext->type == EXT_KCFG) {
e2fa0156
AS
5750 if (obj->gen_loader) {
5751 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5752 insn[0].imm = obj->kconfig_map_idx;
5753 } else {
5754 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5755 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5756 }
1c0c7074
AN
5757 insn[1].imm = ext->kcfg.data_off;
5758 } else /* EXT_KSYM */ {
2211c825 5759 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
d370bbe1 5760 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
284d2587
AN
5761 insn[0].imm = ext->ksym.kernel_btf_id;
5762 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
2211c825 5763 } else { /* typeless ksyms or unresolved typed ksyms */
d370bbe1
HL
5764 insn[0].imm = (__u32)ext->ksym.addr;
5765 insn[1].imm = ext->ksym.addr >> 32;
5766 }
1c0c7074 5767 }
166750bc 5768 break;
5bd022ec
MKL
5769 case RELO_EXTERN_FUNC:
5770 ext = &obj->externs[relo->sym_off];
5771 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
466b2e13
KKD
5772 if (ext->is_set) {
5773 insn[0].imm = ext->ksym.kernel_btf_id;
5774 insn[0].off = ext->ksym.btf_fd_idx;
5775 } else { /* unresolved weak kfunc */
5776 insn[0].imm = 0;
5777 insn[0].off = 0;
5778 }
5bd022ec 5779 break;
53eddb5e 5780 case RELO_SUBPROG_ADDR:
b1268826
AS
5781 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5782 pr_warn("prog '%s': relo #%d: bad insn\n",
5783 prog->name, i);
5784 return -EINVAL;
5785 }
5786 /* handled already */
53eddb5e 5787 break;
166750bc 5788 case RELO_CALL:
b1268826 5789 /* handled already */
166750bc 5790 break;
d0e92887
AS
5791 case RELO_CORE:
5792 /* will be handled by bpf_program_record_relos() */
5793 break;
166750bc 5794 default:
9c0f8cbd
AN
5795 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5796 prog->name, i, relo->type);
166750bc 5797 return -EINVAL;
8a47a6c5 5798 }
8a47a6c5
WN
5799 }
5800
c3c55696
AN
5801 return 0;
5802}
5803
8505e870
AN
5804static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5805 const struct bpf_program *prog,
5806 const struct btf_ext_info *ext_info,
5807 void **prog_info, __u32 *prog_rec_cnt,
5808 __u32 *prog_rec_sz)
5809{
5810 void *copy_start = NULL, *copy_end = NULL;
5811 void *rec, *rec_end, *new_prog_info;
5812 const struct btf_ext_info_sec *sec;
5813 size_t old_sz, new_sz;
5814 const char *sec_name;
5815 int i, off_adj;
5816
5817 for_each_btf_ext_sec(ext_info, sec) {
5818 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5819 if (!sec_name)
5820 return -EINVAL;
52109584 5821 if (strcmp(sec_name, prog->sec_name) != 0)
8505e870
AN
5822 continue;
5823
5824 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5825 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5826
5827 if (insn_off < prog->sec_insn_off)
5828 continue;
5829 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5830 break;
5831
5832 if (!copy_start)
5833 copy_start = rec;
5834 copy_end = rec + ext_info->rec_size;
5835 }
5836
5837 if (!copy_start)
5838 return -ENOENT;
5839
5840 /* append func/line info of a given (sub-)program to the main
5841 * program func/line info
5842 */
8eb62958 5843 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
8505e870
AN
5844 new_sz = old_sz + (copy_end - copy_start);
5845 new_prog_info = realloc(*prog_info, new_sz);
5846 if (!new_prog_info)
5847 return -ENOMEM;
5848 *prog_info = new_prog_info;
5849 *prog_rec_cnt = new_sz / ext_info->rec_size;
5850 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5851
5852 /* Kernel instruction offsets are in units of 8-byte
5853 * instructions, while .BTF.ext instruction offsets generated
5854 * by Clang are in units of bytes. So convert Clang offsets
5855 * into kernel offsets and adjust offset according to program
5856 * relocated position.
5857 */
5858 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5859 rec = new_prog_info + old_sz;
5860 rec_end = new_prog_info + new_sz;
5861 for (; rec < rec_end; rec += ext_info->rec_size) {
5862 __u32 *insn_off = rec;
5863
5864 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5865 }
5866 *prog_rec_sz = ext_info->rec_size;
5867 return 0;
5868 }
5869
5870 return -ENOENT;
5871}
5872
5873static int
5874reloc_prog_func_and_line_info(const struct bpf_object *obj,
5875 struct bpf_program *main_prog,
5876 const struct bpf_program *prog)
5877{
5878 int err;
5879
5880 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5881 * supprot func/line info
5882 */
9ca1f56a 5883 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
8505e870
AN
5884 return 0;
5885
5886 /* only attempt func info relocation if main program's func_info
5887 * relocation was successful
5888 */
5889 if (main_prog != prog && !main_prog->func_info)
5890 goto line_info;
5891
5892 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5893 &main_prog->func_info,
5894 &main_prog->func_info_cnt,
5895 &main_prog->func_info_rec_size);
5896 if (err) {
5897 if (err != -ENOENT) {
5898 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5899 prog->name, err);
5900 return err;
5901 }
5902 if (main_prog->func_info) {
5903 /*
5904 * Some info has already been found but has problem
5905 * in the last btf_ext reloc. Must have to error out.
5906 */
5907 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5908 return err;
5909 }
5910 /* Have problem loading the very first info. Ignore the rest. */
5911 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5912 prog->name);
5913 }
5914
5915line_info:
5916 /* don't relocate line info if main program's relocation failed */
5917 if (main_prog != prog && !main_prog->line_info)
5918 return 0;
5919
5920 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5921 &main_prog->line_info,
5922 &main_prog->line_info_cnt,
5923 &main_prog->line_info_rec_size);
5924 if (err) {
5925 if (err != -ENOENT) {
5926 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5927 prog->name, err);
5928 return err;
5929 }
5930 if (main_prog->line_info) {
5931 /*
5932 * Some info has already been found but has problem
5933 * in the last btf_ext reloc. Must have to error out.
5934 */
5935 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5936 return err;
5937 }
5938 /* Have problem loading the very first info. Ignore the rest. */
5939 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5940 prog->name);
5941 }
5942 return 0;
5943}
5944
c3c55696
AN
5945static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5946{
5947 size_t insn_idx = *(const size_t *)key;
5948 const struct reloc_desc *relo = elem;
5949
5950 if (insn_idx == relo->insn_idx)
5951 return 0;
5952 return insn_idx < relo->insn_idx ? -1 : 1;
5953}
5954
5955static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5956{
2a6a9bf2
AN
5957 if (!prog->nr_reloc)
5958 return NULL;
c3c55696
AN
5959 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5960 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5961}
5962
b1268826
AS
5963static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5964{
5965 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5966 struct reloc_desc *relos;
5967 int i;
5968
5969 if (main_prog == subprog)
5970 return 0;
5971 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5972 if (!relos)
5973 return -ENOMEM;
2a6a9bf2
AN
5974 if (subprog->nr_reloc)
5975 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5976 sizeof(*relos) * subprog->nr_reloc);
b1268826
AS
5977
5978 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5979 relos[i].insn_idx += subprog->sub_insn_off;
5980 /* After insn_idx adjustment the 'relos' array is still sorted
5981 * by insn_idx and doesn't break bsearch.
5982 */
5983 main_prog->reloc_desc = relos;
5984 main_prog->nr_reloc = new_cnt;
5985 return 0;
5986}
5987
c3c55696
AN
5988static int
5989bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5990 struct bpf_program *prog)
5991{
5992 size_t sub_insn_idx, insn_idx, new_cnt;
5993 struct bpf_program *subprog;
5994 struct bpf_insn *insns, *insn;
5995 struct reloc_desc *relo;
5996 int err;
5997
5998 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5999 if (err)
6000 return err;
6001
6002 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6003 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
53eddb5e 6004 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
c3c55696
AN
6005 continue;
6006
6007 relo = find_prog_insn_relo(prog, insn_idx);
b1268826
AS
6008 if (relo && relo->type == RELO_EXTERN_FUNC)
6009 /* kfunc relocations will be handled later
6010 * in bpf_object__relocate_data()
6011 */
6012 continue;
53eddb5e 6013 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
c3c55696
AN
6014 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6015 prog->name, insn_idx, relo->type);
6016 return -LIBBPF_ERRNO__RELOC;
6017 }
6018 if (relo) {
6019 /* sub-program instruction index is a combination of
6020 * an offset of a symbol pointed to by relocation and
6021 * call instruction's imm field; for global functions,
6022 * call always has imm = -1, but for static functions
6023 * relocation is against STT_SECTION and insn->imm
6024 * points to a start of a static function
53eddb5e
YS
6025 *
6026 * for subprog addr relocation, the relo->sym_off + insn->imm is
6027 * the byte offset in the corresponding section.
c3c55696 6028 */
53eddb5e
YS
6029 if (relo->type == RELO_CALL)
6030 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6031 else
6032 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6033 } else if (insn_is_pseudo_func(insn)) {
6034 /*
6035 * RELO_SUBPROG_ADDR relo is always emitted even if both
6036 * functions are in the same section, so it shouldn't reach here.
6037 */
6038 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6039 prog->name, insn_idx);
6040 return -LIBBPF_ERRNO__RELOC;
c3c55696
AN
6041 } else {
6042 /* if subprogram call is to a static function within
6043 * the same ELF section, there won't be any relocation
6044 * emitted, but it also means there is no additional
6045 * offset necessary, insns->imm is relative to
6046 * instruction's original position within the section
6047 */
6048 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6049 }
6050
6051 /* we enforce that sub-programs should be in .text section */
6052 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6053 if (!subprog) {
6054 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6055 prog->name);
6056 return -LIBBPF_ERRNO__RELOC;
6057 }
6058
6059 /* if it's the first call instruction calling into this
6060 * subprogram (meaning this subprog hasn't been processed
6061 * yet) within the context of current main program:
6062 * - append it at the end of main program's instructions blog;
6063 * - process is recursively, while current program is put on hold;
6064 * - if that subprogram calls some other not yet processes
6065 * subprogram, same thing will happen recursively until
6066 * there are no more unprocesses subprograms left to append
6067 * and relocate.
6068 */
6069 if (subprog->sub_insn_off == 0) {
6070 subprog->sub_insn_off = main_prog->insns_cnt;
6071
6072 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6073 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6074 if (!insns) {
6075 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6076 return -ENOMEM;
6077 }
6078 main_prog->insns = insns;
6079 main_prog->insns_cnt = new_cnt;
6080
6081 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6082 subprog->insns_cnt * sizeof(*insns));
6083
6084 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6085 main_prog->name, subprog->insns_cnt, subprog->name);
6086
b1268826
AS
6087 /* The subprog insns are now appended. Append its relos too. */
6088 err = append_subprog_relos(main_prog, subprog);
6089 if (err)
6090 return err;
c3c55696
AN
6091 err = bpf_object__reloc_code(obj, main_prog, subprog);
6092 if (err)
6093 return err;
6094 }
6095
6096 /* main_prog->insns memory could have been re-allocated, so
6097 * calculate pointer again
6098 */
6099 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6100 /* calculate correct instruction position within current main
6101 * prog; each main prog can have a different set of
6102 * subprograms appended (potentially in different order as
6103 * well), so position of any subprog can be different for
6104 * different main programs */
6105 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6106
c3c55696
AN
6107 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6108 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6109 }
6110
6111 return 0;
6112}
6113
6114/*
6115 * Relocate sub-program calls.
6116 *
6117 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6118 * main prog) is processed separately. For each subprog (non-entry functions,
6119 * that can be called from either entry progs or other subprogs) gets their
6120 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6121 * hasn't been yet appended and relocated within current main prog. Once its
6122 * relocated, sub_insn_off will point at the position within current main prog
6123 * where given subprog was appended. This will further be used to relocate all
6124 * the call instructions jumping into this subprog.
6125 *
6126 * We start with main program and process all call instructions. If the call
6127 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6128 * is zero), subprog instructions are appended at the end of main program's
6129 * instruction array. Then main program is "put on hold" while we recursively
6130 * process newly appended subprogram. If that subprogram calls into another
6131 * subprogram that hasn't been appended, new subprogram is appended again to
6132 * the *main* prog's instructions (subprog's instructions are always left
6133 * untouched, as they need to be in unmodified state for subsequent main progs
6134 * and subprog instructions are always sent only as part of a main prog) and
6135 * the process continues recursively. Once all the subprogs called from a main
6136 * prog or any of its subprogs are appended (and relocated), all their
6137 * positions within finalized instructions array are known, so it's easy to
6138 * rewrite call instructions with correct relative offsets, corresponding to
6139 * desired target subprog.
6140 *
6141 * Its important to realize that some subprogs might not be called from some
6142 * main prog and any of its called/used subprogs. Those will keep their
6143 * subprog->sub_insn_off as zero at all times and won't be appended to current
6144 * main prog and won't be relocated within the context of current main prog.
6145 * They might still be used from other main progs later.
6146 *
6147 * Visually this process can be shown as below. Suppose we have two main
6148 * programs mainA and mainB and BPF object contains three subprogs: subA,
6149 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6150 * subC both call subB:
6151 *
6152 * +--------+ +-------+
6153 * | v v |
6154 * +--+---+ +--+-+-+ +---+--+
6155 * | subA | | subB | | subC |
6156 * +--+---+ +------+ +---+--+
6157 * ^ ^
6158 * | |
6159 * +---+-------+ +------+----+
6160 * | mainA | | mainB |
6161 * +-----------+ +-----------+
6162 *
6163 * We'll start relocating mainA, will find subA, append it and start
6164 * processing sub A recursively:
6165 *
6166 * +-----------+------+
6167 * | mainA | subA |
6168 * +-----------+------+
6169 *
6170 * At this point we notice that subB is used from subA, so we append it and
6171 * relocate (there are no further subcalls from subB):
6172 *
6173 * +-----------+------+------+
6174 * | mainA | subA | subB |
6175 * +-----------+------+------+
6176 *
6177 * At this point, we relocate subA calls, then go one level up and finish with
6178 * relocatin mainA calls. mainA is done.
6179 *
6180 * For mainB process is similar but results in different order. We start with
6181 * mainB and skip subA and subB, as mainB never calls them (at least
6182 * directly), but we see subC is needed, so we append and start processing it:
6183 *
6184 * +-----------+------+
6185 * | mainB | subC |
6186 * +-----------+------+
6187 * Now we see subC needs subB, so we go back to it, append and relocate it:
6188 *
6189 * +-----------+------+------+
6190 * | mainB | subC | subB |
6191 * +-----------+------+------+
6192 *
6193 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6194 */
6195static int
6196bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6197{
6198 struct bpf_program *subprog;
d3d93e34 6199 int i, err;
c3c55696 6200
c3c55696
AN
6201 /* mark all subprogs as not relocated (yet) within the context of
6202 * current main program
6203 */
6204 for (i = 0; i < obj->nr_programs; i++) {
6205 subprog = &obj->programs[i];
6206 if (!prog_is_subprog(obj, subprog))
6207 continue;
6208
6209 subprog->sub_insn_off = 0;
c3c55696
AN
6210 }
6211
6212 err = bpf_object__reloc_code(obj, prog, prog);
6213 if (err)
6214 return err;
6215
6216
8a47a6c5
WN
6217 return 0;
6218}
6219
67234743
AS
6220static void
6221bpf_object__free_relocs(struct bpf_object *obj)
6222{
6223 struct bpf_program *prog;
6224 int i;
6225
6226 /* free up relocation descriptors */
6227 for (i = 0; i < obj->nr_programs; i++) {
6228 prog = &obj->programs[i];
6229 zfree(&prog->reloc_desc);
6230 prog->nr_reloc = 0;
6231 }
6232}
6233
d0e92887
AS
6234static int cmp_relocs(const void *_a, const void *_b)
6235{
6236 const struct reloc_desc *a = _a;
6237 const struct reloc_desc *b = _b;
6238
6239 if (a->insn_idx != b->insn_idx)
6240 return a->insn_idx < b->insn_idx ? -1 : 1;
6241
6242 /* no two relocations should have the same insn_idx, but ... */
6243 if (a->type != b->type)
6244 return a->type < b->type ? -1 : 1;
6245
6246 return 0;
6247}
6248
6249static void bpf_object__sort_relos(struct bpf_object *obj)
6250{
6251 int i;
6252
6253 for (i = 0; i < obj->nr_programs; i++) {
6254 struct bpf_program *p = &obj->programs[i];
6255
6256 if (!p->nr_reloc)
6257 continue;
6258
6259 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6260 }
6261}
6262
8a47a6c5 6263static int
ddc7c304 6264bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
8a47a6c5
WN
6265{
6266 struct bpf_program *prog;
b1268826 6267 size_t i, j;
8a47a6c5
WN
6268 int err;
6269
ddc7c304
AN
6270 if (obj->btf_ext) {
6271 err = bpf_object__relocate_core(obj, targ_btf_path);
6272 if (err) {
be18010e
KW
6273 pr_warn("failed to perform CO-RE relocations: %d\n",
6274 err);
ddc7c304
AN
6275 return err;
6276 }
d0e92887
AS
6277 if (obj->gen_loader)
6278 bpf_object__sort_relos(obj);
ddc7c304 6279 }
b1268826
AS
6280
6281 /* Before relocating calls pre-process relocations and mark
6282 * few ld_imm64 instructions that points to subprogs.
6283 * Otherwise bpf_object__reloc_code() later would have to consider
6284 * all ld_imm64 insns as relocation candidates. That would
6285 * reduce relocation speed, since amount of find_prog_insn_relo()
6286 * would increase and most of them will fail to find a relo.
9173cac3
AN
6287 */
6288 for (i = 0; i < obj->nr_programs; i++) {
6289 prog = &obj->programs[i];
b1268826
AS
6290 for (j = 0; j < prog->nr_reloc; j++) {
6291 struct reloc_desc *relo = &prog->reloc_desc[j];
6292 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6293
6294 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6295 if (relo->type == RELO_SUBPROG_ADDR)
6296 insn[0].src_reg = BPF_PSEUDO_FUNC;
9173cac3 6297 }
9173cac3 6298 }
b1268826
AS
6299
6300 /* relocate subprogram calls and append used subprograms to main
c3c55696
AN
6301 * programs; each copy of subprogram code needs to be relocated
6302 * differently for each main program, because its code location might
b1268826
AS
6303 * have changed.
6304 * Append subprog relos to main programs to allow data relos to be
6305 * processed after text is completely relocated.
9173cac3 6306 */
8a47a6c5
WN
6307 for (i = 0; i < obj->nr_programs; i++) {
6308 prog = &obj->programs[i];
c3c55696
AN
6309 /* sub-program's sub-calls are relocated within the context of
6310 * its main program only
6311 */
6312 if (prog_is_subprog(obj, prog))
9173cac3 6313 continue;
16e0c35c
AN
6314 if (!prog->load)
6315 continue;
8a47a6c5 6316
c3c55696 6317 err = bpf_object__relocate_calls(obj, prog);
8a47a6c5 6318 if (err) {
9c0f8cbd
AN
6319 pr_warn("prog '%s': failed to relocate calls: %d\n",
6320 prog->name, err);
8a47a6c5
WN
6321 return err;
6322 }
6323 }
b1268826
AS
6324 /* Process data relos for main programs */
6325 for (i = 0; i < obj->nr_programs; i++) {
6326 prog = &obj->programs[i];
6327 if (prog_is_subprog(obj, prog))
6328 continue;
16e0c35c
AN
6329 if (!prog->load)
6330 continue;
b1268826
AS
6331 err = bpf_object__relocate_data(obj, prog);
6332 if (err) {
6333 pr_warn("prog '%s': failed to relocate data references: %d\n",
6334 prog->name, err);
6335 return err;
6336 }
6337 }
67234743
AS
6338 if (!obj->gen_loader)
6339 bpf_object__free_relocs(obj);
8a47a6c5
WN
6340 return 0;
6341}
6342
646f02ff 6343static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 6344 Elf64_Shdr *shdr, Elf_Data *data);
646f02ff
AN
6345
6346static int bpf_object__collect_map_relos(struct bpf_object *obj,
ad23b723 6347 Elf64_Shdr *shdr, Elf_Data *data)
646f02ff 6348{
15728ad3
AN
6349 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6350 int i, j, nrels, new_sz;
063e6881 6351 const struct btf_var_secinfo *vi = NULL;
646f02ff 6352 const struct btf_type *sec, *var, *def;
341ac5ff
HC
6353 struct bpf_map *map = NULL, *targ_map = NULL;
6354 struct bpf_program *targ_prog = NULL;
6355 bool is_prog_array, is_map_in_map;
646f02ff 6356 const struct btf_member *member;
341ac5ff 6357 const char *name, *mname, *type;
646f02ff 6358 unsigned int moff;
ad23b723
AN
6359 Elf64_Sym *sym;
6360 Elf64_Rel *rel;
646f02ff
AN
6361 void *tmp;
6362
6363 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6364 return -EINVAL;
6365 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6366 if (!sec)
6367 return -EINVAL;
6368
646f02ff
AN
6369 nrels = shdr->sh_size / shdr->sh_entsize;
6370 for (i = 0; i < nrels; i++) {
ad23b723
AN
6371 rel = elf_rel_by_idx(data, i);
6372 if (!rel) {
646f02ff
AN
6373 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6374 return -LIBBPF_ERRNO__FORMAT;
6375 }
ad23b723
AN
6376
6377 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6378 if (!sym) {
646f02ff 6379 pr_warn(".maps relo #%d: symbol %zx not found\n",
ad23b723 6380 i, (size_t)ELF64_R_SYM(rel->r_info));
646f02ff
AN
6381 return -LIBBPF_ERRNO__FORMAT;
6382 }
ad23b723 6383 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
646f02ff 6384
ad23b723
AN
6385 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6386 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6387 (size_t)rel->r_offset, sym->st_name, name);
646f02ff
AN
6388
6389 for (j = 0; j < obj->nr_maps; j++) {
6390 map = &obj->maps[j];
6391 if (map->sec_idx != obj->efile.btf_maps_shndx)
6392 continue;
6393
6394 vi = btf_var_secinfos(sec) + map->btf_var_idx;
ad23b723
AN
6395 if (vi->offset <= rel->r_offset &&
6396 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
646f02ff
AN
6397 break;
6398 }
6399 if (j == obj->nr_maps) {
ad23b723
AN
6400 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6401 i, name, (size_t)rel->r_offset);
646f02ff
AN
6402 return -EINVAL;
6403 }
6404
341ac5ff
HC
6405 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6406 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6407 type = is_map_in_map ? "map" : "prog";
6408 if (is_map_in_map) {
6409 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6410 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6411 i, name);
6412 return -LIBBPF_ERRNO__RELOC;
6413 }
6414 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6415 map->def.key_size != sizeof(int)) {
6416 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6417 i, map->name, sizeof(int));
6418 return -EINVAL;
6419 }
6420 targ_map = bpf_object__find_map_by_name(obj, name);
6421 if (!targ_map) {
6422 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6423 i, name);
6424 return -ESRCH;
6425 }
6426 } else if (is_prog_array) {
6427 targ_prog = bpf_object__find_program_by_name(obj, name);
6428 if (!targ_prog) {
6429 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6430 i, name);
6431 return -ESRCH;
6432 }
6433 if (targ_prog->sec_idx != sym->st_shndx ||
6434 targ_prog->sec_insn_off * 8 != sym->st_value ||
6435 prog_is_subprog(obj, targ_prog)) {
6436 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6437 i, name);
6438 return -LIBBPF_ERRNO__RELOC;
6439 }
6440 } else {
646f02ff
AN
6441 return -EINVAL;
6442 }
6443
646f02ff
AN
6444 var = btf__type_by_id(obj->btf, vi->type);
6445 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6446 if (btf_vlen(def) == 0)
6447 return -EINVAL;
6448 member = btf_members(def) + btf_vlen(def) - 1;
6449 mname = btf__name_by_offset(obj->btf, member->name_off);
6450 if (strcmp(mname, "values"))
6451 return -EINVAL;
6452
6453 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
ad23b723 6454 if (rel->r_offset - vi->offset < moff)
646f02ff
AN
6455 return -EINVAL;
6456
ad23b723 6457 moff = rel->r_offset - vi->offset - moff;
15728ad3
AN
6458 /* here we use BPF pointer size, which is always 64 bit, as we
6459 * are parsing ELF that was built for BPF target
6460 */
6461 if (moff % bpf_ptr_sz)
646f02ff 6462 return -EINVAL;
15728ad3 6463 moff /= bpf_ptr_sz;
646f02ff
AN
6464 if (moff >= map->init_slots_sz) {
6465 new_sz = moff + 1;
029258d7 6466 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
646f02ff
AN
6467 if (!tmp)
6468 return -ENOMEM;
6469 map->init_slots = tmp;
6470 memset(map->init_slots + map->init_slots_sz, 0,
15728ad3 6471 (new_sz - map->init_slots_sz) * host_ptr_sz);
646f02ff
AN
6472 map->init_slots_sz = new_sz;
6473 }
341ac5ff 6474 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
646f02ff 6475
341ac5ff
HC
6476 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6477 i, map->name, moff, type, name);
646f02ff
AN
6478 }
6479
6480 return 0;
6481}
590a0088 6482
c3c55696
AN
6483static int bpf_object__collect_relos(struct bpf_object *obj)
6484{
6485 int i, err;
34090915 6486
25bbbd7a
AN
6487 for (i = 0; i < obj->efile.sec_cnt; i++) {
6488 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6489 Elf64_Shdr *shdr;
6490 Elf_Data *data;
6491 int idx;
6492
6493 if (sec_desc->sec_type != SEC_RELO)
6494 continue;
6495
6496 shdr = sec_desc->shdr;
6497 data = sec_desc->data;
6498 idx = shdr->sh_info;
34090915
WN
6499
6500 if (shdr->sh_type != SHT_REL) {
be18010e 6501 pr_warn("internal error at %d\n", __LINE__);
6371ca3b 6502 return -LIBBPF_ERRNO__INTERNAL;
34090915
WN
6503 }
6504
c3c55696 6505 if (idx == obj->efile.st_ops_shndx)
646f02ff 6506 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
c3c55696 6507 else if (idx == obj->efile.btf_maps_shndx)
646f02ff 6508 err = bpf_object__collect_map_relos(obj, shdr, data);
c3c55696
AN
6509 else
6510 err = bpf_object__collect_prog_relos(obj, shdr, data);
34090915 6511 if (err)
6371ca3b 6512 return err;
34090915 6513 }
c3c55696 6514
d0e92887 6515 bpf_object__sort_relos(obj);
34090915
WN
6516 return 0;
6517}
6518
109cea5a
AN
6519static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6520{
9b2f6fec 6521 if (BPF_CLASS(insn->code) == BPF_JMP &&
109cea5a
AN
6522 BPF_OP(insn->code) == BPF_CALL &&
6523 BPF_SRC(insn->code) == BPF_K &&
9b2f6fec
AN
6524 insn->src_reg == 0 &&
6525 insn->dst_reg == 0) {
6526 *func_id = insn->imm;
109cea5a
AN
6527 return true;
6528 }
6529 return false;
6530}
6531
42869d28 6532static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
109cea5a
AN
6533{
6534 struct bpf_insn *insn = prog->insns;
6535 enum bpf_func_id func_id;
6536 int i;
6537
67234743
AS
6538 if (obj->gen_loader)
6539 return 0;
6540
109cea5a
AN
6541 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6542 if (!insn_is_helper_call(insn, &func_id))
6543 continue;
6544
6545 /* on kernels that don't yet support
6546 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6547 * to bpf_probe_read() which works well for old kernels
6548 */
6549 switch (func_id) {
6550 case BPF_FUNC_probe_read_kernel:
6551 case BPF_FUNC_probe_read_user:
9ca1f56a 6552 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6553 insn->imm = BPF_FUNC_probe_read;
6554 break;
6555 case BPF_FUNC_probe_read_kernel_str:
6556 case BPF_FUNC_probe_read_user_str:
9ca1f56a 6557 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6558 insn->imm = BPF_FUNC_probe_read_str;
6559 break;
6560 default:
6561 break;
6562 }
6563 }
6564 return 0;
6565}
6566
15ea31fa
AN
6567static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6568 int *btf_obj_fd, int *btf_type_id);
12d9466d 6569
4fa5bcfe
AN
6570/* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6571static int libbpf_prepare_prog_load(struct bpf_program *prog,
6572 struct bpf_prog_load_opts *opts, long cookie)
12d9466d 6573{
15ea31fa
AN
6574 enum sec_def_flags def = cookie;
6575
12d9466d 6576 /* old kernels might not support specifying expected_attach_type */
15ea31fa 6577 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
d10ef2b8 6578 opts->expected_attach_type = 0;
12d9466d 6579
15ea31fa 6580 if (def & SEC_SLEEPABLE)
d10ef2b8 6581 opts->prog_flags |= BPF_F_SLEEPABLE;
12d9466d 6582
082c4bfb
LB
6583 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6584 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6585
4a4d4cee
LB
6586 if (def & SEC_DEPRECATED)
6587 pr_warn("SEC(\"%s\") is deprecated, please see https://github.com/libbpf/libbpf/wiki/Libbpf-1.0-migration-guide#bpf-program-sec-annotation-deprecations for details\n",
6588 prog->sec_name);
6589
12d9466d
AN
6590 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6591 prog->type == BPF_PROG_TYPE_LSM ||
6592 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6593 int btf_obj_fd = 0, btf_type_id = 0, err;
15ea31fa 6594 const char *attach_name;
12d9466d 6595
15ea31fa
AN
6596 attach_name = strchr(prog->sec_name, '/') + 1;
6597 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
12d9466d
AN
6598 if (err)
6599 return err;
6600
6601 /* cache resolved BTF FD and BTF type ID in the prog */
6602 prog->attach_btf_obj_fd = btf_obj_fd;
6603 prog->attach_btf_id = btf_type_id;
6604
6605 /* but by now libbpf common logic is not utilizing
6606 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
d10ef2b8
AN
6607 * this callback is called after opts were populated by
6608 * libbpf, so this callback has to update opts explicitly here
12d9466d 6609 */
d10ef2b8
AN
6610 opts->attach_btf_obj_fd = btf_obj_fd;
6611 opts->attach_btf_id = btf_type_id;
12d9466d
AN
6612 }
6613 return 0;
6614}
6615
be2f2d16
AN
6616static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6617 struct bpf_insn *insns, int insns_cnt,
6618 const char *license, __u32 kern_version,
6619 int *prog_fd)
55cffde2 6620{
d10ef2b8
AN
6621 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6622 const char *prog_name = NULL;
1ce6a9fc 6623 char *cp, errmsg[STRERR_BUFSIZE];
8395f320 6624 size_t log_buf_size = 0;
b3ce9079 6625 char *log_buf = NULL, *tmp;
12d9466d 6626 int btf_fd, ret, err;
b3ce9079
AN
6627 bool own_log_buf = true;
6628 __u32 log_level = prog->log_level;
55cffde2 6629
80b2b5c3
AM
6630 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6631 /*
6632 * The program type must be set. Most likely we couldn't find a proper
6633 * section definition at load time, and thus we didn't infer the type.
6634 */
6635 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6636 prog->name, prog->sec_name);
6637 return -EINVAL;
6638 }
6639
fba01a06
AN
6640 if (!insns || !insns_cnt)
6641 return -EINVAL;
6642
12d9466d 6643 load_attr.expected_attach_type = prog->expected_attach_type;
25bbbd7a 6644 if (kernel_supports(obj, FEAT_PROG_NAME))
d10ef2b8 6645 prog_name = prog->name;
12d9466d
AN
6646 load_attr.attach_prog_fd = prog->attach_prog_fd;
6647 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6aef10a4
AN
6648 load_attr.attach_btf_id = prog->attach_btf_id;
6649 load_attr.kern_version = kern_version;
6650 load_attr.prog_ifindex = prog->prog_ifindex;
6651
0f0e55d8 6652 /* specify func_info/line_info only if kernel supports them */
25bbbd7a
AN
6653 btf_fd = bpf_object__btf_fd(obj);
6654 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
0f0e55d8
AN
6655 load_attr.prog_btf_fd = btf_fd;
6656 load_attr.func_info = prog->func_info;
6657 load_attr.func_info_rec_size = prog->func_info_rec_size;
6658 load_attr.func_info_cnt = prog->func_info_cnt;
6659 load_attr.line_info = prog->line_info;
6660 load_attr.line_info_rec_size = prog->line_info_rec_size;
6661 load_attr.line_info_cnt = prog->line_info_cnt;
6662 }
b3ce9079 6663 load_attr.log_level = log_level;
04656198 6664 load_attr.prog_flags = prog->prog_flags;
25bbbd7a 6665 load_attr.fd_array = obj->fd_array;
55cffde2 6666
12d9466d 6667 /* adjust load_attr if sec_def provides custom preload callback */
4fa5bcfe
AN
6668 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6669 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
12d9466d
AN
6670 if (err < 0) {
6671 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6672 prog->name, err);
6673 return err;
6674 }
6675 }
6676
25bbbd7a 6677 if (obj->gen_loader) {
d10ef2b8
AN
6678 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6679 license, insns, insns_cnt, &load_attr,
25bbbd7a 6680 prog - obj->programs);
be2f2d16 6681 *prog_fd = -1;
67234743
AS
6682 return 0;
6683 }
8395f320 6684
b3ce9079
AN
6685retry_load:
6686 /* if log_level is zero, we don't request logs initiallly even if
6687 * custom log_buf is specified; if the program load fails, then we'll
6688 * bump log_level to 1 and use either custom log_buf or we'll allocate
6689 * our own and retry the load to get details on what failed
6690 */
6691 if (log_level) {
6692 if (prog->log_buf) {
6693 log_buf = prog->log_buf;
6694 log_buf_size = prog->log_size;
6695 own_log_buf = false;
6696 } else if (obj->log_buf) {
6697 log_buf = obj->log_buf;
6698 log_buf_size = obj->log_size;
6699 own_log_buf = false;
6700 } else {
6701 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6702 tmp = realloc(log_buf, log_buf_size);
6703 if (!tmp) {
6704 ret = -ENOMEM;
6705 goto out;
6706 }
6707 log_buf = tmp;
6708 log_buf[0] = '\0';
6709 own_log_buf = true;
6710 }
8395f320 6711 }
55cffde2 6712
6aef10a4 6713 load_attr.log_buf = log_buf;
d10ef2b8 6714 load_attr.log_size = log_buf_size;
b3ce9079 6715 load_attr.log_level = log_level;
55cffde2 6716
b3ce9079 6717 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
55cffde2 6718 if (ret >= 0) {
b3ce9079 6719 if (log_level && own_log_buf) {
ad9a7f96
AN
6720 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6721 prog->name, log_buf);
6722 }
5d23328d 6723
25bbbd7a
AN
6724 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6725 struct bpf_map *map;
6726 int i;
6727
6728 for (i = 0; i < obj->nr_maps; i++) {
6729 map = &prog->obj->maps[i];
6730 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6731 continue;
5d23328d 6732
25bbbd7a
AN
6733 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6734 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96
AN
6735 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6736 prog->name, map->real_name, cp);
25bbbd7a
AN
6737 /* Don't fail hard if can't bind rodata. */
6738 }
5d23328d
YZ
6739 }
6740 }
6741
be2f2d16 6742 *prog_fd = ret;
55cffde2
WN
6743 ret = 0;
6744 goto out;
6745 }
6746
b3ce9079
AN
6747 if (log_level == 0) {
6748 log_level = 1;
da11b417
AS
6749 goto retry_load;
6750 }
b3ce9079
AN
6751 /* On ENOSPC, increase log buffer size and retry, unless custom
6752 * log_buf is specified.
6753 * Be careful to not overflow u32, though. Kernel's log buf size limit
6754 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6755 * multiply by 2 unless we are sure we'll fit within 32 bits.
6756 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6757 */
6758 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6759 goto retry_load;
2eda2145
AN
6760
6761 ret = -errno;
24d6a808 6762 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96 6763 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
dc3a2d25 6764 pr_perm_msg(ret);
55cffde2 6765
b3ce9079 6766 if (own_log_buf && log_buf && log_buf[0] != '\0') {
ad9a7f96
AN
6767 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6768 prog->name, log_buf);
6769 }
6770 if (insns_cnt >= BPF_MAXINSNS) {
6771 pr_warn("prog '%s': program too large (%d insns), at most %d insns\n",
6772 prog->name, insns_cnt, BPF_MAXINSNS);
55cffde2
WN
6773 }
6774
6775out:
b3ce9079
AN
6776 if (own_log_buf)
6777 free(log_buf);
55cffde2
WN
6778 return ret;
6779}
6780
d0e92887 6781static int bpf_program_record_relos(struct bpf_program *prog)
67234743
AS
6782{
6783 struct bpf_object *obj = prog->obj;
6784 int i;
6785
6786 for (i = 0; i < prog->nr_reloc; i++) {
6787 struct reloc_desc *relo = &prog->reloc_desc[i];
6788 struct extern_desc *ext = &obj->externs[relo->sym_off];
6789
6790 switch (relo->type) {
6791 case RELO_EXTERN_VAR:
6792 if (ext->type != EXT_KSYM)
6793 continue;
c24941cd
KKD
6794 bpf_gen__record_extern(obj->gen_loader, ext->name,
6795 ext->is_weak, !ext->ksym.type_id,
18f4fccb 6796 BTF_KIND_VAR, relo->insn_idx);
67234743
AS
6797 break;
6798 case RELO_EXTERN_FUNC:
c24941cd
KKD
6799 bpf_gen__record_extern(obj->gen_loader, ext->name,
6800 ext->is_weak, false, BTF_KIND_FUNC,
67234743
AS
6801 relo->insn_idx);
6802 break;
d0e92887
AS
6803 case RELO_CORE: {
6804 struct bpf_core_relo cr = {
6805 .insn_off = relo->insn_idx * 8,
6806 .type_id = relo->core_relo->type_id,
6807 .access_str_off = relo->core_relo->access_str_off,
6808 .kind = relo->core_relo->kind,
6809 };
6810
6811 bpf_gen__record_relo_core(obj->gen_loader, &cr);
6812 break;
6813 }
67234743
AS
6814 default:
6815 continue;
6816 }
6817 }
6818 return 0;
6819}
6820
be2f2d16
AN
6821static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6822 const char *license, __u32 kern_ver)
55cffde2 6823{
91abb4a6 6824 int err = 0, fd, i;
13acb508 6825
be2f2d16 6826 if (obj->loaded) {
52109584 6827 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
e9fc3ce9 6828 return libbpf_err(-EINVAL);
d9297581
AN
6829 }
6830
b580563e
WN
6831 if (prog->instances.nr < 0 || !prog->instances.fds) {
6832 if (prog->preprocessor) {
be18010e 6833 pr_warn("Internal error: can't load program '%s'\n",
52109584 6834 prog->name);
e9fc3ce9 6835 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
b580563e 6836 }
55cffde2 6837
b580563e
WN
6838 prog->instances.fds = malloc(sizeof(int));
6839 if (!prog->instances.fds) {
be18010e 6840 pr_warn("Not enough memory for BPF fds\n");
e9fc3ce9 6841 return libbpf_err(-ENOMEM);
b580563e
WN
6842 }
6843 prog->instances.nr = 1;
6844 prog->instances.fds[0] = -1;
6845 }
6846
6847 if (!prog->preprocessor) {
6848 if (prog->instances.nr != 1) {
52109584
AN
6849 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6850 prog->name, prog->instances.nr);
b580563e 6851 }
be2f2d16 6852 if (obj->gen_loader)
d0e92887 6853 bpf_program_record_relos(prog);
be2f2d16
AN
6854 err = bpf_object_load_prog_instance(obj, prog,
6855 prog->insns, prog->insns_cnt,
6856 license, kern_ver, &fd);
b580563e
WN
6857 if (!err)
6858 prog->instances.fds[0] = fd;
6859 goto out;
6860 }
6861
6862 for (i = 0; i < prog->instances.nr; i++) {
6863 struct bpf_prog_prep_result result;
6864 bpf_program_prep_t preprocessor = prog->preprocessor;
6865
1ad9cbb8 6866 memset(&result, 0, sizeof(result));
b580563e
WN
6867 err = preprocessor(prog, i, prog->insns,
6868 prog->insns_cnt, &result);
6869 if (err) {
be18010e 6870 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
52109584 6871 i, prog->name);
b580563e
WN
6872 goto out;
6873 }
6874
6875 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6876 pr_debug("Skip loading the %dth instance of program '%s'\n",
52109584 6877 i, prog->name);
b580563e
WN
6878 prog->instances.fds[i] = -1;
6879 if (result.pfd)
6880 *result.pfd = -1;
6881 continue;
6882 }
6883
be2f2d16
AN
6884 err = bpf_object_load_prog_instance(obj, prog,
6885 result.new_insn_ptr, result.new_insn_cnt,
6886 license, kern_ver, &fd);
b580563e 6887 if (err) {
be18010e 6888 pr_warn("Loading the %dth instance of program '%s' failed\n",
52109584 6889 i, prog->name);
b580563e
WN
6890 goto out;
6891 }
6892
6893 if (result.pfd)
6894 *result.pfd = fd;
6895 prog->instances.fds[i] = fd;
6896 }
6897out:
55cffde2 6898 if (err)
52109584 6899 pr_warn("failed to load program '%s'\n", prog->name);
e9fc3ce9 6900 return libbpf_err(err);
55cffde2
WN
6901}
6902
be2f2d16
AN
6903int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
6904{
6905 return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
6906}
6907
55cffde2 6908static int
60276f98 6909bpf_object__load_progs(struct bpf_object *obj, int log_level)
55cffde2 6910{
d9297581 6911 struct bpf_program *prog;
55cffde2
WN
6912 size_t i;
6913 int err;
6914
109cea5a
AN
6915 for (i = 0; i < obj->nr_programs; i++) {
6916 prog = &obj->programs[i];
6917 err = bpf_object__sanitize_prog(obj, prog);
6918 if (err)
6919 return err;
6920 }
6921
55cffde2 6922 for (i = 0; i < obj->nr_programs; i++) {
d9297581 6923 prog = &obj->programs[i];
c3c55696 6924 if (prog_is_subprog(obj, prog))
48cca7e4 6925 continue;
d9297581 6926 if (!prog->load) {
9c0f8cbd 6927 pr_debug("prog '%s': skipped loading\n", prog->name);
d9297581
AN
6928 continue;
6929 }
6930 prog->log_level |= log_level;
be2f2d16 6931 err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
55cffde2
WN
6932 if (err)
6933 return err;
6934 }
67234743
AS
6935 if (obj->gen_loader)
6936 bpf_object__free_relocs(obj);
55cffde2
WN
6937 return 0;
6938}
6939
25498a19
AN
6940static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6941
91b4d1d1
AN
6942static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
6943{
6944 struct bpf_program *prog;
12d9466d 6945 int err;
91b4d1d1
AN
6946
6947 bpf_object__for_each_program(prog, obj) {
6948 prog->sec_def = find_sec_def(prog->sec_name);
6949 if (!prog->sec_def) {
6950 /* couldn't guess, but user might manually specify */
6951 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6952 prog->name, prog->sec_name);
6953 continue;
6954 }
6955
91b4d1d1
AN
6956 bpf_program__set_type(prog, prog->sec_def->prog_type);
6957 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type);
6958
91b555d7
AN
6959#pragma GCC diagnostic push
6960#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
91b4d1d1
AN
6961 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6962 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6963 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
91b555d7 6964#pragma GCC diagnostic pop
12d9466d
AN
6965
6966 /* sec_def can have custom callback which should be called
6967 * after bpf_program is initialized to adjust its properties
6968 */
4fa5bcfe
AN
6969 if (prog->sec_def->prog_setup_fn) {
6970 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
12d9466d
AN
6971 if (err < 0) {
6972 pr_warn("prog '%s': failed to initialize: %d\n",
6973 prog->name, err);
6974 return err;
6975 }
6976 }
91b4d1d1
AN
6977 }
6978
6979 return 0;
6980}
6981
ad9a7f96
AN
6982static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6983 const struct bpf_object_open_opts *opts)
1a5e3fb1 6984{
1373ff59 6985 const char *obj_name, *kconfig, *btf_tmp_path;
1a5e3fb1 6986 struct bpf_object *obj;
291ee02b 6987 char tmp_name[64];
6371ca3b 6988 int err;
e0e3ea88
AN
6989 char *log_buf;
6990 size_t log_size;
6991 __u32 log_level;
1a5e3fb1
WN
6992
6993 if (elf_version(EV_CURRENT) == EV_NONE) {
be18010e
KW
6994 pr_warn("failed to init libelf for %s\n",
6995 path ? : "(mem buf)");
6371ca3b 6996 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1a5e3fb1
WN
6997 }
6998
291ee02b
AN
6999 if (!OPTS_VALID(opts, bpf_object_open_opts))
7000 return ERR_PTR(-EINVAL);
7001
1aace10f 7002 obj_name = OPTS_GET(opts, object_name, NULL);
291ee02b
AN
7003 if (obj_buf) {
7004 if (!obj_name) {
7005 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7006 (unsigned long)obj_buf,
7007 (unsigned long)obj_buf_sz);
7008 obj_name = tmp_name;
7009 }
7010 path = obj_name;
7011 pr_debug("loading object '%s' from buffer\n", obj_name);
7012 }
7013
e0e3ea88
AN
7014 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7015 log_size = OPTS_GET(opts, kernel_log_size, 0);
7016 log_level = OPTS_GET(opts, kernel_log_level, 0);
7017 if (log_size > UINT_MAX)
7018 return ERR_PTR(-EINVAL);
7019 if (log_size && !log_buf)
7020 return ERR_PTR(-EINVAL);
7021
2ce8450e 7022 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6371ca3b
WN
7023 if (IS_ERR(obj))
7024 return obj;
1a5e3fb1 7025
e0e3ea88
AN
7026 obj->log_buf = log_buf;
7027 obj->log_size = log_size;
7028 obj->log_level = log_level;
7029
1373ff59
SC
7030 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7031 if (btf_tmp_path) {
7032 if (strlen(btf_tmp_path) >= PATH_MAX) {
7033 err = -ENAMETOOLONG;
7034 goto out;
7035 }
7036 obj->btf_custom_path = strdup(btf_tmp_path);
7037 if (!obj->btf_custom_path) {
7038 err = -ENOMEM;
7039 goto out;
7040 }
7041 }
7042
8601fd42
AN
7043 kconfig = OPTS_GET(opts, kconfig, NULL);
7044 if (kconfig) {
7045 obj->kconfig = strdup(kconfig);
18353c87
SC
7046 if (!obj->kconfig) {
7047 err = -ENOMEM;
7048 goto out;
7049 }
166750bc 7050 }
291ee02b 7051
0d13bfce
AN
7052 err = bpf_object__elf_init(obj);
7053 err = err ? : bpf_object__check_endianness(obj);
7054 err = err ? : bpf_object__elf_collect(obj);
166750bc
AN
7055 err = err ? : bpf_object__collect_externs(obj);
7056 err = err ? : bpf_object__finalize_btf(obj);
0d13bfce 7057 err = err ? : bpf_object__init_maps(obj, opts);
91b4d1d1 7058 err = err ? : bpf_object_init_progs(obj, opts);
c3c55696 7059 err = err ? : bpf_object__collect_relos(obj);
0d13bfce
AN
7060 if (err)
7061 goto out;
dd4436bb 7062
91b4d1d1 7063 bpf_object__elf_finish(obj);
dd4436bb 7064
1a5e3fb1
WN
7065 return obj;
7066out:
7067 bpf_object__close(obj);
6371ca3b 7068 return ERR_PTR(err);
1a5e3fb1
WN
7069}
7070
5e61f270
AN
7071static struct bpf_object *
7072__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
1a5e3fb1 7073{
e00aca65 7074 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
291ee02b
AN
7075 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7076 );
7077
1a5e3fb1 7078 /* param validation */
07f2d4ea 7079 if (!attr->file)
1a5e3fb1
WN
7080 return NULL;
7081
07f2d4ea 7082 pr_debug("loading %s\n", attr->file);
ad9a7f96 7083 return bpf_object_open(attr->file, NULL, 0, &opts);
c034a177
JF
7084}
7085
7086struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7087{
e9fc3ce9 7088 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
07f2d4ea
JK
7089}
7090
7091struct bpf_object *bpf_object__open(const char *path)
7092{
7093 struct bpf_object_open_attr attr = {
7094 .file = path,
7095 .prog_type = BPF_PROG_TYPE_UNSPEC,
7096 };
1a5e3fb1 7097
e9fc3ce9 7098 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6c956392
WN
7099}
7100
2ce8450e 7101struct bpf_object *
01af3bf0 7102bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
2ce8450e 7103{
2ce8450e 7104 if (!path)
e9fc3ce9 7105 return libbpf_err_ptr(-EINVAL);
2ce8450e
AN
7106
7107 pr_debug("loading %s\n", path);
7108
ad9a7f96 7109 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
2ce8450e
AN
7110}
7111
7112struct bpf_object *
7113bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
01af3bf0 7114 const struct bpf_object_open_opts *opts)
6c956392 7115{
2ce8450e 7116 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7117 return libbpf_err_ptr(-EINVAL);
6c956392 7118
ad9a7f96 7119 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
2ce8450e
AN
7120}
7121
7122struct bpf_object *
7123bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7124 const char *name)
7125{
e00aca65 7126 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
2ce8450e
AN
7127 .object_name = name,
7128 /* wrong default, but backwards-compatible */
7129 .relaxed_maps = true,
7130 );
7131
7132 /* returning NULL is wrong, but backwards-compatible */
7133 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7134 return errno = EINVAL, NULL;
6c956392 7135
ad9a7f96 7136 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
1a5e3fb1
WN
7137}
7138
4a404a7e 7139static int bpf_object_unload(struct bpf_object *obj)
52d3352e
WN
7140{
7141 size_t i;
7142
7143 if (!obj)
e9fc3ce9 7144 return libbpf_err(-EINVAL);
52d3352e 7145
590a0088 7146 for (i = 0; i < obj->nr_maps; i++) {
9d759a9b 7147 zclose(obj->maps[i].fd);
590a0088
MKL
7148 if (obj->maps[i].st_ops)
7149 zfree(&obj->maps[i].st_ops->kern_vdata);
7150 }
52d3352e 7151
55cffde2
WN
7152 for (i = 0; i < obj->nr_programs; i++)
7153 bpf_program__unload(&obj->programs[i]);
7154
52d3352e
WN
7155 return 0;
7156}
7157
4a404a7e
HC
7158int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7159
0d13bfce
AN
7160static int bpf_object__sanitize_maps(struct bpf_object *obj)
7161{
7162 struct bpf_map *m;
7163
7164 bpf_object__for_each_map(m, obj) {
7165 if (!bpf_map__is_internal(m))
7166 continue;
9ca1f56a 7167 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
0d13bfce
AN
7168 m->def.map_flags ^= BPF_F_MMAPABLE;
7169 }
7170
7171 return 0;
7172}
7173
1c0c7074
AN
7174static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7175{
7176 char sym_type, sym_name[500];
7177 unsigned long long sym_addr;
5bd022ec 7178 const struct btf_type *t;
1c0c7074
AN
7179 struct extern_desc *ext;
7180 int ret, err = 0;
7181 FILE *f;
7182
7183 f = fopen("/proc/kallsyms", "r");
7184 if (!f) {
7185 err = -errno;
7186 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7187 return err;
7188 }
7189
7190 while (true) {
7191 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7192 &sym_addr, &sym_type, sym_name);
7193 if (ret == EOF && feof(f))
7194 break;
7195 if (ret != 3) {
135c783f 7196 pr_warn("failed to read kallsyms entry: %d\n", ret);
1c0c7074
AN
7197 err = -EINVAL;
7198 goto out;
7199 }
7200
7201 ext = find_extern_by_name(obj, sym_name);
7202 if (!ext || ext->type != EXT_KSYM)
7203 continue;
7204
5bd022ec
MKL
7205 t = btf__type_by_id(obj->btf, ext->btf_id);
7206 if (!btf_is_var(t))
7207 continue;
7208
1c0c7074
AN
7209 if (ext->is_set && ext->ksym.addr != sym_addr) {
7210 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7211 sym_name, ext->ksym.addr, sym_addr);
7212 err = -EINVAL;
7213 goto out;
7214 }
7215 if (!ext->is_set) {
7216 ext->is_set = true;
7217 ext->ksym.addr = sym_addr;
7218 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7219 }
7220 }
7221
7222out:
7223 fclose(f);
7224 return err;
7225}
7226
774e132e
MKL
7227static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7228 __u16 kind, struct btf **res_btf,
9dbe6015 7229 struct module_btf **res_mod_btf)
d370bbe1 7230{
9dbe6015 7231 struct module_btf *mod_btf;
284d2587 7232 struct btf *btf;
9dbe6015 7233 int i, id, err;
d370bbe1 7234
933d1aa3 7235 btf = obj->btf_vmlinux;
9dbe6015 7236 mod_btf = NULL;
774e132e
MKL
7237 id = btf__find_by_name_kind(btf, ksym_name, kind);
7238
933d1aa3
MKL
7239 if (id == -ENOENT) {
7240 err = load_module_btfs(obj);
7241 if (err)
7242 return err;
d370bbe1 7243
933d1aa3 7244 for (i = 0; i < obj->btf_module_cnt; i++) {
9dbe6015
KKD
7245 /* we assume module_btf's BTF FD is always >0 */
7246 mod_btf = &obj->btf_modules[i];
7247 btf = mod_btf->btf;
7248 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
933d1aa3
MKL
7249 if (id != -ENOENT)
7250 break;
7251 }
7252 }
2211c825 7253 if (id <= 0)
933d1aa3 7254 return -ESRCH;
d370bbe1 7255
774e132e 7256 *res_btf = btf;
9dbe6015 7257 *res_mod_btf = mod_btf;
774e132e
MKL
7258 return id;
7259}
7260
7261static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7262 struct extern_desc *ext)
7263{
7264 const struct btf_type *targ_var, *targ_type;
7265 __u32 targ_type_id, local_type_id;
9dbe6015 7266 struct module_btf *mod_btf = NULL;
774e132e 7267 const char *targ_var_name;
774e132e 7268 struct btf *btf = NULL;
9dbe6015 7269 int id, err;
774e132e 7270
9dbe6015 7271 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
466b2e13
KKD
7272 if (id < 0) {
7273 if (id == -ESRCH && ext->is_weak)
7274 return 0;
2211c825
HL
7275 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7276 ext->name);
774e132e 7277 return id;
2211c825 7278 }
774e132e 7279
933d1aa3
MKL
7280 /* find local type_id */
7281 local_type_id = ext->ksym.type_id;
284d2587 7282
933d1aa3
MKL
7283 /* find target type_id */
7284 targ_var = btf__type_by_id(btf, id);
7285 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7286 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
d370bbe1 7287
933d1aa3
MKL
7288 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7289 btf, targ_type_id);
7290 if (err <= 0) {
7291 const struct btf_type *local_type;
7292 const char *targ_name, *local_name;
d370bbe1 7293
933d1aa3
MKL
7294 local_type = btf__type_by_id(obj->btf, local_type_id);
7295 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7296 targ_name = btf__name_by_offset(btf, targ_type->name_off);
d370bbe1 7297
933d1aa3
MKL
7298 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7299 ext->name, local_type_id,
7300 btf_kind_str(local_type), local_name, targ_type_id,
7301 btf_kind_str(targ_type), targ_name);
7302 return -EINVAL;
7303 }
d370bbe1 7304
933d1aa3 7305 ext->is_set = true;
9dbe6015 7306 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
933d1aa3
MKL
7307 ext->ksym.kernel_btf_id = id;
7308 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7309 ext->name, id, btf_kind_str(targ_var), targ_var_name);
d370bbe1 7310
933d1aa3
MKL
7311 return 0;
7312}
d370bbe1 7313
5bd022ec
MKL
7314static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7315 struct extern_desc *ext)
7316{
7317 int local_func_proto_id, kfunc_proto_id, kfunc_id;
9dbe6015 7318 struct module_btf *mod_btf = NULL;
5bd022ec
MKL
7319 const struct btf_type *kern_func;
7320 struct btf *kern_btf = NULL;
9dbe6015 7321 int ret;
5bd022ec
MKL
7322
7323 local_func_proto_id = ext->ksym.type_id;
7324
9dbe6015 7325 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
5bd022ec 7326 if (kfunc_id < 0) {
466b2e13
KKD
7327 if (kfunc_id == -ESRCH && ext->is_weak)
7328 return 0;
7329 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
5bd022ec
MKL
7330 ext->name);
7331 return kfunc_id;
7332 }
7333
5bd022ec
MKL
7334 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7335 kfunc_proto_id = kern_func->type;
7336
7337 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7338 kern_btf, kfunc_proto_id);
7339 if (ret <= 0) {
7340 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7341 ext->name, local_func_proto_id, kfunc_proto_id);
7342 return -EINVAL;
7343 }
7344
9dbe6015
KKD
7345 /* set index for module BTF fd in fd_array, if unset */
7346 if (mod_btf && !mod_btf->fd_array_idx) {
7347 /* insn->off is s16 */
7348 if (obj->fd_array_cnt == INT16_MAX) {
7349 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7350 ext->name, mod_btf->fd_array_idx);
7351 return -E2BIG;
7352 }
7353 /* Cannot use index 0 for module BTF fd */
7354 if (!obj->fd_array_cnt)
7355 obj->fd_array_cnt = 1;
7356
7357 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7358 obj->fd_array_cnt + 1);
7359 if (ret)
7360 return ret;
7361 mod_btf->fd_array_idx = obj->fd_array_cnt;
7362 /* we assume module BTF FD is always >0 */
7363 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7364 }
7365
5bd022ec 7366 ext->is_set = true;
5bd022ec 7367 ext->ksym.kernel_btf_id = kfunc_id;
9dbe6015 7368 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
5bd022ec
MKL
7369 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7370 ext->name, kfunc_id);
7371
7372 return 0;
7373}
7374
933d1aa3
MKL
7375static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7376{
5bd022ec 7377 const struct btf_type *t;
933d1aa3
MKL
7378 struct extern_desc *ext;
7379 int i, err;
7380
7381 for (i = 0; i < obj->nr_extern; i++) {
7382 ext = &obj->externs[i];
7383 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7384 continue;
7385
67234743
AS
7386 if (obj->gen_loader) {
7387 ext->is_set = true;
7388 ext->ksym.kernel_btf_obj_fd = 0;
7389 ext->ksym.kernel_btf_id = 0;
7390 continue;
7391 }
5bd022ec
MKL
7392 t = btf__type_by_id(obj->btf, ext->btf_id);
7393 if (btf_is_var(t))
7394 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7395 else
7396 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
933d1aa3
MKL
7397 if (err)
7398 return err;
d370bbe1
HL
7399 }
7400 return 0;
7401}
7402
166750bc 7403static int bpf_object__resolve_externs(struct bpf_object *obj,
8601fd42 7404 const char *extra_kconfig)
166750bc 7405{
1c0c7074 7406 bool need_config = false, need_kallsyms = false;
d370bbe1 7407 bool need_vmlinux_btf = false;
166750bc 7408 struct extern_desc *ext;
2e33efe3 7409 void *kcfg_data = NULL;
166750bc 7410 int err, i;
166750bc
AN
7411
7412 if (obj->nr_extern == 0)
7413 return 0;
7414
2e33efe3
AN
7415 if (obj->kconfig_map_idx >= 0)
7416 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
166750bc
AN
7417
7418 for (i = 0; i < obj->nr_extern; i++) {
7419 ext = &obj->externs[i];
7420
2e33efe3
AN
7421 if (ext->type == EXT_KCFG &&
7422 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7423 void *ext_val = kcfg_data + ext->kcfg.data_off;
166750bc
AN
7424 __u32 kver = get_kernel_version();
7425
7426 if (!kver) {
7427 pr_warn("failed to get kernel version\n");
7428 return -EINVAL;
7429 }
2e33efe3 7430 err = set_kcfg_value_num(ext, ext_val, kver);
166750bc
AN
7431 if (err)
7432 return err;
2e33efe3 7433 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
13d35a0c 7434 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
166750bc 7435 need_config = true;
1c0c7074 7436 } else if (ext->type == EXT_KSYM) {
d370bbe1
HL
7437 if (ext->ksym.type_id)
7438 need_vmlinux_btf = true;
7439 else
7440 need_kallsyms = true;
166750bc
AN
7441 } else {
7442 pr_warn("unrecognized extern '%s'\n", ext->name);
7443 return -EINVAL;
7444 }
7445 }
8601fd42 7446 if (need_config && extra_kconfig) {
2e33efe3 7447 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8601fd42
AN
7448 if (err)
7449 return -EINVAL;
7450 need_config = false;
7451 for (i = 0; i < obj->nr_extern; i++) {
7452 ext = &obj->externs[i];
2e33efe3 7453 if (ext->type == EXT_KCFG && !ext->is_set) {
8601fd42
AN
7454 need_config = true;
7455 break;
7456 }
7457 }
7458 }
166750bc 7459 if (need_config) {
2e33efe3 7460 err = bpf_object__read_kconfig_file(obj, kcfg_data);
166750bc
AN
7461 if (err)
7462 return -EINVAL;
7463 }
1c0c7074
AN
7464 if (need_kallsyms) {
7465 err = bpf_object__read_kallsyms_file(obj);
7466 if (err)
7467 return -EINVAL;
7468 }
d370bbe1
HL
7469 if (need_vmlinux_btf) {
7470 err = bpf_object__resolve_ksyms_btf_id(obj);
7471 if (err)
7472 return -EINVAL;
7473 }
166750bc
AN
7474 for (i = 0; i < obj->nr_extern; i++) {
7475 ext = &obj->externs[i];
7476
7477 if (!ext->is_set && !ext->is_weak) {
7478 pr_warn("extern %s (strong) not resolved\n", ext->name);
7479 return -ESRCH;
7480 } else if (!ext->is_set) {
7481 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7482 ext->name);
7483 }
7484 }
7485
7486 return 0;
7487}
7488
e7b924ca 7489static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
52d3352e 7490{
ec6d5f47 7491 int err, i;
6371ca3b 7492
52d3352e 7493 if (!obj)
e9fc3ce9 7494 return libbpf_err(-EINVAL);
52d3352e
WN
7495
7496 if (obj->loaded) {
d9297581 7497 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
e9fc3ce9 7498 return libbpf_err(-EINVAL);
52d3352e
WN
7499 }
7500
67234743 7501 if (obj->gen_loader)
be315829 7502 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
67234743 7503
fd9eef1a 7504 err = bpf_object__probe_loading(obj);
fe62de31 7505 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8601fd42 7506 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
0d13bfce
AN
7507 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7508 err = err ? : bpf_object__sanitize_maps(obj);
590a0088 7509 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
0d13bfce 7510 err = err ? : bpf_object__create_maps(obj);
e7b924ca
AN
7511 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7512 err = err ? : bpf_object__load_progs(obj, extra_log_level);
341ac5ff 7513 err = err ? : bpf_object_init_prog_arrays(obj);
a6ed02ca 7514
67234743
AS
7515 if (obj->gen_loader) {
7516 /* reset FDs */
4729445b
KKD
7517 if (obj->btf)
7518 btf__set_fd(obj->btf, -1);
67234743
AS
7519 for (i = 0; i < obj->nr_maps; i++)
7520 obj->maps[i].fd = -1;
7521 if (!err)
ba05fd36 7522 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
67234743
AS
7523 }
7524
9dbe6015
KKD
7525 /* clean up fd_array */
7526 zfree(&obj->fd_array);
7527
4f33a53d
AN
7528 /* clean up module BTFs */
7529 for (i = 0; i < obj->btf_module_cnt; i++) {
91abb4a6 7530 close(obj->btf_modules[i].fd);
4f33a53d
AN
7531 btf__free(obj->btf_modules[i].btf);
7532 free(obj->btf_modules[i].name);
7533 }
7534 free(obj->btf_modules);
7535
7536 /* clean up vmlinux BTF */
a6ed02ca
KS
7537 btf__free(obj->btf_vmlinux);
7538 obj->btf_vmlinux = NULL;
7539
d9297581
AN
7540 obj->loaded = true; /* doesn't matter if successfully or not */
7541
0d13bfce
AN
7542 if (err)
7543 goto out;
52d3352e
WN
7544
7545 return 0;
7546out:
ec6d5f47
THJ
7547 /* unpin any maps that were auto-pinned during load */
7548 for (i = 0; i < obj->nr_maps; i++)
7549 if (obj->maps[i].pinned && !obj->maps[i].reused)
7550 bpf_map__unpin(&obj->maps[i], NULL);
7551
4a404a7e 7552 bpf_object_unload(obj);
be18010e 7553 pr_warn("failed to load object '%s'\n", obj->path);
e9fc3ce9 7554 return libbpf_err(err);
52d3352e
WN
7555}
7556
e7b924ca 7557int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
60276f98 7558{
e7b924ca
AN
7559 return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7560}
60276f98 7561
e7b924ca
AN
7562int bpf_object__load(struct bpf_object *obj)
7563{
7564 return bpf_object_load(obj, 0, NULL);
60276f98
QM
7565}
7566
196f8487
THJ
7567static int make_parent_dir(const char *path)
7568{
7569 char *cp, errmsg[STRERR_BUFSIZE];
7570 char *dname, *dir;
7571 int err = 0;
7572
7573 dname = strdup(path);
7574 if (dname == NULL)
7575 return -ENOMEM;
7576
7577 dir = dirname(dname);
7578 if (mkdir(dir, 0700) && errno != EEXIST)
7579 err = -errno;
7580
7581 free(dname);
7582 if (err) {
7583 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7584 pr_warn("failed to mkdir %s: %s\n", path, cp);
7585 }
7586 return err;
7587}
7588
f367540c
JS
7589static int check_path(const char *path)
7590{
1ce6a9fc 7591 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7592 struct statfs st_fs;
7593 char *dname, *dir;
7594 int err = 0;
7595
7596 if (path == NULL)
7597 return -EINVAL;
7598
7599 dname = strdup(path);
7600 if (dname == NULL)
7601 return -ENOMEM;
7602
7603 dir = dirname(dname);
7604 if (statfs(dir, &st_fs)) {
24d6a808 7605 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
be18010e 7606 pr_warn("failed to statfs %s: %s\n", dir, cp);
f367540c
JS
7607 err = -errno;
7608 }
7609 free(dname);
7610
7611 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
be18010e 7612 pr_warn("specified path %s is not on BPF FS\n", path);
f367540c
JS
7613 err = -EINVAL;
7614 }
7615
7616 return err;
7617}
7618
e21d585c 7619static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
f367540c 7620{
1ce6a9fc 7621 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7622 int err;
7623
196f8487
THJ
7624 err = make_parent_dir(path);
7625 if (err)
e9fc3ce9 7626 return libbpf_err(err);
196f8487 7627
f367540c
JS
7628 err = check_path(path);
7629 if (err)
e9fc3ce9 7630 return libbpf_err(err);
f367540c
JS
7631
7632 if (prog == NULL) {
be18010e 7633 pr_warn("invalid program pointer\n");
e9fc3ce9 7634 return libbpf_err(-EINVAL);
f367540c
JS
7635 }
7636
7637 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7638 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7639 instance, prog->name, prog->instances.nr);
e9fc3ce9 7640 return libbpf_err(-EINVAL);
f367540c
JS
7641 }
7642
7643 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
23ab656b
THJ
7644 err = -errno;
7645 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e 7646 pr_warn("failed to pin program: %s\n", cp);
e9fc3ce9 7647 return libbpf_err(err);
f367540c
JS
7648 }
7649 pr_debug("pinned program '%s'\n", path);
7650
7651 return 0;
7652}
7653
e21d585c 7654static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
0c19a9fb
SF
7655{
7656 int err;
7657
7658 err = check_path(path);
7659 if (err)
e9fc3ce9 7660 return libbpf_err(err);
0c19a9fb
SF
7661
7662 if (prog == NULL) {
be18010e 7663 pr_warn("invalid program pointer\n");
e9fc3ce9 7664 return libbpf_err(-EINVAL);
0c19a9fb
SF
7665 }
7666
7667 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7668 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7669 instance, prog->name, prog->instances.nr);
e9fc3ce9 7670 return libbpf_err(-EINVAL);
0c19a9fb
SF
7671 }
7672
7673 err = unlink(path);
7674 if (err != 0)
e9fc3ce9
AN
7675 return libbpf_err(-errno);
7676
0c19a9fb
SF
7677 pr_debug("unpinned program '%s'\n", path);
7678
7679 return 0;
7680}
7681
e21d585c
AN
7682__attribute__((alias("bpf_program_pin_instance")))
7683int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
7684
7685__attribute__((alias("bpf_program_unpin_instance")))
7686int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
7687
f367540c
JS
7688int bpf_program__pin(struct bpf_program *prog, const char *path)
7689{
7690 int i, err;
7691
196f8487
THJ
7692 err = make_parent_dir(path);
7693 if (err)
e9fc3ce9 7694 return libbpf_err(err);
196f8487 7695
f367540c
JS
7696 err = check_path(path);
7697 if (err)
e9fc3ce9 7698 return libbpf_err(err);
f367540c
JS
7699
7700 if (prog == NULL) {
be18010e 7701 pr_warn("invalid program pointer\n");
e9fc3ce9 7702 return libbpf_err(-EINVAL);
f367540c
JS
7703 }
7704
7705 if (prog->instances.nr <= 0) {
52109584 7706 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7707 return libbpf_err(-EINVAL);
f367540c
JS
7708 }
7709
fd734c5c
SF
7710 if (prog->instances.nr == 1) {
7711 /* don't create subdirs when pinning single instance */
e21d585c 7712 return bpf_program_pin_instance(prog, path, 0);
fd734c5c
SF
7713 }
7714
0c19a9fb
SF
7715 for (i = 0; i < prog->instances.nr; i++) {
7716 char buf[PATH_MAX];
7717 int len;
7718
7719 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7720 if (len < 0) {
7721 err = -EINVAL;
7722 goto err_unpin;
7723 } else if (len >= PATH_MAX) {
7724 err = -ENAMETOOLONG;
7725 goto err_unpin;
7726 }
7727
e21d585c 7728 err = bpf_program_pin_instance(prog, buf, i);
0c19a9fb
SF
7729 if (err)
7730 goto err_unpin;
7731 }
7732
7733 return 0;
7734
7735err_unpin:
7736 for (i = i - 1; i >= 0; i--) {
7737 char buf[PATH_MAX];
7738 int len;
7739
7740 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7741 if (len < 0)
7742 continue;
7743 else if (len >= PATH_MAX)
7744 continue;
7745
e21d585c 7746 bpf_program_unpin_instance(prog, buf, i);
0c19a9fb
SF
7747 }
7748
7749 rmdir(path);
7750
e9fc3ce9 7751 return libbpf_err(err);
0c19a9fb
SF
7752}
7753
7754int bpf_program__unpin(struct bpf_program *prog, const char *path)
7755{
7756 int i, err;
7757
7758 err = check_path(path);
7759 if (err)
e9fc3ce9 7760 return libbpf_err(err);
0c19a9fb
SF
7761
7762 if (prog == NULL) {
be18010e 7763 pr_warn("invalid program pointer\n");
e9fc3ce9 7764 return libbpf_err(-EINVAL);
0c19a9fb
SF
7765 }
7766
7767 if (prog->instances.nr <= 0) {
52109584 7768 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7769 return libbpf_err(-EINVAL);
fd734c5c
SF
7770 }
7771
7772 if (prog->instances.nr == 1) {
7773 /* don't create subdirs when pinning single instance */
e21d585c 7774 return bpf_program_unpin_instance(prog, path, 0);
0c19a9fb
SF
7775 }
7776
f367540c
JS
7777 for (i = 0; i < prog->instances.nr; i++) {
7778 char buf[PATH_MAX];
7779 int len;
7780
7781 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7782 if (len < 0)
e9fc3ce9 7783 return libbpf_err(-EINVAL);
f367540c 7784 else if (len >= PATH_MAX)
e9fc3ce9 7785 return libbpf_err(-ENAMETOOLONG);
f367540c 7786
e21d585c 7787 err = bpf_program_unpin_instance(prog, buf, i);
f367540c
JS
7788 if (err)
7789 return err;
7790 }
7791
0c19a9fb
SF
7792 err = rmdir(path);
7793 if (err)
e9fc3ce9 7794 return libbpf_err(-errno);
0c19a9fb 7795
f367540c
JS
7796 return 0;
7797}
7798
b6989f35
JS
7799int bpf_map__pin(struct bpf_map *map, const char *path)
7800{
1ce6a9fc 7801 char *cp, errmsg[STRERR_BUFSIZE];
b6989f35
JS
7802 int err;
7803
b6989f35 7804 if (map == NULL) {
be18010e 7805 pr_warn("invalid map pointer\n");
e9fc3ce9 7806 return libbpf_err(-EINVAL);
b6989f35
JS
7807 }
7808
4580b25f
THJ
7809 if (map->pin_path) {
7810 if (path && strcmp(path, map->pin_path)) {
7811 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7812 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7813 return libbpf_err(-EINVAL);
4580b25f
THJ
7814 } else if (map->pinned) {
7815 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7816 bpf_map__name(map), map->pin_path);
7817 return 0;
7818 }
7819 } else {
7820 if (!path) {
7821 pr_warn("missing a path to pin map '%s' at\n",
7822 bpf_map__name(map));
e9fc3ce9 7823 return libbpf_err(-EINVAL);
4580b25f
THJ
7824 } else if (map->pinned) {
7825 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
e9fc3ce9 7826 return libbpf_err(-EEXIST);
4580b25f
THJ
7827 }
7828
7829 map->pin_path = strdup(path);
7830 if (!map->pin_path) {
7831 err = -errno;
7832 goto out_err;
7833 }
b6989f35
JS
7834 }
7835
196f8487
THJ
7836 err = make_parent_dir(map->pin_path);
7837 if (err)
e9fc3ce9 7838 return libbpf_err(err);
196f8487 7839
4580b25f
THJ
7840 err = check_path(map->pin_path);
7841 if (err)
e9fc3ce9 7842 return libbpf_err(err);
4580b25f
THJ
7843
7844 if (bpf_obj_pin(map->fd, map->pin_path)) {
7845 err = -errno;
7846 goto out_err;
7847 }
7848
7849 map->pinned = true;
7850 pr_debug("pinned map '%s'\n", map->pin_path);
0c19a9fb 7851
b6989f35 7852 return 0;
4580b25f
THJ
7853
7854out_err:
7855 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7856 pr_warn("failed to pin map: %s\n", cp);
e9fc3ce9 7857 return libbpf_err(err);
b6989f35
JS
7858}
7859
0c19a9fb
SF
7860int bpf_map__unpin(struct bpf_map *map, const char *path)
7861{
7862 int err;
7863
0c19a9fb 7864 if (map == NULL) {
be18010e 7865 pr_warn("invalid map pointer\n");
e9fc3ce9 7866 return libbpf_err(-EINVAL);
0c19a9fb
SF
7867 }
7868
4580b25f
THJ
7869 if (map->pin_path) {
7870 if (path && strcmp(path, map->pin_path)) {
7871 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7872 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7873 return libbpf_err(-EINVAL);
4580b25f
THJ
7874 }
7875 path = map->pin_path;
7876 } else if (!path) {
7877 pr_warn("no path to unpin map '%s' from\n",
7878 bpf_map__name(map));
e9fc3ce9 7879 return libbpf_err(-EINVAL);
4580b25f
THJ
7880 }
7881
7882 err = check_path(path);
7883 if (err)
e9fc3ce9 7884 return libbpf_err(err);
4580b25f 7885
0c19a9fb
SF
7886 err = unlink(path);
7887 if (err != 0)
e9fc3ce9 7888 return libbpf_err(-errno);
4580b25f
THJ
7889
7890 map->pinned = false;
7891 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
0c19a9fb
SF
7892
7893 return 0;
7894}
7895
4580b25f
THJ
7896int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7897{
7898 char *new = NULL;
7899
7900 if (path) {
7901 new = strdup(path);
7902 if (!new)
e9fc3ce9 7903 return libbpf_err(-errno);
4580b25f
THJ
7904 }
7905
7906 free(map->pin_path);
7907 map->pin_path = new;
7908 return 0;
7909}
7910
20eccf29
AN
7911__alias(bpf_map__pin_path)
7912const char *bpf_map__get_pin_path(const struct bpf_map *map);
4580b25f 7913
e244d34d
EL
7914const char *bpf_map__pin_path(const struct bpf_map *map)
7915{
7916 return map->pin_path;
7917}
7918
4580b25f
THJ
7919bool bpf_map__is_pinned(const struct bpf_map *map)
7920{
7921 return map->pinned;
7922}
7923
9cf309c5
THJ
7924static void sanitize_pin_path(char *s)
7925{
7926 /* bpffs disallows periods in path names */
7927 while (*s) {
7928 if (*s == '.')
7929 *s = '_';
7930 s++;
7931 }
7932}
7933
0c19a9fb 7934int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
d5148d85 7935{
d5148d85
JS
7936 struct bpf_map *map;
7937 int err;
7938
7939 if (!obj)
e9fc3ce9 7940 return libbpf_err(-ENOENT);
d5148d85
JS
7941
7942 if (!obj->loaded) {
be18010e 7943 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 7944 return libbpf_err(-ENOENT);
d5148d85
JS
7945 }
7946
f74a53d9 7947 bpf_object__for_each_map(map, obj) {
4580b25f 7948 char *pin_path = NULL;
0c19a9fb 7949 char buf[PATH_MAX];
0c19a9fb 7950
229fae38
SC
7951 if (map->skipped)
7952 continue;
7953
4580b25f
THJ
7954 if (path) {
7955 int len;
7956
7957 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7958 bpf_map__name(map));
7959 if (len < 0) {
7960 err = -EINVAL;
7961 goto err_unpin_maps;
7962 } else if (len >= PATH_MAX) {
7963 err = -ENAMETOOLONG;
7964 goto err_unpin_maps;
7965 }
9cf309c5 7966 sanitize_pin_path(buf);
4580b25f
THJ
7967 pin_path = buf;
7968 } else if (!map->pin_path) {
7969 continue;
0c19a9fb
SF
7970 }
7971
4580b25f 7972 err = bpf_map__pin(map, pin_path);
0c19a9fb
SF
7973 if (err)
7974 goto err_unpin_maps;
7975 }
7976
7977 return 0;
7978
7979err_unpin_maps:
bcc40fc0 7980 while ((map = bpf_object__prev_map(obj, map))) {
4580b25f 7981 if (!map->pin_path)
0c19a9fb
SF
7982 continue;
7983
4580b25f 7984 bpf_map__unpin(map, NULL);
0c19a9fb
SF
7985 }
7986
e9fc3ce9 7987 return libbpf_err(err);
0c19a9fb
SF
7988}
7989
7990int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7991{
7992 struct bpf_map *map;
7993 int err;
7994
7995 if (!obj)
e9fc3ce9 7996 return libbpf_err(-ENOENT);
0c19a9fb 7997
f74a53d9 7998 bpf_object__for_each_map(map, obj) {
4580b25f 7999 char *pin_path = NULL;
d5148d85 8000 char buf[PATH_MAX];
d5148d85 8001
4580b25f
THJ
8002 if (path) {
8003 int len;
8004
8005 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8006 bpf_map__name(map));
8007 if (len < 0)
e9fc3ce9 8008 return libbpf_err(-EINVAL);
4580b25f 8009 else if (len >= PATH_MAX)
e9fc3ce9 8010 return libbpf_err(-ENAMETOOLONG);
9cf309c5 8011 sanitize_pin_path(buf);
4580b25f
THJ
8012 pin_path = buf;
8013 } else if (!map->pin_path) {
8014 continue;
8015 }
d5148d85 8016
4580b25f 8017 err = bpf_map__unpin(map, pin_path);
d5148d85 8018 if (err)
e9fc3ce9 8019 return libbpf_err(err);
d5148d85
JS
8020 }
8021
0c19a9fb
SF
8022 return 0;
8023}
8024
8025int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8026{
8027 struct bpf_program *prog;
8028 int err;
8029
8030 if (!obj)
e9fc3ce9 8031 return libbpf_err(-ENOENT);
0c19a9fb
SF
8032
8033 if (!obj->loaded) {
be18010e 8034 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 8035 return libbpf_err(-ENOENT);
0c19a9fb
SF
8036 }
8037
0c19a9fb
SF
8038 bpf_object__for_each_program(prog, obj) {
8039 char buf[PATH_MAX];
8040 int len;
8041
8042 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8043 prog->pin_name);
0c19a9fb
SF
8044 if (len < 0) {
8045 err = -EINVAL;
8046 goto err_unpin_programs;
8047 } else if (len >= PATH_MAX) {
8048 err = -ENAMETOOLONG;
8049 goto err_unpin_programs;
8050 }
8051
8052 err = bpf_program__pin(prog, buf);
8053 if (err)
8054 goto err_unpin_programs;
8055 }
8056
8057 return 0;
8058
8059err_unpin_programs:
bcc40fc0 8060 while ((prog = bpf_object__prev_program(obj, prog))) {
0c19a9fb
SF
8061 char buf[PATH_MAX];
8062 int len;
8063
8064 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8065 prog->pin_name);
0c19a9fb
SF
8066 if (len < 0)
8067 continue;
8068 else if (len >= PATH_MAX)
8069 continue;
8070
8071 bpf_program__unpin(prog, buf);
8072 }
8073
e9fc3ce9 8074 return libbpf_err(err);
0c19a9fb
SF
8075}
8076
8077int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8078{
8079 struct bpf_program *prog;
8080 int err;
8081
8082 if (!obj)
e9fc3ce9 8083 return libbpf_err(-ENOENT);
0c19a9fb 8084
d5148d85
JS
8085 bpf_object__for_each_program(prog, obj) {
8086 char buf[PATH_MAX];
8087 int len;
8088
8089 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8090 prog->pin_name);
d5148d85 8091 if (len < 0)
e9fc3ce9 8092 return libbpf_err(-EINVAL);
d5148d85 8093 else if (len >= PATH_MAX)
e9fc3ce9 8094 return libbpf_err(-ENAMETOOLONG);
d5148d85 8095
0c19a9fb 8096 err = bpf_program__unpin(prog, buf);
d5148d85 8097 if (err)
e9fc3ce9 8098 return libbpf_err(err);
d5148d85
JS
8099 }
8100
8101 return 0;
8102}
8103
0c19a9fb
SF
8104int bpf_object__pin(struct bpf_object *obj, const char *path)
8105{
8106 int err;
8107
8108 err = bpf_object__pin_maps(obj, path);
8109 if (err)
e9fc3ce9 8110 return libbpf_err(err);
0c19a9fb
SF
8111
8112 err = bpf_object__pin_programs(obj, path);
8113 if (err) {
8114 bpf_object__unpin_maps(obj, path);
e9fc3ce9 8115 return libbpf_err(err);
0c19a9fb
SF
8116 }
8117
8118 return 0;
8119}
8120
2d39d7c5
AN
8121static void bpf_map__destroy(struct bpf_map *map)
8122{
8123 if (map->clear_priv)
8124 map->clear_priv(map, map->priv);
8125 map->priv = NULL;
8126 map->clear_priv = NULL;
8127
646f02ff
AN
8128 if (map->inner_map) {
8129 bpf_map__destroy(map->inner_map);
8130 zfree(&map->inner_map);
8131 }
8132
8133 zfree(&map->init_slots);
8134 map->init_slots_sz = 0;
8135
2d39d7c5
AN
8136 if (map->mmaped) {
8137 munmap(map->mmaped, bpf_map_mmap_sz(map));
8138 map->mmaped = NULL;
8139 }
8140
8141 if (map->st_ops) {
8142 zfree(&map->st_ops->data);
8143 zfree(&map->st_ops->progs);
8144 zfree(&map->st_ops->kern_func_off);
8145 zfree(&map->st_ops);
8146 }
8147
8148 zfree(&map->name);
aed65917 8149 zfree(&map->real_name);
2d39d7c5
AN
8150 zfree(&map->pin_path);
8151
8152 if (map->fd >= 0)
8153 zclose(map->fd);
8154}
8155
1a5e3fb1
WN
8156void bpf_object__close(struct bpf_object *obj)
8157{
a5b8bd47
WN
8158 size_t i;
8159
50450fc7 8160 if (IS_ERR_OR_NULL(obj))
1a5e3fb1
WN
8161 return;
8162
10931d24
WN
8163 if (obj->clear_priv)
8164 obj->clear_priv(obj, obj->priv);
8165
67234743 8166 bpf_gen__free(obj->gen_loader);
1a5e3fb1 8167 bpf_object__elf_finish(obj);
4a404a7e 8168 bpf_object_unload(obj);
8a138aed 8169 btf__free(obj->btf);
2993e051 8170 btf_ext__free(obj->btf_ext);
1a5e3fb1 8171
2d39d7c5
AN
8172 for (i = 0; i < obj->nr_maps; i++)
8173 bpf_map__destroy(&obj->maps[i]);
d859900c 8174
1373ff59 8175 zfree(&obj->btf_custom_path);
8601fd42 8176 zfree(&obj->kconfig);
166750bc
AN
8177 zfree(&obj->externs);
8178 obj->nr_extern = 0;
8179
9d759a9b
WN
8180 zfree(&obj->maps);
8181 obj->nr_maps = 0;
a5b8bd47
WN
8182
8183 if (obj->programs && obj->nr_programs) {
8184 for (i = 0; i < obj->nr_programs; i++)
8185 bpf_program__exit(&obj->programs[i]);
8186 }
8187 zfree(&obj->programs);
8188
9a208eff 8189 list_del(&obj->list);
1a5e3fb1
WN
8190 free(obj);
8191}
aa9b1ac3 8192
9a208eff
WN
8193struct bpf_object *
8194bpf_object__next(struct bpf_object *prev)
8195{
8196 struct bpf_object *next;
689624f0
JB
8197 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8198
8199 if (strict)
8200 return NULL;
9a208eff
WN
8201
8202 if (!prev)
8203 next = list_first_entry(&bpf_objects_list,
8204 struct bpf_object,
8205 list);
8206 else
8207 next = list_next_entry(prev, list);
8208
8209 /* Empty list is noticed here so don't need checking on entry. */
8210 if (&next->list == &bpf_objects_list)
8211 return NULL;
8212
8213 return next;
8214}
8215
a324aae3 8216const char *bpf_object__name(const struct bpf_object *obj)
acf860ae 8217{
e9fc3ce9 8218 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
acf860ae
WN
8219}
8220
a324aae3 8221unsigned int bpf_object__kversion(const struct bpf_object *obj)
45825d8a 8222{
a7fe0450 8223 return obj ? obj->kern_version : 0;
45825d8a
WN
8224}
8225
a324aae3 8226struct btf *bpf_object__btf(const struct bpf_object *obj)
789f6bab
AI
8227{
8228 return obj ? obj->btf : NULL;
8229}
8230
8a138aed
MKL
8231int bpf_object__btf_fd(const struct bpf_object *obj)
8232{
8233 return obj->btf ? btf__fd(obj->btf) : -1;
8234}
8235
155f556d
RDT
8236int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8237{
8238 if (obj->loaded)
e9fc3ce9 8239 return libbpf_err(-EINVAL);
155f556d
RDT
8240
8241 obj->kern_version = kern_version;
8242
8243 return 0;
8244}
8245
10931d24
WN
8246int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8247 bpf_object_clear_priv_t clear_priv)
8248{
8249 if (obj->priv && obj->clear_priv)
8250 obj->clear_priv(obj, obj->priv);
8251
8252 obj->priv = priv;
8253 obj->clear_priv = clear_priv;
8254 return 0;
8255}
8256
a324aae3 8257void *bpf_object__priv(const struct bpf_object *obj)
10931d24 8258{
e9fc3ce9 8259 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
10931d24
WN
8260}
8261
67234743
AS
8262int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8263{
8264 struct bpf_gen *gen;
8265
8266 if (!opts)
8267 return -EFAULT;
8268 if (!OPTS_VALID(opts, gen_loader_opts))
8269 return -EINVAL;
8270 gen = calloc(sizeof(*gen), 1);
8271 if (!gen)
8272 return -ENOMEM;
8273 gen->opts = opts;
8274 obj->gen_loader = gen;
8275 return 0;
8276}
8277
eac7d845 8278static struct bpf_program *
a324aae3
AN
8279__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8280 bool forward)
aa9b1ac3 8281{
a83d6e76 8282 size_t nr_programs = obj->nr_programs;
0c19a9fb 8283 ssize_t idx;
aa9b1ac3 8284
a83d6e76 8285 if (!nr_programs)
aa9b1ac3 8286 return NULL;
aa9b1ac3 8287
a83d6e76
MKL
8288 if (!p)
8289 /* Iter from the beginning */
8290 return forward ? &obj->programs[0] :
8291 &obj->programs[nr_programs - 1];
8292
0c19a9fb 8293 if (p->obj != obj) {
be18010e 8294 pr_warn("error: program handler doesn't match object\n");
e9fc3ce9 8295 return errno = EINVAL, NULL;
aa9b1ac3
WN
8296 }
8297
a83d6e76 8298 idx = (p - obj->programs) + (forward ? 1 : -1);
0c19a9fb 8299 if (idx >= obj->nr_programs || idx < 0)
aa9b1ac3
WN
8300 return NULL;
8301 return &obj->programs[idx];
8302}
8303
eac7d845 8304struct bpf_program *
a324aae3 8305bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
2088a3a7
HC
8306{
8307 return bpf_object__next_program(obj, prev);
8308}
8309
8310struct bpf_program *
8311bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
eac7d845
JK
8312{
8313 struct bpf_program *prog = prev;
8314
8315 do {
a83d6e76 8316 prog = __bpf_program__iter(prog, obj, true);
c3c55696 8317 } while (prog && prog_is_subprog(obj, prog));
0c19a9fb
SF
8318
8319 return prog;
8320}
8321
8322struct bpf_program *
a324aae3 8323bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
2088a3a7
HC
8324{
8325 return bpf_object__prev_program(obj, next);
8326}
8327
8328struct bpf_program *
8329bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
0c19a9fb
SF
8330{
8331 struct bpf_program *prog = next;
8332
0c19a9fb 8333 do {
a83d6e76 8334 prog = __bpf_program__iter(prog, obj, false);
c3c55696 8335 } while (prog && prog_is_subprog(obj, prog));
eac7d845
JK
8336
8337 return prog;
8338}
8339
edb13ed4
ACM
8340int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8341 bpf_program_clear_priv_t clear_priv)
aa9b1ac3
WN
8342{
8343 if (prog->priv && prog->clear_priv)
8344 prog->clear_priv(prog, prog->priv);
8345
8346 prog->priv = priv;
8347 prog->clear_priv = clear_priv;
8348 return 0;
8349}
8350
a324aae3 8351void *bpf_program__priv(const struct bpf_program *prog)
aa9b1ac3 8352{
e9fc3ce9 8353 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
aa9b1ac3
WN
8354}
8355
9aba3613
JK
8356void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8357{
8358 prog->prog_ifindex = ifindex;
8359}
8360
01af3bf0
AN
8361const char *bpf_program__name(const struct bpf_program *prog)
8362{
8363 return prog->name;
8364}
8365
52109584
AN
8366const char *bpf_program__section_name(const struct bpf_program *prog)
8367{
8368 return prog->sec_name;
8369}
8370
a324aae3 8371const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
aa9b1ac3
WN
8372{
8373 const char *title;
8374
52109584 8375 title = prog->sec_name;
715f8db9 8376 if (needs_copy) {
aa9b1ac3
WN
8377 title = strdup(title);
8378 if (!title) {
be18010e 8379 pr_warn("failed to strdup program title\n");
e9fc3ce9 8380 return libbpf_err_ptr(-ENOMEM);
aa9b1ac3
WN
8381 }
8382 }
8383
8384 return title;
8385}
8386
d9297581
AN
8387bool bpf_program__autoload(const struct bpf_program *prog)
8388{
8389 return prog->load;
8390}
8391
8392int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8393{
8394 if (prog->obj->loaded)
e9fc3ce9 8395 return libbpf_err(-EINVAL);
d9297581
AN
8396
8397 prog->load = autoload;
8398 return 0;
8399}
8400
bcc40fc0
AN
8401static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8402
a324aae3 8403int bpf_program__fd(const struct bpf_program *prog)
aa9b1ac3 8404{
bcc40fc0 8405 return bpf_program_nth_fd(prog, 0);
b580563e
WN
8406}
8407
1a734efe
THJ
8408size_t bpf_program__size(const struct bpf_program *prog)
8409{
9c0f8cbd 8410 return prog->insns_cnt * BPF_INSN_SZ;
1a734efe
THJ
8411}
8412
65a7fa2e
AN
8413const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8414{
8415 return prog->insns;
8416}
8417
8418size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8419{
8420 return prog->insns_cnt;
8421}
8422
b580563e
WN
8423int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8424 bpf_program_prep_t prep)
8425{
8426 int *instances_fds;
8427
8428 if (nr_instances <= 0 || !prep)
e9fc3ce9 8429 return libbpf_err(-EINVAL);
b580563e
WN
8430
8431 if (prog->instances.nr > 0 || prog->instances.fds) {
be18010e 8432 pr_warn("Can't set pre-processor after loading\n");
e9fc3ce9 8433 return libbpf_err(-EINVAL);
b580563e
WN
8434 }
8435
8436 instances_fds = malloc(sizeof(int) * nr_instances);
8437 if (!instances_fds) {
be18010e 8438 pr_warn("alloc memory failed for fds\n");
e9fc3ce9 8439 return libbpf_err(-ENOMEM);
b580563e
WN
8440 }
8441
8442 /* fill all fd with -1 */
8443 memset(instances_fds, -1, sizeof(int) * nr_instances);
8444
8445 prog->instances.nr = nr_instances;
8446 prog->instances.fds = instances_fds;
8447 prog->preprocessor = prep;
8448 return 0;
8449}
8450
bcc40fc0
AN
8451__attribute__((alias("bpf_program_nth_fd")))
8452int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8453
8454static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
b580563e
WN
8455{
8456 int fd;
8457
1e960043 8458 if (!prog)
e9fc3ce9 8459 return libbpf_err(-EINVAL);
1e960043 8460
b580563e 8461 if (n >= prog->instances.nr || n < 0) {
be18010e 8462 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
52109584 8463 n, prog->name, prog->instances.nr);
e9fc3ce9 8464 return libbpf_err(-EINVAL);
b580563e
WN
8465 }
8466
8467 fd = prog->instances.fds[n];
8468 if (fd < 0) {
be18010e 8469 pr_warn("%dth instance of program '%s' is invalid\n",
52109584 8470 n, prog->name);
e9fc3ce9 8471 return libbpf_err(-ENOENT);
b580563e
WN
8472 }
8473
8474 return fd;
aa9b1ac3 8475}
9d759a9b 8476
20eccf29
AN
8477__alias(bpf_program__type)
8478enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8479
8480enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
f1eead9e
AN
8481{
8482 return prog->type;
8483}
8484
dd26b7f5 8485void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5f44e4c8
WN
8486{
8487 prog->type = type;
8488}
8489
a324aae3 8490static bool bpf_program__is_type(const struct bpf_program *prog,
5f44e4c8
WN
8491 enum bpf_prog_type type)
8492{
8493 return prog ? (prog->type == type) : false;
8494}
8495
a324aae3
AN
8496#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8497int bpf_program__set_##NAME(struct bpf_program *prog) \
8498{ \
8499 if (!prog) \
e9fc3ce9 8500 return libbpf_err(-EINVAL); \
a324aae3
AN
8501 bpf_program__set_type(prog, TYPE); \
8502 return 0; \
8503} \
8504 \
8505bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8506{ \
8507 return bpf_program__is_type(prog, TYPE); \
8508} \
ed794073 8509
7803ba73 8510BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1e092a03 8511BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
ed794073 8512BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7803ba73
JS
8513BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8514BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
ed794073 8515BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
e14c93fd 8516BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7803ba73
JS
8517BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8518BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
12a8654b 8519BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
590a0088 8520BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
2db6eab1 8521BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
499dd29d 8522BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
5f44e4c8 8523
20eccf29
AN
8524__alias(bpf_program__expected_attach_type)
8525enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8526
8527enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
f1eead9e
AN
8528{
8529 return prog->expected_attach_type;
8530}
8531
16962b24
JF
8532void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8533 enum bpf_attach_type type)
d7be143b
AI
8534{
8535 prog->expected_attach_type = type;
8536}
8537
a6ca7158
AN
8538__u32 bpf_program__flags(const struct bpf_program *prog)
8539{
8540 return prog->prog_flags;
8541}
8542
8cccee9e 8543int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
a6ca7158
AN
8544{
8545 if (prog->obj->loaded)
8546 return libbpf_err(-EBUSY);
8547
8cccee9e 8548 prog->prog_flags = flags;
a6ca7158
AN
8549 return 0;
8550}
8551
dbdd2c7f
AN
8552__u32 bpf_program__log_level(const struct bpf_program *prog)
8553{
8554 return prog->log_level;
8555}
8556
8557int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8558{
8559 if (prog->obj->loaded)
8560 return libbpf_err(-EBUSY);
8561
8562 prog->log_level = log_level;
8563 return 0;
8564}
8565
b3ce9079
AN
8566const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8567{
8568 *log_size = prog->log_size;
8569 return prog->log_buf;
8570}
8571
8572int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8573{
8574 if (log_size && !log_buf)
8575 return -EINVAL;
8576 if (prog->log_size > UINT_MAX)
8577 return -EINVAL;
8578 if (prog->obj->loaded)
8579 return -EBUSY;
8580
8581 prog->log_buf = log_buf;
8582 prog->log_size = log_size;
a6ca7158
AN
8583 return 0;
8584}
8585
15ea31fa 8586#define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
697f104d 8587 .sec = (char *)sec_pfx, \
d7a18ea7 8588 .prog_type = BPF_PROG_TYPE_##ptype, \
15ea31fa
AN
8589 .expected_attach_type = atype, \
8590 .cookie = (long)(flags), \
4fa5bcfe 8591 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
d7a18ea7
AN
8592 __VA_ARGS__ \
8593}
8594
4fa5bcfe
AN
8595static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8596static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8597static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8598static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8599static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8600static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
d7a18ea7 8601
d7a18ea7 8602static const struct bpf_sec_def section_defs[] = {
dd94d45c
AN
8603 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8604 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8605 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
15ea31fa
AN
8606 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8607 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE),
8608 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8609 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE),
15ea31fa 8610 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
4a4d4cee 8611 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX | SEC_DEPRECATED),
dd94d45c 8612 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
15ea31fa
AN
8613 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8614 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8615 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8616 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
ccaf12d6
HT
8617 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8618 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
15ea31fa
AN
8619 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8620 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8621 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8622 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8623 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8624 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8625 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8626 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8627 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8628 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8629 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
a8b77f74 8630 SEC_DEF("iter.s/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
15ea31fa 8631 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
082c4bfb 8632 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
4a4d4cee
LB
8633 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8634 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
082c4bfb 8635 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
4a4d4cee
LB
8636 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8637 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
082c4bfb 8638 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
dd94d45c
AN
8639 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8640 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8641 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8642 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8643 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8644 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8645 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8646 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8647 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8648 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8649 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8650 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8651 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8652 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8653 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8654 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8655 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8656 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8657 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8658 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8659 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8660 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8661 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8662 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8663 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8664 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8665 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8666 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8667 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8668 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8669 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8670 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8671 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8672 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8673 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8674 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8675 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8676 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
7c80c87a 8677 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
583c9009 8678};
d7be143b 8679
697f104d
AN
8680static size_t custom_sec_def_cnt;
8681static struct bpf_sec_def *custom_sec_defs;
8682static struct bpf_sec_def custom_fallback_def;
8683static bool has_custom_fallback_def;
c76e4c22 8684
697f104d
AN
8685static int last_custom_sec_def_handler_id;
8686
8687int libbpf_register_prog_handler(const char *sec,
8688 enum bpf_prog_type prog_type,
8689 enum bpf_attach_type exp_attach_type,
8690 const struct libbpf_prog_handler_opts *opts)
d7a18ea7 8691{
697f104d 8692 struct bpf_sec_def *sec_def;
d7a18ea7 8693
697f104d
AN
8694 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8695 return libbpf_err(-EINVAL);
dd94d45c 8696
697f104d
AN
8697 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8698 return libbpf_err(-E2BIG);
dd94d45c 8699
697f104d
AN
8700 if (sec) {
8701 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8702 sizeof(*sec_def));
8703 if (!sec_def)
8704 return libbpf_err(-ENOMEM);
dd94d45c 8705
697f104d
AN
8706 custom_sec_defs = sec_def;
8707 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8708 } else {
8709 if (has_custom_fallback_def)
8710 return libbpf_err(-EBUSY);
dd94d45c 8711
697f104d
AN
8712 sec_def = &custom_fallback_def;
8713 }
8714
8715 sec_def->sec = sec ? strdup(sec) : NULL;
8716 if (sec && !sec_def->sec)
8717 return libbpf_err(-ENOMEM);
8718
8719 sec_def->prog_type = prog_type;
8720 sec_def->expected_attach_type = exp_attach_type;
8721 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8722
8723 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8724 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8725 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8726
8727 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8728
8729 if (sec)
8730 custom_sec_def_cnt++;
8731 else
8732 has_custom_fallback_def = true;
8733
8734 return sec_def->handler_id;
8735}
8736
8737int libbpf_unregister_prog_handler(int handler_id)
8738{
8739 struct bpf_sec_def *sec_defs;
8740 int i;
8741
8742 if (handler_id <= 0)
8743 return libbpf_err(-EINVAL);
8744
8745 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8746 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8747 has_custom_fallback_def = false;
8748 return 0;
8749 }
8750
8751 for (i = 0; i < custom_sec_def_cnt; i++) {
8752 if (custom_sec_defs[i].handler_id == handler_id)
8753 break;
8754 }
8755
8756 if (i == custom_sec_def_cnt)
8757 return libbpf_err(-ENOENT);
8758
8759 free(custom_sec_defs[i].sec);
8760 for (i = i + 1; i < custom_sec_def_cnt; i++)
8761 custom_sec_defs[i - 1] = custom_sec_defs[i];
8762 custom_sec_def_cnt--;
8763
8764 /* try to shrink the array, but it's ok if we couldn't */
8765 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8766 if (sec_defs)
8767 custom_sec_defs = sec_defs;
8768
8769 return 0;
8770}
8771
8772static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name,
8773 bool allow_sloppy)
8774{
8775 size_t len = strlen(sec_def->sec);
8776
8777 /* "type/" always has to have proper SEC("type/extras") form */
8778 if (sec_def->sec[len - 1] == '/') {
8779 if (str_has_pfx(sec_name, sec_def->sec))
8780 return true;
8781 return false;
8782 }
8783
8784 /* "type+" means it can be either exact SEC("type") or
8785 * well-formed SEC("type/extras") with proper '/' separator
8786 */
8787 if (sec_def->sec[len - 1] == '+') {
8788 len--;
8789 /* not even a prefix */
8790 if (strncmp(sec_name, sec_def->sec, len) != 0)
8791 return false;
8792 /* exact match or has '/' separator */
8793 if (sec_name[len] == '\0' || sec_name[len] == '/')
8794 return true;
8795 return false;
8796 }
8797
8798 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8799 * matches, unless strict section name mode
8800 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8801 * match has to be exact.
8802 */
8803 if (allow_sloppy && str_has_pfx(sec_name, sec_def->sec))
8804 return true;
8805
8806 /* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8807 * SEC("syscall")) are exact matches in both modes.
8808 */
8809 return strcmp(sec_name, sec_def->sec) == 0;
8810}
8811
8812static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8813{
8814 const struct bpf_sec_def *sec_def;
8815 int i, n;
8816 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME, allow_sloppy;
8817
8818 n = custom_sec_def_cnt;
8819 for (i = 0; i < n; i++) {
8820 sec_def = &custom_sec_defs[i];
8821 if (sec_def_matches(sec_def, sec_name, false))
8822 return sec_def;
8823 }
8824
8825 n = ARRAY_SIZE(section_defs);
8826 for (i = 0; i < n; i++) {
8827 sec_def = &section_defs[i];
8828 allow_sloppy = (sec_def->cookie & SEC_SLOPPY_PFX) && !strict;
8829 if (sec_def_matches(sec_def, sec_name, allow_sloppy))
dd94d45c 8830 return sec_def;
d7a18ea7 8831 }
697f104d
AN
8832
8833 if (has_custom_fallback_def)
8834 return &custom_fallback_def;
8835
d7a18ea7
AN
8836 return NULL;
8837}
8838
697f104d
AN
8839#define MAX_TYPE_NAME_SIZE 32
8840
c76e4c22
TS
8841static char *libbpf_get_type_names(bool attach_type)
8842{
d7a18ea7 8843 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
c76e4c22
TS
8844 char *buf;
8845
8846 buf = malloc(len);
8847 if (!buf)
8848 return NULL;
8849
8850 buf[0] = '\0';
8851 /* Forge string buf with all available names */
d7a18ea7 8852 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
15ea31fa
AN
8853 const struct bpf_sec_def *sec_def = &section_defs[i];
8854
8855 if (attach_type) {
4fa5bcfe 8856 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
15ea31fa
AN
8857 continue;
8858
8859 if (!(sec_def->cookie & SEC_ATTACHABLE))
8860 continue;
8861 }
c76e4c22 8862
d7a18ea7 8863 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
c76e4c22
TS
8864 free(buf);
8865 return NULL;
8866 }
8867 strcat(buf, " ");
d7a18ea7 8868 strcat(buf, section_defs[i].sec);
c76e4c22
TS
8869 }
8870
8871 return buf;
8872}
8873
b60df2a0
JK
8874int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8875 enum bpf_attach_type *expected_attach_type)
583c9009 8876{
d7a18ea7 8877 const struct bpf_sec_def *sec_def;
c76e4c22 8878 char *type_names;
583c9009 8879
b60df2a0 8880 if (!name)
e9fc3ce9 8881 return libbpf_err(-EINVAL);
583c9009 8882
d7a18ea7
AN
8883 sec_def = find_sec_def(name);
8884 if (sec_def) {
8885 *prog_type = sec_def->prog_type;
8886 *expected_attach_type = sec_def->expected_attach_type;
b60df2a0
JK
8887 return 0;
8888 }
d7a18ea7 8889
4a3d6c6a 8890 pr_debug("failed to guess program type from ELF section '%s'\n", name);
c76e4c22
TS
8891 type_names = libbpf_get_type_names(false);
8892 if (type_names != NULL) {
3f519353 8893 pr_debug("supported section(type) names are:%s\n", type_names);
c76e4c22
TS
8894 free(type_names);
8895 }
8896
e9fc3ce9 8897 return libbpf_err(-ESRCH);
b60df2a0 8898}
583c9009 8899
590a0088
MKL
8900static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8901 size_t offset)
8902{
8903 struct bpf_map *map;
8904 size_t i;
8905
8906 for (i = 0; i < obj->nr_maps; i++) {
8907 map = &obj->maps[i];
8908 if (!bpf_map__is_struct_ops(map))
8909 continue;
8910 if (map->sec_offset <= offset &&
8911 offset - map->sec_offset < map->def.value_size)
8912 return map;
8913 }
8914
8915 return NULL;
8916}
8917
8918/* Collect the reloc from ELF and populate the st_ops->progs[] */
646f02ff 8919static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 8920 Elf64_Shdr *shdr, Elf_Data *data)
590a0088
MKL
8921{
8922 const struct btf_member *member;
8923 struct bpf_struct_ops *st_ops;
8924 struct bpf_program *prog;
8925 unsigned int shdr_idx;
8926 const struct btf *btf;
8927 struct bpf_map *map;
7e06aad5 8928 unsigned int moff, insn_idx;
590a0088 8929 const char *name;
1d1a3bcf 8930 __u32 member_idx;
ad23b723
AN
8931 Elf64_Sym *sym;
8932 Elf64_Rel *rel;
590a0088
MKL
8933 int i, nrels;
8934
590a0088
MKL
8935 btf = obj->btf;
8936 nrels = shdr->sh_size / shdr->sh_entsize;
8937 for (i = 0; i < nrels; i++) {
ad23b723
AN
8938 rel = elf_rel_by_idx(data, i);
8939 if (!rel) {
590a0088
MKL
8940 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8941 return -LIBBPF_ERRNO__FORMAT;
8942 }
8943
ad23b723
AN
8944 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8945 if (!sym) {
590a0088 8946 pr_warn("struct_ops reloc: symbol %zx not found\n",
ad23b723 8947 (size_t)ELF64_R_SYM(rel->r_info));
590a0088
MKL
8948 return -LIBBPF_ERRNO__FORMAT;
8949 }
8950
ad23b723
AN
8951 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8952 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
590a0088 8953 if (!map) {
ad23b723
AN
8954 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8955 (size_t)rel->r_offset);
590a0088
MKL
8956 return -EINVAL;
8957 }
8958
ad23b723
AN
8959 moff = rel->r_offset - map->sec_offset;
8960 shdr_idx = sym->st_shndx;
590a0088 8961 st_ops = map->st_ops;
ad23b723 8962 pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
590a0088 8963 map->name,
ad23b723
AN
8964 (long long)(rel->r_info >> 32),
8965 (long long)sym->st_value,
8966 shdr_idx, (size_t)rel->r_offset,
8967 map->sec_offset, sym->st_name, name);
590a0088
MKL
8968
8969 if (shdr_idx >= SHN_LORESERVE) {
ad23b723
AN
8970 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8971 map->name, (size_t)rel->r_offset, shdr_idx);
590a0088
MKL
8972 return -LIBBPF_ERRNO__RELOC;
8973 }
ad23b723 8974 if (sym->st_value % BPF_INSN_SZ) {
7e06aad5 8975 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
ad23b723 8976 map->name, (unsigned long long)sym->st_value);
7e06aad5
AN
8977 return -LIBBPF_ERRNO__FORMAT;
8978 }
ad23b723 8979 insn_idx = sym->st_value / BPF_INSN_SZ;
590a0088
MKL
8980
8981 member = find_member_by_offset(st_ops->type, moff * 8);
8982 if (!member) {
8983 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8984 map->name, moff);
8985 return -EINVAL;
8986 }
8987 member_idx = member - btf_members(st_ops->type);
8988 name = btf__name_by_offset(btf, member->name_off);
8989
8990 if (!resolve_func_ptr(btf, member->type, NULL)) {
8991 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8992 map->name, name);
8993 return -EINVAL;
8994 }
8995
7e06aad5 8996 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
590a0088
MKL
8997 if (!prog) {
8998 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8999 map->name, shdr_idx, name);
9000 return -EINVAL;
9001 }
9002
91b4d1d1
AN
9003 /* prevent the use of BPF prog with invalid type */
9004 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9005 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9006 map->name, prog->name);
9007 return -EINVAL;
9008 }
590a0088 9009
91b4d1d1
AN
9010 /* if we haven't yet processed this BPF program, record proper
9011 * attach_btf_id and member_idx
9012 */
9013 if (!prog->attach_btf_id) {
590a0088
MKL
9014 prog->attach_btf_id = st_ops->type_id;
9015 prog->expected_attach_type = member_idx;
590a0088 9016 }
91b4d1d1
AN
9017
9018 /* struct_ops BPF prog can be re-used between multiple
9019 * .struct_ops as long as it's the same struct_ops struct
9020 * definition and the same function pointer field
9021 */
9022 if (prog->attach_btf_id != st_ops->type_id ||
9023 prog->expected_attach_type != member_idx) {
9024 pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
9025 map->name, prog->name, prog->sec_name, prog->type,
9026 prog->attach_btf_id, prog->expected_attach_type, name);
9027 return -EINVAL;
9028 }
9029
590a0088
MKL
9030 st_ops->progs[member_idx] = prog;
9031 }
9032
9033 return 0;
590a0088
MKL
9034}
9035
a6ed02ca 9036#define BTF_TRACE_PREFIX "btf_trace_"
1e092a03 9037#define BTF_LSM_PREFIX "bpf_lsm_"
21aef70e 9038#define BTF_ITER_PREFIX "bpf_iter_"
a6ed02ca
KS
9039#define BTF_MAX_NAME_SIZE 128
9040
67234743
AS
9041void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9042 const char **prefix, int *kind)
9043{
9044 switch (attach_type) {
9045 case BPF_TRACE_RAW_TP:
9046 *prefix = BTF_TRACE_PREFIX;
9047 *kind = BTF_KIND_TYPEDEF;
9048 break;
9049 case BPF_LSM_MAC:
9050 *prefix = BTF_LSM_PREFIX;
9051 *kind = BTF_KIND_FUNC;
9052 break;
9053 case BPF_TRACE_ITER:
9054 *prefix = BTF_ITER_PREFIX;
9055 *kind = BTF_KIND_FUNC;
9056 break;
9057 default:
9058 *prefix = "";
9059 *kind = BTF_KIND_FUNC;
9060 }
9061}
9062
a6ed02ca
KS
9063static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9064 const char *name, __u32 kind)
9065{
9066 char btf_type_name[BTF_MAX_NAME_SIZE];
9067 int ret;
9068
9069 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9070 "%s%s", prefix, name);
9071 /* snprintf returns the number of characters written excluding the
c139e40a 9072 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
a6ed02ca
KS
9073 * indicates truncation.
9074 */
9075 if (ret < 0 || ret >= sizeof(btf_type_name))
9076 return -ENAMETOOLONG;
9077 return btf__find_by_name_kind(btf, btf_type_name, kind);
9078}
9079
91abb4a6
AN
9080static inline int find_attach_btf_id(struct btf *btf, const char *name,
9081 enum bpf_attach_type attach_type)
a6ed02ca 9082{
67234743
AS
9083 const char *prefix;
9084 int kind;
a6ed02ca 9085
67234743
AS
9086 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9087 return find_btf_by_prefix_kind(btf, prefix, name, kind);
a6ed02ca
KS
9088}
9089
b8c54ea4
AS
9090int libbpf_find_vmlinux_btf_id(const char *name,
9091 enum bpf_attach_type attach_type)
12a8654b 9092{
a6ed02ca 9093 struct btf *btf;
3521ffa2 9094 int err;
12a8654b 9095
a710eed3 9096 btf = btf__load_vmlinux_btf();
e9fc3ce9
AN
9097 err = libbpf_get_error(btf);
9098 if (err) {
12a8654b 9099 pr_warn("vmlinux BTF is not found\n");
e9fc3ce9 9100 return libbpf_err(err);
12a8654b
AS
9101 }
9102
91abb4a6
AN
9103 err = find_attach_btf_id(btf, name, attach_type);
9104 if (err <= 0)
9105 pr_warn("%s is not found in vmlinux BTF\n", name);
9106
3521ffa2 9107 btf__free(btf);
e9fc3ce9 9108 return libbpf_err(err);
b8c54ea4
AS
9109}
9110
e7bf94db
AS
9111static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9112{
ebc7b50a
DM
9113 struct bpf_prog_info info = {};
9114 __u32 info_len = sizeof(info);
6cc93e2f 9115 struct btf *btf;
6d2d73cd 9116 int err;
e7bf94db 9117
ebc7b50a 9118 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
e9fc3ce9 9119 if (err) {
ebc7b50a
DM
9120 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9121 attach_prog_fd, err);
e9fc3ce9 9122 return err;
e7bf94db 9123 }
6d2d73cd
QM
9124
9125 err = -EINVAL;
ebc7b50a 9126 if (!info.btf_id) {
e7bf94db
AS
9127 pr_warn("The target program doesn't have BTF\n");
9128 goto out;
9129 }
ebc7b50a
DM
9130 btf = btf__load_from_kernel_by_id(info.btf_id);
9131 err = libbpf_get_error(btf);
9132 if (err) {
9133 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
e7bf94db
AS
9134 goto out;
9135 }
9136 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9137 btf__free(btf);
9138 if (err <= 0) {
9139 pr_warn("%s is not found in prog's BTF\n", name);
9140 goto out;
9141 }
9142out:
e7bf94db
AS
9143 return err;
9144}
9145
91abb4a6
AN
9146static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9147 enum bpf_attach_type attach_type,
9148 int *btf_obj_fd, int *btf_type_id)
9149{
9150 int ret, i;
9151
9152 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9153 if (ret > 0) {
9154 *btf_obj_fd = 0; /* vmlinux BTF */
9155 *btf_type_id = ret;
9156 return 0;
9157 }
9158 if (ret != -ENOENT)
9159 return ret;
9160
9161 ret = load_module_btfs(obj);
9162 if (ret)
9163 return ret;
9164
9165 for (i = 0; i < obj->btf_module_cnt; i++) {
9166 const struct module_btf *mod = &obj->btf_modules[i];
9167
9168 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9169 if (ret > 0) {
9170 *btf_obj_fd = mod->fd;
9171 *btf_type_id = ret;
9172 return 0;
9173 }
9174 if (ret == -ENOENT)
9175 continue;
9176
9177 return ret;
9178 }
9179
9180 return -ESRCH;
9181}
9182
15ea31fa
AN
9183static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9184 int *btf_obj_fd, int *btf_type_id)
b8c54ea4 9185{
a6ed02ca
KS
9186 enum bpf_attach_type attach_type = prog->expected_attach_type;
9187 __u32 attach_prog_fd = prog->attach_prog_fd;
b6291a6f 9188 int err = 0;
b8c54ea4 9189
91abb4a6
AN
9190 /* BPF program's BTF ID */
9191 if (attach_prog_fd) {
9192 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9193 if (err < 0) {
9194 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9195 attach_prog_fd, attach_name, err);
9196 return err;
9197 }
9198 *btf_obj_fd = 0;
9199 *btf_type_id = err;
9200 return 0;
9201 }
9202
9203 /* kernel/module BTF ID */
67234743
AS
9204 if (prog->obj->gen_loader) {
9205 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9206 *btf_obj_fd = 0;
9207 *btf_type_id = 1;
9208 } else {
9209 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9210 }
91abb4a6
AN
9211 if (err) {
9212 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
b8c54ea4 9213 return err;
12a8654b 9214 }
91abb4a6 9215 return 0;
12a8654b
AS
9216}
9217
956b620f
AI
9218int libbpf_attach_type_by_name(const char *name,
9219 enum bpf_attach_type *attach_type)
9220{
c76e4c22 9221 char *type_names;
b6291a6f 9222 const struct bpf_sec_def *sec_def;
956b620f
AI
9223
9224 if (!name)
e9fc3ce9 9225 return libbpf_err(-EINVAL);
956b620f 9226
b6291a6f
AN
9227 sec_def = find_sec_def(name);
9228 if (!sec_def) {
9229 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9230 type_names = libbpf_get_type_names(true);
9231 if (type_names != NULL) {
9232 pr_debug("attachable section(type) names are:%s\n", type_names);
9233 free(type_names);
9234 }
9235
9236 return libbpf_err(-EINVAL);
c76e4c22
TS
9237 }
9238
4fa5bcfe 9239 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
15ea31fa
AN
9240 return libbpf_err(-EINVAL);
9241 if (!(sec_def->cookie & SEC_ATTACHABLE))
b6291a6f
AN
9242 return libbpf_err(-EINVAL);
9243
9244 *attach_type = sec_def->expected_attach_type;
9245 return 0;
956b620f
AI
9246}
9247
a324aae3 9248int bpf_map__fd(const struct bpf_map *map)
9d759a9b 9249{
e9fc3ce9 9250 return map ? map->fd : libbpf_err(-EINVAL);
9d759a9b
WN
9251}
9252
a324aae3 9253const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9d759a9b 9254{
e9fc3ce9 9255 return map ? &map->def : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9256}
9257
aed65917
AN
9258static bool map_uses_real_name(const struct bpf_map *map)
9259{
9260 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9261 * their user-visible name differs from kernel-visible name. Users see
9262 * such map's corresponding ELF section name as a map name.
9263 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9264 * maps to know which name has to be returned to the user.
9265 */
9266 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9267 return true;
9268 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9269 return true;
9270 return false;
9271}
9272
a324aae3 9273const char *bpf_map__name(const struct bpf_map *map)
561bbcca 9274{
aed65917
AN
9275 if (!map)
9276 return NULL;
9277
9278 if (map_uses_real_name(map))
9279 return map->real_name;
9280
9281 return map->name;
561bbcca
WN
9282}
9283
1bdb6c9a
AN
9284enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9285{
9286 return map->def.type;
9287}
9288
9289int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9290{
9291 if (map->fd >= 0)
e9fc3ce9 9292 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9293 map->def.type = type;
9294 return 0;
9295}
9296
9297__u32 bpf_map__map_flags(const struct bpf_map *map)
9298{
9299 return map->def.map_flags;
9300}
9301
9302int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9303{
9304 if (map->fd >= 0)
e9fc3ce9 9305 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9306 map->def.map_flags = flags;
9307 return 0;
9308}
9309
47512102
JK
9310__u64 bpf_map__map_extra(const struct bpf_map *map)
9311{
9312 return map->map_extra;
9313}
9314
9315int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9316{
9317 if (map->fd >= 0)
9318 return libbpf_err(-EBUSY);
9319 map->map_extra = map_extra;
9320 return 0;
9321}
9322
1bdb6c9a
AN
9323__u32 bpf_map__numa_node(const struct bpf_map *map)
9324{
9325 return map->numa_node;
9326}
9327
9328int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9329{
9330 if (map->fd >= 0)
e9fc3ce9 9331 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9332 map->numa_node = numa_node;
9333 return 0;
9334}
9335
9336__u32 bpf_map__key_size(const struct bpf_map *map)
9337{
9338 return map->def.key_size;
9339}
9340
9341int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9342{
9343 if (map->fd >= 0)
e9fc3ce9 9344 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9345 map->def.key_size = size;
9346 return 0;
9347}
9348
9349__u32 bpf_map__value_size(const struct bpf_map *map)
9350{
9351 return map->def.value_size;
9352}
9353
9354int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9355{
9356 if (map->fd >= 0)
e9fc3ce9 9357 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9358 map->def.value_size = size;
9359 return 0;
9360}
9361
5b891af7 9362__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8a138aed 9363{
61746dbe 9364 return map ? map->btf_key_type_id : 0;
8a138aed
MKL
9365}
9366
5b891af7 9367__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8a138aed 9368{
61746dbe 9369 return map ? map->btf_value_type_id : 0;
8a138aed
MKL
9370}
9371
edb13ed4
ACM
9372int bpf_map__set_priv(struct bpf_map *map, void *priv,
9373 bpf_map_clear_priv_t clear_priv)
9d759a9b
WN
9374{
9375 if (!map)
e9fc3ce9 9376 return libbpf_err(-EINVAL);
9d759a9b
WN
9377
9378 if (map->priv) {
9379 if (map->clear_priv)
9380 map->clear_priv(map, map->priv);
9381 }
9382
9383 map->priv = priv;
9384 map->clear_priv = clear_priv;
9385 return 0;
9386}
9387
a324aae3 9388void *bpf_map__priv(const struct bpf_map *map)
9d759a9b 9389{
e9fc3ce9 9390 return map ? map->priv : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9391}
9392
e2842be5
THJ
9393int bpf_map__set_initial_value(struct bpf_map *map,
9394 const void *data, size_t size)
9395{
9396 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9397 size != map->def.value_size || map->fd >= 0)
e9fc3ce9 9398 return libbpf_err(-EINVAL);
e2842be5
THJ
9399
9400 memcpy(map->mmaped, data, size);
9401 return 0;
9402}
9403
7723256b
AS
9404const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9405{
9406 if (!map->mmaped)
9407 return NULL;
9408 *psize = map->def.value_size;
9409 return map->mmaped;
9410}
9411
a324aae3 9412bool bpf_map__is_offload_neutral(const struct bpf_map *map)
f83fb22c
JK
9413{
9414 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9415}
9416
a324aae3 9417bool bpf_map__is_internal(const struct bpf_map *map)
d859900c
DB
9418{
9419 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9420}
9421
1bdb6c9a
AN
9422__u32 bpf_map__ifindex(const struct bpf_map *map)
9423{
9424 return map->map_ifindex;
9425}
9426
9427int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9aba3613 9428{
1bdb6c9a 9429 if (map->fd >= 0)
e9fc3ce9 9430 return libbpf_err(-EBUSY);
9aba3613 9431 map->map_ifindex = ifindex;
1bdb6c9a 9432 return 0;
9aba3613
JK
9433}
9434
addb9fc9
NS
9435int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9436{
9437 if (!bpf_map_type__is_map_in_map(map->def.type)) {
be18010e 9438 pr_warn("error: unsupported map type\n");
e9fc3ce9 9439 return libbpf_err(-EINVAL);
addb9fc9
NS
9440 }
9441 if (map->inner_map_fd != -1) {
be18010e 9442 pr_warn("error: inner_map_fd already specified\n");
e9fc3ce9 9443 return libbpf_err(-EINVAL);
addb9fc9 9444 }
8f7b239e
AN
9445 if (map->inner_map) {
9446 bpf_map__destroy(map->inner_map);
9447 zfree(&map->inner_map);
9448 }
addb9fc9
NS
9449 map->inner_map_fd = fd;
9450 return 0;
9451}
9452
0c19a9fb 9453static struct bpf_map *
a324aae3 9454__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9d759a9b 9455{
0c19a9fb 9456 ssize_t idx;
9d759a9b
WN
9457 struct bpf_map *s, *e;
9458
9459 if (!obj || !obj->maps)
e9fc3ce9 9460 return errno = EINVAL, NULL;
9d759a9b
WN
9461
9462 s = obj->maps;
9463 e = obj->maps + obj->nr_maps;
9464
0c19a9fb 9465 if ((m < s) || (m >= e)) {
be18010e
KW
9466 pr_warn("error in %s: map handler doesn't belong to object\n",
9467 __func__);
e9fc3ce9 9468 return errno = EINVAL, NULL;
9d759a9b
WN
9469 }
9470
0c19a9fb
SF
9471 idx = (m - obj->maps) + i;
9472 if (idx >= obj->nr_maps || idx < 0)
9d759a9b
WN
9473 return NULL;
9474 return &obj->maps[idx];
9475}
561bbcca 9476
0c19a9fb 9477struct bpf_map *
a324aae3 9478bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
2088a3a7
HC
9479{
9480 return bpf_object__next_map(obj, prev);
9481}
9482
9483struct bpf_map *
9484bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
0c19a9fb
SF
9485{
9486 if (prev == NULL)
9487 return obj->maps;
9488
9489 return __bpf_map__iter(prev, obj, 1);
9490}
9491
9492struct bpf_map *
a324aae3 9493bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
2088a3a7
HC
9494{
9495 return bpf_object__prev_map(obj, next);
9496}
9497
9498struct bpf_map *
9499bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
0c19a9fb
SF
9500{
9501 if (next == NULL) {
9502 if (!obj->nr_maps)
9503 return NULL;
9504 return obj->maps + obj->nr_maps - 1;
9505 }
9506
9507 return __bpf_map__iter(next, obj, -1);
9508}
9509
561bbcca 9510struct bpf_map *
a324aae3 9511bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
561bbcca
WN
9512{
9513 struct bpf_map *pos;
9514
f74a53d9 9515 bpf_object__for_each_map(pos, obj) {
26071635
AN
9516 /* if it's a special internal map name (which always starts
9517 * with dot) then check if that special name matches the
9518 * real map name (ELF section name)
9519 */
9520 if (name[0] == '.') {
9521 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9522 return pos;
9523 continue;
9524 }
9525 /* otherwise map name has to be an exact match */
aed65917
AN
9526 if (map_uses_real_name(pos)) {
9527 if (strcmp(pos->real_name, name) == 0)
9528 return pos;
9529 continue;
9530 }
9531 if (strcmp(pos->name, name) == 0)
561bbcca
WN
9532 return pos;
9533 }
e9fc3ce9 9534 return errno = ENOENT, NULL;
561bbcca 9535}
5a6acad1 9536
f3cea32d 9537int
a324aae3 9538bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
f3cea32d
MF
9539{
9540 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9541}
9542
5a6acad1
WN
9543struct bpf_map *
9544bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9545{
e9fc3ce9 9546 return libbpf_err_ptr(-ENOTSUP);
5a6acad1 9547}
e28ff1a8
JS
9548
9549long libbpf_get_error(const void *ptr)
9550{
e9fc3ce9
AN
9551 if (!IS_ERR_OR_NULL(ptr))
9552 return 0;
9553
9554 if (IS_ERR(ptr))
9555 errno = -PTR_ERR(ptr);
9556
9557 /* If ptr == NULL, then errno should be already set by the failing
9558 * API, because libbpf never returns NULL on success and it now always
9559 * sets errno on error. So no extra errno handling for ptr == NULL
9560 * case.
9561 */
9562 return -errno;
e28ff1a8 9563}
6f6d33f3 9564
e32660ac 9565__attribute__((alias("bpf_prog_load_xattr2")))
d7be143b 9566int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
e32660ac
AN
9567 struct bpf_object **pobj, int *prog_fd);
9568
9569static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
9570 struct bpf_object **pobj, int *prog_fd)
6f6d33f3 9571{
33bae185 9572 struct bpf_object_open_attr open_attr = {};
48cca7e4 9573 struct bpf_program *prog, *first_prog = NULL;
6f6d33f3 9574 struct bpf_object *obj;
f0307a7e 9575 struct bpf_map *map;
6f6d33f3
JF
9576 int err;
9577
d7be143b 9578 if (!attr)
e9fc3ce9 9579 return libbpf_err(-EINVAL);
17387dd5 9580 if (!attr->file)
e9fc3ce9 9581 return libbpf_err(-EINVAL);
d7be143b 9582
33bae185
LY
9583 open_attr.file = attr->file;
9584 open_attr.prog_type = attr->prog_type;
9585
fc763870 9586 obj = __bpf_object__open_xattr(&open_attr, 0);
e9fc3ce9
AN
9587 err = libbpf_get_error(obj);
9588 if (err)
9589 return libbpf_err(-ENOENT);
6f6d33f3 9590
48cca7e4 9591 bpf_object__for_each_program(prog, obj) {
dd4436bb 9592 enum bpf_attach_type attach_type = attr->expected_attach_type;
48cca7e4 9593 /*
dd4436bb
AN
9594 * to preserve backwards compatibility, bpf_prog_load treats
9595 * attr->prog_type, if specified, as an override to whatever
9596 * bpf_object__open guessed
48cca7e4 9597 */
dd4436bb
AN
9598 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
9599 bpf_program__set_type(prog, attr->prog_type);
9600 bpf_program__set_expected_attach_type(prog,
9601 attach_type);
9602 }
20eccf29 9603 if (bpf_program__type(prog) == BPF_PROG_TYPE_UNSPEC) {
dd4436bb
AN
9604 /*
9605 * we haven't guessed from section name and user
9606 * didn't provide a fallback type, too bad...
9607 */
9608 bpf_object__close(obj);
e9fc3ce9 9609 return libbpf_err(-EINVAL);
583c9009 9610 }
48cca7e4 9611
dd4436bb 9612 prog->prog_ifindex = attr->ifindex;
da11b417 9613 prog->log_level = attr->log_level;
2b288740 9614 prog->prog_flags |= attr->prog_flags;
69495d2a 9615 if (!first_prog)
48cca7e4
AS
9616 first_prog = prog;
9617 }
9618
f74a53d9 9619 bpf_object__for_each_map(map, obj) {
a5dd9589 9620 if (map->def.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
f83fb22c 9621 map->map_ifindex = attr->ifindex;
f0307a7e
DB
9622 }
9623
48cca7e4 9624 if (!first_prog) {
be18010e 9625 pr_warn("object file doesn't contain bpf program\n");
48cca7e4 9626 bpf_object__close(obj);
e9fc3ce9 9627 return libbpf_err(-ENOENT);
583c9009
RG
9628 }
9629
6f6d33f3
JF
9630 err = bpf_object__load(obj);
9631 if (err) {
9632 bpf_object__close(obj);
e9fc3ce9 9633 return libbpf_err(err);
6f6d33f3
JF
9634 }
9635
9636 *pobj = obj;
48cca7e4 9637 *prog_fd = bpf_program__fd(first_prog);
6f6d33f3
JF
9638 return 0;
9639}
d0cabbb0 9640
e32660ac
AN
9641COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
9642int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
9643 struct bpf_object **pobj, int *prog_fd)
9644{
9645 struct bpf_prog_load_attr attr;
9646
9647 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9648 attr.file = file;
9649 attr.prog_type = type;
9650 attr.expected_attach_type = 0;
9651
9652 return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
9653}
9654
1c2e9efc 9655struct bpf_link {
d6958706 9656 int (*detach)(struct bpf_link *link);
d88b71d4 9657 void (*dealloc)(struct bpf_link *link);
c016b68e
AN
9658 char *pin_path; /* NULL, if not pinned */
9659 int fd; /* hook FD, -1 if not applicable */
d6958706 9660 bool disconnected;
1c2e9efc
AN
9661};
9662
cc4f864b
AN
9663/* Replace link's underlying BPF program with the new one */
9664int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9665{
e9fc3ce9 9666 int ret;
c139e40a 9667
e9fc3ce9
AN
9668 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9669 return libbpf_err_errno(ret);
cc4f864b
AN
9670}
9671
d6958706
AN
9672/* Release "ownership" of underlying BPF resource (typically, BPF program
9673 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9674 * link, when destructed through bpf_link__destroy() call won't attempt to
9675 * detach/unregisted that BPF resource. This is useful in situations where,
9676 * say, attached BPF program has to outlive userspace program that attached it
9677 * in the system. Depending on type of BPF program, though, there might be
9678 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9679 * exit of userspace program doesn't trigger automatic detachment and clean up
9680 * inside the kernel.
9681 */
9682void bpf_link__disconnect(struct bpf_link *link)
9683{
9684 link->disconnected = true;
9685}
9686
1c2e9efc
AN
9687int bpf_link__destroy(struct bpf_link *link)
9688{
d6958706 9689 int err = 0;
1c2e9efc 9690
50450fc7 9691 if (IS_ERR_OR_NULL(link))
1c2e9efc
AN
9692 return 0;
9693
d6958706
AN
9694 if (!link->disconnected && link->detach)
9695 err = link->detach(link);
c016b68e
AN
9696 if (link->pin_path)
9697 free(link->pin_path);
d88b71d4
AN
9698 if (link->dealloc)
9699 link->dealloc(link);
9700 else
9701 free(link);
1c2e9efc 9702
e9fc3ce9 9703 return libbpf_err(err);
1c2e9efc
AN
9704}
9705
c016b68e
AN
9706int bpf_link__fd(const struct bpf_link *link)
9707{
9708 return link->fd;
9709}
9710
9711const char *bpf_link__pin_path(const struct bpf_link *link)
9712{
9713 return link->pin_path;
9714}
9715
9716static int bpf_link__detach_fd(struct bpf_link *link)
9717{
e9fc3ce9 9718 return libbpf_err_errno(close(link->fd));
c016b68e
AN
9719}
9720
9721struct bpf_link *bpf_link__open(const char *path)
9722{
9723 struct bpf_link *link;
9724 int fd;
9725
9726 fd = bpf_obj_get(path);
9727 if (fd < 0) {
9728 fd = -errno;
9729 pr_warn("failed to open link at %s: %d\n", path, fd);
e9fc3ce9 9730 return libbpf_err_ptr(fd);
c016b68e
AN
9731 }
9732
9733 link = calloc(1, sizeof(*link));
9734 if (!link) {
9735 close(fd);
e9fc3ce9 9736 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9737 }
9738 link->detach = &bpf_link__detach_fd;
9739 link->fd = fd;
9740
9741 link->pin_path = strdup(path);
9742 if (!link->pin_path) {
9743 bpf_link__destroy(link);
e9fc3ce9 9744 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9745 }
9746
9747 return link;
9748}
9749
2e49527e
AN
9750int bpf_link__detach(struct bpf_link *link)
9751{
9752 return bpf_link_detach(link->fd) ? -errno : 0;
9753}
9754
c016b68e
AN
9755int bpf_link__pin(struct bpf_link *link, const char *path)
9756{
9757 int err;
9758
9759 if (link->pin_path)
e9fc3ce9 9760 return libbpf_err(-EBUSY);
c016b68e
AN
9761 err = make_parent_dir(path);
9762 if (err)
e9fc3ce9 9763 return libbpf_err(err);
c016b68e
AN
9764 err = check_path(path);
9765 if (err)
e9fc3ce9 9766 return libbpf_err(err);
c016b68e
AN
9767
9768 link->pin_path = strdup(path);
9769 if (!link->pin_path)
e9fc3ce9 9770 return libbpf_err(-ENOMEM);
c016b68e
AN
9771
9772 if (bpf_obj_pin(link->fd, link->pin_path)) {
9773 err = -errno;
9774 zfree(&link->pin_path);
e9fc3ce9 9775 return libbpf_err(err);
c016b68e
AN
9776 }
9777
9778 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9779 return 0;
9780}
9781
9782int bpf_link__unpin(struct bpf_link *link)
9783{
9784 int err;
9785
9786 if (!link->pin_path)
e9fc3ce9 9787 return libbpf_err(-EINVAL);
c016b68e
AN
9788
9789 err = unlink(link->pin_path);
9790 if (err != 0)
af0efa05 9791 return -errno;
c016b68e
AN
9792
9793 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9794 zfree(&link->pin_path);
9795 return 0;
9796}
63f2f5ee 9797
668ace0e
AN
9798struct bpf_link_perf {
9799 struct bpf_link link;
9800 int perf_event_fd;
ca304b40
RDT
9801 /* legacy kprobe support: keep track of probe identifier and type */
9802 char *legacy_probe_name;
46ed5fc3 9803 bool legacy_is_kprobe;
ca304b40 9804 bool legacy_is_retprobe;
668ace0e
AN
9805};
9806
46ed5fc3 9807static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
cc10623c 9808static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
46ed5fc3 9809
668ace0e 9810static int bpf_link_perf_detach(struct bpf_link *link)
63f2f5ee 9811{
668ace0e
AN
9812 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9813 int err = 0;
63f2f5ee 9814
668ace0e 9815 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
63f2f5ee
AN
9816 err = -errno;
9817
668ace0e
AN
9818 if (perf_link->perf_event_fd != link->fd)
9819 close(perf_link->perf_event_fd);
c016b68e 9820 close(link->fd);
668ace0e 9821
cc10623c 9822 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
46ed5fc3
AN
9823 if (perf_link->legacy_probe_name) {
9824 if (perf_link->legacy_is_kprobe) {
9825 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9826 perf_link->legacy_is_retprobe);
cc10623c
AN
9827 } else {
9828 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9829 perf_link->legacy_is_retprobe);
46ed5fc3
AN
9830 }
9831 }
ca304b40
RDT
9832
9833 return err;
63f2f5ee
AN
9834}
9835
668ace0e
AN
9836static void bpf_link_perf_dealloc(struct bpf_link *link)
9837{
9838 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9839
ca304b40 9840 free(perf_link->legacy_probe_name);
668ace0e
AN
9841 free(perf_link);
9842}
9843
942025c9 9844struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
47faff37 9845 const struct bpf_perf_event_opts *opts)
63f2f5ee
AN
9846{
9847 char errmsg[STRERR_BUFSIZE];
668ace0e
AN
9848 struct bpf_link_perf *link;
9849 int prog_fd, link_fd = -1, err;
63f2f5ee 9850
47faff37
AN
9851 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9852 return libbpf_err_ptr(-EINVAL);
9853
63f2f5ee 9854 if (pfd < 0) {
52109584
AN
9855 pr_warn("prog '%s': invalid perf event FD %d\n",
9856 prog->name, pfd);
e9fc3ce9 9857 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9858 }
9859 prog_fd = bpf_program__fd(prog);
9860 if (prog_fd < 0) {
52109584
AN
9861 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9862 prog->name);
e9fc3ce9 9863 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9864 }
9865
d6958706 9866 link = calloc(1, sizeof(*link));
63f2f5ee 9867 if (!link)
e9fc3ce9 9868 return libbpf_err_ptr(-ENOMEM);
668ace0e
AN
9869 link->link.detach = &bpf_link_perf_detach;
9870 link->link.dealloc = &bpf_link_perf_dealloc;
9871 link->perf_event_fd = pfd;
63f2f5ee 9872
668ace0e 9873 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
47faff37
AN
9874 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9875 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9876
9877 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
668ace0e
AN
9878 if (link_fd < 0) {
9879 err = -errno;
9880 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9881 prog->name, pfd,
9882 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9883 goto err_out;
9884 }
9885 link->link.fd = link_fd;
9886 } else {
47faff37
AN
9887 if (OPTS_GET(opts, bpf_cookie, 0)) {
9888 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9889 err = -EOPNOTSUPP;
9890 goto err_out;
9891 }
9892
668ace0e
AN
9893 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9894 err = -errno;
9895 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9896 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9897 if (err == -EPROTO)
9898 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9899 prog->name, pfd);
9900 goto err_out;
9901 }
9902 link->link.fd = pfd;
63f2f5ee
AN
9903 }
9904 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9905 err = -errno;
668ace0e 9906 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
52109584 9907 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
668ace0e 9908 goto err_out;
63f2f5ee 9909 }
668ace0e
AN
9910
9911 return &link->link;
9912err_out:
9913 if (link_fd >= 0)
9914 close(link_fd);
9915 free(link);
9916 return libbpf_err_ptr(err);
63f2f5ee
AN
9917}
9918
942025c9 9919struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
47faff37
AN
9920{
9921 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9922}
9923
b2650027
AN
9924/*
9925 * this function is expected to parse integer in the range of [0, 2^31-1] from
9926 * given file using scanf format string fmt. If actual parsed value is
9927 * negative, the result might be indistinguishable from error
9928 */
9929static int parse_uint_from_file(const char *file, const char *fmt)
9930{
9931 char buf[STRERR_BUFSIZE];
9932 int err, ret;
9933 FILE *f;
9934
9935 f = fopen(file, "r");
9936 if (!f) {
9937 err = -errno;
9938 pr_debug("failed to open '%s': %s\n", file,
9939 libbpf_strerror_r(err, buf, sizeof(buf)));
9940 return err;
9941 }
9942 err = fscanf(f, fmt, &ret);
9943 if (err != 1) {
9944 err = err == EOF ? -EIO : -errno;
9945 pr_debug("failed to parse '%s': %s\n", file,
9946 libbpf_strerror_r(err, buf, sizeof(buf)));
9947 fclose(f);
9948 return err;
9949 }
9950 fclose(f);
9951 return ret;
9952}
9953
9954static int determine_kprobe_perf_type(void)
9955{
9956 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9957
9958 return parse_uint_from_file(file, "%d\n");
9959}
9960
9961static int determine_uprobe_perf_type(void)
9962{
9963 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9964
9965 return parse_uint_from_file(file, "%d\n");
9966}
9967
9968static int determine_kprobe_retprobe_bit(void)
9969{
9970 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9971
9972 return parse_uint_from_file(file, "config:%d\n");
9973}
9974
9975static int determine_uprobe_retprobe_bit(void)
9976{
9977 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9978
9979 return parse_uint_from_file(file, "config:%d\n");
9980}
9981
5e3b8356
AN
9982#define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9983#define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9984
b2650027 9985static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5e3b8356 9986 uint64_t offset, int pid, size_t ref_ctr_off)
b2650027
AN
9987{
9988 struct perf_event_attr attr = {};
9989 char errmsg[STRERR_BUFSIZE];
9990 int type, pfd, err;
9991
5e3b8356
AN
9992 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9993 return -EINVAL;
9994
b2650027
AN
9995 type = uprobe ? determine_uprobe_perf_type()
9996 : determine_kprobe_perf_type();
9997 if (type < 0) {
be18010e
KW
9998 pr_warn("failed to determine %s perf type: %s\n",
9999 uprobe ? "uprobe" : "kprobe",
10000 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
b2650027
AN
10001 return type;
10002 }
10003 if (retprobe) {
10004 int bit = uprobe ? determine_uprobe_retprobe_bit()
10005 : determine_kprobe_retprobe_bit();
10006
10007 if (bit < 0) {
be18010e
KW
10008 pr_warn("failed to determine %s retprobe bit: %s\n",
10009 uprobe ? "uprobe" : "kprobe",
10010 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
b2650027
AN
10011 return bit;
10012 }
10013 attr.config |= 1 << bit;
10014 }
10015 attr.size = sizeof(attr);
10016 attr.type = type;
5e3b8356 10017 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
36db2a94
AN
10018 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10019 attr.config2 = offset; /* kprobe_addr or probe_offset */
b2650027
AN
10020
10021 /* pid filter is meaningful only for uprobes */
10022 pfd = syscall(__NR_perf_event_open, &attr,
10023 pid < 0 ? -1 : pid /* pid */,
10024 pid == -1 ? 0 : -1 /* cpu */,
10025 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10026 if (pfd < 0) {
10027 err = -errno;
be18010e
KW
10028 pr_warn("%s perf_event_open() failed: %s\n",
10029 uprobe ? "uprobe" : "kprobe",
10030 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
b2650027
AN
10031 return err;
10032 }
10033 return pfd;
10034}
10035
46ed5fc3
AN
10036static int append_to_file(const char *file, const char *fmt, ...)
10037{
10038 int fd, n, err = 0;
10039 va_list ap;
10040
92274e24 10041 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
46ed5fc3
AN
10042 if (fd < 0)
10043 return -errno;
10044
10045 va_start(ap, fmt);
10046 n = vdprintf(fd, fmt, ap);
10047 va_end(ap);
10048
10049 if (n < 0)
10050 err = -errno;
10051
10052 close(fd);
10053 return err;
10054}
10055
10056static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10057 const char *kfunc_name, size_t offset)
10058{
51a33c60
QW
10059 static int index = 0;
10060
10061 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10062 __sync_fetch_and_add(&index, 1));
46ed5fc3
AN
10063}
10064
10065static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10066 const char *kfunc_name, size_t offset)
10067{
10068 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10069
10070 return append_to_file(file, "%c:%s/%s %s+0x%zx",
10071 retprobe ? 'r' : 'p',
10072 retprobe ? "kretprobes" : "kprobes",
10073 probe_name, kfunc_name, offset);
10074}
10075
10076static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10077{
10078 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10079
10080 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
10081}
10082
10083static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10084{
10085 char file[256];
10086
10087 snprintf(file, sizeof(file),
10088 "/sys/kernel/debug/tracing/events/%s/%s/id",
10089 retprobe ? "kretprobes" : "kprobes", probe_name);
10090
10091 return parse_uint_from_file(file, "%d\n");
10092}
10093
10094static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10095 const char *kfunc_name, size_t offset, int pid)
ca304b40
RDT
10096{
10097 struct perf_event_attr attr = {};
10098 char errmsg[STRERR_BUFSIZE];
10099 int type, pfd, err;
10100
46ed5fc3 10101 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
ca304b40 10102 if (err < 0) {
46ed5fc3
AN
10103 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10104 kfunc_name, offset,
ca304b40
RDT
10105 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10106 return err;
10107 }
46ed5fc3 10108 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
ca304b40 10109 if (type < 0) {
46ed5fc3
AN
10110 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10111 kfunc_name, offset,
ca304b40
RDT
10112 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10113 return type;
10114 }
10115 attr.size = sizeof(attr);
10116 attr.config = type;
10117 attr.type = PERF_TYPE_TRACEPOINT;
10118
10119 pfd = syscall(__NR_perf_event_open, &attr,
10120 pid < 0 ? -1 : pid, /* pid */
10121 pid == -1 ? 0 : -1, /* cpu */
10122 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10123 if (pfd < 0) {
10124 err = -errno;
10125 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10126 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10127 return err;
10128 }
10129 return pfd;
10130}
10131
da97553e 10132struct bpf_link *
942025c9 10133bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
ac0ed488 10134 const char *func_name,
47faff37 10135 const struct bpf_kprobe_opts *opts)
b2650027 10136{
47faff37 10137 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
b2650027 10138 char errmsg[STRERR_BUFSIZE];
ca304b40 10139 char *legacy_probe = NULL;
b2650027 10140 struct bpf_link *link;
46ed5fc3 10141 size_t offset;
ca304b40 10142 bool retprobe, legacy;
b2650027
AN
10143 int pfd, err;
10144
da97553e
JO
10145 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10146 return libbpf_err_ptr(-EINVAL);
10147
10148 retprobe = OPTS_GET(opts, retprobe, false);
10149 offset = OPTS_GET(opts, offset, 0);
47faff37 10150 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
da97553e 10151
ca304b40
RDT
10152 legacy = determine_kprobe_perf_type() < 0;
10153 if (!legacy) {
10154 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10155 func_name, offset,
10156 -1 /* pid */, 0 /* ref_ctr_off */);
10157 } else {
46ed5fc3
AN
10158 char probe_name[256];
10159
10160 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10161 func_name, offset);
10162
71cff670 10163 legacy_probe = strdup(probe_name);
ca304b40
RDT
10164 if (!legacy_probe)
10165 return libbpf_err_ptr(-ENOMEM);
10166
46ed5fc3 10167 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
ca304b40
RDT
10168 offset, -1 /* pid */);
10169 }
b2650027 10170 if (pfd < 0) {
46ed5fc3
AN
10171 err = -errno;
10172 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10173 prog->name, retprobe ? "kretprobe" : "kprobe",
10174 func_name, offset,
303a2572
AN
10175 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10176 goto err_out;
b2650027 10177 }
47faff37 10178 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10179 err = libbpf_get_error(link);
10180 if (err) {
b2650027 10181 close(pfd);
46ed5fc3
AN
10182 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10183 prog->name, retprobe ? "kretprobe" : "kprobe",
10184 func_name, offset,
be18010e 10185 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
303a2572 10186 goto err_out;
b2650027 10187 }
ca304b40
RDT
10188 if (legacy) {
10189 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10190
10191 perf_link->legacy_probe_name = legacy_probe;
46ed5fc3 10192 perf_link->legacy_is_kprobe = true;
ca304b40
RDT
10193 perf_link->legacy_is_retprobe = retprobe;
10194 }
10195
b2650027 10196 return link;
303a2572
AN
10197err_out:
10198 free(legacy_probe);
10199 return libbpf_err_ptr(err);
b2650027
AN
10200}
10201
942025c9 10202struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
ac0ed488
JO
10203 bool retprobe,
10204 const char *func_name)
10205{
da97553e 10206 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
ac0ed488 10207 .retprobe = retprobe,
da97553e 10208 );
ac0ed488
JO
10209
10210 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10211}
10212
4fa5bcfe 10213static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 10214{
da97553e 10215 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
a2488b5f 10216 unsigned long offset = 0;
d7a18ea7 10217 const char *func_name;
a2488b5f 10218 char *func;
4fa5bcfe 10219 int n;
d7a18ea7 10220
13d35a0c
AN
10221 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10222 if (opts.retprobe)
10223 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10224 else
10225 func_name = prog->sec_name + sizeof("kprobe/") - 1;
d7a18ea7 10226
e3f9bc35 10227 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
a2488b5f 10228 if (n < 1) {
a2488b5f 10229 pr_warn("kprobe name is invalid: %s\n", func_name);
4fa5bcfe 10230 return -EINVAL;
a2488b5f
AM
10231 }
10232 if (opts.retprobe && offset != 0) {
1f71a468 10233 free(func);
a2488b5f 10234 pr_warn("kretprobes do not support offset specification\n");
4fa5bcfe 10235 return -EINVAL;
a2488b5f 10236 }
d7a18ea7 10237
a2488b5f 10238 opts.offset = offset;
4fa5bcfe 10239 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
a2488b5f 10240 free(func);
4fa5bcfe 10241 return libbpf_get_error(*link);
d7a18ea7
AN
10242}
10243
cc10623c
AN
10244static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10245 const char *binary_path, uint64_t offset)
10246{
10247 int i;
10248
10249 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10250
10251 /* sanitize binary_path in the probe name */
10252 for (i = 0; buf[i]; i++) {
10253 if (!isalnum(buf[i]))
10254 buf[i] = '_';
10255 }
10256}
10257
10258static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10259 const char *binary_path, size_t offset)
10260{
10261 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10262
10263 return append_to_file(file, "%c:%s/%s %s:0x%zx",
10264 retprobe ? 'r' : 'p',
10265 retprobe ? "uretprobes" : "uprobes",
10266 probe_name, binary_path, offset);
10267}
10268
10269static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10270{
10271 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10272
10273 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10274}
10275
10276static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10277{
10278 char file[512];
10279
10280 snprintf(file, sizeof(file),
10281 "/sys/kernel/debug/tracing/events/%s/%s/id",
10282 retprobe ? "uretprobes" : "uprobes", probe_name);
10283
10284 return parse_uint_from_file(file, "%d\n");
10285}
10286
10287static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10288 const char *binary_path, size_t offset, int pid)
10289{
10290 struct perf_event_attr attr;
10291 int type, pfd, err;
10292
10293 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10294 if (err < 0) {
10295 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10296 binary_path, (size_t)offset, err);
10297 return err;
10298 }
10299 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10300 if (type < 0) {
10301 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10302 binary_path, offset, err);
10303 return type;
10304 }
10305
10306 memset(&attr, 0, sizeof(attr));
10307 attr.size = sizeof(attr);
10308 attr.config = type;
10309 attr.type = PERF_TYPE_TRACEPOINT;
10310
10311 pfd = syscall(__NR_perf_event_open, &attr,
10312 pid < 0 ? -1 : pid, /* pid */
10313 pid == -1 ? 0 : -1, /* cpu */
10314 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10315 if (pfd < 0) {
10316 err = -errno;
10317 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10318 return err;
10319 }
10320 return pfd;
10321}
10322
47faff37 10323LIBBPF_API struct bpf_link *
942025c9 10324bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
47faff37
AN
10325 const char *binary_path, size_t func_offset,
10326 const struct bpf_uprobe_opts *opts)
b2650027 10327{
47faff37 10328 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
cc10623c 10329 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
b2650027 10330 struct bpf_link *link;
5e3b8356 10331 size_t ref_ctr_off;
b2650027 10332 int pfd, err;
cc10623c 10333 bool retprobe, legacy;
47faff37
AN
10334
10335 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10336 return libbpf_err_ptr(-EINVAL);
10337
10338 retprobe = OPTS_GET(opts, retprobe, false);
5e3b8356 10339 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
47faff37 10340 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
b2650027 10341
cc10623c
AN
10342 legacy = determine_uprobe_perf_type() < 0;
10343 if (!legacy) {
10344 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10345 func_offset, pid, ref_ctr_off);
10346 } else {
10347 char probe_name[512];
10348
10349 if (ref_ctr_off)
10350 return libbpf_err_ptr(-EINVAL);
10351
10352 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10353 binary_path, func_offset);
10354
10355 legacy_probe = strdup(probe_name);
10356 if (!legacy_probe)
10357 return libbpf_err_ptr(-ENOMEM);
10358
10359 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10360 binary_path, func_offset, pid);
10361 }
b2650027 10362 if (pfd < 0) {
cc10623c 10363 err = -errno;
52109584
AN
10364 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10365 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e 10366 binary_path, func_offset,
cc10623c
AN
10367 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10368 goto err_out;
b2650027 10369 }
cc10623c 10370
47faff37 10371 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10372 err = libbpf_get_error(link);
10373 if (err) {
b2650027 10374 close(pfd);
52109584
AN
10375 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10376 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e
KW
10377 binary_path, func_offset,
10378 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
cc10623c
AN
10379 goto err_out;
10380 }
10381 if (legacy) {
10382 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10383
10384 perf_link->legacy_probe_name = legacy_probe;
10385 perf_link->legacy_is_kprobe = false;
10386 perf_link->legacy_is_retprobe = retprobe;
b2650027
AN
10387 }
10388 return link;
cc10623c
AN
10389err_out:
10390 free(legacy_probe);
10391 return libbpf_err_ptr(err);
10392
b2650027
AN
10393}
10394
942025c9 10395struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
47faff37
AN
10396 bool retprobe, pid_t pid,
10397 const char *binary_path,
10398 size_t func_offset)
10399{
10400 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10401
10402 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10403}
10404
f6de59c1
AN
10405static int determine_tracepoint_id(const char *tp_category,
10406 const char *tp_name)
10407{
10408 char file[PATH_MAX];
10409 int ret;
10410
10411 ret = snprintf(file, sizeof(file),
10412 "/sys/kernel/debug/tracing/events/%s/%s/id",
10413 tp_category, tp_name);
10414 if (ret < 0)
10415 return -errno;
10416 if (ret >= sizeof(file)) {
10417 pr_debug("tracepoint %s/%s path is too long\n",
10418 tp_category, tp_name);
10419 return -E2BIG;
10420 }
10421 return parse_uint_from_file(file, "%d\n");
10422}
10423
10424static int perf_event_open_tracepoint(const char *tp_category,
10425 const char *tp_name)
10426{
10427 struct perf_event_attr attr = {};
10428 char errmsg[STRERR_BUFSIZE];
10429 int tp_id, pfd, err;
10430
10431 tp_id = determine_tracepoint_id(tp_category, tp_name);
10432 if (tp_id < 0) {
be18010e
KW
10433 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10434 tp_category, tp_name,
10435 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
f6de59c1
AN
10436 return tp_id;
10437 }
10438
10439 attr.type = PERF_TYPE_TRACEPOINT;
10440 attr.size = sizeof(attr);
10441 attr.config = tp_id;
10442
10443 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
10444 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10445 if (pfd < 0) {
10446 err = -errno;
be18010e
KW
10447 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
10448 tp_category, tp_name,
10449 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
f6de59c1
AN
10450 return err;
10451 }
10452 return pfd;
10453}
10454
942025c9 10455struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
47faff37
AN
10456 const char *tp_category,
10457 const char *tp_name,
10458 const struct bpf_tracepoint_opts *opts)
f6de59c1 10459{
47faff37 10460 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
f6de59c1
AN
10461 char errmsg[STRERR_BUFSIZE];
10462 struct bpf_link *link;
10463 int pfd, err;
10464
47faff37
AN
10465 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
10466 return libbpf_err_ptr(-EINVAL);
10467
10468 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10469
f6de59c1
AN
10470 pfd = perf_event_open_tracepoint(tp_category, tp_name);
10471 if (pfd < 0) {
52109584
AN
10472 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
10473 prog->name, tp_category, tp_name,
be18010e 10474 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10475 return libbpf_err_ptr(pfd);
f6de59c1 10476 }
47faff37 10477 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10478 err = libbpf_get_error(link);
10479 if (err) {
f6de59c1 10480 close(pfd);
52109584
AN
10481 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
10482 prog->name, tp_category, tp_name,
be18010e 10483 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
e9fc3ce9 10484 return libbpf_err_ptr(err);
f6de59c1
AN
10485 }
10486 return link;
10487}
10488
942025c9 10489struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
47faff37
AN
10490 const char *tp_category,
10491 const char *tp_name)
10492{
10493 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
10494}
10495
4fa5bcfe 10496static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7
AN
10497{
10498 char *sec_name, *tp_cat, *tp_name;
d7a18ea7 10499
52109584 10500 sec_name = strdup(prog->sec_name);
d7a18ea7 10501 if (!sec_name)
4fa5bcfe 10502 return -ENOMEM;
d7a18ea7 10503
13d35a0c
AN
10504 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
10505 if (str_has_pfx(prog->sec_name, "tp/"))
10506 tp_cat = sec_name + sizeof("tp/") - 1;
10507 else
10508 tp_cat = sec_name + sizeof("tracepoint/") - 1;
d7a18ea7
AN
10509 tp_name = strchr(tp_cat, '/');
10510 if (!tp_name) {
e9fc3ce9 10511 free(sec_name);
4fa5bcfe 10512 return -EINVAL;
d7a18ea7
AN
10513 }
10514 *tp_name = '\0';
10515 tp_name++;
10516
4fa5bcfe 10517 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
d7a18ea7 10518 free(sec_name);
4fa5bcfe 10519 return libbpf_get_error(*link);
d7a18ea7
AN
10520}
10521
942025c9 10522struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
84bf5e1f
AN
10523 const char *tp_name)
10524{
10525 char errmsg[STRERR_BUFSIZE];
c016b68e 10526 struct bpf_link *link;
84bf5e1f
AN
10527 int prog_fd, pfd;
10528
10529 prog_fd = bpf_program__fd(prog);
10530 if (prog_fd < 0) {
52109584 10531 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10532 return libbpf_err_ptr(-EINVAL);
84bf5e1f
AN
10533 }
10534
d6958706 10535 link = calloc(1, sizeof(*link));
84bf5e1f 10536 if (!link)
e9fc3ce9 10537 return libbpf_err_ptr(-ENOMEM);
c016b68e 10538 link->detach = &bpf_link__detach_fd;
84bf5e1f
AN
10539
10540 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
10541 if (pfd < 0) {
10542 pfd = -errno;
10543 free(link);
52109584
AN
10544 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
10545 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10546 return libbpf_err_ptr(pfd);
84bf5e1f
AN
10547 }
10548 link->fd = pfd;
c016b68e 10549 return link;
84bf5e1f
AN
10550}
10551
4fa5bcfe 10552static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 10553{
ccaf12d6
HT
10554 static const char *const prefixes[] = {
10555 "raw_tp/",
10556 "raw_tracepoint/",
10557 "raw_tp.w/",
10558 "raw_tracepoint.w/",
10559 };
10560 size_t i;
10561 const char *tp_name = NULL;
13d35a0c 10562
ccaf12d6
HT
10563 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
10564 if (str_has_pfx(prog->sec_name, prefixes[i])) {
10565 tp_name = prog->sec_name + strlen(prefixes[i]);
10566 break;
10567 }
10568 }
10569 if (!tp_name) {
10570 pr_warn("prog '%s': invalid section name '%s'\n",
10571 prog->name, prog->sec_name);
4fa5bcfe 10572 return -EINVAL;
ccaf12d6 10573 }
d7a18ea7 10574
4fa5bcfe
AN
10575 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
10576 return libbpf_get_error(link);
d7a18ea7
AN
10577}
10578
1e092a03 10579/* Common logic for all BPF program types that attach to a btf_id */
942025c9 10580static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
b8c54ea4
AS
10581{
10582 char errmsg[STRERR_BUFSIZE];
c016b68e 10583 struct bpf_link *link;
b8c54ea4
AS
10584 int prog_fd, pfd;
10585
10586 prog_fd = bpf_program__fd(prog);
10587 if (prog_fd < 0) {
52109584 10588 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10589 return libbpf_err_ptr(-EINVAL);
b8c54ea4
AS
10590 }
10591
d6958706 10592 link = calloc(1, sizeof(*link));
b8c54ea4 10593 if (!link)
e9fc3ce9 10594 return libbpf_err_ptr(-ENOMEM);
c016b68e 10595 link->detach = &bpf_link__detach_fd;
b8c54ea4
AS
10596
10597 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
10598 if (pfd < 0) {
10599 pfd = -errno;
10600 free(link);
52109584
AN
10601 pr_warn("prog '%s': failed to attach: %s\n",
10602 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10603 return libbpf_err_ptr(pfd);
b8c54ea4
AS
10604 }
10605 link->fd = pfd;
10606 return (struct bpf_link *)link;
10607}
10608
942025c9 10609struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
1e092a03
KS
10610{
10611 return bpf_program__attach_btf_id(prog);
10612}
10613
942025c9 10614struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
1e092a03
KS
10615{
10616 return bpf_program__attach_btf_id(prog);
10617}
10618
4fa5bcfe 10619static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 10620{
4fa5bcfe
AN
10621 *link = bpf_program__attach_trace(prog);
10622 return libbpf_get_error(*link);
d7a18ea7
AN
10623}
10624
4fa5bcfe 10625static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
1e092a03 10626{
4fa5bcfe
AN
10627 *link = bpf_program__attach_lsm(prog);
10628 return libbpf_get_error(*link);
1e092a03
KS
10629}
10630
d60d81ac 10631static struct bpf_link *
942025c9 10632bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
d60d81ac 10633 const char *target_name)
cc4f864b 10634{
a5359091
THJ
10635 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
10636 .target_btf_id = btf_id);
cc4f864b
AN
10637 enum bpf_attach_type attach_type;
10638 char errmsg[STRERR_BUFSIZE];
10639 struct bpf_link *link;
10640 int prog_fd, link_fd;
10641
10642 prog_fd = bpf_program__fd(prog);
10643 if (prog_fd < 0) {
52109584 10644 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10645 return libbpf_err_ptr(-EINVAL);
cc4f864b
AN
10646 }
10647
10648 link = calloc(1, sizeof(*link));
10649 if (!link)
e9fc3ce9 10650 return libbpf_err_ptr(-ENOMEM);
cc4f864b
AN
10651 link->detach = &bpf_link__detach_fd;
10652
20eccf29 10653 attach_type = bpf_program__expected_attach_type(prog);
a5359091 10654 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
cc4f864b
AN
10655 if (link_fd < 0) {
10656 link_fd = -errno;
10657 free(link);
52109584
AN
10658 pr_warn("prog '%s': failed to attach to %s: %s\n",
10659 prog->name, target_name,
cc4f864b 10660 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 10661 return libbpf_err_ptr(link_fd);
cc4f864b
AN
10662 }
10663 link->fd = link_fd;
10664 return link;
10665}
10666
d60d81ac 10667struct bpf_link *
942025c9 10668bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
d60d81ac 10669{
a5359091 10670 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
d60d81ac
JS
10671}
10672
10673struct bpf_link *
942025c9 10674bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
d60d81ac 10675{
a5359091 10676 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
d60d81ac
JS
10677}
10678
942025c9 10679struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
dc8698ca
AN
10680{
10681 /* target_fd/target_ifindex use the same field in LINK_CREATE */
a5359091
THJ
10682 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
10683}
10684
942025c9 10685struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
a5359091
THJ
10686 int target_fd,
10687 const char *attach_func_name)
10688{
10689 int btf_id;
10690
10691 if (!!target_fd != !!attach_func_name) {
10692 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
10693 prog->name);
e9fc3ce9 10694 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
10695 }
10696
10697 if (prog->type != BPF_PROG_TYPE_EXT) {
10698 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
10699 prog->name);
e9fc3ce9 10700 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
10701 }
10702
10703 if (target_fd) {
10704 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
10705 if (btf_id < 0)
e9fc3ce9 10706 return libbpf_err_ptr(btf_id);
a5359091
THJ
10707
10708 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
10709 } else {
10710 /* no target, so use raw_tracepoint_open for compatibility
10711 * with old kernels
10712 */
10713 return bpf_program__attach_trace(prog);
10714 }
dc8698ca
AN
10715}
10716
c09add2f 10717struct bpf_link *
942025c9 10718bpf_program__attach_iter(const struct bpf_program *prog,
c09add2f
YS
10719 const struct bpf_iter_attach_opts *opts)
10720{
cd31039a 10721 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
c09add2f
YS
10722 char errmsg[STRERR_BUFSIZE];
10723 struct bpf_link *link;
10724 int prog_fd, link_fd;
cd31039a 10725 __u32 target_fd = 0;
c09add2f
YS
10726
10727 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
e9fc3ce9 10728 return libbpf_err_ptr(-EINVAL);
c09add2f 10729
74fc097d
YS
10730 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
10731 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
cd31039a 10732
c09add2f
YS
10733 prog_fd = bpf_program__fd(prog);
10734 if (prog_fd < 0) {
52109584 10735 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10736 return libbpf_err_ptr(-EINVAL);
c09add2f
YS
10737 }
10738
10739 link = calloc(1, sizeof(*link));
10740 if (!link)
e9fc3ce9 10741 return libbpf_err_ptr(-ENOMEM);
c09add2f
YS
10742 link->detach = &bpf_link__detach_fd;
10743
cd31039a
YS
10744 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
10745 &link_create_opts);
c09add2f
YS
10746 if (link_fd < 0) {
10747 link_fd = -errno;
10748 free(link);
52109584
AN
10749 pr_warn("prog '%s': failed to attach to iterator: %s\n",
10750 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 10751 return libbpf_err_ptr(link_fd);
c09add2f
YS
10752 }
10753 link->fd = link_fd;
10754 return link;
10755}
10756
4fa5bcfe 10757static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
e9fc3ce9 10758{
4fa5bcfe
AN
10759 *link = bpf_program__attach_iter(prog, NULL);
10760 return libbpf_get_error(*link);
e9fc3ce9
AN
10761}
10762
942025c9 10763struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
d7a18ea7 10764{
4fa5bcfe
AN
10765 struct bpf_link *link = NULL;
10766 int err;
10767
10768 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
10769 return libbpf_err_ptr(-EOPNOTSUPP);
d7a18ea7 10770
4fa5bcfe
AN
10771 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
10772 if (err)
10773 return libbpf_err_ptr(err);
10774
10775 /* When calling bpf_program__attach() explicitly, auto-attach support
10776 * is expected to work, so NULL returned link is considered an error.
10777 * This is different for skeleton's attach, see comment in
10778 * bpf_object__attach_skeleton().
10779 */
10780 if (!link)
10781 return libbpf_err_ptr(-EOPNOTSUPP);
10782
10783 return link;
d7a18ea7
AN
10784}
10785
590a0088
MKL
10786static int bpf_link__detach_struct_ops(struct bpf_link *link)
10787{
590a0088
MKL
10788 __u32 zero = 0;
10789
c016b68e 10790 if (bpf_map_delete_elem(link->fd, &zero))
590a0088
MKL
10791 return -errno;
10792
10793 return 0;
10794}
10795
942025c9 10796struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
590a0088
MKL
10797{
10798 struct bpf_struct_ops *st_ops;
c016b68e 10799 struct bpf_link *link;
590a0088
MKL
10800 __u32 i, zero = 0;
10801 int err;
10802
10803 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
e9fc3ce9 10804 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
10805
10806 link = calloc(1, sizeof(*link));
10807 if (!link)
e9fc3ce9 10808 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
10809
10810 st_ops = map->st_ops;
10811 for (i = 0; i < btf_vlen(st_ops->type); i++) {
10812 struct bpf_program *prog = st_ops->progs[i];
10813 void *kern_data;
10814 int prog_fd;
10815
10816 if (!prog)
10817 continue;
10818
10819 prog_fd = bpf_program__fd(prog);
10820 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10821 *(unsigned long *)kern_data = prog_fd;
10822 }
10823
10824 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10825 if (err) {
10826 err = -errno;
10827 free(link);
e9fc3ce9 10828 return libbpf_err_ptr(err);
590a0088
MKL
10829 }
10830
c016b68e 10831 link->detach = bpf_link__detach_struct_ops;
590a0088
MKL
10832 link->fd = map->fd;
10833
c016b68e 10834 return link;
590a0088
MKL
10835}
10836
7218c28c
CL
10837static enum bpf_perf_event_ret
10838perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10839 void **copy_mem, size_t *copy_size,
10840 bpf_perf_event_print_t fn, void *private_data)
d0cabbb0 10841{
3dca2115 10842 struct perf_event_mmap_page *header = mmap_mem;
a64af0ef 10843 __u64 data_head = ring_buffer_read_head(header);
d0cabbb0 10844 __u64 data_tail = header->data_tail;
3dca2115
DB
10845 void *base = ((__u8 *)header) + page_size;
10846 int ret = LIBBPF_PERF_EVENT_CONT;
10847 struct perf_event_header *ehdr;
10848 size_t ehdr_size;
10849
10850 while (data_head != data_tail) {
10851 ehdr = base + (data_tail & (mmap_size - 1));
10852 ehdr_size = ehdr->size;
10853
10854 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10855 void *copy_start = ehdr;
10856 size_t len_first = base + mmap_size - copy_start;
10857 size_t len_secnd = ehdr_size - len_first;
10858
10859 if (*copy_size < ehdr_size) {
10860 free(*copy_mem);
10861 *copy_mem = malloc(ehdr_size);
10862 if (!*copy_mem) {
10863 *copy_size = 0;
d0cabbb0
JK
10864 ret = LIBBPF_PERF_EVENT_ERROR;
10865 break;
10866 }
3dca2115 10867 *copy_size = ehdr_size;
d0cabbb0
JK
10868 }
10869
3dca2115
DB
10870 memcpy(*copy_mem, copy_start, len_first);
10871 memcpy(*copy_mem + len_first, base, len_secnd);
10872 ehdr = *copy_mem;
d0cabbb0
JK
10873 }
10874
3dca2115
DB
10875 ret = fn(ehdr, private_data);
10876 data_tail += ehdr_size;
d0cabbb0
JK
10877 if (ret != LIBBPF_PERF_EVENT_CONT)
10878 break;
d0cabbb0
JK
10879 }
10880
a64af0ef 10881 ring_buffer_write_tail(header, data_tail);
e9fc3ce9 10882 return libbpf_err(ret);
d0cabbb0 10883}
34be1646 10884
7218c28c
CL
10885__attribute__((alias("perf_event_read_simple")))
10886enum bpf_perf_event_ret
10887bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10888 void **copy_mem, size_t *copy_size,
10889 bpf_perf_event_print_t fn, void *private_data);
10890
fb84b822
AN
10891struct perf_buffer;
10892
10893struct perf_buffer_params {
10894 struct perf_event_attr *attr;
10895 /* if event_cb is specified, it takes precendence */
10896 perf_buffer_event_fn event_cb;
10897 /* sample_cb and lost_cb are higher-level common-case callbacks */
10898 perf_buffer_sample_fn sample_cb;
10899 perf_buffer_lost_fn lost_cb;
10900 void *ctx;
10901 int cpu_cnt;
10902 int *cpus;
10903 int *map_keys;
10904};
10905
10906struct perf_cpu_buf {
10907 struct perf_buffer *pb;
10908 void *base; /* mmap()'ed memory */
10909 void *buf; /* for reconstructing segmented data */
10910 size_t buf_size;
10911 int fd;
10912 int cpu;
10913 int map_key;
10914};
10915
10916struct perf_buffer {
10917 perf_buffer_event_fn event_cb;
10918 perf_buffer_sample_fn sample_cb;
10919 perf_buffer_lost_fn lost_cb;
10920 void *ctx; /* passed into callbacks */
10921
10922 size_t page_size;
10923 size_t mmap_size;
10924 struct perf_cpu_buf **cpu_bufs;
10925 struct epoll_event *events;
783b8f01 10926 int cpu_cnt; /* number of allocated CPU buffers */
fb84b822
AN
10927 int epoll_fd; /* perf event FD */
10928 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10929};
10930
10931static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10932 struct perf_cpu_buf *cpu_buf)
10933{
10934 if (!cpu_buf)
10935 return;
10936 if (cpu_buf->base &&
10937 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
be18010e 10938 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
fb84b822
AN
10939 if (cpu_buf->fd >= 0) {
10940 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10941 close(cpu_buf->fd);
10942 }
10943 free(cpu_buf->buf);
10944 free(cpu_buf);
10945}
10946
10947void perf_buffer__free(struct perf_buffer *pb)
10948{
10949 int i;
10950
50450fc7 10951 if (IS_ERR_OR_NULL(pb))
fb84b822
AN
10952 return;
10953 if (pb->cpu_bufs) {
601b05ca 10954 for (i = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
10955 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10956
601b05ca
EC
10957 if (!cpu_buf)
10958 continue;
10959
fb84b822
AN
10960 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10961 perf_buffer__free_cpu_buf(pb, cpu_buf);
10962 }
10963 free(pb->cpu_bufs);
10964 }
10965 if (pb->epoll_fd >= 0)
10966 close(pb->epoll_fd);
10967 free(pb->events);
10968 free(pb);
10969}
10970
10971static struct perf_cpu_buf *
10972perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10973 int cpu, int map_key)
10974{
10975 struct perf_cpu_buf *cpu_buf;
10976 char msg[STRERR_BUFSIZE];
10977 int err;
10978
10979 cpu_buf = calloc(1, sizeof(*cpu_buf));
10980 if (!cpu_buf)
10981 return ERR_PTR(-ENOMEM);
10982
10983 cpu_buf->pb = pb;
10984 cpu_buf->cpu = cpu;
10985 cpu_buf->map_key = map_key;
10986
10987 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10988 -1, PERF_FLAG_FD_CLOEXEC);
10989 if (cpu_buf->fd < 0) {
10990 err = -errno;
be18010e
KW
10991 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10992 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
10993 goto error;
10994 }
10995
10996 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10997 PROT_READ | PROT_WRITE, MAP_SHARED,
10998 cpu_buf->fd, 0);
10999 if (cpu_buf->base == MAP_FAILED) {
11000 cpu_buf->base = NULL;
11001 err = -errno;
be18010e
KW
11002 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11003 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11004 goto error;
11005 }
11006
11007 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11008 err = -errno;
be18010e
KW
11009 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11010 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11011 goto error;
11012 }
11013
11014 return cpu_buf;
11015
11016error:
11017 perf_buffer__free_cpu_buf(pb, cpu_buf);
11018 return (struct perf_cpu_buf *)ERR_PTR(err);
11019}
11020
11021static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11022 struct perf_buffer_params *p);
11023
41788934
AN
11024DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
11025struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
11026 perf_buffer_sample_fn sample_cb,
11027 perf_buffer_lost_fn lost_cb,
11028 void *ctx,
11029 const struct perf_buffer_opts *opts)
fb84b822
AN
11030{
11031 struct perf_buffer_params p = {};
41788934
AN
11032 struct perf_event_attr attr = {};
11033
11034 if (!OPTS_VALID(opts, perf_buffer_opts))
11035 return libbpf_err_ptr(-EINVAL);
4be6e05c 11036
65bb2e0f 11037 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
4be6e05c
ACM
11038 attr.type = PERF_TYPE_SOFTWARE;
11039 attr.sample_type = PERF_SAMPLE_RAW;
11040 attr.sample_period = 1;
11041 attr.wakeup_events = 1;
fb84b822
AN
11042
11043 p.attr = &attr;
41788934
AN
11044 p.sample_cb = sample_cb;
11045 p.lost_cb = lost_cb;
11046 p.ctx = ctx;
fb84b822 11047
e9fc3ce9 11048 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
11049}
11050
41788934
AN
11051COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
11052struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
11053 const struct perf_buffer_opts *opts)
11054{
11055 return perf_buffer__new_v0_6_0(map_fd, page_cnt,
11056 opts ? opts->sample_cb : NULL,
11057 opts ? opts->lost_cb : NULL,
11058 opts ? opts->ctx : NULL,
11059 NULL);
11060}
11061
11062DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
11063struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
11064 struct perf_event_attr *attr,
11065 perf_buffer_event_fn event_cb, void *ctx,
11066 const struct perf_buffer_raw_opts *opts)
fb84b822
AN
11067{
11068 struct perf_buffer_params p = {};
11069
41332d6e 11070 if (!attr)
41788934
AN
11071 return libbpf_err_ptr(-EINVAL);
11072
11073 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11074 return libbpf_err_ptr(-EINVAL);
11075
11076 p.attr = attr;
11077 p.event_cb = event_cb;
11078 p.ctx = ctx;
11079 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11080 p.cpus = OPTS_GET(opts, cpus, NULL);
11081 p.map_keys = OPTS_GET(opts, map_keys, NULL);
fb84b822 11082
e9fc3ce9 11083 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
11084}
11085
41788934
AN
11086COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
11087struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
11088 const struct perf_buffer_raw_opts *opts)
11089{
11090 LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
11091 .cpu_cnt = opts->cpu_cnt,
11092 .cpus = opts->cpus,
11093 .map_keys = opts->map_keys,
11094 );
11095
11096 return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
11097 opts->event_cb, opts->ctx, &inner_opts);
11098}
11099
fb84b822
AN
11100static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11101 struct perf_buffer_params *p)
11102{
783b8f01 11103 const char *online_cpus_file = "/sys/devices/system/cpu/online";
0e289487 11104 struct bpf_map_info map;
fb84b822
AN
11105 char msg[STRERR_BUFSIZE];
11106 struct perf_buffer *pb;
783b8f01 11107 bool *online = NULL;
fb84b822 11108 __u32 map_info_len;
783b8f01 11109 int err, i, j, n;
fb84b822 11110
41332d6e 11111 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
be18010e
KW
11112 pr_warn("page count should be power of two, but is %zu\n",
11113 page_cnt);
fb84b822
AN
11114 return ERR_PTR(-EINVAL);
11115 }
11116
0e289487
AN
11117 /* best-effort sanity checks */
11118 memset(&map, 0, sizeof(map));
fb84b822
AN
11119 map_info_len = sizeof(map);
11120 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11121 if (err) {
11122 err = -errno;
0e289487
AN
11123 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11124 * -EBADFD, -EFAULT, or -E2BIG on real error
11125 */
11126 if (err != -EINVAL) {
11127 pr_warn("failed to get map info for map FD %d: %s\n",
11128 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11129 return ERR_PTR(err);
11130 }
11131 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11132 map_fd);
11133 } else {
11134 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11135 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11136 map.name);
11137 return ERR_PTR(-EINVAL);
11138 }
fb84b822
AN
11139 }
11140
11141 pb = calloc(1, sizeof(*pb));
11142 if (!pb)
11143 return ERR_PTR(-ENOMEM);
11144
11145 pb->event_cb = p->event_cb;
11146 pb->sample_cb = p->sample_cb;
11147 pb->lost_cb = p->lost_cb;
11148 pb->ctx = p->ctx;
11149
11150 pb->page_size = getpagesize();
11151 pb->mmap_size = pb->page_size * page_cnt;
11152 pb->map_fd = map_fd;
11153
11154 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11155 if (pb->epoll_fd < 0) {
11156 err = -errno;
be18010e
KW
11157 pr_warn("failed to create epoll instance: %s\n",
11158 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11159 goto error;
11160 }
11161
11162 if (p->cpu_cnt > 0) {
11163 pb->cpu_cnt = p->cpu_cnt;
11164 } else {
11165 pb->cpu_cnt = libbpf_num_possible_cpus();
11166 if (pb->cpu_cnt < 0) {
11167 err = pb->cpu_cnt;
11168 goto error;
11169 }
0e289487 11170 if (map.max_entries && map.max_entries < pb->cpu_cnt)
fb84b822
AN
11171 pb->cpu_cnt = map.max_entries;
11172 }
11173
11174 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11175 if (!pb->events) {
11176 err = -ENOMEM;
be18010e 11177 pr_warn("failed to allocate events: out of memory\n");
fb84b822
AN
11178 goto error;
11179 }
11180 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11181 if (!pb->cpu_bufs) {
11182 err = -ENOMEM;
be18010e 11183 pr_warn("failed to allocate buffers: out of memory\n");
fb84b822
AN
11184 goto error;
11185 }
11186
783b8f01
AN
11187 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11188 if (err) {
11189 pr_warn("failed to get online CPU mask: %d\n", err);
11190 goto error;
11191 }
11192
11193 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
11194 struct perf_cpu_buf *cpu_buf;
11195 int cpu, map_key;
11196
11197 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11198 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11199
783b8f01
AN
11200 /* in case user didn't explicitly requested particular CPUs to
11201 * be attached to, skip offline/not present CPUs
11202 */
11203 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11204 continue;
11205
fb84b822
AN
11206 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11207 if (IS_ERR(cpu_buf)) {
11208 err = PTR_ERR(cpu_buf);
11209 goto error;
11210 }
11211
783b8f01 11212 pb->cpu_bufs[j] = cpu_buf;
fb84b822
AN
11213
11214 err = bpf_map_update_elem(pb->map_fd, &map_key,
11215 &cpu_buf->fd, 0);
11216 if (err) {
11217 err = -errno;
be18010e
KW
11218 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11219 cpu, map_key, cpu_buf->fd,
11220 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11221 goto error;
11222 }
11223
783b8f01
AN
11224 pb->events[j].events = EPOLLIN;
11225 pb->events[j].data.ptr = cpu_buf;
fb84b822 11226 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
783b8f01 11227 &pb->events[j]) < 0) {
fb84b822 11228 err = -errno;
be18010e
KW
11229 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11230 cpu, cpu_buf->fd,
11231 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11232 goto error;
11233 }
783b8f01 11234 j++;
fb84b822 11235 }
783b8f01
AN
11236 pb->cpu_cnt = j;
11237 free(online);
fb84b822
AN
11238
11239 return pb;
11240
11241error:
783b8f01 11242 free(online);
fb84b822
AN
11243 if (pb)
11244 perf_buffer__free(pb);
11245 return ERR_PTR(err);
11246}
11247
11248struct perf_sample_raw {
11249 struct perf_event_header header;
11250 uint32_t size;
385bbf7b 11251 char data[];
fb84b822
AN
11252};
11253
11254struct perf_sample_lost {
11255 struct perf_event_header header;
11256 uint64_t id;
11257 uint64_t lost;
11258 uint64_t sample_id;
11259};
11260
11261static enum bpf_perf_event_ret
11262perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11263{
11264 struct perf_cpu_buf *cpu_buf = ctx;
11265 struct perf_buffer *pb = cpu_buf->pb;
11266 void *data = e;
11267
11268 /* user wants full control over parsing perf event */
11269 if (pb->event_cb)
11270 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11271
11272 switch (e->type) {
11273 case PERF_RECORD_SAMPLE: {
11274 struct perf_sample_raw *s = data;
11275
11276 if (pb->sample_cb)
11277 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11278 break;
11279 }
11280 case PERF_RECORD_LOST: {
11281 struct perf_sample_lost *s = data;
11282
11283 if (pb->lost_cb)
11284 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11285 break;
11286 }
11287 default:
be18010e 11288 pr_warn("unknown perf sample type %d\n", e->type);
fb84b822
AN
11289 return LIBBPF_PERF_EVENT_ERROR;
11290 }
11291 return LIBBPF_PERF_EVENT_CONT;
11292}
11293
11294static int perf_buffer__process_records(struct perf_buffer *pb,
11295 struct perf_cpu_buf *cpu_buf)
11296{
11297 enum bpf_perf_event_ret ret;
11298
7218c28c
CL
11299 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11300 pb->page_size, &cpu_buf->buf,
11301 &cpu_buf->buf_size,
11302 perf_buffer__process_record, cpu_buf);
fb84b822
AN
11303 if (ret != LIBBPF_PERF_EVENT_CONT)
11304 return ret;
11305 return 0;
11306}
11307
dca5612f
AN
11308int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11309{
11310 return pb->epoll_fd;
11311}
11312
fb84b822
AN
11313int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11314{
11315 int i, cnt, err;
11316
11317 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
e9fc3ce9 11318 if (cnt < 0)
af0efa05 11319 return -errno;
e9fc3ce9 11320
fb84b822
AN
11321 for (i = 0; i < cnt; i++) {
11322 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11323
11324 err = perf_buffer__process_records(pb, cpu_buf);
11325 if (err) {
be18010e 11326 pr_warn("error while processing records: %d\n", err);
e9fc3ce9 11327 return libbpf_err(err);
fb84b822
AN
11328 }
11329 }
e9fc3ce9 11330 return cnt;
fb84b822
AN
11331}
11332
dca5612f
AN
11333/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11334 * manager.
11335 */
11336size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11337{
11338 return pb->cpu_cnt;
11339}
11340
11341/*
11342 * Return perf_event FD of a ring buffer in *buf_idx* slot of
11343 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11344 * select()/poll()/epoll() Linux syscalls.
11345 */
11346int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11347{
11348 struct perf_cpu_buf *cpu_buf;
11349
11350 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 11351 return libbpf_err(-EINVAL);
dca5612f
AN
11352
11353 cpu_buf = pb->cpu_bufs[buf_idx];
11354 if (!cpu_buf)
e9fc3ce9 11355 return libbpf_err(-ENOENT);
dca5612f
AN
11356
11357 return cpu_buf->fd;
11358}
11359
11360/*
11361 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11362 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11363 * consume, do nothing and return success.
11364 * Returns:
11365 * - 0 on success;
11366 * - <0 on failure.
11367 */
11368int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11369{
11370 struct perf_cpu_buf *cpu_buf;
11371
11372 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 11373 return libbpf_err(-EINVAL);
dca5612f
AN
11374
11375 cpu_buf = pb->cpu_bufs[buf_idx];
11376 if (!cpu_buf)
e9fc3ce9 11377 return libbpf_err(-ENOENT);
dca5612f
AN
11378
11379 return perf_buffer__process_records(pb, cpu_buf);
11380}
11381
272d51af
EC
11382int perf_buffer__consume(struct perf_buffer *pb)
11383{
11384 int i, err;
11385
11386 for (i = 0; i < pb->cpu_cnt; i++) {
11387 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11388
11389 if (!cpu_buf)
11390 continue;
11391
11392 err = perf_buffer__process_records(pb, cpu_buf);
11393 if (err) {
dca5612f 11394 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
e9fc3ce9 11395 return libbpf_err(err);
272d51af
EC
11396 }
11397 }
11398 return 0;
11399}
11400
34be1646
SL
11401struct bpf_prog_info_array_desc {
11402 int array_offset; /* e.g. offset of jited_prog_insns */
11403 int count_offset; /* e.g. offset of jited_prog_len */
11404 int size_offset; /* > 0: offset of rec size,
11405 * < 0: fix size of -size_offset
11406 */
11407};
11408
11409static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
11410 [BPF_PROG_INFO_JITED_INSNS] = {
11411 offsetof(struct bpf_prog_info, jited_prog_insns),
11412 offsetof(struct bpf_prog_info, jited_prog_len),
11413 -1,
11414 },
11415 [BPF_PROG_INFO_XLATED_INSNS] = {
11416 offsetof(struct bpf_prog_info, xlated_prog_insns),
11417 offsetof(struct bpf_prog_info, xlated_prog_len),
11418 -1,
11419 },
11420 [BPF_PROG_INFO_MAP_IDS] = {
11421 offsetof(struct bpf_prog_info, map_ids),
11422 offsetof(struct bpf_prog_info, nr_map_ids),
11423 -(int)sizeof(__u32),
11424 },
11425 [BPF_PROG_INFO_JITED_KSYMS] = {
11426 offsetof(struct bpf_prog_info, jited_ksyms),
11427 offsetof(struct bpf_prog_info, nr_jited_ksyms),
11428 -(int)sizeof(__u64),
11429 },
11430 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
11431 offsetof(struct bpf_prog_info, jited_func_lens),
11432 offsetof(struct bpf_prog_info, nr_jited_func_lens),
11433 -(int)sizeof(__u32),
11434 },
11435 [BPF_PROG_INFO_FUNC_INFO] = {
11436 offsetof(struct bpf_prog_info, func_info),
11437 offsetof(struct bpf_prog_info, nr_func_info),
11438 offsetof(struct bpf_prog_info, func_info_rec_size),
11439 },
11440 [BPF_PROG_INFO_LINE_INFO] = {
11441 offsetof(struct bpf_prog_info, line_info),
11442 offsetof(struct bpf_prog_info, nr_line_info),
11443 offsetof(struct bpf_prog_info, line_info_rec_size),
11444 },
11445 [BPF_PROG_INFO_JITED_LINE_INFO] = {
11446 offsetof(struct bpf_prog_info, jited_line_info),
11447 offsetof(struct bpf_prog_info, nr_jited_line_info),
11448 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
11449 },
11450 [BPF_PROG_INFO_PROG_TAGS] = {
11451 offsetof(struct bpf_prog_info, prog_tags),
11452 offsetof(struct bpf_prog_info, nr_prog_tags),
11453 -(int)sizeof(__u8) * BPF_TAG_SIZE,
11454 },
11455
11456};
11457
8983b731
AN
11458static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
11459 int offset)
34be1646
SL
11460{
11461 __u32 *array = (__u32 *)info;
11462
11463 if (offset >= 0)
11464 return array[offset / sizeof(__u32)];
11465 return -(int)offset;
11466}
11467
8983b731
AN
11468static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
11469 int offset)
34be1646
SL
11470{
11471 __u64 *array = (__u64 *)info;
11472
11473 if (offset >= 0)
11474 return array[offset / sizeof(__u64)];
11475 return -(int)offset;
11476}
11477
11478static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
11479 __u32 val)
11480{
11481 __u32 *array = (__u32 *)info;
11482
11483 if (offset >= 0)
11484 array[offset / sizeof(__u32)] = val;
11485}
11486
11487static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
11488 __u64 val)
11489{
11490 __u64 *array = (__u64 *)info;
11491
11492 if (offset >= 0)
11493 array[offset / sizeof(__u64)] = val;
11494}
11495
11496struct bpf_prog_info_linear *
11497bpf_program__get_prog_info_linear(int fd, __u64 arrays)
11498{
11499 struct bpf_prog_info_linear *info_linear;
11500 struct bpf_prog_info info = {};
11501 __u32 info_len = sizeof(info);
11502 __u32 data_len = 0;
11503 int i, err;
11504 void *ptr;
11505
11506 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
e9fc3ce9 11507 return libbpf_err_ptr(-EINVAL);
34be1646
SL
11508
11509 /* step 1: get array dimensions */
11510 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
11511 if (err) {
11512 pr_debug("can't get prog info: %s", strerror(errno));
e9fc3ce9 11513 return libbpf_err_ptr(-EFAULT);
34be1646
SL
11514 }
11515
11516 /* step 2: calculate total size of all arrays */
11517 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11518 bool include_array = (arrays & (1UL << i)) > 0;
11519 struct bpf_prog_info_array_desc *desc;
11520 __u32 count, size;
11521
11522 desc = bpf_prog_info_array_desc + i;
11523
11524 /* kernel is too old to support this field */
11525 if (info_len < desc->array_offset + sizeof(__u32) ||
11526 info_len < desc->count_offset + sizeof(__u32) ||
11527 (desc->size_offset > 0 && info_len < desc->size_offset))
11528 include_array = false;
11529
11530 if (!include_array) {
11531 arrays &= ~(1UL << i); /* clear the bit */
11532 continue;
11533 }
11534
11535 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11536 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11537
11538 data_len += count * size;
11539 }
11540
11541 /* step 3: allocate continuous memory */
11542 data_len = roundup(data_len, sizeof(__u64));
11543 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
11544 if (!info_linear)
e9fc3ce9 11545 return libbpf_err_ptr(-ENOMEM);
34be1646
SL
11546
11547 /* step 4: fill data to info_linear->info */
11548 info_linear->arrays = arrays;
11549 memset(&info_linear->info, 0, sizeof(info));
11550 ptr = info_linear->data;
11551
11552 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11553 struct bpf_prog_info_array_desc *desc;
11554 __u32 count, size;
11555
11556 if ((arrays & (1UL << i)) == 0)
11557 continue;
11558
11559 desc = bpf_prog_info_array_desc + i;
11560 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11561 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11562 bpf_prog_info_set_offset_u32(&info_linear->info,
11563 desc->count_offset, count);
11564 bpf_prog_info_set_offset_u32(&info_linear->info,
11565 desc->size_offset, size);
11566 bpf_prog_info_set_offset_u64(&info_linear->info,
11567 desc->array_offset,
11568 ptr_to_u64(ptr));
11569 ptr += count * size;
11570 }
11571
11572 /* step 5: call syscall again to get required arrays */
11573 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
11574 if (err) {
11575 pr_debug("can't get prog info: %s", strerror(errno));
11576 free(info_linear);
e9fc3ce9 11577 return libbpf_err_ptr(-EFAULT);
34be1646
SL
11578 }
11579
11580 /* step 6: verify the data */
11581 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11582 struct bpf_prog_info_array_desc *desc;
11583 __u32 v1, v2;
11584
11585 if ((arrays & (1UL << i)) == 0)
11586 continue;
11587
11588 desc = bpf_prog_info_array_desc + i;
11589 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11590 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11591 desc->count_offset);
11592 if (v1 != v2)
be18010e 11593 pr_warn("%s: mismatch in element count\n", __func__);
34be1646
SL
11594
11595 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11596 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11597 desc->size_offset);
11598 if (v1 != v2)
be18010e 11599 pr_warn("%s: mismatch in rec size\n", __func__);
34be1646
SL
11600 }
11601
11602 /* step 7: update info_len and data_len */
11603 info_linear->info_len = sizeof(struct bpf_prog_info);
11604 info_linear->data_len = data_len;
11605
11606 return info_linear;
11607}
11608
11609void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
11610{
11611 int i;
11612
11613 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11614 struct bpf_prog_info_array_desc *desc;
11615 __u64 addr, offs;
11616
11617 if ((info_linear->arrays & (1UL << i)) == 0)
11618 continue;
11619
11620 desc = bpf_prog_info_array_desc + i;
11621 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
11622 desc->array_offset);
11623 offs = addr - ptr_to_u64(info_linear->data);
11624 bpf_prog_info_set_offset_u64(&info_linear->info,
11625 desc->array_offset, offs);
11626 }
11627}
11628
11629void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
11630{
11631 int i;
11632
11633 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11634 struct bpf_prog_info_array_desc *desc;
11635 __u64 addr, offs;
11636
11637 if ((info_linear->arrays & (1UL << i)) == 0)
11638 continue;
11639
11640 desc = bpf_prog_info_array_desc + i;
11641 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
11642 desc->array_offset);
11643 addr = offs + ptr_to_u64(info_linear->data);
11644 bpf_prog_info_set_offset_u64(&info_linear->info,
11645 desc->array_offset, addr);
11646 }
11647}
6446b315 11648
ff26ce5c
EC
11649int bpf_program__set_attach_target(struct bpf_program *prog,
11650 int attach_prog_fd,
11651 const char *attach_func_name)
11652{
fe62de31 11653 int btf_obj_fd = 0, btf_id = 0, err;
ff26ce5c 11654
2d5ec1c6 11655 if (!prog || attach_prog_fd < 0)
e9fc3ce9 11656 return libbpf_err(-EINVAL);
ff26ce5c 11657
fe62de31 11658 if (prog->obj->loaded)
e9fc3ce9 11659 return libbpf_err(-EINVAL);
fe62de31 11660
2d5ec1c6
AN
11661 if (attach_prog_fd && !attach_func_name) {
11662 /* remember attach_prog_fd and let bpf_program__load() find
11663 * BTF ID during the program load
11664 */
11665 prog->attach_prog_fd = attach_prog_fd;
11666 return 0;
11667 }
11668
fe62de31 11669 if (attach_prog_fd) {
ff26ce5c
EC
11670 btf_id = libbpf_find_prog_btf_id(attach_func_name,
11671 attach_prog_fd);
fe62de31 11672 if (btf_id < 0)
e9fc3ce9 11673 return libbpf_err(btf_id);
fe62de31 11674 } else {
2d5ec1c6
AN
11675 if (!attach_func_name)
11676 return libbpf_err(-EINVAL);
11677
fe62de31
AN
11678 /* load btf_vmlinux, if not yet */
11679 err = bpf_object__load_vmlinux_btf(prog->obj, true);
11680 if (err)
e9fc3ce9 11681 return libbpf_err(err);
fe62de31
AN
11682 err = find_kernel_btf_id(prog->obj, attach_func_name,
11683 prog->expected_attach_type,
11684 &btf_obj_fd, &btf_id);
11685 if (err)
e9fc3ce9 11686 return libbpf_err(err);
fe62de31 11687 }
ff26ce5c
EC
11688
11689 prog->attach_btf_id = btf_id;
fe62de31 11690 prog->attach_btf_obj_fd = btf_obj_fd;
ff26ce5c
EC
11691 prog->attach_prog_fd = attach_prog_fd;
11692 return 0;
11693}
11694
6803ee25 11695int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
6446b315 11696{
6803ee25
AN
11697 int err = 0, n, len, start, end = -1;
11698 bool *tmp;
6446b315 11699
6803ee25
AN
11700 *mask = NULL;
11701 *mask_sz = 0;
11702
11703 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
11704 while (*s) {
11705 if (*s == ',' || *s == '\n') {
11706 s++;
11707 continue;
11708 }
11709 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
11710 if (n <= 0 || n > 2) {
11711 pr_warn("Failed to get CPU range %s: %d\n", s, n);
11712 err = -EINVAL;
11713 goto cleanup;
11714 } else if (n == 1) {
11715 end = start;
11716 }
11717 if (start < 0 || start > end) {
11718 pr_warn("Invalid CPU range [%d,%d] in %s\n",
11719 start, end, s);
11720 err = -EINVAL;
11721 goto cleanup;
11722 }
11723 tmp = realloc(*mask, end + 1);
11724 if (!tmp) {
11725 err = -ENOMEM;
11726 goto cleanup;
11727 }
11728 *mask = tmp;
11729 memset(tmp + *mask_sz, 0, start - *mask_sz);
11730 memset(tmp + start, 1, end - start + 1);
11731 *mask_sz = end + 1;
11732 s += len;
11733 }
11734 if (!*mask_sz) {
11735 pr_warn("Empty CPU range\n");
11736 return -EINVAL;
11737 }
11738 return 0;
11739cleanup:
11740 free(*mask);
11741 *mask = NULL;
11742 return err;
11743}
11744
11745int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
11746{
11747 int fd, err = 0, len;
11748 char buf[128];
6446b315 11749
92274e24 11750 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
6446b315 11751 if (fd < 0) {
6803ee25
AN
11752 err = -errno;
11753 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
11754 return err;
6446b315
HL
11755 }
11756 len = read(fd, buf, sizeof(buf));
11757 close(fd);
11758 if (len <= 0) {
6803ee25
AN
11759 err = len ? -errno : -EINVAL;
11760 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
11761 return err;
6446b315 11762 }
6803ee25
AN
11763 if (len >= sizeof(buf)) {
11764 pr_warn("CPU mask is too big in file %s\n", fcpu);
11765 return -E2BIG;
6446b315
HL
11766 }
11767 buf[len] = '\0';
11768
6803ee25
AN
11769 return parse_cpu_mask_str(buf, mask, mask_sz);
11770}
11771
11772int libbpf_num_possible_cpus(void)
11773{
11774 static const char *fcpu = "/sys/devices/system/cpu/possible";
11775 static int cpus;
11776 int err, n, i, tmp_cpus;
11777 bool *mask;
11778
11779 tmp_cpus = READ_ONCE(cpus);
11780 if (tmp_cpus > 0)
11781 return tmp_cpus;
11782
11783 err = parse_cpu_mask_file(fcpu, &mask, &n);
11784 if (err)
e9fc3ce9 11785 return libbpf_err(err);
6803ee25
AN
11786
11787 tmp_cpus = 0;
11788 for (i = 0; i < n; i++) {
11789 if (mask[i])
11790 tmp_cpus++;
6446b315 11791 }
6803ee25 11792 free(mask);
56fbc241
TC
11793
11794 WRITE_ONCE(cpus, tmp_cpus);
11795 return tmp_cpus;
6446b315 11796}
d66562fb
AN
11797
11798int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
11799 const struct bpf_object_open_opts *opts)
11800{
11801 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
11802 .object_name = s->name,
11803 );
11804 struct bpf_object *obj;
e9fc3ce9 11805 int i, err;
d66562fb
AN
11806
11807 /* Attempt to preserve opts->object_name, unless overriden by user
11808 * explicitly. Overwriting object name for skeletons is discouraged,
11809 * as it breaks global data maps, because they contain object name
11810 * prefix as their own map name prefix. When skeleton is generated,
11811 * bpftool is making an assumption that this name will stay the same.
11812 */
11813 if (opts) {
11814 memcpy(&skel_opts, opts, sizeof(*opts));
11815 if (!opts->object_name)
11816 skel_opts.object_name = s->name;
11817 }
11818
11819 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
e9fc3ce9
AN
11820 err = libbpf_get_error(obj);
11821 if (err) {
11822 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11823 s->name, err);
11824 return libbpf_err(err);
d66562fb
AN
11825 }
11826
11827 *s->obj = obj;
11828
11829 for (i = 0; i < s->map_cnt; i++) {
11830 struct bpf_map **map = s->maps[i].map;
11831 const char *name = s->maps[i].name;
11832 void **mmaped = s->maps[i].mmaped;
11833
11834 *map = bpf_object__find_map_by_name(obj, name);
11835 if (!*map) {
11836 pr_warn("failed to find skeleton map '%s'\n", name);
e9fc3ce9 11837 return libbpf_err(-ESRCH);
d66562fb
AN
11838 }
11839
2ad97d47 11840 /* externs shouldn't be pre-setup from user code */
81bfdd08 11841 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
d66562fb
AN
11842 *mmaped = (*map)->mmaped;
11843 }
11844
11845 for (i = 0; i < s->prog_cnt; i++) {
11846 struct bpf_program **prog = s->progs[i].prog;
11847 const char *name = s->progs[i].name;
11848
11849 *prog = bpf_object__find_program_by_name(obj, name);
11850 if (!*prog) {
11851 pr_warn("failed to find skeleton program '%s'\n", name);
e9fc3ce9 11852 return libbpf_err(-ESRCH);
d66562fb
AN
11853 }
11854 }
11855
11856 return 0;
11857}
11858
11859int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11860{
11861 int i, err;
11862
11863 err = bpf_object__load(*s->obj);
11864 if (err) {
11865 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
e9fc3ce9 11866 return libbpf_err(err);
d66562fb
AN
11867 }
11868
11869 for (i = 0; i < s->map_cnt; i++) {
11870 struct bpf_map *map = *s->maps[i].map;
11871 size_t mmap_sz = bpf_map_mmap_sz(map);
11872 int prot, map_fd = bpf_map__fd(map);
11873 void **mmaped = s->maps[i].mmaped;
d66562fb
AN
11874
11875 if (!mmaped)
11876 continue;
11877
11878 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11879 *mmaped = NULL;
11880 continue;
11881 }
11882
11883 if (map->def.map_flags & BPF_F_RDONLY_PROG)
11884 prot = PROT_READ;
11885 else
11886 prot = PROT_READ | PROT_WRITE;
11887
11888 /* Remap anonymous mmap()-ed "map initialization image" as
11889 * a BPF map-backed mmap()-ed memory, but preserving the same
11890 * memory address. This will cause kernel to change process'
11891 * page table to point to a different piece of kernel memory,
11892 * but from userspace point of view memory address (and its
11893 * contents, being identical at this point) will stay the
11894 * same. This mapping will be released by bpf_object__close()
11895 * as per normal clean up procedure, so we don't need to worry
11896 * about it from skeleton's clean up perspective.
11897 */
2ad97d47
AN
11898 *mmaped = mmap(map->mmaped, mmap_sz, prot,
11899 MAP_SHARED | MAP_FIXED, map_fd, 0);
11900 if (*mmaped == MAP_FAILED) {
d66562fb
AN
11901 err = -errno;
11902 *mmaped = NULL;
11903 pr_warn("failed to re-mmap() map '%s': %d\n",
11904 bpf_map__name(map), err);
e9fc3ce9 11905 return libbpf_err(err);
d66562fb
AN
11906 }
11907 }
11908
11909 return 0;
11910}
11911
11912int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11913{
e9fc3ce9 11914 int i, err;
d66562fb
AN
11915
11916 for (i = 0; i < s->prog_cnt; i++) {
11917 struct bpf_program *prog = *s->progs[i].prog;
11918 struct bpf_link **link = s->progs[i].link;
d66562fb 11919
d9297581
AN
11920 if (!prog->load)
11921 continue;
11922
5532dfd4 11923 /* auto-attaching not supported for this program */
4fa5bcfe 11924 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
d66562fb
AN
11925 continue;
11926
4fa5bcfe
AN
11927 /* if user already set the link manually, don't attempt auto-attach */
11928 if (*link)
11929 continue;
11930
11931 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
e9fc3ce9 11932 if (err) {
4fa5bcfe 11933 pr_warn("prog '%s': failed to auto-attach: %d\n",
e9fc3ce9
AN
11934 bpf_program__name(prog), err);
11935 return libbpf_err(err);
d66562fb 11936 }
4fa5bcfe
AN
11937
11938 /* It's possible that for some SEC() definitions auto-attach
11939 * is supported in some cases (e.g., if definition completely
11940 * specifies target information), but is not in other cases.
11941 * SEC("uprobe") is one such case. If user specified target
11942 * binary and function name, such BPF program can be
11943 * auto-attached. But if not, it shouldn't trigger skeleton's
11944 * attach to fail. It should just be skipped.
11945 * attach_fn signals such case with returning 0 (no error) and
11946 * setting link to NULL.
11947 */
d66562fb
AN
11948 }
11949
11950 return 0;
11951}
11952
11953void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11954{
11955 int i;
11956
11957 for (i = 0; i < s->prog_cnt; i++) {
11958 struct bpf_link **link = s->progs[i].link;
11959
50450fc7 11960 bpf_link__destroy(*link);
d66562fb
AN
11961 *link = NULL;
11962 }
11963}
11964
11965void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11966{
a32ea51a
YS
11967 if (!s)
11968 return;
11969
d66562fb
AN
11970 if (s->progs)
11971 bpf_object__detach_skeleton(s);
11972 if (s->obj)
11973 bpf_object__close(*s->obj);
11974 free(s->maps);
11975 free(s->progs);
11976 free(s);
11977}