selftests/bpf: Add CO-RE relos and SEC("?...") to linked_funcs selftests
[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
a3820c48 305 bool autoload;
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
2e4913e0
AN
486struct usdt_manager;
487
1a5e3fb1 488struct bpf_object {
d859900c 489 char name[BPF_OBJ_NAME_LEN];
cb1e5e96 490 char license[64];
438363c0 491 __u32 kern_version;
0b3d1efa 492
a5b8bd47
WN
493 struct bpf_program *programs;
494 size_t nr_programs;
9d759a9b
WN
495 struct bpf_map *maps;
496 size_t nr_maps;
bf829271 497 size_t maps_cap;
9d759a9b 498
8601fd42 499 char *kconfig;
166750bc
AN
500 struct extern_desc *externs;
501 int nr_extern;
81bfdd08 502 int kconfig_map_idx;
166750bc 503
52d3352e 504 bool loaded;
c3c55696 505 bool has_subcalls;
25bbbd7a 506 bool has_rodata;
a5b8bd47 507
e2fa0156
AS
508 struct bpf_gen *gen_loader;
509
29a30ff5
AN
510 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
511 struct elf_state efile;
1a5e3fb1 512 /*
29a30ff5 513 * All loaded bpf_object are linked in a list, which is
9a208eff
WN
514 * hidden to caller. bpf_objects__<func> handlers deal with
515 * all objects.
516 */
517 struct list_head list;
10931d24 518
8a138aed 519 struct btf *btf;
0f7515ca
AN
520 struct btf_ext *btf_ext;
521
a6ed02ca
KS
522 /* Parse and load BTF vmlinux if any of the programs in the object need
523 * it at load time.
524 */
525 struct btf *btf_vmlinux;
1373ff59
SC
526 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
527 * override for vmlinux BTF.
528 */
529 char *btf_custom_path;
0f7515ca
AN
530 /* vmlinux BTF override for CO-RE relocations */
531 struct btf *btf_vmlinux_override;
4f33a53d
AN
532 /* Lazily initialized kernel module BTFs */
533 struct module_btf *btf_modules;
534 bool btf_modules_loaded;
535 size_t btf_module_cnt;
536 size_t btf_module_cap;
8a138aed 537
e0e3ea88
AN
538 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
539 char *log_buf;
540 size_t log_size;
541 __u32 log_level;
542
10931d24
WN
543 void *priv;
544 bpf_object_clear_priv_t clear_priv;
545
9dbe6015
KKD
546 int *fd_array;
547 size_t fd_array_cap;
548 size_t fd_array_cnt;
549
2e4913e0
AN
550 struct usdt_manager *usdt_man;
551
1a5e3fb1
WN
552 char path[];
553};
1a5e3fb1 554
88a82120
AN
555static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
556static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
557static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
558static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
ad23b723 559static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
88a82120
AN
560static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
561static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
ad23b723
AN
562static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
563static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
88a82120 564
29cd77f4 565void bpf_program__unload(struct bpf_program *prog)
55cffde2 566{
b580563e
WN
567 int i;
568
55cffde2
WN
569 if (!prog)
570 return;
571
b580563e
WN
572 /*
573 * If the object is opened but the program was never loaded,
574 * it is possible that prog->instances.nr == -1.
575 */
576 if (prog->instances.nr > 0) {
577 for (i = 0; i < prog->instances.nr; i++)
578 zclose(prog->instances.fds[i]);
579 } else if (prog->instances.nr != -1) {
be18010e
KW
580 pr_warn("Internal error: instances.nr is %d\n",
581 prog->instances.nr);
b580563e
WN
582 }
583
584 prog->instances.nr = -1;
585 zfree(&prog->instances.fds);
2993e051 586
2993e051 587 zfree(&prog->func_info);
07a09d1b 588 zfree(&prog->line_info);
55cffde2
WN
589}
590
a5b8bd47
WN
591static void bpf_program__exit(struct bpf_program *prog)
592{
593 if (!prog)
594 return;
595
aa9b1ac3
WN
596 if (prog->clear_priv)
597 prog->clear_priv(prog, prog->priv);
598
599 prog->priv = NULL;
600 prog->clear_priv = NULL;
601
55cffde2 602 bpf_program__unload(prog);
88cda1c9 603 zfree(&prog->name);
52109584 604 zfree(&prog->sec_name);
33a2c75c 605 zfree(&prog->pin_name);
a5b8bd47 606 zfree(&prog->insns);
34090915
WN
607 zfree(&prog->reloc_desc);
608
609 prog->nr_reloc = 0;
a5b8bd47 610 prog->insns_cnt = 0;
c1122392 611 prog->sec_idx = -1;
a5b8bd47
WN
612}
613
33a2c75c
SF
614static char *__bpf_program__pin_name(struct bpf_program *prog)
615{
616 char *name, *p;
617
a77f879b
SF
618 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
619 name = strdup(prog->name);
620 else
621 name = strdup(prog->sec_name);
622
623 if (!name)
624 return NULL;
625
626 p = name;
627
33a2c75c
SF
628 while ((p = strchr(p, '/')))
629 *p = '_';
630
631 return name;
632}
633
c3c55696
AN
634static bool insn_is_subprog_call(const struct bpf_insn *insn)
635{
636 return BPF_CLASS(insn->code) == BPF_JMP &&
637 BPF_OP(insn->code) == BPF_CALL &&
638 BPF_SRC(insn->code) == BPF_K &&
639 insn->src_reg == BPF_PSEUDO_CALL &&
640 insn->dst_reg == 0 &&
641 insn->off == 0;
642}
643
aa0b8d43
MKL
644static bool is_call_insn(const struct bpf_insn *insn)
645{
646 return insn->code == (BPF_JMP | BPF_CALL);
647}
648
53eddb5e
YS
649static bool insn_is_pseudo_func(struct bpf_insn *insn)
650{
aa0b8d43 651 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
53eddb5e
YS
652}
653
a5b8bd47 654static int
c3c55696
AN
655bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
656 const char *name, size_t sec_idx, const char *sec_name,
657 size_t sec_off, void *insn_data, size_t insn_data_sz)
a5b8bd47 658{
c1122392
AN
659 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
660 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
661 sec_name, name, sec_off, insn_data_sz);
a5b8bd47
WN
662 return -EINVAL;
663 }
664
1ad9cbb8 665 memset(prog, 0, sizeof(*prog));
c3c55696
AN
666 prog->obj = obj;
667
c1122392
AN
668 prog->sec_idx = sec_idx;
669 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
670 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
671 /* insns_cnt can later be increased by appending used subprograms */
672 prog->insns_cnt = prog->sec_insn_cnt;
a5b8bd47 673
c1122392 674 prog->type = BPF_PROG_TYPE_UNSPEC;
a3820c48
AN
675
676 /* libbpf's convention for SEC("?abc...") is that it's just like
677 * SEC("abc...") but the corresponding bpf_program starts out with
678 * autoload set to false.
679 */
680 if (sec_name[0] == '?') {
681 prog->autoload = false;
682 /* from now on forget there was ? in section name */
683 sec_name++;
684 } else {
685 prog->autoload = true;
686 }
a5b8bd47 687
c1122392
AN
688 prog->instances.fds = NULL;
689 prog->instances.nr = -1;
690
b3ce9079
AN
691 /* inherit object's log_level */
692 prog->log_level = obj->log_level;
693
52109584
AN
694 prog->sec_name = strdup(sec_name);
695 if (!prog->sec_name)
c1122392
AN
696 goto errout;
697
698 prog->name = strdup(name);
699 if (!prog->name)
a5b8bd47 700 goto errout;
a5b8bd47 701
33a2c75c 702 prog->pin_name = __bpf_program__pin_name(prog);
c1122392 703 if (!prog->pin_name)
33a2c75c 704 goto errout;
33a2c75c 705
c1122392
AN
706 prog->insns = malloc(insn_data_sz);
707 if (!prog->insns)
a5b8bd47 708 goto errout;
c1122392 709 memcpy(prog->insns, insn_data, insn_data_sz);
a5b8bd47
WN
710
711 return 0;
712errout:
c1122392 713 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
a5b8bd47
WN
714 bpf_program__exit(prog);
715 return -ENOMEM;
716}
717
718static int
c1122392
AN
719bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
720 const char *sec_name, int sec_idx)
a5b8bd47 721{
6245947c 722 Elf_Data *symbols = obj->efile.symbols;
c1122392
AN
723 struct bpf_program *prog, *progs;
724 void *data = sec_data->d_buf;
6245947c
AN
725 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
726 int nr_progs, err, i;
c1122392 727 const char *name;
ad23b723 728 Elf64_Sym *sym;
a5b8bd47
WN
729
730 progs = obj->programs;
731 nr_progs = obj->nr_programs;
ad23b723 732 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
c1122392 733 sec_off = 0;
a5b8bd47 734
6245947c 735 for (i = 0; i < nr_syms; i++) {
ad23b723
AN
736 sym = elf_sym_by_idx(obj, i);
737
738 if (sym->st_shndx != sec_idx)
6245947c 739 continue;
ad23b723 740 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
6245947c 741 continue;
88cda1c9 742
ad23b723
AN
743 prog_sz = sym->st_size;
744 sec_off = sym->st_value;
88cda1c9 745
ad23b723 746 name = elf_sym_str(obj, sym->st_name);
c1122392
AN
747 if (!name) {
748 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
749 sec_name, sec_off);
750 return -LIBBPF_ERRNO__FORMAT;
751 }
88cda1c9 752
c1122392
AN
753 if (sec_off + prog_sz > sec_sz) {
754 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
755 sec_name, sec_off);
756 return -LIBBPF_ERRNO__FORMAT;
757 }
88cda1c9 758
ad23b723 759 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
513f485c
AN
760 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
761 return -ENOTSUP;
762 }
763
c3c55696
AN
764 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
765 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
88cda1c9 766
c3c55696 767 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
c1122392
AN
768 if (!progs) {
769 /*
770 * In this case the original obj->programs
771 * is still valid, so don't need special treat for
772 * bpf_close_object().
773 */
774 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
775 sec_name, name);
776 return -ENOMEM;
88cda1c9 777 }
c1122392 778 obj->programs = progs;
88cda1c9 779
c1122392 780 prog = &progs[nr_progs];
9a94f277 781
c3c55696
AN
782 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
783 sec_off, data + sec_off, prog_sz);
c1122392
AN
784 if (err)
785 return err;
9a94f277 786
e5670fa0
AN
787 /* if function is a global/weak symbol, but has restricted
788 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
789 * as static to enable more permissive BPF verification mode
790 * with more outside context available to BPF verifier
aea28a60 791 */
ad23b723
AN
792 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
793 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
794 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
aea28a60
AN
795 prog->mark_btf_static = true;
796
c1122392
AN
797 nr_progs++;
798 obj->nr_programs = nr_progs;
88cda1c9
MKL
799 }
800
801 return 0;
802}
803
5b3d7298 804__u32 get_kernel_version(void)
5e61f270 805{
5b3d7298
AN
806 /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
807 * but Ubuntu provides /proc/version_signature file, as described at
808 * https://ubuntu.com/kernel, with an example contents below, which we
809 * can use to get a proper LINUX_VERSION_CODE.
810 *
811 * Ubuntu 5.4.0-12.15-generic 5.4.8
812 *
813 * In the above, 5.4.8 is what kernel is actually expecting, while
814 * uname() call will return 5.4.0 in info.release.
815 */
816 const char *ubuntu_kver_file = "/proc/version_signature";
5e61f270
AN
817 __u32 major, minor, patch;
818 struct utsname info;
819
5b3d7298
AN
820 if (access(ubuntu_kver_file, R_OK) == 0) {
821 FILE *f;
822
823 f = fopen(ubuntu_kver_file, "r");
824 if (f) {
825 if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
826 fclose(f);
827 return KERNEL_VERSION(major, minor, patch);
828 }
829 fclose(f);
830 }
831 /* something went wrong, fall back to uname() approach */
832 }
833
5e61f270
AN
834 uname(&info);
835 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
836 return 0;
837 return KERNEL_VERSION(major, minor, patch);
838}
839
590a0088
MKL
840static const struct btf_member *
841find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
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 (btf_member_bit_offset(t, i) == bit_offset)
848 return m;
849 }
850
851 return NULL;
852}
853
854static const struct btf_member *
855find_member_by_name(const struct btf *btf, const struct btf_type *t,
856 const char *name)
857{
858 struct btf_member *m;
859 int i;
860
861 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
862 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
863 return m;
864 }
865
866 return NULL;
867}
868
869#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
a6ed02ca
KS
870static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
871 const char *name, __u32 kind);
590a0088
MKL
872
873static int
874find_struct_ops_kern_types(const struct btf *btf, const char *tname,
875 const struct btf_type **type, __u32 *type_id,
876 const struct btf_type **vtype, __u32 *vtype_id,
877 const struct btf_member **data_member)
878{
879 const struct btf_type *kern_type, *kern_vtype;
880 const struct btf_member *kern_data_member;
881 __s32 kern_vtype_id, kern_type_id;
590a0088
MKL
882 __u32 i;
883
884 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
885 if (kern_type_id < 0) {
886 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
887 tname);
888 return kern_type_id;
889 }
890 kern_type = btf__type_by_id(btf, kern_type_id);
891
892 /* Find the corresponding "map_value" type that will be used
893 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
894 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
895 * btf_vmlinux.
896 */
a6ed02ca
KS
897 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
898 tname, BTF_KIND_STRUCT);
590a0088 899 if (kern_vtype_id < 0) {
a6ed02ca
KS
900 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
901 STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
902 return kern_vtype_id;
903 }
904 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
905
906 /* Find "struct tcp_congestion_ops" from
907 * struct bpf_struct_ops_tcp_congestion_ops {
908 * [ ... ]
909 * struct tcp_congestion_ops data;
910 * }
911 */
912 kern_data_member = btf_members(kern_vtype);
913 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
914 if (kern_data_member->type == kern_type_id)
915 break;
916 }
917 if (i == btf_vlen(kern_vtype)) {
a6ed02ca
KS
918 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
919 tname, STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
920 return -EINVAL;
921 }
922
923 *type = kern_type;
924 *type_id = kern_type_id;
925 *vtype = kern_vtype;
926 *vtype_id = kern_vtype_id;
927 *data_member = kern_data_member;
928
929 return 0;
930}
931
932static bool bpf_map__is_struct_ops(const struct bpf_map *map)
933{
934 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
935}
936
937/* Init the map's fields that depend on kern_btf */
938static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
939 const struct btf *btf,
940 const struct btf *kern_btf)
941{
942 const struct btf_member *member, *kern_member, *kern_data_member;
943 const struct btf_type *type, *kern_type, *kern_vtype;
944 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
945 struct bpf_struct_ops *st_ops;
946 void *data, *kern_data;
947 const char *tname;
948 int err;
949
950 st_ops = map->st_ops;
951 type = st_ops->type;
952 tname = st_ops->tname;
953 err = find_struct_ops_kern_types(kern_btf, tname,
954 &kern_type, &kern_type_id,
955 &kern_vtype, &kern_vtype_id,
956 &kern_data_member);
957 if (err)
958 return err;
959
960 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
961 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
962
963 map->def.value_size = kern_vtype->size;
964 map->btf_vmlinux_value_type_id = kern_vtype_id;
965
966 st_ops->kern_vdata = calloc(1, kern_vtype->size);
967 if (!st_ops->kern_vdata)
968 return -ENOMEM;
969
970 data = st_ops->data;
971 kern_data_off = kern_data_member->offset / 8;
972 kern_data = st_ops->kern_vdata + kern_data_off;
973
974 member = btf_members(type);
975 for (i = 0; i < btf_vlen(type); i++, member++) {
976 const struct btf_type *mtype, *kern_mtype;
977 __u32 mtype_id, kern_mtype_id;
978 void *mdata, *kern_mdata;
979 __s64 msize, kern_msize;
980 __u32 moff, kern_moff;
981 __u32 kern_member_idx;
982 const char *mname;
983
984 mname = btf__name_by_offset(btf, member->name_off);
985 kern_member = find_member_by_name(kern_btf, kern_type, mname);
986 if (!kern_member) {
987 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
988 map->name, mname);
989 return -ENOTSUP;
990 }
991
992 kern_member_idx = kern_member - btf_members(kern_type);
993 if (btf_member_bitfield_size(type, i) ||
994 btf_member_bitfield_size(kern_type, kern_member_idx)) {
995 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
996 map->name, mname);
997 return -ENOTSUP;
998 }
999
1000 moff = member->offset / 8;
1001 kern_moff = kern_member->offset / 8;
1002
1003 mdata = data + moff;
1004 kern_mdata = kern_data + kern_moff;
1005
1006 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1007 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1008 &kern_mtype_id);
1009 if (BTF_INFO_KIND(mtype->info) !=
1010 BTF_INFO_KIND(kern_mtype->info)) {
1011 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1012 map->name, mname, BTF_INFO_KIND(mtype->info),
1013 BTF_INFO_KIND(kern_mtype->info));
1014 return -ENOTSUP;
1015 }
1016
1017 if (btf_is_ptr(mtype)) {
1018 struct bpf_program *prog;
1019
d2836ddd
MKL
1020 prog = st_ops->progs[i];
1021 if (!prog)
1022 continue;
1023
590a0088
MKL
1024 kern_mtype = skip_mods_and_typedefs(kern_btf,
1025 kern_mtype->type,
1026 &kern_mtype_id);
d2836ddd
MKL
1027
1028 /* mtype->type must be a func_proto which was
1029 * guaranteed in bpf_object__collect_st_ops_relos(),
1030 * so only check kern_mtype for func_proto here.
1031 */
1032 if (!btf_is_func_proto(kern_mtype)) {
1033 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
590a0088
MKL
1034 map->name, mname);
1035 return -ENOTSUP;
1036 }
1037
590a0088
MKL
1038 prog->attach_btf_id = kern_type_id;
1039 prog->expected_attach_type = kern_member_idx;
1040
1041 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1042
1043 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1044 map->name, mname, prog->name, moff,
1045 kern_moff);
1046
1047 continue;
1048 }
1049
1050 msize = btf__resolve_size(btf, mtype_id);
1051 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1052 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1053 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1054 map->name, mname, (ssize_t)msize,
1055 (ssize_t)kern_msize);
1056 return -ENOTSUP;
1057 }
1058
1059 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1060 map->name, mname, (unsigned int)msize,
1061 moff, kern_moff);
1062 memcpy(kern_mdata, mdata, msize);
1063 }
1064
1065 return 0;
1066}
1067
1068static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1069{
590a0088
MKL
1070 struct bpf_map *map;
1071 size_t i;
1072 int err;
1073
1074 for (i = 0; i < obj->nr_maps; i++) {
1075 map = &obj->maps[i];
1076
1077 if (!bpf_map__is_struct_ops(map))
1078 continue;
1079
a6ed02ca
KS
1080 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1081 obj->btf_vmlinux);
1082 if (err)
590a0088 1083 return err;
590a0088
MKL
1084 }
1085
590a0088
MKL
1086 return 0;
1087}
1088
1089static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1090{
1091 const struct btf_type *type, *datasec;
1092 const struct btf_var_secinfo *vsi;
1093 struct bpf_struct_ops *st_ops;
1094 const char *tname, *var_name;
1095 __s32 type_id, datasec_id;
1096 const struct btf *btf;
1097 struct bpf_map *map;
1098 __u32 i;
1099
1100 if (obj->efile.st_ops_shndx == -1)
1101 return 0;
1102
1103 btf = obj->btf;
1104 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1105 BTF_KIND_DATASEC);
1106 if (datasec_id < 0) {
1107 pr_warn("struct_ops init: DATASEC %s not found\n",
1108 STRUCT_OPS_SEC);
1109 return -EINVAL;
1110 }
1111
1112 datasec = btf__type_by_id(btf, datasec_id);
1113 vsi = btf_var_secinfos(datasec);
1114 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1115 type = btf__type_by_id(obj->btf, vsi->type);
1116 var_name = btf__name_by_offset(obj->btf, type->name_off);
1117
1118 type_id = btf__resolve_type(obj->btf, vsi->type);
1119 if (type_id < 0) {
1120 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1121 vsi->type, STRUCT_OPS_SEC);
1122 return -EINVAL;
1123 }
1124
1125 type = btf__type_by_id(obj->btf, type_id);
1126 tname = btf__name_by_offset(obj->btf, type->name_off);
1127 if (!tname[0]) {
1128 pr_warn("struct_ops init: anonymous type is not supported\n");
1129 return -ENOTSUP;
1130 }
1131 if (!btf_is_struct(type)) {
1132 pr_warn("struct_ops init: %s is not a struct\n", tname);
1133 return -EINVAL;
1134 }
1135
1136 map = bpf_object__add_map(obj);
1137 if (IS_ERR(map))
1138 return PTR_ERR(map);
1139
1140 map->sec_idx = obj->efile.st_ops_shndx;
1141 map->sec_offset = vsi->offset;
1142 map->name = strdup(var_name);
1143 if (!map->name)
1144 return -ENOMEM;
1145
1146 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1147 map->def.key_size = sizeof(int);
1148 map->def.value_size = type->size;
1149 map->def.max_entries = 1;
1150
1151 map->st_ops = calloc(1, sizeof(*map->st_ops));
1152 if (!map->st_ops)
1153 return -ENOMEM;
1154 st_ops = map->st_ops;
1155 st_ops->data = malloc(type->size);
1156 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1157 st_ops->kern_func_off = malloc(btf_vlen(type) *
1158 sizeof(*st_ops->kern_func_off));
1159 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1160 return -ENOMEM;
1161
1162 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1163 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1164 var_name, STRUCT_OPS_SEC);
1165 return -EINVAL;
1166 }
1167
1168 memcpy(st_ops->data,
1169 obj->efile.st_ops_data->d_buf + vsi->offset,
1170 type->size);
1171 st_ops->tname = tname;
1172 st_ops->type = type;
1173 st_ops->type_id = type_id;
1174
1175 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1176 tname, type_id, var_name, vsi->offset);
1177 }
1178
1179 return 0;
1180}
1181
6c956392 1182static struct bpf_object *bpf_object__new(const char *path,
5e61f270 1183 const void *obj_buf,
2ce8450e
AN
1184 size_t obj_buf_sz,
1185 const char *obj_name)
1a5e3fb1 1186{
689624f0 1187 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1a5e3fb1 1188 struct bpf_object *obj;
d859900c 1189 char *end;
1a5e3fb1
WN
1190
1191 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1192 if (!obj) {
be18010e 1193 pr_warn("alloc memory failed for %s\n", path);
6371ca3b 1194 return ERR_PTR(-ENOMEM);
1a5e3fb1
WN
1195 }
1196
1197 strcpy(obj->path, path);
2ce8450e 1198 if (obj_name) {
9fc205b4 1199 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
2ce8450e
AN
1200 } else {
1201 /* Using basename() GNU version which doesn't modify arg. */
9fc205b4 1202 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
2ce8450e
AN
1203 end = strchr(obj->name, '.');
1204 if (end)
1205 *end = 0;
1206 }
6c956392 1207
d859900c 1208 obj->efile.fd = -1;
6c956392 1209 /*
76e1022b 1210 * Caller of this function should also call
6c956392
WN
1211 * bpf_object__elf_finish() after data collection to return
1212 * obj_buf to user. If not, we should duplicate the buffer to
1213 * avoid user freeing them before elf finish.
1214 */
1215 obj->efile.obj_buf = obj_buf;
1216 obj->efile.obj_buf_sz = obj_buf_sz;
666810e8 1217 obj->efile.maps_shndx = -1;
abd29c93 1218 obj->efile.btf_maps_shndx = -1;
590a0088 1219 obj->efile.st_ops_shndx = -1;
81bfdd08 1220 obj->kconfig_map_idx = -1;
6c956392 1221
5e61f270 1222 obj->kern_version = get_kernel_version();
52d3352e 1223 obj->loaded = false;
9a208eff
WN
1224
1225 INIT_LIST_HEAD(&obj->list);
689624f0
JB
1226 if (!strict)
1227 list_add(&obj->list, &bpf_objects_list);
1a5e3fb1
WN
1228 return obj;
1229}
1230
1231static void bpf_object__elf_finish(struct bpf_object *obj)
1232{
29a30ff5 1233 if (!obj->efile.elf)
1a5e3fb1
WN
1234 return;
1235
b71a2ebf
GC
1236 elf_end(obj->efile.elf);
1237 obj->efile.elf = NULL;
bec7d68c 1238 obj->efile.symbols = NULL;
590a0088 1239 obj->efile.st_ops_data = NULL;
b62f06e8 1240
25bbbd7a
AN
1241 zfree(&obj->efile.secs);
1242 obj->efile.sec_cnt = 0;
1a5e3fb1 1243 zclose(obj->efile.fd);
6c956392
WN
1244 obj->efile.obj_buf = NULL;
1245 obj->efile.obj_buf_sz = 0;
1a5e3fb1
WN
1246}
1247
1248static int bpf_object__elf_init(struct bpf_object *obj)
1249{
ad23b723 1250 Elf64_Ehdr *ehdr;
1a5e3fb1 1251 int err = 0;
ad23b723 1252 Elf *elf;
1a5e3fb1 1253
29a30ff5 1254 if (obj->efile.elf) {
88a82120 1255 pr_warn("elf: init internal error\n");
6371ca3b 1256 return -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1257 }
1258
6c956392
WN
1259 if (obj->efile.obj_buf_sz > 0) {
1260 /*
1261 * obj_buf should have been validated by
1262 * bpf_object__open_buffer().
1263 */
ad23b723 1264 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
6c956392 1265 } else {
92274e24 1266 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
6c956392 1267 if (obj->efile.fd < 0) {
be5c5d4e 1268 char errmsg[STRERR_BUFSIZE], *cp;
1ce6a9fc 1269
be5c5d4e
AN
1270 err = -errno;
1271 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
88a82120 1272 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
be5c5d4e 1273 return err;
6c956392
WN
1274 }
1275
ad23b723 1276 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1a5e3fb1
WN
1277 }
1278
ad23b723 1279 if (!elf) {
88a82120 1280 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1281 err = -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1282 goto errout;
1283 }
1284
ad23b723
AN
1285 obj->efile.elf = elf;
1286
1287 if (elf_kind(elf) != ELF_K_ELF) {
1288 err = -LIBBPF_ERRNO__FORMAT;
1289 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1290 goto errout;
1291 }
1292
1293 if (gelf_getclass(elf) != ELFCLASS64) {
1294 err = -LIBBPF_ERRNO__FORMAT;
1295 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1296 goto errout;
1297 }
1298
1299 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1300 if (!obj->efile.ehdr) {
88a82120 1301 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1302 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1303 goto errout;
1304 }
1a5e3fb1 1305
ad23b723 1306 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
88a82120
AN
1307 pr_warn("elf: failed to get section names section index for %s: %s\n",
1308 obj->path, elf_errmsg(-1));
1309 err = -LIBBPF_ERRNO__FORMAT;
1310 goto errout;
1311 }
1312
1313 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
ad23b723 1314 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
88a82120
AN
1315 pr_warn("elf: failed to get section names strings from %s: %s\n",
1316 obj->path, elf_errmsg(-1));
8f3f5792
NK
1317 err = -LIBBPF_ERRNO__FORMAT;
1318 goto errout;
88a82120
AN
1319 }
1320
9b16137a 1321 /* Old LLVM set e_machine to EM_NONE */
ad23b723 1322 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
88a82120 1323 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
6371ca3b 1324 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1325 goto errout;
1326 }
1327
1328 return 0;
1329errout:
1330 bpf_object__elf_finish(obj);
1331 return err;
1332}
1333
12ef5634 1334static int bpf_object__check_endianness(struct bpf_object *obj)
cc4228d5 1335{
3930198d 1336#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
ad23b723 1337 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
12ef5634 1338 return 0;
3930198d 1339#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
ad23b723 1340 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
12ef5634
AN
1341 return 0;
1342#else
1343# error "Unrecognized __BYTE_ORDER__"
1344#endif
88a82120 1345 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
6371ca3b 1346 return -LIBBPF_ERRNO__ENDIAN;
cc4228d5
WN
1347}
1348
cb1e5e96 1349static int
399dc65e 1350bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
cb1e5e96 1351{
f9798239
AN
1352 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1353 * go over allowed ELF data section buffer
1354 */
1355 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
cb1e5e96
WN
1356 pr_debug("license of %s is %s\n", obj->path, obj->license);
1357 return 0;
1358}
1359
54b8625c
JF
1360static int
1361bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1362{
1363 __u32 kver;
1364
1365 if (size != sizeof(kver)) {
be18010e 1366 pr_warn("invalid kver section in %s\n", obj->path);
54b8625c
JF
1367 return -LIBBPF_ERRNO__FORMAT;
1368 }
1369 memcpy(&kver, data, sizeof(kver));
1370 obj->kern_version = kver;
1371 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1372 return 0;
1373}
1374
addb9fc9
NS
1375static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1376{
1377 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1378 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1379 return true;
1380 return false;
1381}
1382
b96c07f3 1383static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1713d68b 1384{
25bbbd7a
AN
1385 Elf_Data *data;
1386 Elf_Scn *scn;
1713d68b 1387
25bbbd7a 1388 if (!name)
1713d68b 1389 return -EINVAL;
88a82120 1390
25bbbd7a
AN
1391 scn = elf_sec_by_name(obj, name);
1392 data = elf_sec_data(obj, scn);
1393 if (data) {
25bbbd7a 1394 *size = data->d_size;
08894d9c 1395 return 0; /* found it */
1713d68b
DB
1396 }
1397
08894d9c 1398 return -ENOENT;
1713d68b
DB
1399}
1400
b96c07f3 1401static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1713d68b
DB
1402{
1403 Elf_Data *symbols = obj->efile.symbols;
1404 const char *sname;
1405 size_t si;
1406
1407 if (!name || !off)
1408 return -EINVAL;
1409
ad23b723
AN
1410 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1411 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1713d68b 1412
3a06ec0a
AN
1413 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1414 continue;
1415
1416 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1417 ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1713d68b
DB
1418 continue;
1419
ad23b723 1420 sname = elf_sym_str(obj, sym->st_name);
1713d68b 1421 if (!sname) {
ad23b723 1422 pr_warn("failed to get sym name string for var %s\n", name);
1713d68b
DB
1423 return -EIO;
1424 }
1425 if (strcmp(name, sname) == 0) {
ad23b723 1426 *off = sym->st_value;
1713d68b
DB
1427 return 0;
1428 }
1429 }
1430
1431 return -ENOENT;
1432}
1433
bf829271 1434static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
d859900c 1435{
bf829271
AN
1436 struct bpf_map *new_maps;
1437 size_t new_cap;
1438 int i;
1439
1440 if (obj->nr_maps < obj->maps_cap)
1441 return &obj->maps[obj->nr_maps++];
1442
95064979 1443 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
029258d7 1444 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
bf829271 1445 if (!new_maps) {
be18010e 1446 pr_warn("alloc maps for object failed\n");
bf829271
AN
1447 return ERR_PTR(-ENOMEM);
1448 }
1449
1450 obj->maps_cap = new_cap;
1451 obj->maps = new_maps;
1452
1453 /* zero out new maps */
1454 memset(obj->maps + obj->nr_maps, 0,
1455 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1456 /*
1457 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1458 * when failure (zclose won't close negative fd)).
1459 */
1460 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1461 obj->maps[i].fd = -1;
1462 obj->maps[i].inner_map_fd = -1;
1463 }
1464
1465 return &obj->maps[obj->nr_maps++];
d859900c
DB
1466}
1467
eba9c5f4
AN
1468static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1469{
1470 long page_sz = sysconf(_SC_PAGE_SIZE);
1471 size_t map_sz;
1472
c701917e 1473 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
eba9c5f4
AN
1474 map_sz = roundup(map_sz, page_sz);
1475 return map_sz;
1476}
1477
aed65917 1478static char *internal_map_name(struct bpf_object *obj, const char *real_name)
81bfdd08 1479{
113e6b7e 1480 char map_name[BPF_OBJ_NAME_LEN], *p;
aed65917
AN
1481 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1482
1483 /* This is one of the more confusing parts of libbpf for various
1484 * reasons, some of which are historical. The original idea for naming
1485 * internal names was to include as much of BPF object name prefix as
1486 * possible, so that it can be distinguished from similar internal
1487 * maps of a different BPF object.
1488 * As an example, let's say we have bpf_object named 'my_object_name'
1489 * and internal map corresponding to '.rodata' ELF section. The final
1490 * map name advertised to user and to the kernel will be
1491 * 'my_objec.rodata', taking first 8 characters of object name and
1492 * entire 7 characters of '.rodata'.
1493 * Somewhat confusingly, if internal map ELF section name is shorter
1494 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1495 * for the suffix, even though we only have 4 actual characters, and
1496 * resulting map will be called 'my_objec.bss', not even using all 15
1497 * characters allowed by the kernel. Oh well, at least the truncated
1498 * object name is somewhat consistent in this case. But if the map
1499 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1500 * (8 chars) and thus will be left with only first 7 characters of the
1501 * object name ('my_obje'). Happy guessing, user, that the final map
1502 * name will be "my_obje.kconfig".
1503 * Now, with libbpf starting to support arbitrarily named .rodata.*
1504 * and .data.* data sections, it's possible that ELF section name is
1505 * longer than allowed 15 chars, so we now need to be careful to take
1506 * only up to 15 first characters of ELF name, taking no BPF object
1507 * name characters at all. So '.rodata.abracadabra' will result in
1508 * '.rodata.abracad' kernel and user-visible name.
1509 * We need to keep this convoluted logic intact for .data, .bss and
1510 * .rodata maps, but for new custom .data.custom and .rodata.custom
1511 * maps we use their ELF names as is, not prepending bpf_object name
1512 * in front. We still need to truncate them to 15 characters for the
1513 * kernel. Full name can be recovered for such maps by using DATASEC
1514 * BTF type associated with such map's value type, though.
1515 */
1516 if (sfx_len >= BPF_OBJ_NAME_LEN)
1517 sfx_len = BPF_OBJ_NAME_LEN - 1;
1518
1519 /* if there are two or more dots in map name, it's a custom dot map */
1520 if (strchr(real_name + 1, '.') != NULL)
1521 pfx_len = 0;
1522 else
1523 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
81bfdd08
AN
1524
1525 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
aed65917 1526 sfx_len, real_name);
81bfdd08 1527
113e6b7e
THJ
1528 /* sanitise map name to characters allowed by kernel */
1529 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1530 if (!isalnum(*p) && *p != '_' && *p != '.')
1531 *p = '_';
1532
81bfdd08
AN
1533 return strdup(map_name);
1534}
1535
262cfb74
DK
1536static int
1537bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1538
d859900c 1539static int
bf829271 1540bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
aed65917 1541 const char *real_name, int sec_idx, void *data, size_t data_sz)
d859900c 1542{
bf829271
AN
1543 struct bpf_map_def *def;
1544 struct bpf_map *map;
eba9c5f4 1545 int err;
bf829271
AN
1546
1547 map = bpf_object__add_map(obj);
1548 if (IS_ERR(map))
1549 return PTR_ERR(map);
d859900c
DB
1550
1551 map->libbpf_type = type;
db48814b
AN
1552 map->sec_idx = sec_idx;
1553 map->sec_offset = 0;
aed65917
AN
1554 map->real_name = strdup(real_name);
1555 map->name = internal_map_name(obj, real_name);
1556 if (!map->real_name || !map->name) {
1557 zfree(&map->real_name);
1558 zfree(&map->name);
d859900c
DB
1559 return -ENOMEM;
1560 }
1561
bf829271 1562 def = &map->def;
d859900c
DB
1563 def->type = BPF_MAP_TYPE_ARRAY;
1564 def->key_size = sizeof(int);
eba9c5f4 1565 def->value_size = data_sz;
d859900c 1566 def->max_entries = 1;
81bfdd08 1567 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
166750bc 1568 ? BPF_F_RDONLY_PROG : 0;
0d13bfce 1569 def->map_flags |= BPF_F_MMAPABLE;
7fe74b43
AN
1570
1571 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
81bfdd08 1572 map->name, map->sec_idx, map->sec_offset, def->map_flags);
7fe74b43 1573
eba9c5f4
AN
1574 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1575 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1576 if (map->mmaped == MAP_FAILED) {
1577 err = -errno;
1578 map->mmaped = NULL;
1579 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1580 map->name, err);
aed65917 1581 zfree(&map->real_name);
eba9c5f4
AN
1582 zfree(&map->name);
1583 return err;
d859900c
DB
1584 }
1585
262cfb74
DK
1586 /* failures are fine because of maps like .rodata.str1.1 */
1587 (void) bpf_map_find_btf_info(obj, map);
1588
166750bc 1589 if (data)
eba9c5f4
AN
1590 memcpy(map->mmaped, data, data_sz);
1591
e1d1dc46 1592 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
d859900c
DB
1593 return 0;
1594}
1595
bf829271
AN
1596static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1597{
25bbbd7a 1598 struct elf_sec_desc *sec_desc;
aed65917 1599 const char *sec_name;
25bbbd7a 1600 int err = 0, sec_idx;
bf829271 1601
bf829271
AN
1602 /*
1603 * Populate obj->maps with libbpf internal maps.
1604 */
25bbbd7a
AN
1605 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1606 sec_desc = &obj->efile.secs[sec_idx];
1607
1608 switch (sec_desc->sec_type) {
1609 case SEC_DATA:
aed65917 1610 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1611 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
aed65917 1612 sec_name, sec_idx,
25bbbd7a
AN
1613 sec_desc->data->d_buf,
1614 sec_desc->data->d_size);
1615 break;
1616 case SEC_RODATA:
1617 obj->has_rodata = true;
aed65917 1618 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1619 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
aed65917 1620 sec_name, sec_idx,
25bbbd7a
AN
1621 sec_desc->data->d_buf,
1622 sec_desc->data->d_size);
1623 break;
1624 case SEC_BSS:
aed65917 1625 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1626 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
aed65917 1627 sec_name, sec_idx,
25bbbd7a
AN
1628 NULL,
1629 sec_desc->data->d_size);
1630 break;
1631 default:
1632 /* skip */
1633 break;
1634 }
bf829271
AN
1635 if (err)
1636 return err;
1637 }
1638 return 0;
1639}
1640
166750bc
AN
1641
1642static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1643 const void *name)
1644{
1645 int i;
1646
1647 for (i = 0; i < obj->nr_extern; i++) {
1648 if (strcmp(obj->externs[i].name, name) == 0)
1649 return &obj->externs[i];
1650 }
1651 return NULL;
1652}
1653
2e33efe3
AN
1654static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1655 char value)
166750bc 1656{
2e33efe3
AN
1657 switch (ext->kcfg.type) {
1658 case KCFG_BOOL:
166750bc 1659 if (value == 'm') {
2e33efe3 1660 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
166750bc
AN
1661 ext->name, value);
1662 return -EINVAL;
1663 }
1664 *(bool *)ext_val = value == 'y' ? true : false;
1665 break;
2e33efe3 1666 case KCFG_TRISTATE:
166750bc
AN
1667 if (value == 'y')
1668 *(enum libbpf_tristate *)ext_val = TRI_YES;
1669 else if (value == 'm')
1670 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1671 else /* value == 'n' */
1672 *(enum libbpf_tristate *)ext_val = TRI_NO;
1673 break;
2e33efe3 1674 case KCFG_CHAR:
166750bc
AN
1675 *(char *)ext_val = value;
1676 break;
2e33efe3
AN
1677 case KCFG_UNKNOWN:
1678 case KCFG_INT:
1679 case KCFG_CHAR_ARR:
166750bc 1680 default:
2e33efe3 1681 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
166750bc
AN
1682 ext->name, value);
1683 return -EINVAL;
1684 }
1685 ext->is_set = true;
1686 return 0;
1687}
1688
2e33efe3
AN
1689static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1690 const char *value)
166750bc
AN
1691{
1692 size_t len;
1693
2e33efe3
AN
1694 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1695 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
166750bc
AN
1696 return -EINVAL;
1697 }
1698
1699 len = strlen(value);
1700 if (value[len - 1] != '"') {
2e33efe3 1701 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
166750bc
AN
1702 ext->name, value);
1703 return -EINVAL;
1704 }
1705
1706 /* strip quotes */
1707 len -= 2;
2e33efe3
AN
1708 if (len >= ext->kcfg.sz) {
1709 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1710 ext->name, value, len, ext->kcfg.sz - 1);
1711 len = ext->kcfg.sz - 1;
166750bc
AN
1712 }
1713 memcpy(ext_val, value + 1, len);
1714 ext_val[len] = '\0';
1715 ext->is_set = true;
1716 return 0;
1717}
1718
1719static int parse_u64(const char *value, __u64 *res)
1720{
1721 char *value_end;
1722 int err;
1723
1724 errno = 0;
1725 *res = strtoull(value, &value_end, 0);
1726 if (errno) {
1727 err = -errno;
1728 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1729 return err;
1730 }
1731 if (*value_end) {
1732 pr_warn("failed to parse '%s' as integer completely\n", value);
1733 return -EINVAL;
1734 }
1735 return 0;
1736}
1737
2e33efe3 1738static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
166750bc 1739{
2e33efe3 1740 int bit_sz = ext->kcfg.sz * 8;
166750bc 1741
2e33efe3 1742 if (ext->kcfg.sz == 8)
166750bc
AN
1743 return true;
1744
1745 /* Validate that value stored in u64 fits in integer of `ext->sz`
1746 * bytes size without any loss of information. If the target integer
1747 * is signed, we rely on the following limits of integer type of
1748 * Y bits and subsequent transformation:
1749 *
1750 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1751 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1752 * 0 <= X + 2^(Y-1) < 2^Y
1753 *
1754 * For unsigned target integer, check that all the (64 - Y) bits are
1755 * zero.
1756 */
2e33efe3 1757 if (ext->kcfg.is_signed)
166750bc
AN
1758 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1759 else
1760 return (v >> bit_sz) == 0;
1761}
1762
2e33efe3
AN
1763static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1764 __u64 value)
166750bc 1765{
2e33efe3
AN
1766 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1767 pr_warn("extern (kcfg) %s=%llu should be integer\n",
7745ff98 1768 ext->name, (unsigned long long)value);
166750bc
AN
1769 return -EINVAL;
1770 }
2e33efe3
AN
1771 if (!is_kcfg_value_in_range(ext, value)) {
1772 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1773 ext->name, (unsigned long long)value, ext->kcfg.sz);
166750bc
AN
1774 return -ERANGE;
1775 }
2e33efe3 1776 switch (ext->kcfg.sz) {
166750bc
AN
1777 case 1: *(__u8 *)ext_val = value; break;
1778 case 2: *(__u16 *)ext_val = value; break;
1779 case 4: *(__u32 *)ext_val = value; break;
1780 case 8: *(__u64 *)ext_val = value; break;
1781 default:
1782 return -EINVAL;
1783 }
1784 ext->is_set = true;
1785 return 0;
1786}
1787
8601fd42
AN
1788static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1789 char *buf, void *data)
166750bc 1790{
166750bc 1791 struct extern_desc *ext;
8601fd42 1792 char *sep, *value;
166750bc
AN
1793 int len, err = 0;
1794 void *ext_val;
1795 __u64 num;
166750bc 1796
13d35a0c 1797 if (!str_has_pfx(buf, "CONFIG_"))
8601fd42 1798 return 0;
166750bc 1799
8601fd42
AN
1800 sep = strchr(buf, '=');
1801 if (!sep) {
1802 pr_warn("failed to parse '%s': no separator\n", buf);
1803 return -EINVAL;
1804 }
1805
1806 /* Trim ending '\n' */
1807 len = strlen(buf);
1808 if (buf[len - 1] == '\n')
1809 buf[len - 1] = '\0';
1810 /* Split on '=' and ensure that a value is present. */
1811 *sep = '\0';
1812 if (!sep[1]) {
1813 *sep = '=';
1814 pr_warn("failed to parse '%s': no value\n", buf);
1815 return -EINVAL;
1816 }
1817
1818 ext = find_extern_by_name(obj, buf);
1819 if (!ext || ext->is_set)
1820 return 0;
1821
2e33efe3 1822 ext_val = data + ext->kcfg.data_off;
8601fd42
AN
1823 value = sep + 1;
1824
1825 switch (*value) {
1826 case 'y': case 'n': case 'm':
2e33efe3 1827 err = set_kcfg_value_tri(ext, ext_val, *value);
8601fd42
AN
1828 break;
1829 case '"':
2e33efe3 1830 err = set_kcfg_value_str(ext, ext_val, value);
8601fd42
AN
1831 break;
1832 default:
1833 /* assume integer */
1834 err = parse_u64(value, &num);
1835 if (err) {
2e33efe3 1836 pr_warn("extern (kcfg) %s=%s should be integer\n",
8601fd42
AN
1837 ext->name, value);
1838 return err;
1839 }
2e33efe3 1840 err = set_kcfg_value_num(ext, ext_val, num);
8601fd42 1841 break;
166750bc 1842 }
8601fd42
AN
1843 if (err)
1844 return err;
2e33efe3 1845 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
8601fd42
AN
1846 return 0;
1847}
1848
1849static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1850{
1851 char buf[PATH_MAX];
1852 struct utsname uts;
1853 int len, err = 0;
1854 gzFile file;
1855
1856 uname(&uts);
1857 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1858 if (len < 0)
1859 return -EINVAL;
1860 else if (len >= PATH_MAX)
1861 return -ENAMETOOLONG;
1862
1863 /* gzopen also accepts uncompressed files. */
1864 file = gzopen(buf, "r");
1865 if (!file)
1866 file = gzopen("/proc/config.gz", "r");
1867
166750bc 1868 if (!file) {
8601fd42 1869 pr_warn("failed to open system Kconfig\n");
166750bc
AN
1870 return -ENOENT;
1871 }
1872
1873 while (gzgets(file, buf, sizeof(buf))) {
8601fd42
AN
1874 err = bpf_object__process_kconfig_line(obj, buf, data);
1875 if (err) {
1876 pr_warn("error parsing system Kconfig line '%s': %d\n",
1877 buf, err);
166750bc
AN
1878 goto out;
1879 }
8601fd42 1880 }
166750bc 1881
8601fd42
AN
1882out:
1883 gzclose(file);
1884 return err;
1885}
166750bc 1886
8601fd42
AN
1887static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1888 const char *config, void *data)
1889{
1890 char buf[PATH_MAX];
1891 int err = 0;
1892 FILE *file;
166750bc 1893
8601fd42
AN
1894 file = fmemopen((void *)config, strlen(config), "r");
1895 if (!file) {
1896 err = -errno;
1897 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1898 return err;
1899 }
1900
1901 while (fgets(buf, sizeof(buf), file)) {
1902 err = bpf_object__process_kconfig_line(obj, buf, data);
1903 if (err) {
1904 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1905 buf, err);
166750bc
AN
1906 break;
1907 }
166750bc
AN
1908 }
1909
8601fd42 1910 fclose(file);
166750bc
AN
1911 return err;
1912}
1913
81bfdd08 1914static int bpf_object__init_kconfig_map(struct bpf_object *obj)
166750bc 1915{
2e33efe3 1916 struct extern_desc *last_ext = NULL, *ext;
166750bc 1917 size_t map_sz;
2e33efe3 1918 int i, err;
166750bc 1919
2e33efe3
AN
1920 for (i = 0; i < obj->nr_extern; i++) {
1921 ext = &obj->externs[i];
1922 if (ext->type == EXT_KCFG)
1923 last_ext = ext;
1924 }
166750bc 1925
2e33efe3
AN
1926 if (!last_ext)
1927 return 0;
166750bc 1928
2e33efe3 1929 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
81bfdd08 1930 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
aed65917 1931 ".kconfig", obj->efile.symbols_shndx,
166750bc
AN
1932 NULL, map_sz);
1933 if (err)
1934 return err;
1935
81bfdd08 1936 obj->kconfig_map_idx = obj->nr_maps - 1;
166750bc
AN
1937
1938 return 0;
1939}
1940
bf829271 1941static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
561bbcca 1942{
561bbcca 1943 Elf_Data *symbols = obj->efile.symbols;
bf829271 1944 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
d859900c 1945 Elf_Data *data = NULL;
bf829271
AN
1946 Elf_Scn *scn;
1947
1948 if (obj->efile.maps_shndx < 0)
1949 return 0;
561bbcca 1950
93b8952d
AN
1951 if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
1952 pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
1953 return -EOPNOTSUPP;
1954 }
1955
4708bbda
EL
1956 if (!symbols)
1957 return -EINVAL;
1958
88a82120
AN
1959 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1960 data = elf_sec_data(obj, scn);
bf829271 1961 if (!scn || !data) {
88a82120
AN
1962 pr_warn("elf: failed to get legacy map definitions for %s\n",
1963 obj->path);
bf829271 1964 return -EINVAL;
4708bbda 1965 }
561bbcca 1966
4708bbda
EL
1967 /*
1968 * Count number of maps. Each map has a name.
1969 * Array of maps is not supported: only the first element is
1970 * considered.
1971 *
1972 * TODO: Detect array of map and report error.
1973 */
ad23b723 1974 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
bf829271 1975 for (i = 0; i < nr_syms; i++) {
ad23b723 1976 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4708bbda 1977
ad23b723 1978 if (sym->st_shndx != obj->efile.maps_shndx)
4708bbda 1979 continue;
ad23b723 1980 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
161ecd53 1981 continue;
4708bbda
EL
1982 nr_maps++;
1983 }
b13c5c14 1984 /* Assume equally sized map definitions */
88a82120
AN
1985 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1986 nr_maps, data->d_size, obj->path);
bf829271 1987
98e527af 1988 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
88a82120
AN
1989 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1990 obj->path);
bf829271 1991 return -EINVAL;
addb9fc9 1992 }
98e527af 1993 map_def_sz = data->d_size / nr_maps;
4708bbda 1994
bf829271
AN
1995 /* Fill obj->maps using data in "maps" section. */
1996 for (i = 0; i < nr_syms; i++) {
ad23b723 1997 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
561bbcca 1998 const char *map_name;
4708bbda 1999 struct bpf_map_def *def;
bf829271 2000 struct bpf_map *map;
561bbcca 2001
ad23b723 2002 if (sym->st_shndx != obj->efile.maps_shndx)
561bbcca 2003 continue;
ad23b723 2004 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
c3e8c44a 2005 continue;
561bbcca 2006
bf829271
AN
2007 map = bpf_object__add_map(obj);
2008 if (IS_ERR(map))
2009 return PTR_ERR(map);
2010
ad23b723 2011 map_name = elf_sym_str(obj, sym->st_name);
c51829bb 2012 if (!map_name) {
be18010e
KW
2013 pr_warn("failed to get map #%d name sym string for obj %s\n",
2014 i, obj->path);
c51829bb
AN
2015 return -LIBBPF_ERRNO__FORMAT;
2016 }
d859900c 2017
93b8952d
AN
2018 pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2019
ad23b723 2020 if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
c1cccec9
AN
2021 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2022 return -ENOTSUP;
2023 }
2024
bf829271 2025 map->libbpf_type = LIBBPF_MAP_UNSPEC;
ad23b723
AN
2026 map->sec_idx = sym->st_shndx;
2027 map->sec_offset = sym->st_value;
db48814b
AN
2028 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2029 map_name, map->sec_idx, map->sec_offset);
ad23b723 2030 if (sym->st_value + map_def_sz > data->d_size) {
be18010e
KW
2031 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2032 obj->path, map_name);
4708bbda 2033 return -EINVAL;
561bbcca 2034 }
4708bbda 2035
bf829271
AN
2036 map->name = strdup(map_name);
2037 if (!map->name) {
aed65917 2038 pr_warn("map '%s': failed to alloc map name\n", map_name);
973170e6
WN
2039 return -ENOMEM;
2040 }
bf829271 2041 pr_debug("map %d is \"%s\"\n", i, map->name);
ad23b723 2042 def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
b13c5c14
CG
2043 /*
2044 * If the definition of the map in the object file fits in
2045 * bpf_map_def, copy it. Any extra fields in our version
2046 * of bpf_map_def will default to zero as a result of the
2047 * calloc above.
2048 */
2049 if (map_def_sz <= sizeof(struct bpf_map_def)) {
bf829271 2050 memcpy(&map->def, def, map_def_sz);
b13c5c14
CG
2051 } else {
2052 /*
2053 * Here the map structure being read is bigger than what
2054 * we expect, truncate if the excess bits are all zero.
2055 * If they are not zero, reject this map as
2056 * incompatible.
2057 */
2058 char *b;
8983b731 2059
b13c5c14
CG
2060 for (b = ((char *)def) + sizeof(struct bpf_map_def);
2061 b < ((char *)def) + map_def_sz; b++) {
2062 if (*b != 0) {
8983b731 2063 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
be18010e 2064 obj->path, map_name);
c034a177
JF
2065 if (strict)
2066 return -EINVAL;
b13c5c14
CG
2067 }
2068 }
bf829271 2069 memcpy(&map->def, def, sizeof(struct bpf_map_def));
b13c5c14 2070 }
262cfb74
DK
2071
2072 /* btf info may not exist but fill it in if it does exist */
2073 (void) bpf_map_find_btf_info(obj, map);
561bbcca 2074 }
bf829271
AN
2075 return 0;
2076}
4708bbda 2077
42869d28 2078const struct btf_type *
ddc7c304 2079skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
abd29c93
AN
2080{
2081 const struct btf_type *t = btf__type_by_id(btf, id);
8837fe5d 2082
ddc7c304
AN
2083 if (res_id)
2084 *res_id = id;
2085
2086 while (btf_is_mod(t) || btf_is_typedef(t)) {
2087 if (res_id)
2088 *res_id = t->type;
2089 t = btf__type_by_id(btf, t->type);
abd29c93 2090 }
ddc7c304
AN
2091
2092 return t;
abd29c93
AN
2093}
2094
590a0088
MKL
2095static const struct btf_type *
2096resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2097{
2098 const struct btf_type *t;
2099
2100 t = skip_mods_and_typedefs(btf, id, NULL);
2101 if (!btf_is_ptr(t))
2102 return NULL;
2103
2104 t = skip_mods_and_typedefs(btf, t->type, res_id);
2105
2106 return btf_is_func_proto(t) ? t : NULL;
2107}
2108
774e132e 2109static const char *__btf_kind_str(__u16 kind)
81ba0889 2110{
774e132e 2111 switch (kind) {
81ba0889
AN
2112 case BTF_KIND_UNKN: return "void";
2113 case BTF_KIND_INT: return "int";
2114 case BTF_KIND_PTR: return "ptr";
2115 case BTF_KIND_ARRAY: return "array";
2116 case BTF_KIND_STRUCT: return "struct";
2117 case BTF_KIND_UNION: return "union";
2118 case BTF_KIND_ENUM: return "enum";
2119 case BTF_KIND_FWD: return "fwd";
2120 case BTF_KIND_TYPEDEF: return "typedef";
2121 case BTF_KIND_VOLATILE: return "volatile";
2122 case BTF_KIND_CONST: return "const";
2123 case BTF_KIND_RESTRICT: return "restrict";
2124 case BTF_KIND_FUNC: return "func";
2125 case BTF_KIND_FUNC_PROTO: return "func_proto";
2126 case BTF_KIND_VAR: return "var";
2127 case BTF_KIND_DATASEC: return "datasec";
22541a9e 2128 case BTF_KIND_FLOAT: return "float";
223f903e 2129 case BTF_KIND_DECL_TAG: return "decl_tag";
2dc1e488 2130 case BTF_KIND_TYPE_TAG: return "type_tag";
81ba0889
AN
2131 default: return "unknown";
2132 }
2133}
2134
42869d28 2135const char *btf_kind_str(const struct btf_type *t)
774e132e
MKL
2136{
2137 return __btf_kind_str(btf_kind(t));
2138}
2139
ef99b02b
AN
2140/*
2141 * Fetch integer attribute of BTF map definition. Such attributes are
2142 * represented using a pointer to an array, in which dimensionality of array
2143 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2144 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2145 * type definition, while using only sizeof(void *) space in ELF data section.
2146 */
2147static bool get_map_field_int(const char *map_name, const struct btf *btf,
8983b731
AN
2148 const struct btf_member *m, __u32 *res)
2149{
ddc7c304 2150 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
abd29c93 2151 const char *name = btf__name_by_offset(btf, m->name_off);
ef99b02b
AN
2152 const struct btf_array *arr_info;
2153 const struct btf_type *arr_t;
abd29c93 2154
b03bc685 2155 if (!btf_is_ptr(t)) {
81ba0889
AN
2156 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2157 map_name, name, btf_kind_str(t));
abd29c93
AN
2158 return false;
2159 }
ef99b02b
AN
2160
2161 arr_t = btf__type_by_id(btf, t->type);
2162 if (!arr_t) {
be18010e
KW
2163 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2164 map_name, name, t->type);
abd29c93
AN
2165 return false;
2166 }
b03bc685 2167 if (!btf_is_array(arr_t)) {
81ba0889
AN
2168 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2169 map_name, name, btf_kind_str(arr_t));
abd29c93
AN
2170 return false;
2171 }
b03bc685 2172 arr_info = btf_array(arr_t);
ef99b02b 2173 *res = arr_info->nelems;
abd29c93
AN
2174 return true;
2175}
2176
57a00f41
THJ
2177static int build_map_pin_path(struct bpf_map *map, const char *path)
2178{
2179 char buf[PATH_MAX];
6e9cab2e 2180 int len;
57a00f41
THJ
2181
2182 if (!path)
2183 path = "/sys/fs/bpf";
2184
2185 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2186 if (len < 0)
2187 return -EINVAL;
2188 else if (len >= PATH_MAX)
2189 return -ENAMETOOLONG;
2190
6e9cab2e 2191 return bpf_map__set_pin_path(map, buf);
57a00f41
THJ
2192}
2193
c7ef5ec9
AN
2194int parse_btf_map_def(const char *map_name, struct btf *btf,
2195 const struct btf_type *def_t, bool strict,
2196 struct btf_map_def *map_def, struct btf_map_def *inner_def)
abd29c93 2197{
41017e56 2198 const struct btf_type *t;
abd29c93 2199 const struct btf_member *m;
c7ef5ec9 2200 bool is_inner = inner_def == NULL;
abd29c93
AN
2201 int vlen, i;
2202
c7ef5ec9
AN
2203 vlen = btf_vlen(def_t);
2204 m = btf_members(def_t);
abd29c93 2205 for (i = 0; i < vlen; i++, m++) {
c7ef5ec9 2206 const char *name = btf__name_by_offset(btf, m->name_off);
abd29c93
AN
2207
2208 if (!name) {
c7ef5ec9 2209 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
abd29c93
AN
2210 return -EINVAL;
2211 }
2212 if (strcmp(name, "type") == 0) {
c7ef5ec9 2213 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
abd29c93 2214 return -EINVAL;
c7ef5ec9 2215 map_def->parts |= MAP_DEF_MAP_TYPE;
abd29c93 2216 } else if (strcmp(name, "max_entries") == 0) {
c7ef5ec9 2217 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
abd29c93 2218 return -EINVAL;
c7ef5ec9 2219 map_def->parts |= MAP_DEF_MAX_ENTRIES;
abd29c93 2220 } else if (strcmp(name, "map_flags") == 0) {
c7ef5ec9 2221 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
abd29c93 2222 return -EINVAL;
c7ef5ec9 2223 map_def->parts |= MAP_DEF_MAP_FLAGS;
1bdb6c9a 2224 } else if (strcmp(name, "numa_node") == 0) {
c7ef5ec9 2225 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
1bdb6c9a 2226 return -EINVAL;
c7ef5ec9 2227 map_def->parts |= MAP_DEF_NUMA_NODE;
abd29c93
AN
2228 } else if (strcmp(name, "key_size") == 0) {
2229 __u32 sz;
2230
c7ef5ec9 2231 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2232 return -EINVAL;
c7ef5ec9 2233 if (map_def->key_size && map_def->key_size != sz) {
be18010e 2234 pr_warn("map '%s': conflicting key size %u != %u.\n",
c7ef5ec9 2235 map_name, map_def->key_size, sz);
abd29c93
AN
2236 return -EINVAL;
2237 }
c7ef5ec9
AN
2238 map_def->key_size = sz;
2239 map_def->parts |= MAP_DEF_KEY_SIZE;
abd29c93
AN
2240 } else if (strcmp(name, "key") == 0) {
2241 __s64 sz;
2242
c7ef5ec9 2243 t = btf__type_by_id(btf, m->type);
abd29c93 2244 if (!t) {
be18010e 2245 pr_warn("map '%s': key type [%d] not found.\n",
c7ef5ec9 2246 map_name, m->type);
abd29c93
AN
2247 return -EINVAL;
2248 }
b03bc685 2249 if (!btf_is_ptr(t)) {
81ba0889 2250 pr_warn("map '%s': key spec is not PTR: %s.\n",
c7ef5ec9 2251 map_name, btf_kind_str(t));
abd29c93
AN
2252 return -EINVAL;
2253 }
c7ef5ec9 2254 sz = btf__resolve_size(btf, t->type);
abd29c93 2255 if (sz < 0) {
679152d3 2256 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
c7ef5ec9 2257 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2258 return sz;
2259 }
c7ef5ec9 2260 if (map_def->key_size && map_def->key_size != sz) {
679152d3 2261 pr_warn("map '%s': conflicting key size %u != %zd.\n",
c7ef5ec9 2262 map_name, map_def->key_size, (ssize_t)sz);
abd29c93
AN
2263 return -EINVAL;
2264 }
c7ef5ec9
AN
2265 map_def->key_size = sz;
2266 map_def->key_type_id = t->type;
2267 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
abd29c93
AN
2268 } else if (strcmp(name, "value_size") == 0) {
2269 __u32 sz;
2270
c7ef5ec9 2271 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2272 return -EINVAL;
c7ef5ec9 2273 if (map_def->value_size && map_def->value_size != sz) {
be18010e 2274 pr_warn("map '%s': conflicting value size %u != %u.\n",
c7ef5ec9 2275 map_name, map_def->value_size, sz);
abd29c93
AN
2276 return -EINVAL;
2277 }
c7ef5ec9
AN
2278 map_def->value_size = sz;
2279 map_def->parts |= MAP_DEF_VALUE_SIZE;
abd29c93
AN
2280 } else if (strcmp(name, "value") == 0) {
2281 __s64 sz;
2282
c7ef5ec9 2283 t = btf__type_by_id(btf, m->type);
abd29c93 2284 if (!t) {
be18010e 2285 pr_warn("map '%s': value type [%d] not found.\n",
c7ef5ec9 2286 map_name, m->type);
abd29c93
AN
2287 return -EINVAL;
2288 }
b03bc685 2289 if (!btf_is_ptr(t)) {
81ba0889 2290 pr_warn("map '%s': value spec is not PTR: %s.\n",
c7ef5ec9 2291 map_name, btf_kind_str(t));
abd29c93
AN
2292 return -EINVAL;
2293 }
c7ef5ec9 2294 sz = btf__resolve_size(btf, t->type);
abd29c93 2295 if (sz < 0) {
679152d3 2296 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
c7ef5ec9 2297 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2298 return sz;
2299 }
c7ef5ec9 2300 if (map_def->value_size && map_def->value_size != sz) {
679152d3 2301 pr_warn("map '%s': conflicting value size %u != %zd.\n",
c7ef5ec9 2302 map_name, map_def->value_size, (ssize_t)sz);
abd29c93
AN
2303 return -EINVAL;
2304 }
c7ef5ec9
AN
2305 map_def->value_size = sz;
2306 map_def->value_type_id = t->type;
2307 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
646f02ff
AN
2308 }
2309 else if (strcmp(name, "values") == 0) {
341ac5ff
HC
2310 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2311 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2312 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
c7ef5ec9 2313 char inner_map_name[128];
646f02ff
AN
2314 int err;
2315
2316 if (is_inner) {
2317 pr_warn("map '%s': multi-level inner maps not supported.\n",
c7ef5ec9 2318 map_name);
646f02ff
AN
2319 return -ENOTSUP;
2320 }
2321 if (i != vlen - 1) {
2322 pr_warn("map '%s': '%s' member should be last.\n",
c7ef5ec9 2323 map_name, name);
646f02ff
AN
2324 return -EINVAL;
2325 }
341ac5ff
HC
2326 if (!is_map_in_map && !is_prog_array) {
2327 pr_warn("map '%s': should be map-in-map or prog-array.\n",
c7ef5ec9 2328 map_name);
646f02ff
AN
2329 return -ENOTSUP;
2330 }
c7ef5ec9 2331 if (map_def->value_size && map_def->value_size != 4) {
646f02ff 2332 pr_warn("map '%s': conflicting value size %u != 4.\n",
c7ef5ec9 2333 map_name, map_def->value_size);
646f02ff
AN
2334 return -EINVAL;
2335 }
c7ef5ec9
AN
2336 map_def->value_size = 4;
2337 t = btf__type_by_id(btf, m->type);
646f02ff 2338 if (!t) {
341ac5ff
HC
2339 pr_warn("map '%s': %s type [%d] not found.\n",
2340 map_name, desc, m->type);
646f02ff
AN
2341 return -EINVAL;
2342 }
2343 if (!btf_is_array(t) || btf_array(t)->nelems) {
341ac5ff
HC
2344 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2345 map_name, desc);
646f02ff
AN
2346 return -EINVAL;
2347 }
c7ef5ec9 2348 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
646f02ff 2349 if (!btf_is_ptr(t)) {
341ac5ff
HC
2350 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2351 map_name, desc, btf_kind_str(t));
646f02ff
AN
2352 return -EINVAL;
2353 }
c7ef5ec9 2354 t = skip_mods_and_typedefs(btf, t->type, NULL);
341ac5ff
HC
2355 if (is_prog_array) {
2356 if (!btf_is_func_proto(t)) {
2357 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2358 map_name, btf_kind_str(t));
2359 return -EINVAL;
2360 }
2361 continue;
2362 }
646f02ff 2363 if (!btf_is_struct(t)) {
81ba0889 2364 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
c7ef5ec9 2365 map_name, btf_kind_str(t));
646f02ff
AN
2366 return -EINVAL;
2367 }
2368
c7ef5ec9
AN
2369 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2370 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
646f02ff
AN
2371 if (err)
2372 return err;
c7ef5ec9
AN
2373
2374 map_def->parts |= MAP_DEF_INNER_MAP;
57a00f41
THJ
2375 } else if (strcmp(name, "pinning") == 0) {
2376 __u32 val;
57a00f41 2377
646f02ff 2378 if (is_inner) {
c7ef5ec9 2379 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
646f02ff
AN
2380 return -EINVAL;
2381 }
c7ef5ec9 2382 if (!get_map_field_int(map_name, btf, m, &val))
57a00f41 2383 return -EINVAL;
c7ef5ec9 2384 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
57a00f41 2385 pr_warn("map '%s': invalid pinning value %u.\n",
c7ef5ec9 2386 map_name, val);
57a00f41
THJ
2387 return -EINVAL;
2388 }
c7ef5ec9
AN
2389 map_def->pinning = val;
2390 map_def->parts |= MAP_DEF_PINNING;
47512102
JK
2391 } else if (strcmp(name, "map_extra") == 0) {
2392 __u32 map_extra;
2393
2394 if (!get_map_field_int(map_name, btf, m, &map_extra))
2395 return -EINVAL;
2396 map_def->map_extra = map_extra;
2397 map_def->parts |= MAP_DEF_MAP_EXTRA;
abd29c93
AN
2398 } else {
2399 if (strict) {
c7ef5ec9 2400 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
abd29c93
AN
2401 return -ENOTSUP;
2402 }
c7ef5ec9 2403 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
abd29c93
AN
2404 }
2405 }
2406
c7ef5ec9
AN
2407 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2408 pr_warn("map '%s': map type isn't specified.\n", map_name);
abd29c93
AN
2409 return -EINVAL;
2410 }
2411
2412 return 0;
2413}
2414
c7ef5ec9
AN
2415static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2416{
2417 map->def.type = def->map_type;
2418 map->def.key_size = def->key_size;
2419 map->def.value_size = def->value_size;
2420 map->def.max_entries = def->max_entries;
2421 map->def.map_flags = def->map_flags;
47512102 2422 map->map_extra = def->map_extra;
c7ef5ec9
AN
2423
2424 map->numa_node = def->numa_node;
2425 map->btf_key_type_id = def->key_type_id;
2426 map->btf_value_type_id = def->value_type_id;
2427
2428 if (def->parts & MAP_DEF_MAP_TYPE)
2429 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2430
2431 if (def->parts & MAP_DEF_KEY_TYPE)
2432 pr_debug("map '%s': found key [%u], sz = %u.\n",
2433 map->name, def->key_type_id, def->key_size);
2434 else if (def->parts & MAP_DEF_KEY_SIZE)
2435 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2436
2437 if (def->parts & MAP_DEF_VALUE_TYPE)
2438 pr_debug("map '%s': found value [%u], sz = %u.\n",
2439 map->name, def->value_type_id, def->value_size);
2440 else if (def->parts & MAP_DEF_VALUE_SIZE)
2441 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2442
2443 if (def->parts & MAP_DEF_MAX_ENTRIES)
2444 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2445 if (def->parts & MAP_DEF_MAP_FLAGS)
47512102
JK
2446 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2447 if (def->parts & MAP_DEF_MAP_EXTRA)
2448 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2449 (unsigned long long)def->map_extra);
c7ef5ec9
AN
2450 if (def->parts & MAP_DEF_PINNING)
2451 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2452 if (def->parts & MAP_DEF_NUMA_NODE)
2453 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2454
2455 if (def->parts & MAP_DEF_INNER_MAP)
2456 pr_debug("map '%s': found inner map definition.\n", map->name);
2457}
2458
c1cccec9
AN
2459static const char *btf_var_linkage_str(__u32 linkage)
2460{
2461 switch (linkage) {
2462 case BTF_VAR_STATIC: return "static";
2463 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2464 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2465 default: return "unknown";
2466 }
2467}
2468
41017e56
AN
2469static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2470 const struct btf_type *sec,
2471 int var_idx, int sec_idx,
2472 const Elf_Data *data, bool strict,
2473 const char *pin_root_path)
2474{
c7ef5ec9 2475 struct btf_map_def map_def = {}, inner_def = {};
41017e56
AN
2476 const struct btf_type *var, *def;
2477 const struct btf_var_secinfo *vi;
2478 const struct btf_var *var_extra;
2479 const char *map_name;
2480 struct bpf_map *map;
c7ef5ec9 2481 int err;
41017e56
AN
2482
2483 vi = btf_var_secinfos(sec) + var_idx;
2484 var = btf__type_by_id(obj->btf, vi->type);
2485 var_extra = btf_var(var);
2486 map_name = btf__name_by_offset(obj->btf, var->name_off);
2487
2488 if (map_name == NULL || map_name[0] == '\0') {
2489 pr_warn("map #%d: empty name.\n", var_idx);
2490 return -EINVAL;
2491 }
2492 if ((__u64)vi->offset + vi->size > data->d_size) {
2493 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2494 return -EINVAL;
2495 }
2496 if (!btf_is_var(var)) {
81ba0889
AN
2497 pr_warn("map '%s': unexpected var kind %s.\n",
2498 map_name, btf_kind_str(var));
41017e56
AN
2499 return -EINVAL;
2500 }
c1cccec9
AN
2501 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2502 pr_warn("map '%s': unsupported map linkage %s.\n",
2503 map_name, btf_var_linkage_str(var_extra->linkage));
41017e56
AN
2504 return -EOPNOTSUPP;
2505 }
2506
2507 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2508 if (!btf_is_struct(def)) {
81ba0889
AN
2509 pr_warn("map '%s': unexpected def kind %s.\n",
2510 map_name, btf_kind_str(var));
41017e56
AN
2511 return -EINVAL;
2512 }
2513 if (def->size > vi->size) {
2514 pr_warn("map '%s': invalid def size.\n", map_name);
2515 return -EINVAL;
2516 }
2517
2518 map = bpf_object__add_map(obj);
2519 if (IS_ERR(map))
2520 return PTR_ERR(map);
2521 map->name = strdup(map_name);
2522 if (!map->name) {
2523 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2524 return -ENOMEM;
2525 }
2526 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2527 map->def.type = BPF_MAP_TYPE_UNSPEC;
2528 map->sec_idx = sec_idx;
2529 map->sec_offset = vi->offset;
646f02ff 2530 map->btf_var_idx = var_idx;
41017e56
AN
2531 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2532 map_name, map->sec_idx, map->sec_offset);
2533
c7ef5ec9
AN
2534 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2535 if (err)
2536 return err;
2537
2538 fill_map_from_def(map, &map_def);
2539
2540 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2541 err = build_map_pin_path(map, pin_root_path);
2542 if (err) {
2543 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2544 return err;
2545 }
2546 }
2547
2548 if (map_def.parts & MAP_DEF_INNER_MAP) {
2549 map->inner_map = calloc(1, sizeof(*map->inner_map));
2550 if (!map->inner_map)
2551 return -ENOMEM;
2552 map->inner_map->fd = -1;
2553 map->inner_map->sec_idx = sec_idx;
2554 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2555 if (!map->inner_map->name)
2556 return -ENOMEM;
2557 sprintf(map->inner_map->name, "%s.inner", map_name);
2558
2559 fill_map_from_def(map->inner_map, &inner_def);
2560 }
2561
262cfb74
DK
2562 err = bpf_map_find_btf_info(obj, map);
2563 if (err)
2564 return err;
2565
c7ef5ec9 2566 return 0;
41017e56
AN
2567}
2568
57a00f41
THJ
2569static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2570 const char *pin_root_path)
abd29c93
AN
2571{
2572 const struct btf_type *sec = NULL;
2573 int nr_types, i, vlen, err;
2574 const struct btf_type *t;
2575 const char *name;
2576 Elf_Data *data;
2577 Elf_Scn *scn;
2578
2579 if (obj->efile.btf_maps_shndx < 0)
2580 return 0;
2581
88a82120
AN
2582 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2583 data = elf_sec_data(obj, scn);
abd29c93 2584 if (!scn || !data) {
88a82120
AN
2585 pr_warn("elf: failed to get %s map definitions for %s\n",
2586 MAPS_ELF_SEC, obj->path);
abd29c93
AN
2587 return -EINVAL;
2588 }
2589
6a886de0
HC
2590 nr_types = btf__type_cnt(obj->btf);
2591 for (i = 1; i < nr_types; i++) {
abd29c93 2592 t = btf__type_by_id(obj->btf, i);
b03bc685 2593 if (!btf_is_datasec(t))
abd29c93
AN
2594 continue;
2595 name = btf__name_by_offset(obj->btf, t->name_off);
2596 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2597 sec = t;
646f02ff 2598 obj->efile.btf_maps_sec_btf_id = i;
abd29c93
AN
2599 break;
2600 }
2601 }
2602
2603 if (!sec) {
be18010e 2604 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
abd29c93
AN
2605 return -ENOENT;
2606 }
2607
b03bc685 2608 vlen = btf_vlen(sec);
abd29c93
AN
2609 for (i = 0; i < vlen; i++) {
2610 err = bpf_object__init_user_btf_map(obj, sec, i,
2611 obj->efile.btf_maps_shndx,
8983b731
AN
2612 data, strict,
2613 pin_root_path);
abd29c93
AN
2614 if (err)
2615 return err;
2616 }
2617
2618 return 0;
2619}
2620
0d13bfce 2621static int bpf_object__init_maps(struct bpf_object *obj,
01af3bf0 2622 const struct bpf_object_open_opts *opts)
bf829271 2623{
166750bc
AN
2624 const char *pin_root_path;
2625 bool strict;
bf829271 2626 int err;
8837fe5d 2627
166750bc
AN
2628 strict = !OPTS_GET(opts, relaxed_maps, false);
2629 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
bf829271 2630
166750bc
AN
2631 err = bpf_object__init_user_maps(obj, strict);
2632 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2633 err = err ?: bpf_object__init_global_data_maps(obj);
81bfdd08 2634 err = err ?: bpf_object__init_kconfig_map(obj);
590a0088 2635 err = err ?: bpf_object__init_struct_ops_maps(obj);
bf829271 2636
3b3af91c 2637 return err;
561bbcca
WN
2638}
2639
e3d91b0c
JDB
2640static bool section_have_execinstr(struct bpf_object *obj, int idx)
2641{
ad23b723 2642 Elf64_Shdr *sh;
e3d91b0c 2643
ad23b723
AN
2644 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2645 if (!sh)
e3d91b0c
JDB
2646 return false;
2647
ad23b723 2648 return sh->sh_flags & SHF_EXECINSTR;
e3d91b0c
JDB
2649}
2650
0f0e55d8
AN
2651static bool btf_needs_sanitization(struct bpf_object *obj)
2652{
9ca1f56a
AS
2653 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2654 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2655 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2656 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2657 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2658 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
0f0e55d8 2659
2dc1e488
YS
2660 return !has_func || !has_datasec || !has_func_global || !has_float ||
2661 !has_decl_tag || !has_type_tag;
0f0e55d8
AN
2662}
2663
2664static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
d7c4b398 2665{
9ca1f56a
AS
2666 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2667 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2668 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2669 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2670 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2671 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
d7c4b398
AN
2672 struct btf_type *t;
2673 int i, j, vlen;
d7c4b398 2674
6a886de0 2675 for (i = 1; i < btf__type_cnt(btf); i++) {
d7c4b398 2676 t = (struct btf_type *)btf__type_by_id(btf, i);
d7c4b398 2677
223f903e
YS
2678 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2679 /* replace VAR/DECL_TAG with INT */
d7c4b398 2680 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1d4126c4
AN
2681 /*
2682 * using size = 1 is the safest choice, 4 will be too
2683 * big and cause kernel BTF validation failure if
2684 * original variable took less than 4 bytes
2685 */
2686 t->size = 1;
708852dc 2687 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
b03bc685 2688 } else if (!has_datasec && btf_is_datasec(t)) {
d7c4b398 2689 /* replace DATASEC with STRUCT */
b03bc685
AN
2690 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2691 struct btf_member *m = btf_members(t);
d7c4b398
AN
2692 struct btf_type *vt;
2693 char *name;
2694
2695 name = (char *)btf__name_by_offset(btf, t->name_off);
2696 while (*name) {
2697 if (*name == '.')
2698 *name = '_';
2699 name++;
2700 }
2701
b03bc685 2702 vlen = btf_vlen(t);
d7c4b398
AN
2703 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2704 for (j = 0; j < vlen; j++, v++, m++) {
2705 /* order of field assignments is important */
2706 m->offset = v->offset * 8;
2707 m->type = v->type;
2708 /* preserve variable name as member name */
2709 vt = (void *)btf__type_by_id(btf, v->type);
2710 m->name_off = vt->name_off;
2711 }
b03bc685 2712 } else if (!has_func && btf_is_func_proto(t)) {
d7c4b398 2713 /* replace FUNC_PROTO with ENUM */
b03bc685 2714 vlen = btf_vlen(t);
d7c4b398
AN
2715 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2716 t->size = sizeof(__u32); /* kernel enforced */
b03bc685 2717 } else if (!has_func && btf_is_func(t)) {
d7c4b398
AN
2718 /* replace FUNC with TYPEDEF */
2719 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2d3eb67f
AS
2720 } else if (!has_func_global && btf_is_func(t)) {
2721 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2722 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
22541a9e
IL
2723 } else if (!has_float && btf_is_float(t)) {
2724 /* replace FLOAT with an equally-sized empty STRUCT;
2725 * since C compilers do not accept e.g. "float" as a
2726 * valid struct name, make it anonymous
2727 */
2728 t->name_off = 0;
2729 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2dc1e488
YS
2730 } else if (!has_type_tag && btf_is_type_tag(t)) {
2731 /* replace TYPE_TAG with a CONST */
2732 t->name_off = 0;
2733 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
d7c4b398
AN
2734 }
2735 }
2736}
2737
b35f14f4 2738static bool libbpf_needs_btf(const struct bpf_object *obj)
abd29c93 2739{
b35f14f4
AN
2740 return obj->efile.btf_maps_shndx >= 0 ||
2741 obj->efile.st_ops_shndx >= 0 ||
2742 obj->nr_extern > 0;
2743}
2744
2745static bool kernel_needs_btf(const struct bpf_object *obj)
2746{
2747 return obj->efile.st_ops_shndx >= 0;
abd29c93
AN
2748}
2749
063183bf 2750static int bpf_object__init_btf(struct bpf_object *obj,
9c6660d0
AN
2751 Elf_Data *btf_data,
2752 Elf_Data *btf_ext_data)
2753{
b7d7f3e1 2754 int err = -ENOENT;
9c6660d0
AN
2755
2756 if (btf_data) {
2757 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
e9fc3ce9
AN
2758 err = libbpf_get_error(obj->btf);
2759 if (err) {
b7d7f3e1 2760 obj->btf = NULL;
e9fc3ce9 2761 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
9c6660d0
AN
2762 goto out;
2763 }
4c01925f
AN
2764 /* enforce 8-byte pointers for BPF-targeted BTFs */
2765 btf__set_pointer_size(obj->btf, 8);
9c6660d0
AN
2766 }
2767 if (btf_ext_data) {
11d5daa8
AN
2768 struct btf_ext_info *ext_segs[3];
2769 int seg_num, sec_num;
2770
9c6660d0
AN
2771 if (!obj->btf) {
2772 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2773 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2774 goto out;
2775 }
e9fc3ce9
AN
2776 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2777 err = libbpf_get_error(obj->btf_ext);
2778 if (err) {
2779 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2780 BTF_EXT_ELF_SEC, err);
9c6660d0
AN
2781 obj->btf_ext = NULL;
2782 goto out;
2783 }
11d5daa8
AN
2784
2785 /* setup .BTF.ext to ELF section mapping */
2786 ext_segs[0] = &obj->btf_ext->func_info;
2787 ext_segs[1] = &obj->btf_ext->line_info;
2788 ext_segs[2] = &obj->btf_ext->core_relo_info;
2789 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2790 struct btf_ext_info *seg = ext_segs[seg_num];
2791 const struct btf_ext_info_sec *sec;
2792 const char *sec_name;
2793 Elf_Scn *scn;
2794
2795 if (seg->sec_cnt == 0)
2796 continue;
2797
2798 seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2799 if (!seg->sec_idxs) {
2800 err = -ENOMEM;
2801 goto out;
2802 }
2803
2804 sec_num = 0;
2805 for_each_btf_ext_sec(seg, sec) {
2806 /* preventively increment index to avoid doing
2807 * this before every continue below
2808 */
2809 sec_num++;
2810
2811 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2812 if (str_is_empty(sec_name))
2813 continue;
2814 scn = elf_sec_by_name(obj, sec_name);
2815 if (!scn)
2816 continue;
2817
2818 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2819 }
2820 }
9c6660d0
AN
2821 }
2822out:
b35f14f4 2823 if (err && libbpf_needs_btf(obj)) {
be18010e 2824 pr_warn("BTF is required, but is missing or corrupted.\n");
b7d7f3e1 2825 return err;
abd29c93 2826 }
9c6660d0
AN
2827 return 0;
2828}
2829
b96c07f3
AN
2830static int compare_vsi_off(const void *_a, const void *_b)
2831{
2832 const struct btf_var_secinfo *a = _a;
2833 const struct btf_var_secinfo *b = _b;
2834
2835 return a->offset - b->offset;
2836}
2837
2838static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2839 struct btf_type *t)
2840{
2841 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2842 const char *name = btf__name_by_offset(btf, t->name_off);
2843 const struct btf_type *t_var;
2844 struct btf_var_secinfo *vsi;
2845 const struct btf_var *var;
2846 int ret;
2847
2848 if (!name) {
2849 pr_debug("No name found in string section for DATASEC kind.\n");
2850 return -ENOENT;
2851 }
2852
2853 /* .extern datasec size and var offsets were set correctly during
2854 * extern collection step, so just skip straight to sorting variables
2855 */
2856 if (t->size)
2857 goto sort_vars;
2858
2859 ret = find_elf_sec_sz(obj, name, &size);
6966d4c4 2860 if (ret || !size) {
b96c07f3
AN
2861 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2862 return -ENOENT;
2863 }
2864
2865 t->size = size;
2866
2867 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2868 t_var = btf__type_by_id(btf, vsi->type);
88918dc1 2869 if (!t_var || !btf_is_var(t_var)) {
b96c07f3
AN
2870 pr_debug("Non-VAR type seen in section %s\n", name);
2871 return -EINVAL;
2872 }
2873
88918dc1 2874 var = btf_var(t_var);
b96c07f3
AN
2875 if (var->linkage == BTF_VAR_STATIC)
2876 continue;
2877
2878 name = btf__name_by_offset(btf, t_var->name_off);
2879 if (!name) {
2880 pr_debug("No name found in string section for VAR kind\n");
2881 return -ENOENT;
2882 }
2883
2884 ret = find_elf_var_offset(obj, name, &off);
2885 if (ret) {
2886 pr_debug("No offset found in symbol table for VAR %s\n",
2887 name);
2888 return -ENOENT;
2889 }
2890
2891 vsi->offset = off;
2892 }
2893
2894sort_vars:
2895 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2896 return 0;
2897}
2898
2899static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2900{
2901 int err = 0;
6a886de0 2902 __u32 i, n = btf__type_cnt(btf);
b96c07f3 2903
6a886de0 2904 for (i = 1; i < n; i++) {
b96c07f3
AN
2905 struct btf_type *t = btf_type_by_id(btf, i);
2906
2907 /* Loader needs to fix up some of the things compiler
2908 * couldn't get its hands on while emitting BTF. This
2909 * is section size and global variable offset. We use
2910 * the info from the ELF itself for this purpose.
2911 */
2912 if (btf_is_datasec(t)) {
2913 err = btf_fixup_datasec(obj, btf, t);
2914 if (err)
2915 break;
2916 }
2917 }
2918
2919 return libbpf_err(err);
2920}
2921
2922int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2923{
2924 return btf_finalize_data(obj, btf);
2925}
2926
166750bc
AN
2927static int bpf_object__finalize_btf(struct bpf_object *obj)
2928{
2929 int err;
2930
2931 if (!obj->btf)
2932 return 0;
2933
b96c07f3 2934 err = btf_finalize_data(obj, obj->btf);
bfc96656
AN
2935 if (err) {
2936 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2937 return err;
166750bc 2938 }
bfc96656 2939
166750bc
AN
2940 return 0;
2941}
2942
fe62de31 2943static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
a6ed02ca 2944{
1e092a03
KS
2945 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2946 prog->type == BPF_PROG_TYPE_LSM)
a6ed02ca
KS
2947 return true;
2948
2949 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2950 * also need vmlinux BTF
2951 */
2952 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2953 return true;
2954
2955 return false;
2956}
2957
fe62de31 2958static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
a6ed02ca
KS
2959{
2960 struct bpf_program *prog;
fe62de31 2961 int i;
a6ed02ca 2962
1373ff59
SC
2963 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2964 * is not specified
2965 */
2966 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
fe62de31 2967 return true;
192b6638 2968
d370bbe1
HL
2969 /* Support for typed ksyms needs kernel BTF */
2970 for (i = 0; i < obj->nr_extern; i++) {
2971 const struct extern_desc *ext;
2972
2973 ext = &obj->externs[i];
fe62de31
AN
2974 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2975 return true;
d370bbe1
HL
2976 }
2977
a6ed02ca 2978 bpf_object__for_each_program(prog, obj) {
a3820c48 2979 if (!prog->autoload)
d9297581 2980 continue;
fe62de31
AN
2981 if (prog_needs_vmlinux_btf(prog))
2982 return true;
a6ed02ca
KS
2983 }
2984
fe62de31
AN
2985 return false;
2986}
2987
2988static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2989{
2990 int err;
2991
2992 /* btf_vmlinux could be loaded earlier */
67234743 2993 if (obj->btf_vmlinux || obj->gen_loader)
fe62de31
AN
2994 return 0;
2995
2996 if (!force && !obj_needs_vmlinux_btf(obj))
192b6638
AN
2997 return 0;
2998
a710eed3 2999 obj->btf_vmlinux = btf__load_vmlinux_btf();
e9fc3ce9
AN
3000 err = libbpf_get_error(obj->btf_vmlinux);
3001 if (err) {
192b6638
AN
3002 pr_warn("Error loading vmlinux BTF: %d\n", err);
3003 obj->btf_vmlinux = NULL;
3004 return err;
3005 }
a6ed02ca
KS
3006 return 0;
3007}
3008
063183bf
AN
3009static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3010{
0f0e55d8
AN
3011 struct btf *kern_btf = obj->btf;
3012 bool btf_mandatory, sanitize;
aea28a60 3013 int i, err = 0;
063183bf
AN
3014
3015 if (!obj->btf)
3016 return 0;
3017
9ca1f56a 3018 if (!kernel_supports(obj, FEAT_BTF)) {
68b08647
AN
3019 if (kernel_needs_btf(obj)) {
3020 err = -EOPNOTSUPP;
3021 goto report;
3022 }
3023 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3024 return 0;
3025 }
3026
aea28a60
AN
3027 /* Even though some subprogs are global/weak, user might prefer more
3028 * permissive BPF verification process that BPF verifier performs for
3029 * static functions, taking into account more context from the caller
3030 * functions. In such case, they need to mark such subprogs with
3031 * __attribute__((visibility("hidden"))) and libbpf will adjust
3032 * corresponding FUNC BTF type to be marked as static and trigger more
3033 * involved BPF verification process.
3034 */
3035 for (i = 0; i < obj->nr_programs; i++) {
3036 struct bpf_program *prog = &obj->programs[i];
3037 struct btf_type *t;
3038 const char *name;
3039 int j, n;
3040
3041 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3042 continue;
3043
6a886de0
HC
3044 n = btf__type_cnt(obj->btf);
3045 for (j = 1; j < n; j++) {
aea28a60
AN
3046 t = btf_type_by_id(obj->btf, j);
3047 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3048 continue;
3049
3050 name = btf__str_by_offset(obj->btf, t->name_off);
3051 if (strcmp(name, prog->name) != 0)
3052 continue;
3053
3054 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3055 break;
3056 }
3057 }
3058
0f0e55d8
AN
3059 sanitize = btf_needs_sanitization(obj);
3060 if (sanitize) {
5c3320d7 3061 const void *raw_data;
0f0e55d8 3062 __u32 sz;
063183bf 3063
0f0e55d8 3064 /* clone BTF to sanitize a copy and leave the original intact */
6a886de0 3065 raw_data = btf__raw_data(obj->btf, &sz);
5c3320d7 3066 kern_btf = btf__new(raw_data, sz);
e9fc3ce9
AN
3067 err = libbpf_get_error(kern_btf);
3068 if (err)
3069 return err;
04efe591 3070
4c01925f
AN
3071 /* enforce 8-byte pointers for BPF-targeted BTFs */
3072 btf__set_pointer_size(obj->btf, 8);
0f0e55d8 3073 bpf_object__sanitize_btf(obj, kern_btf);
063183bf 3074 }
0f0e55d8 3075
67234743
AS
3076 if (obj->gen_loader) {
3077 __u32 raw_size = 0;
6a886de0 3078 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
67234743
AS
3079
3080 if (!raw_data)
3081 return -ENOMEM;
3082 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3083 /* Pretend to have valid FD to pass various fd >= 0 checks.
3084 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3085 */
3086 btf__set_fd(kern_btf, 0);
3087 } else {
e0e3ea88
AN
3088 /* currently BPF_BTF_LOAD only supports log_level 1 */
3089 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3090 obj->log_level ? 1 : 0);
67234743 3091 }
0f0e55d8
AN
3092 if (sanitize) {
3093 if (!err) {
3094 /* move fd to libbpf's BTF */
3095 btf__set_fd(obj->btf, btf__fd(kern_btf));
3096 btf__set_fd(kern_btf, -1);
3097 }
3098 btf__free(kern_btf);
3099 }
68b08647 3100report:
0f0e55d8
AN
3101 if (err) {
3102 btf_mandatory = kernel_needs_btf(obj);
3103 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3104 btf_mandatory ? "BTF is mandatory, can't proceed."
3105 : "BTF is optional, ignoring.");
3106 if (!btf_mandatory)
3107 err = 0;
3108 }
3109 return err;
063183bf
AN
3110}
3111
88a82120
AN
3112static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3113{
3114 const char *name;
3115
3116 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3117 if (!name) {
3118 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3119 off, obj->path, elf_errmsg(-1));
3120 return NULL;
3121 }
3122
3123 return name;
3124}
3125
3126static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3127{
3128 const char *name;
3129
3130 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3131 if (!name) {
3132 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3133 off, obj->path, elf_errmsg(-1));
3134 return NULL;
3135 }
3136
3137 return name;
3138}
3139
3140static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3141{
3142 Elf_Scn *scn;
3143
3144 scn = elf_getscn(obj->efile.elf, idx);
3145 if (!scn) {
3146 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3147 idx, obj->path, elf_errmsg(-1));
3148 return NULL;
3149 }
3150 return scn;
3151}
3152
3153static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3154{
3155 Elf_Scn *scn = NULL;
3156 Elf *elf = obj->efile.elf;
3157 const char *sec_name;
3158
3159 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3160 sec_name = elf_sec_name(obj, scn);
3161 if (!sec_name)
3162 return NULL;
3163
3164 if (strcmp(sec_name, name) != 0)
3165 continue;
3166
3167 return scn;
3168 }
3169 return NULL;
3170}
3171
ad23b723 3172static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
88a82120 3173{
ad23b723
AN
3174 Elf64_Shdr *shdr;
3175
88a82120 3176 if (!scn)
ad23b723 3177 return NULL;
88a82120 3178
ad23b723
AN
3179 shdr = elf64_getshdr(scn);
3180 if (!shdr) {
88a82120
AN
3181 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3182 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
ad23b723 3183 return NULL;
88a82120
AN
3184 }
3185
ad23b723 3186 return shdr;
88a82120
AN
3187}
3188
3189static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3190{
3191 const char *name;
ad23b723 3192 Elf64_Shdr *sh;
88a82120
AN
3193
3194 if (!scn)
3195 return NULL;
3196
ad23b723
AN
3197 sh = elf_sec_hdr(obj, scn);
3198 if (!sh)
88a82120
AN
3199 return NULL;
3200
ad23b723 3201 name = elf_sec_str(obj, sh->sh_name);
88a82120
AN
3202 if (!name) {
3203 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3204 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3205 return NULL;
3206 }
3207
3208 return name;
3209}
3210
3211static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3212{
3213 Elf_Data *data;
3214
3215 if (!scn)
3216 return NULL;
3217
3218 data = elf_getdata(scn, 0);
3219 if (!data) {
3220 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3221 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3222 obj->path, elf_errmsg(-1));
3223 return NULL;
3224 }
3225
3226 return data;
3227}
3228
ad23b723
AN
3229static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3230{
3231 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3232 return NULL;
3233
3234 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3235}
3236
3237static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3238{
3239 if (idx >= data->d_size / sizeof(Elf64_Rel))
3240 return NULL;
3241
3242 return (Elf64_Rel *)data->d_buf + idx;
3243}
3244
50e09460
AN
3245static bool is_sec_name_dwarf(const char *name)
3246{
3247 /* approximation, but the actual list is too long */
13d35a0c 3248 return str_has_pfx(name, ".debug_");
50e09460
AN
3249}
3250
ad23b723 3251static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
50e09460
AN
3252{
3253 /* no special handling of .strtab */
3254 if (hdr->sh_type == SHT_STRTAB)
3255 return true;
3256
3257 /* ignore .llvm_addrsig section as well */
faf6ed32 3258 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
50e09460
AN
3259 return true;
3260
3261 /* no subprograms will lead to an empty .text section, ignore it */
3262 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3263 strcmp(name, ".text") == 0)
3264 return true;
3265
3266 /* DWARF sections */
3267 if (is_sec_name_dwarf(name))
3268 return true;
3269
13d35a0c 3270 if (str_has_pfx(name, ".rel")) {
50e09460
AN
3271 name += sizeof(".rel") - 1;
3272 /* DWARF section relocations */
3273 if (is_sec_name_dwarf(name))
3274 return true;
3275
3276 /* .BTF and .BTF.ext don't need relocations */
3277 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3278 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3279 return true;
3280 }
3281
3282 return false;
3283}
3284
db2b8b06
AN
3285static int cmp_progs(const void *_a, const void *_b)
3286{
3287 const struct bpf_program *a = _a;
3288 const struct bpf_program *b = _b;
3289
3290 if (a->sec_idx != b->sec_idx)
3291 return a->sec_idx < b->sec_idx ? -1 : 1;
3292
3293 /* sec_insn_off can't be the same within the section */
3294 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3295}
3296
0d13bfce 3297static int bpf_object__elf_collect(struct bpf_object *obj)
29603665 3298{
25bbbd7a 3299 struct elf_sec_desc *sec_desc;
29603665 3300 Elf *elf = obj->efile.elf;
f0187f0b 3301 Elf_Data *btf_ext_data = NULL;
1713d68b 3302 Elf_Data *btf_data = NULL;
666810e8 3303 int idx = 0, err = 0;
0201c575
AN
3304 const char *name;
3305 Elf_Data *data;
3306 Elf_Scn *scn;
ad23b723 3307 Elf64_Shdr *sh;
29603665 3308
0d6988e1
AN
3309 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3310 * section. e_shnum does include sec #0, so e_shnum is the necessary
3311 * size of an array to keep all the sections.
25bbbd7a 3312 */
0d6988e1 3313 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
25bbbd7a
AN
3314 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3315 if (!obj->efile.secs)
3316 return -ENOMEM;
29603665 3317
0201c575
AN
3318 /* a bunch of ELF parsing functionality depends on processing symbols,
3319 * so do the first pass and find the symbol table
3320 */
3321 scn = NULL;
29603665 3322 while ((scn = elf_nextscn(elf, scn)) != NULL) {
ad23b723
AN
3323 sh = elf_sec_hdr(obj, scn);
3324 if (!sh)
0201c575
AN
3325 return -LIBBPF_ERRNO__FORMAT;
3326
ad23b723 3327 if (sh->sh_type == SHT_SYMTAB) {
0201c575
AN
3328 if (obj->efile.symbols) {
3329 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3330 return -LIBBPF_ERRNO__FORMAT;
3331 }
29603665 3332
0201c575
AN
3333 data = elf_sec_data(obj, scn);
3334 if (!data)
3335 return -LIBBPF_ERRNO__FORMAT;
3336
25bbbd7a
AN
3337 idx = elf_ndxscn(scn);
3338
0201c575 3339 obj->efile.symbols = data;
25bbbd7a 3340 obj->efile.symbols_shndx = idx;
ad23b723 3341 obj->efile.strtabidx = sh->sh_link;
0201c575
AN
3342 }
3343 }
3344
03e601f4
THJ
3345 if (!obj->efile.symbols) {
3346 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3347 obj->path);
3348 return -ENOENT;
3349 }
3350
0201c575
AN
3351 scn = NULL;
3352 while ((scn = elf_nextscn(elf, scn)) != NULL) {
25bbbd7a
AN
3353 idx = elf_ndxscn(scn);
3354 sec_desc = &obj->efile.secs[idx];
88a82120 3355
ad23b723
AN
3356 sh = elf_sec_hdr(obj, scn);
3357 if (!sh)
01b29d1d 3358 return -LIBBPF_ERRNO__FORMAT;
29603665 3359
ad23b723 3360 name = elf_sec_str(obj, sh->sh_name);
88a82120 3361 if (!name)
01b29d1d 3362 return -LIBBPF_ERRNO__FORMAT;
29603665 3363
ad23b723 3364 if (ignore_elf_section(sh, name))
50e09460
AN
3365 continue;
3366
88a82120
AN
3367 data = elf_sec_data(obj, scn);
3368 if (!data)
01b29d1d 3369 return -LIBBPF_ERRNO__FORMAT;
88a82120
AN
3370
3371 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
077c066a 3372 idx, name, (unsigned long)data->d_size,
ad23b723
AN
3373 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3374 (int)sh->sh_type);
cb1e5e96 3375
1713d68b 3376 if (strcmp(name, "license") == 0) {
88a82120 3377 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
01b29d1d
AN
3378 if (err)
3379 return err;
1713d68b 3380 } else if (strcmp(name, "version") == 0) {
88a82120 3381 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
54b8625c
JF
3382 if (err)
3383 return err;
1713d68b 3384 } else if (strcmp(name, "maps") == 0) {
666810e8 3385 obj->efile.maps_shndx = idx;
abd29c93
AN
3386 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3387 obj->efile.btf_maps_shndx = idx;
1713d68b 3388 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
62554d52
AN
3389 if (sh->sh_type != SHT_PROGBITS)
3390 return -LIBBPF_ERRNO__FORMAT;
1713d68b 3391 btf_data = data;
2993e051 3392 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
62554d52
AN
3393 if (sh->sh_type != SHT_PROGBITS)
3394 return -LIBBPF_ERRNO__FORMAT;
f0187f0b 3395 btf_ext_data = data;
ad23b723 3396 } else if (sh->sh_type == SHT_SYMTAB) {
0201c575 3397 /* already processed during the first pass above */
ad23b723
AN
3398 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3399 if (sh->sh_flags & SHF_EXECINSTR) {
f8c7a4d4
JS
3400 if (strcmp(name, ".text") == 0)
3401 obj->efile.text_shndx = idx;
c1122392 3402 err = bpf_object__add_programs(obj, data, name, idx);
88a82120 3403 if (err)
01b29d1d 3404 return err;
aed65917
AN
3405 } else if (strcmp(name, DATA_SEC) == 0 ||
3406 str_has_pfx(name, DATA_SEC ".")) {
25bbbd7a
AN
3407 sec_desc->sec_type = SEC_DATA;
3408 sec_desc->shdr = sh;
3409 sec_desc->data = data;
aed65917
AN
3410 } else if (strcmp(name, RODATA_SEC) == 0 ||
3411 str_has_pfx(name, RODATA_SEC ".")) {
25bbbd7a
AN
3412 sec_desc->sec_type = SEC_RODATA;
3413 sec_desc->shdr = sh;
3414 sec_desc->data = data;
590a0088
MKL
3415 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3416 obj->efile.st_ops_data = data;
3417 obj->efile.st_ops_shndx = idx;
d859900c 3418 } else {
50e09460
AN
3419 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3420 idx, name);
a5b8bd47 3421 }
ad23b723 3422 } else if (sh->sh_type == SHT_REL) {
25bbbd7a 3423 int targ_sec_idx = sh->sh_info; /* points to other section */
e3d91b0c 3424
b7332d28
AN
3425 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3426 targ_sec_idx >= obj->efile.sec_cnt)
3427 return -LIBBPF_ERRNO__FORMAT;
3428
e3d91b0c 3429 /* Only do relo for section with exec instructions */
25bbbd7a 3430 if (!section_have_execinstr(obj, targ_sec_idx) &&
646f02ff
AN
3431 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3432 strcmp(name, ".rel" MAPS_ELF_SEC)) {
50e09460 3433 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
25bbbd7a
AN
3434 idx, name, targ_sec_idx,
3435 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
e3d91b0c
JDB
3436 continue;
3437 }
b62f06e8 3438
25bbbd7a
AN
3439 sec_desc->sec_type = SEC_RELO;
3440 sec_desc->shdr = sh;
3441 sec_desc->data = data;
ad23b723 3442 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
25bbbd7a
AN
3443 sec_desc->sec_type = SEC_BSS;
3444 sec_desc->shdr = sh;
3445 sec_desc->data = data;
077c066a 3446 } else {
2e80be60 3447 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
ad23b723 3448 (size_t)sh->sh_size);
bec7d68c 3449 }
29603665 3450 }
561bbcca 3451
d3a3aa0c 3452 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
88a82120 3453 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
f102154d 3454 return -LIBBPF_ERRNO__FORMAT;
77ba9a5b 3455 }
db2b8b06
AN
3456
3457 /* sort BPF programs by section name and in-section instruction offset
3458 * for faster search */
2a6a9bf2
AN
3459 if (obj->nr_programs)
3460 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
db2b8b06 3461
0d13bfce 3462 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
29603665
WN
3463}
3464
ad23b723 3465static bool sym_is_extern(const Elf64_Sym *sym)
166750bc 3466{
ad23b723 3467 int bind = ELF64_ST_BIND(sym->st_info);
166750bc
AN
3468 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3469 return sym->st_shndx == SHN_UNDEF &&
3470 (bind == STB_GLOBAL || bind == STB_WEAK) &&
ad23b723 3471 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
166750bc
AN
3472}
3473
ad23b723 3474static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
53eddb5e 3475{
ad23b723
AN
3476 int bind = ELF64_ST_BIND(sym->st_info);
3477 int type = ELF64_ST_TYPE(sym->st_info);
53eddb5e
YS
3478
3479 /* in .text section */
3480 if (sym->st_shndx != text_shndx)
3481 return false;
3482
3483 /* local function */
3484 if (bind == STB_LOCAL && type == STT_SECTION)
3485 return true;
3486
3487 /* global function */
3488 return bind == STB_GLOBAL && type == STT_FUNC;
3489}
3490
166750bc
AN
3491static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3492{
3493 const struct btf_type *t;
5bd022ec 3494 const char *tname;
166750bc
AN
3495 int i, n;
3496
3497 if (!btf)
3498 return -ESRCH;
3499
6a886de0
HC
3500 n = btf__type_cnt(btf);
3501 for (i = 1; i < n; i++) {
166750bc
AN
3502 t = btf__type_by_id(btf, i);
3503
5bd022ec 3504 if (!btf_is_var(t) && !btf_is_func(t))
166750bc
AN
3505 continue;
3506
5bd022ec
MKL
3507 tname = btf__name_by_offset(btf, t->name_off);
3508 if (strcmp(tname, ext_name))
166750bc
AN
3509 continue;
3510
5bd022ec
MKL
3511 if (btf_is_var(t) &&
3512 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3513 return -EINVAL;
3514
3515 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
166750bc
AN
3516 return -EINVAL;
3517
3518 return i;
3519 }
3520
3521 return -ENOENT;
3522}
3523
2e33efe3
AN
3524static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3525 const struct btf_var_secinfo *vs;
3526 const struct btf_type *t;
3527 int i, j, n;
3528
3529 if (!btf)
3530 return -ESRCH;
3531
6a886de0
HC
3532 n = btf__type_cnt(btf);
3533 for (i = 1; i < n; i++) {
2e33efe3
AN
3534 t = btf__type_by_id(btf, i);
3535
3536 if (!btf_is_datasec(t))
3537 continue;
3538
3539 vs = btf_var_secinfos(t);
3540 for (j = 0; j < btf_vlen(t); j++, vs++) {
3541 if (vs->type == ext_btf_id)
3542 return i;
3543 }
3544 }
3545
3546 return -ENOENT;
3547}
3548
3549static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3550 bool *is_signed)
166750bc
AN
3551{
3552 const struct btf_type *t;
3553 const char *name;
3554
3555 t = skip_mods_and_typedefs(btf, id, NULL);
3556 name = btf__name_by_offset(btf, t->name_off);
3557
3558 if (is_signed)
3559 *is_signed = false;
3560 switch (btf_kind(t)) {
3561 case BTF_KIND_INT: {
3562 int enc = btf_int_encoding(t);
3563
3564 if (enc & BTF_INT_BOOL)
2e33efe3 3565 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
166750bc
AN
3566 if (is_signed)
3567 *is_signed = enc & BTF_INT_SIGNED;
3568 if (t->size == 1)
2e33efe3 3569 return KCFG_CHAR;
166750bc 3570 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2e33efe3
AN
3571 return KCFG_UNKNOWN;
3572 return KCFG_INT;
166750bc
AN
3573 }
3574 case BTF_KIND_ENUM:
3575 if (t->size != 4)
2e33efe3 3576 return KCFG_UNKNOWN;
166750bc 3577 if (strcmp(name, "libbpf_tristate"))
2e33efe3
AN
3578 return KCFG_UNKNOWN;
3579 return KCFG_TRISTATE;
166750bc
AN
3580 case BTF_KIND_ARRAY:
3581 if (btf_array(t)->nelems == 0)
2e33efe3
AN
3582 return KCFG_UNKNOWN;
3583 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3584 return KCFG_UNKNOWN;
3585 return KCFG_CHAR_ARR;
166750bc 3586 default:
2e33efe3 3587 return KCFG_UNKNOWN;
166750bc
AN
3588 }
3589}
3590
3591static int cmp_externs(const void *_a, const void *_b)
3592{
3593 const struct extern_desc *a = _a;
3594 const struct extern_desc *b = _b;
3595
2e33efe3
AN
3596 if (a->type != b->type)
3597 return a->type < b->type ? -1 : 1;
3598
3599 if (a->type == EXT_KCFG) {
3600 /* descending order by alignment requirements */
3601 if (a->kcfg.align != b->kcfg.align)
3602 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3603 /* ascending order by size, within same alignment class */
3604 if (a->kcfg.sz != b->kcfg.sz)
3605 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3606 }
3607
166750bc
AN
3608 /* resolve ties by name */
3609 return strcmp(a->name, b->name);
3610}
3611
1c0c7074
AN
3612static int find_int_btf_id(const struct btf *btf)
3613{
3614 const struct btf_type *t;
3615 int i, n;
3616
6a886de0
HC
3617 n = btf__type_cnt(btf);
3618 for (i = 1; i < n; i++) {
1c0c7074
AN
3619 t = btf__type_by_id(btf, i);
3620
3621 if (btf_is_int(t) && btf_int_bits(t) == 32)
3622 return i;
3623 }
3624
3625 return 0;
3626}
3627
5bd022ec
MKL
3628static int add_dummy_ksym_var(struct btf *btf)
3629{
3630 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3631 const struct btf_var_secinfo *vs;
3632 const struct btf_type *sec;
3633
9683e577
IR
3634 if (!btf)
3635 return 0;
3636
5bd022ec
MKL
3637 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3638 BTF_KIND_DATASEC);
3639 if (sec_btf_id < 0)
3640 return 0;
3641
3642 sec = btf__type_by_id(btf, sec_btf_id);
3643 vs = btf_var_secinfos(sec);
3644 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3645 const struct btf_type *vt;
3646
3647 vt = btf__type_by_id(btf, vs->type);
3648 if (btf_is_func(vt))
3649 break;
3650 }
3651
3652 /* No func in ksyms sec. No need to add dummy var. */
3653 if (i == btf_vlen(sec))
3654 return 0;
3655
3656 int_btf_id = find_int_btf_id(btf);
3657 dummy_var_btf_id = btf__add_var(btf,
3658 "dummy_ksym",
3659 BTF_VAR_GLOBAL_ALLOCATED,
3660 int_btf_id);
3661 if (dummy_var_btf_id < 0)
3662 pr_warn("cannot create a dummy_ksym var\n");
3663
3664 return dummy_var_btf_id;
3665}
3666
166750bc
AN
3667static int bpf_object__collect_externs(struct bpf_object *obj)
3668{
1c0c7074 3669 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
166750bc
AN
3670 const struct btf_type *t;
3671 struct extern_desc *ext;
5bd022ec 3672 int i, n, off, dummy_var_btf_id;
2e33efe3 3673 const char *ext_name, *sec_name;
166750bc 3674 Elf_Scn *scn;
ad23b723 3675 Elf64_Shdr *sh;
166750bc
AN
3676
3677 if (!obj->efile.symbols)
3678 return 0;
3679
88a82120 3680 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
ad23b723 3681 sh = elf_sec_hdr(obj, scn);
83390787 3682 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
166750bc 3683 return -LIBBPF_ERRNO__FORMAT;
166750bc 3684
5bd022ec
MKL
3685 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3686 if (dummy_var_btf_id < 0)
3687 return dummy_var_btf_id;
3688
ad23b723 3689 n = sh->sh_size / sh->sh_entsize;
166750bc 3690 pr_debug("looking for externs among %d symbols...\n", n);
88a82120 3691
166750bc 3692 for (i = 0; i < n; i++) {
ad23b723 3693 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
166750bc 3694
ad23b723 3695 if (!sym)
166750bc 3696 return -LIBBPF_ERRNO__FORMAT;
ad23b723 3697 if (!sym_is_extern(sym))
166750bc 3698 continue;
ad23b723 3699 ext_name = elf_sym_str(obj, sym->st_name);
166750bc
AN
3700 if (!ext_name || !ext_name[0])
3701 continue;
3702
3703 ext = obj->externs;
029258d7 3704 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
166750bc
AN
3705 if (!ext)
3706 return -ENOMEM;
3707 obj->externs = ext;
3708 ext = &ext[obj->nr_extern];
3709 memset(ext, 0, sizeof(*ext));
3710 obj->nr_extern++;
3711
3712 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3713 if (ext->btf_id <= 0) {
3714 pr_warn("failed to find BTF for extern '%s': %d\n",
3715 ext_name, ext->btf_id);
3716 return ext->btf_id;
3717 }
3718 t = btf__type_by_id(obj->btf, ext->btf_id);
3719 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3720 ext->sym_idx = i;
ad23b723 3721 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
2e33efe3
AN
3722
3723 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3724 if (ext->sec_btf_id <= 0) {
3725 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3726 ext_name, ext->btf_id, ext->sec_btf_id);
3727 return ext->sec_btf_id;
166750bc 3728 }
2e33efe3
AN
3729 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3730 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3731
3732 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
5bd022ec
MKL
3733 if (btf_is_func(t)) {
3734 pr_warn("extern function %s is unsupported under %s section\n",
3735 ext->name, KCONFIG_SEC);
3736 return -ENOTSUP;
3737 }
2e33efe3
AN
3738 kcfg_sec = sec;
3739 ext->type = EXT_KCFG;
3740 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3741 if (ext->kcfg.sz <= 0) {
3742 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3743 ext_name, ext->kcfg.sz);
3744 return ext->kcfg.sz;
3745 }
3746 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3747 if (ext->kcfg.align <= 0) {
3748 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3749 ext_name, ext->kcfg.align);
3750 return -EINVAL;
3751 }
3752 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3753 &ext->kcfg.is_signed);
3754 if (ext->kcfg.type == KCFG_UNKNOWN) {
3755 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3756 return -ENOTSUP;
3757 }
1c0c7074 3758 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
1c0c7074
AN
3759 ksym_sec = sec;
3760 ext->type = EXT_KSYM;
d370bbe1
HL
3761 skip_mods_and_typedefs(obj->btf, t->type,
3762 &ext->ksym.type_id);
2e33efe3
AN
3763 } else {
3764 pr_warn("unrecognized extern section '%s'\n", sec_name);
166750bc
AN
3765 return -ENOTSUP;
3766 }
3767 }
3768 pr_debug("collected %d externs total\n", obj->nr_extern);
3769
3770 if (!obj->nr_extern)
3771 return 0;
3772
2e33efe3 3773 /* sort externs by type, for kcfg ones also by (align, size, name) */
166750bc 3774 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
166750bc 3775
1c0c7074
AN
3776 /* for .ksyms section, we need to turn all externs into allocated
3777 * variables in BTF to pass kernel verification; we do this by
3778 * pretending that each extern is a 8-byte variable
3779 */
3780 if (ksym_sec) {
3781 /* find existing 4-byte integer type in BTF to use for fake
3782 * extern variables in DATASEC
3783 */
3784 int int_btf_id = find_int_btf_id(obj->btf);
5bd022ec
MKL
3785 /* For extern function, a dummy_var added earlier
3786 * will be used to replace the vs->type and
3787 * its name string will be used to refill
3788 * the missing param's name.
3789 */
3790 const struct btf_type *dummy_var;
1c0c7074 3791
5bd022ec 3792 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
1c0c7074
AN
3793 for (i = 0; i < obj->nr_extern; i++) {
3794 ext = &obj->externs[i];
3795 if (ext->type != EXT_KSYM)
3796 continue;
3797 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3798 i, ext->sym_idx, ext->name);
3799 }
3800
3801 sec = ksym_sec;
3802 n = btf_vlen(sec);
3803 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3804 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3805 struct btf_type *vt;
3806
3807 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3808 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3809 ext = find_extern_by_name(obj, ext_name);
3810 if (!ext) {
5bd022ec
MKL
3811 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3812 btf_kind_str(vt), ext_name);
1c0c7074
AN
3813 return -ESRCH;
3814 }
5bd022ec
MKL
3815 if (btf_is_func(vt)) {
3816 const struct btf_type *func_proto;
3817 struct btf_param *param;
3818 int j;
3819
3820 func_proto = btf__type_by_id(obj->btf,
3821 vt->type);
3822 param = btf_params(func_proto);
3823 /* Reuse the dummy_var string if the
3824 * func proto does not have param name.
3825 */
3826 for (j = 0; j < btf_vlen(func_proto); j++)
3827 if (param[j].type && !param[j].name_off)
3828 param[j].name_off =
3829 dummy_var->name_off;
3830 vs->type = dummy_var_btf_id;
3831 vt->info &= ~0xffff;
3832 vt->info |= BTF_FUNC_GLOBAL;
3833 } else {
3834 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3835 vt->type = int_btf_id;
3836 }
1c0c7074
AN
3837 vs->offset = off;
3838 vs->size = sizeof(int);
3839 }
3840 sec->size = off;
3841 }
3842
2e33efe3
AN
3843 if (kcfg_sec) {
3844 sec = kcfg_sec;
3845 /* for kcfg externs calculate their offsets within a .kconfig map */
3846 off = 0;
3847 for (i = 0; i < obj->nr_extern; i++) {
3848 ext = &obj->externs[i];
3849 if (ext->type != EXT_KCFG)
3850 continue;
166750bc 3851
2e33efe3
AN
3852 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3853 off = ext->kcfg.data_off + ext->kcfg.sz;
1c0c7074 3854 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
2e33efe3
AN
3855 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3856 }
3857 sec->size = off;
3858 n = btf_vlen(sec);
3859 for (i = 0; i < n; i++) {
3860 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3861
3862 t = btf__type_by_id(obj->btf, vs->type);
3863 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3864 ext = find_extern_by_name(obj, ext_name);
3865 if (!ext) {
3866 pr_warn("failed to find extern definition for BTF var '%s'\n",
3867 ext_name);
3868 return -ESRCH;
3869 }
3870 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3871 vs->offset = ext->kcfg.data_off;
166750bc 3872 }
166750bc 3873 }
166750bc
AN
3874 return 0;
3875}
3876
6d4b198b 3877struct bpf_program *
a324aae3
AN
3878bpf_object__find_program_by_title(const struct bpf_object *obj,
3879 const char *title)
6d4b198b
JK
3880{
3881 struct bpf_program *pos;
3882
3883 bpf_object__for_each_program(pos, obj) {
52109584 3884 if (pos->sec_name && !strcmp(pos->sec_name, title))
6d4b198b
JK
3885 return pos;
3886 }
e9fc3ce9 3887 return errno = ENOENT, NULL;
6d4b198b
JK
3888}
3889
c3c55696
AN
3890static bool prog_is_subprog(const struct bpf_object *obj,
3891 const struct bpf_program *prog)
3892{
197afc63
AN
3893 /* For legacy reasons, libbpf supports an entry-point BPF programs
3894 * without SEC() attribute, i.e., those in the .text section. But if
3895 * there are 2 or more such programs in the .text section, they all
3896 * must be subprograms called from entry-point BPF programs in
3897 * designated SEC()'tions, otherwise there is no way to distinguish
3898 * which of those programs should be loaded vs which are a subprogram.
3899 * Similarly, if there is a function/program in .text and at least one
3900 * other BPF program with custom SEC() attribute, then we just assume
3901 * .text programs are subprograms (even if they are not called from
3902 * other programs), because libbpf never explicitly supported mixing
3903 * SEC()-designated BPF programs and .text entry-point BPF programs.
bc380eb9
DK
3904 *
3905 * In libbpf 1.0 strict mode, we always consider .text
3906 * programs to be subprograms.
197afc63 3907 */
bc380eb9
DK
3908
3909 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
3910 return prog->sec_idx == obj->efile.text_shndx;
3911
197afc63 3912 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
c3c55696
AN
3913}
3914
01af3bf0
AN
3915struct bpf_program *
3916bpf_object__find_program_by_name(const struct bpf_object *obj,
3917 const char *name)
3918{
3919 struct bpf_program *prog;
3920
3921 bpf_object__for_each_program(prog, obj) {
c3c55696
AN
3922 if (prog_is_subprog(obj, prog))
3923 continue;
01af3bf0
AN
3924 if (!strcmp(prog->name, name))
3925 return prog;
3926 }
e9fc3ce9 3927 return errno = ENOENT, NULL;
01af3bf0
AN
3928}
3929
d859900c
DB
3930static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3931 int shndx)
3932{
25bbbd7a
AN
3933 switch (obj->efile.secs[shndx].sec_type) {
3934 case SEC_BSS:
3935 case SEC_DATA:
3936 case SEC_RODATA:
3937 return true;
3938 default:
3939 return false;
3940 }
d859900c
DB
3941}
3942
3943static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3944 int shndx)
3945{
abd29c93
AN
3946 return shndx == obj->efile.maps_shndx ||
3947 shndx == obj->efile.btf_maps_shndx;
d859900c
DB
3948}
3949
d859900c
DB
3950static enum libbpf_map_type
3951bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3952{
25bbbd7a
AN
3953 if (shndx == obj->efile.symbols_shndx)
3954 return LIBBPF_MAP_KCONFIG;
3955
3956 switch (obj->efile.secs[shndx].sec_type) {
3957 case SEC_BSS:
d859900c 3958 return LIBBPF_MAP_BSS;
25bbbd7a
AN
3959 case SEC_DATA:
3960 return LIBBPF_MAP_DATA;
3961 case SEC_RODATA:
d859900c 3962 return LIBBPF_MAP_RODATA;
25bbbd7a 3963 default:
d859900c 3964 return LIBBPF_MAP_UNSPEC;
25bbbd7a 3965 }
d859900c
DB
3966}
3967
1f8e2bcb
AN
3968static int bpf_program__record_reloc(struct bpf_program *prog,
3969 struct reloc_desc *reloc_desc,
9c0f8cbd 3970 __u32 insn_idx, const char *sym_name,
ad23b723 3971 const Elf64_Sym *sym, const Elf64_Rel *rel)
1f8e2bcb
AN
3972{
3973 struct bpf_insn *insn = &prog->insns[insn_idx];
3974 size_t map_idx, nr_maps = prog->obj->nr_maps;
3975 struct bpf_object *obj = prog->obj;
3976 __u32 shdr_idx = sym->st_shndx;
3977 enum libbpf_map_type type;
9c0f8cbd 3978 const char *sym_sec_name;
1f8e2bcb
AN
3979 struct bpf_map *map;
3980
aa0b8d43 3981 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
9c0f8cbd
AN
3982 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3983 prog->name, sym_name, insn_idx, insn->code);
1f8e2bcb
AN
3984 return -LIBBPF_ERRNO__RELOC;
3985 }
166750bc
AN
3986
3987 if (sym_is_extern(sym)) {
ad23b723 3988 int sym_idx = ELF64_R_SYM(rel->r_info);
166750bc
AN
3989 int i, n = obj->nr_extern;
3990 struct extern_desc *ext;
3991
3992 for (i = 0; i < n; i++) {
3993 ext = &obj->externs[i];
3994 if (ext->sym_idx == sym_idx)
3995 break;
3996 }
3997 if (i >= n) {
9c0f8cbd
AN
3998 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3999 prog->name, sym_name, sym_idx);
166750bc
AN
4000 return -LIBBPF_ERRNO__RELOC;
4001 }
9c0f8cbd
AN
4002 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4003 prog->name, i, ext->name, ext->sym_idx, insn_idx);
5bd022ec
MKL
4004 if (insn->code == (BPF_JMP | BPF_CALL))
4005 reloc_desc->type = RELO_EXTERN_FUNC;
4006 else
4007 reloc_desc->type = RELO_EXTERN_VAR;
166750bc 4008 reloc_desc->insn_idx = insn_idx;
2e33efe3 4009 reloc_desc->sym_off = i; /* sym_off stores extern index */
166750bc
AN
4010 return 0;
4011 }
4012
aa0b8d43
MKL
4013 /* sub-program call relocation */
4014 if (is_call_insn(insn)) {
4015 if (insn->src_reg != BPF_PSEUDO_CALL) {
4016 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4017 return -LIBBPF_ERRNO__RELOC;
4018 }
4019 /* text_shndx can be 0, if no default "main" program exists */
4020 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4021 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4022 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4023 prog->name, sym_name, sym_sec_name);
4024 return -LIBBPF_ERRNO__RELOC;
4025 }
4026 if (sym->st_value % BPF_INSN_SZ) {
4027 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4028 prog->name, sym_name, (size_t)sym->st_value);
4029 return -LIBBPF_ERRNO__RELOC;
4030 }
4031 reloc_desc->type = RELO_CALL;
4032 reloc_desc->insn_idx = insn_idx;
4033 reloc_desc->sym_off = sym->st_value;
4034 return 0;
4035 }
4036
1f8e2bcb 4037 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
9c0f8cbd
AN
4038 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4039 prog->name, sym_name, shdr_idx);
1f8e2bcb
AN
4040 return -LIBBPF_ERRNO__RELOC;
4041 }
4042
53eddb5e
YS
4043 /* loading subprog addresses */
4044 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4045 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4046 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4047 */
4048 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4049 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4050 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4051 return -LIBBPF_ERRNO__RELOC;
4052 }
4053
4054 reloc_desc->type = RELO_SUBPROG_ADDR;
4055 reloc_desc->insn_idx = insn_idx;
4056 reloc_desc->sym_off = sym->st_value;
4057 return 0;
4058 }
4059
1f8e2bcb 4060 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
9c0f8cbd 4061 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
1f8e2bcb
AN
4062
4063 /* generic map reference relocation */
4064 if (type == LIBBPF_MAP_UNSPEC) {
4065 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
9c0f8cbd
AN
4066 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4067 prog->name, sym_name, sym_sec_name);
1f8e2bcb
AN
4068 return -LIBBPF_ERRNO__RELOC;
4069 }
4070 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4071 map = &obj->maps[map_idx];
4072 if (map->libbpf_type != type ||
4073 map->sec_idx != sym->st_shndx ||
4074 map->sec_offset != sym->st_value)
4075 continue;
9c0f8cbd
AN
4076 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4077 prog->name, map_idx, map->name, map->sec_idx,
1f8e2bcb
AN
4078 map->sec_offset, insn_idx);
4079 break;
4080 }
4081 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4082 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4083 prog->name, sym_sec_name, (size_t)sym->st_value);
1f8e2bcb
AN
4084 return -LIBBPF_ERRNO__RELOC;
4085 }
4086 reloc_desc->type = RELO_LD64;
4087 reloc_desc->insn_idx = insn_idx;
4088 reloc_desc->map_idx = map_idx;
53f8dd43 4089 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1f8e2bcb
AN
4090 return 0;
4091 }
4092
4093 /* global data map relocation */
4094 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
9c0f8cbd
AN
4095 pr_warn("prog '%s': bad data relo against section '%s'\n",
4096 prog->name, sym_sec_name);
1f8e2bcb 4097 return -LIBBPF_ERRNO__RELOC;
1f8e2bcb 4098 }
1f8e2bcb
AN
4099 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4100 map = &obj->maps[map_idx];
25bbbd7a 4101 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
1f8e2bcb 4102 continue;
9c0f8cbd
AN
4103 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4104 prog->name, map_idx, map->name, map->sec_idx,
4105 map->sec_offset, insn_idx);
1f8e2bcb
AN
4106 break;
4107 }
4108 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4109 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4110 prog->name, sym_sec_name);
1f8e2bcb
AN
4111 return -LIBBPF_ERRNO__RELOC;
4112 }
4113
4114 reloc_desc->type = RELO_DATA;
4115 reloc_desc->insn_idx = insn_idx;
4116 reloc_desc->map_idx = map_idx;
53f8dd43 4117 reloc_desc->sym_off = sym->st_value;
1f8e2bcb
AN
4118 return 0;
4119}
4120
db2b8b06
AN
4121static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4122{
4123 return insn_idx >= prog->sec_insn_off &&
4124 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4125}
4126
4127static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4128 size_t sec_idx, size_t insn_idx)
4129{
4130 int l = 0, r = obj->nr_programs - 1, m;
4131 struct bpf_program *prog;
4132
4133 while (l < r) {
4134 m = l + (r - l + 1) / 2;
4135 prog = &obj->programs[m];
4136
4137 if (prog->sec_idx < sec_idx ||
4138 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4139 l = m;
4140 else
4141 r = m - 1;
4142 }
4143 /* matching program could be at index l, but it still might be the
4144 * wrong one, so we need to double check conditions for the last time
4145 */
4146 prog = &obj->programs[l];
4147 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4148 return prog;
4149 return NULL;
4150}
4151
34090915 4152static int
ad23b723 4153bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
34090915 4154{
9c0f8cbd 4155 const char *relo_sec_name, *sec_name;
b7332d28 4156 size_t sec_idx = shdr->sh_info, sym_idx;
c3c55696
AN
4157 struct bpf_program *prog;
4158 struct reloc_desc *relos;
1f8e2bcb 4159 int err, i, nrels;
c3c55696
AN
4160 const char *sym_name;
4161 __u32 insn_idx;
6245947c
AN
4162 Elf_Scn *scn;
4163 Elf_Data *scn_data;
ad23b723
AN
4164 Elf64_Sym *sym;
4165 Elf64_Rel *rel;
34090915 4166
b7332d28
AN
4167 if (sec_idx >= obj->efile.sec_cnt)
4168 return -EINVAL;
4169
6245947c
AN
4170 scn = elf_sec_by_idx(obj, sec_idx);
4171 scn_data = elf_sec_data(obj, scn);
4172
9c0f8cbd 4173 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
6245947c 4174 sec_name = elf_sec_name(obj, scn);
9c0f8cbd
AN
4175 if (!relo_sec_name || !sec_name)
4176 return -EINVAL;
4177
4178 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4179 relo_sec_name, sec_idx, sec_name);
34090915
WN
4180 nrels = shdr->sh_size / shdr->sh_entsize;
4181
34090915 4182 for (i = 0; i < nrels; i++) {
ad23b723
AN
4183 rel = elf_rel_by_idx(data, i);
4184 if (!rel) {
9c0f8cbd 4185 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
6371ca3b 4186 return -LIBBPF_ERRNO__FORMAT;
34090915 4187 }
ad23b723 4188
b7332d28
AN
4189 sym_idx = ELF64_R_SYM(rel->r_info);
4190 sym = elf_sym_by_idx(obj, sym_idx);
ad23b723 4191 if (!sym) {
b7332d28
AN
4192 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4193 relo_sec_name, sym_idx, i);
4194 return -LIBBPF_ERRNO__FORMAT;
4195 }
4196
4197 if (sym->st_shndx >= obj->efile.sec_cnt) {
4198 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4199 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
6371ca3b 4200 return -LIBBPF_ERRNO__FORMAT;
34090915 4201 }
6245947c 4202
ad23b723 4203 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
9c0f8cbd 4204 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
b7332d28 4205 relo_sec_name, (size_t)rel->r_offset, i);
1f8e2bcb 4206 return -LIBBPF_ERRNO__FORMAT;
9c0f8cbd 4207 }
d859900c 4208
ad23b723 4209 insn_idx = rel->r_offset / BPF_INSN_SZ;
c3c55696
AN
4210 /* relocations against static functions are recorded as
4211 * relocations against the section that contains a function;
4212 * in such case, symbol will be STT_SECTION and sym.st_name
4213 * will point to empty string (0), so fetch section name
4214 * instead
4215 */
ad23b723
AN
4216 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4217 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
c3c55696 4218 else
ad23b723 4219 sym_name = elf_sym_str(obj, sym->st_name);
c3c55696 4220 sym_name = sym_name ?: "<?";
d859900c 4221
9c0f8cbd
AN
4222 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4223 relo_sec_name, i, insn_idx, sym_name);
666810e8 4224
c3c55696
AN
4225 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4226 if (!prog) {
6245947c 4227 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
c3c55696 4228 relo_sec_name, i, sec_name, insn_idx);
6245947c 4229 continue;
c3c55696
AN
4230 }
4231
4232 relos = libbpf_reallocarray(prog->reloc_desc,
4233 prog->nr_reloc + 1, sizeof(*relos));
4234 if (!relos)
4235 return -ENOMEM;
4236 prog->reloc_desc = relos;
4237
4238 /* adjust insn_idx to local BPF program frame of reference */
4239 insn_idx -= prog->sec_insn_off;
4240 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
ad23b723 4241 insn_idx, sym_name, sym, rel);
1f8e2bcb
AN
4242 if (err)
4243 return err;
c3c55696
AN
4244
4245 prog->nr_reloc++;
34090915
WN
4246 }
4247 return 0;
4248}
4249
abd29c93 4250static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
8a138aed
MKL
4251{
4252 struct bpf_map_def *def = &map->def;
d859900c 4253 __u32 key_type_id = 0, value_type_id = 0;
96408c43 4254 int ret;
8a138aed 4255
a8fee962
AN
4256 if (!obj->btf)
4257 return -ENOENT;
4258
590a0088
MKL
4259 /* if it's BTF-defined map, we don't need to search for type IDs.
4260 * For struct_ops map, it does not need btf_key_type_id and
4261 * btf_value_type_id.
4262 */
4263 if (map->sec_idx == obj->efile.btf_maps_shndx ||
4264 bpf_map__is_struct_ops(map))
abd29c93
AN
4265 return 0;
4266
d859900c 4267 if (!bpf_map__is_internal(map)) {
93b8952d 4268 pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
227a0713
AN
4269#pragma GCC diagnostic push
4270#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
abd29c93 4271 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
d859900c
DB
4272 def->value_size, &key_type_id,
4273 &value_type_id);
227a0713 4274#pragma GCC diagnostic pop
d859900c
DB
4275 } else {
4276 /*
4277 * LLVM annotates global data differently in BTF, that is,
4278 * only as '.data', '.bss' or '.rodata'.
4279 */
aed65917 4280 ret = btf__find_by_name(obj->btf, map->real_name);
d859900c
DB
4281 }
4282 if (ret < 0)
96408c43 4283 return ret;
8a138aed 4284
96408c43 4285 map->btf_key_type_id = key_type_id;
d859900c
DB
4286 map->btf_value_type_id = bpf_map__is_internal(map) ?
4287 ret : value_type_id;
8a138aed
MKL
4288 return 0;
4289}
4290
97eb3138
MP
4291static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4292{
4293 char file[PATH_MAX], buff[4096];
4294 FILE *fp;
4295 __u32 val;
4296 int err;
4297
4298 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4299 memset(info, 0, sizeof(*info));
4300
4301 fp = fopen(file, "r");
4302 if (!fp) {
4303 err = -errno;
4304 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4305 err);
4306 return err;
4307 }
4308
4309 while (fgets(buff, sizeof(buff), fp)) {
4310 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4311 info->type = val;
4312 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4313 info->key_size = val;
4314 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4315 info->value_size = val;
4316 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4317 info->max_entries = val;
4318 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4319 info->map_flags = val;
4320 }
4321
4322 fclose(fp);
4323
4324 return 0;
4325}
4326
26736eb9
JK
4327int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4328{
4329 struct bpf_map_info info = {};
4330 __u32 len = sizeof(info);
4331 int new_fd, err;
4332 char *new_name;
4333
4334 err = bpf_obj_get_info_by_fd(fd, &info, &len);
97eb3138
MP
4335 if (err && errno == EINVAL)
4336 err = bpf_get_map_info_from_fdinfo(fd, &info);
26736eb9 4337 if (err)
e9fc3ce9 4338 return libbpf_err(err);
26736eb9
JK
4339
4340 new_name = strdup(info.name);
4341 if (!new_name)
e9fc3ce9 4342 return libbpf_err(-errno);
26736eb9
JK
4343
4344 new_fd = open("/", O_RDONLY | O_CLOEXEC);
d1b4574a
THJ
4345 if (new_fd < 0) {
4346 err = -errno;
26736eb9 4347 goto err_free_new_name;
d1b4574a 4348 }
26736eb9
JK
4349
4350 new_fd = dup3(fd, new_fd, O_CLOEXEC);
d1b4574a
THJ
4351 if (new_fd < 0) {
4352 err = -errno;
26736eb9 4353 goto err_close_new_fd;
d1b4574a 4354 }
26736eb9
JK
4355
4356 err = zclose(map->fd);
d1b4574a
THJ
4357 if (err) {
4358 err = -errno;
26736eb9 4359 goto err_close_new_fd;
d1b4574a 4360 }
26736eb9
JK
4361 free(map->name);
4362
4363 map->fd = new_fd;
4364 map->name = new_name;
4365 map->def.type = info.type;
4366 map->def.key_size = info.key_size;
4367 map->def.value_size = info.value_size;
4368 map->def.max_entries = info.max_entries;
4369 map->def.map_flags = info.map_flags;
4370 map->btf_key_type_id = info.btf_key_type_id;
4371 map->btf_value_type_id = info.btf_value_type_id;
ec6d5f47 4372 map->reused = true;
47512102 4373 map->map_extra = info.map_extra;
26736eb9
JK
4374
4375 return 0;
4376
4377err_close_new_fd:
4378 close(new_fd);
4379err_free_new_name:
4380 free(new_name);
e9fc3ce9 4381 return libbpf_err(err);
26736eb9
JK
4382}
4383
1bdb6c9a 4384__u32 bpf_map__max_entries(const struct bpf_map *map)
1a11a4c7 4385{
1bdb6c9a
AN
4386 return map->def.max_entries;
4387}
1a11a4c7 4388
b3278099
AN
4389struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4390{
4391 if (!bpf_map_type__is_map_in_map(map->def.type))
e9fc3ce9 4392 return errno = EINVAL, NULL;
b3278099
AN
4393
4394 return map->inner_map;
4395}
4396
1bdb6c9a
AN
4397int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4398{
1a11a4c7 4399 if (map->fd >= 0)
e9fc3ce9 4400 return libbpf_err(-EBUSY);
1a11a4c7 4401 map->def.max_entries = max_entries;
1a11a4c7
AI
4402 return 0;
4403}
4404
1bdb6c9a
AN
4405int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4406{
4407 if (!map || !max_entries)
e9fc3ce9 4408 return libbpf_err(-EINVAL);
1bdb6c9a
AN
4409
4410 return bpf_map__set_max_entries(map, max_entries);
4411}
4412
47eff617 4413static int
fd9eef1a 4414bpf_object__probe_loading(struct bpf_object *obj)
47eff617 4415{
47eff617
SF
4416 char *cp, errmsg[STRERR_BUFSIZE];
4417 struct bpf_insn insns[] = {
4418 BPF_MOV64_IMM(BPF_REG_0, 0),
4419 BPF_EXIT_INSN(),
4420 };
e32660ac 4421 int ret, insn_cnt = ARRAY_SIZE(insns);
47eff617 4422
f9bceaa5
SF
4423 if (obj->gen_loader)
4424 return 0;
4425
e542f2c4
AN
4426 ret = bump_rlimit_memlock();
4427 if (ret)
4428 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4429
47eff617 4430 /* make sure basic loading works */
e32660ac
AN
4431 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4432 if (ret < 0)
4433 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
47eff617 4434 if (ret < 0) {
fd9eef1a
EC
4435 ret = errno;
4436 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4437 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4438 "program. Make sure your kernel supports BPF "
4439 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4440 "set to big enough value.\n", __func__, cp, ret);
4441 return -ret;
47eff617
SF
4442 }
4443 close(ret);
4444
fd9eef1a
EC
4445 return 0;
4446}
4447
bb180fb2
AN
4448static int probe_fd(int fd)
4449{
4450 if (fd >= 0)
4451 close(fd);
4452 return fd >= 0;
4453}
4454
47b6cb4d 4455static int probe_kern_prog_name(void)
fd9eef1a 4456{
fd9eef1a
EC
4457 struct bpf_insn insns[] = {
4458 BPF_MOV64_IMM(BPF_REG_0, 0),
4459 BPF_EXIT_INSN(),
4460 };
e32660ac 4461 int ret, insn_cnt = ARRAY_SIZE(insns);
fd9eef1a
EC
4462
4463 /* make sure loading with name works */
e32660ac 4464 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
bb180fb2 4465 return probe_fd(ret);
47eff617
SF
4466}
4467
47b6cb4d 4468static int probe_kern_global_data(void)
8837fe5d 4469{
8837fe5d
DB
4470 char *cp, errmsg[STRERR_BUFSIZE];
4471 struct bpf_insn insns[] = {
4472 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4473 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4474 BPF_MOV64_IMM(BPF_REG_0, 0),
4475 BPF_EXIT_INSN(),
4476 };
e32660ac 4477 int ret, map, insn_cnt = ARRAY_SIZE(insns);
8837fe5d 4478
a9606f40 4479 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
8837fe5d 4480 if (map < 0) {
23ab656b
THJ
4481 ret = -errno;
4482 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
be18010e 4483 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
23ab656b
THJ
4484 __func__, cp, -ret);
4485 return ret;
8837fe5d
DB
4486 }
4487
4488 insns[0].imm = map;
4489
e32660ac 4490 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
47b6cb4d 4491 close(map);
bb180fb2 4492 return probe_fd(ret);
8837fe5d
DB
4493}
4494
68b08647
AN
4495static int probe_kern_btf(void)
4496{
4497 static const char strs[] = "\0int";
4498 __u32 types[] = {
4499 /* int */
4500 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4501 };
4502
4503 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4504 strs, sizeof(strs)));
4505}
4506
47b6cb4d 4507static int probe_kern_btf_func(void)
d7c4b398 4508{
8983b731 4509 static const char strs[] = "\0int\0x\0a";
d7c4b398
AN
4510 /* void x(int a) {} */
4511 __u32 types[] = {
4512 /* int */
4513 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4514 /* FUNC_PROTO */ /* [2] */
4515 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4516 BTF_PARAM_ENC(7, 1),
4517 /* FUNC x */ /* [3] */
4518 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4519 };
d7c4b398 4520
bb180fb2
AN
4521 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4522 strs, sizeof(strs)));
d7c4b398
AN
4523}
4524
47b6cb4d 4525static int probe_kern_btf_func_global(void)
2d3eb67f
AS
4526{
4527 static const char strs[] = "\0int\0x\0a";
4528 /* static void x(int a) {} */
4529 __u32 types[] = {
4530 /* int */
4531 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4532 /* FUNC_PROTO */ /* [2] */
4533 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4534 BTF_PARAM_ENC(7, 1),
4535 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4536 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4537 };
2d3eb67f 4538
bb180fb2
AN
4539 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4540 strs, sizeof(strs)));
2d3eb67f
AS
4541}
4542
47b6cb4d 4543static int probe_kern_btf_datasec(void)
d7c4b398 4544{
8983b731 4545 static const char strs[] = "\0x\0.data";
d7c4b398
AN
4546 /* static int a; */
4547 __u32 types[] = {
4548 /* int */
4549 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4550 /* VAR x */ /* [2] */
4551 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4552 BTF_VAR_STATIC,
4553 /* DATASEC val */ /* [3] */
4554 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4555 BTF_VAR_SECINFO_ENC(2, 0, 4),
4556 };
cfd49210 4557
bb180fb2
AN
4558 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4559 strs, sizeof(strs)));
d7c4b398
AN
4560}
4561
22541a9e
IL
4562static int probe_kern_btf_float(void)
4563{
4564 static const char strs[] = "\0float";
4565 __u32 types[] = {
4566 /* float */
4567 BTF_TYPE_FLOAT_ENC(1, 4),
4568 };
4569
4570 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4571 strs, sizeof(strs)));
4572}
4573
223f903e 4574static int probe_kern_btf_decl_tag(void)
5b84bd10
YS
4575{
4576 static const char strs[] = "\0tag";
4577 __u32 types[] = {
4578 /* int */
4579 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4580 /* VAR x */ /* [2] */
4581 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4582 BTF_VAR_STATIC,
4583 /* attr */
223f903e 4584 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
5b84bd10
YS
4585 };
4586
4587 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4588 strs, sizeof(strs)));
4589}
4590
2dc1e488
YS
4591static int probe_kern_btf_type_tag(void)
4592{
4593 static const char strs[] = "\0tag";
4594 __u32 types[] = {
4595 /* int */
4596 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4597 /* attr */
4598 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4599 /* ptr */
4600 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4601 };
4602
4603 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4604 strs, sizeof(strs)));
4605}
4606
47b6cb4d 4607static int probe_kern_array_mmap(void)
7fe74b43 4608{
a9606f40
AN
4609 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4610 int fd;
7fe74b43 4611
a9606f40
AN
4612 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4613 return probe_fd(fd);
7fe74b43
AN
4614}
4615
47b6cb4d 4616static int probe_kern_exp_attach_type(void)
25498a19 4617{
e32660ac 4618 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
25498a19
AN
4619 struct bpf_insn insns[] = {
4620 BPF_MOV64_IMM(BPF_REG_0, 0),
4621 BPF_EXIT_INSN(),
4622 };
e32660ac 4623 int fd, insn_cnt = ARRAY_SIZE(insns);
25498a19 4624
25498a19
AN
4625 /* use any valid combination of program type and (optional)
4626 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4627 * to see if kernel supports expected_attach_type field for
4628 * BPF_PROG_LOAD command
4629 */
e32660ac
AN
4630 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4631 return probe_fd(fd);
25498a19
AN
4632}
4633
109cea5a
AN
4634static int probe_kern_probe_read_kernel(void)
4635{
109cea5a
AN
4636 struct bpf_insn insns[] = {
4637 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4638 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4639 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4640 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4641 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4642 BPF_EXIT_INSN(),
4643 };
e32660ac 4644 int fd, insn_cnt = ARRAY_SIZE(insns);
109cea5a 4645
d252a4a4 4646 fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
e32660ac 4647 return probe_fd(fd);
109cea5a
AN
4648}
4649
5d23328d
YZ
4650static int probe_prog_bind_map(void)
4651{
5d23328d
YZ
4652 char *cp, errmsg[STRERR_BUFSIZE];
4653 struct bpf_insn insns[] = {
4654 BPF_MOV64_IMM(BPF_REG_0, 0),
4655 BPF_EXIT_INSN(),
4656 };
e32660ac 4657 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
5d23328d 4658
a9606f40 4659 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
5d23328d
YZ
4660 if (map < 0) {
4661 ret = -errno;
4662 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4663 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4664 __func__, cp, -ret);
4665 return ret;
4666 }
4667
e32660ac 4668 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5d23328d
YZ
4669 if (prog < 0) {
4670 close(map);
4671 return 0;
4672 }
4673
4674 ret = bpf_prog_bind_map(prog, map, NULL);
4675
4676 close(map);
4677 close(prog);
4678
4679 return ret >= 0;
4680}
4681
4f33a53d
AN
4682static int probe_module_btf(void)
4683{
4684 static const char strs[] = "\0int";
4685 __u32 types[] = {
4686 /* int */
4687 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4688 };
4689 struct bpf_btf_info info;
4690 __u32 len = sizeof(info);
4691 char name[16];
4692 int fd, err;
4693
4694 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4695 if (fd < 0)
4696 return 0; /* BTF not supported at all */
4697
4698 memset(&info, 0, sizeof(info));
4699 info.name = ptr_to_u64(name);
4700 info.name_len = sizeof(name);
4701
4702 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4703 * kernel's module BTF support coincides with support for
4704 * name/name_len fields in struct bpf_btf_info.
4705 */
4706 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4707 close(fd);
4708 return !err;
4709}
4710
668ace0e
AN
4711static int probe_perf_link(void)
4712{
668ace0e
AN
4713 struct bpf_insn insns[] = {
4714 BPF_MOV64_IMM(BPF_REG_0, 0),
4715 BPF_EXIT_INSN(),
4716 };
4717 int prog_fd, link_fd, err;
4718
e32660ac
AN
4719 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4720 insns, ARRAY_SIZE(insns), NULL);
668ace0e
AN
4721 if (prog_fd < 0)
4722 return -errno;
4723
4724 /* use invalid perf_event FD to get EBADF, if link is supported;
4725 * otherwise EINVAL should be returned
4726 */
4727 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4728 err = -errno; /* close() can clobber errno */
4729
4730 if (link_fd >= 0)
4731 close(link_fd);
4732 close(prog_fd);
4733
4734 return link_fd < 0 && err == -EBADF;
4735}
4736
2e4913e0
AN
4737static int probe_kern_bpf_cookie(void)
4738{
4739 struct bpf_insn insns[] = {
4740 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4741 BPF_EXIT_INSN(),
4742 };
4743 int ret, insn_cnt = ARRAY_SIZE(insns);
4744
4745 ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4746 return probe_fd(ret);
4747}
4748
47b6cb4d
AN
4749enum kern_feature_result {
4750 FEAT_UNKNOWN = 0,
4751 FEAT_SUPPORTED = 1,
4752 FEAT_MISSING = 2,
4753};
4754
4755typedef int (*feature_probe_fn)(void);
4756
4757static struct kern_feature_desc {
4758 const char *desc;
4759 feature_probe_fn probe;
4760 enum kern_feature_result res;
4761} feature_probes[__FEAT_CNT] = {
4762 [FEAT_PROG_NAME] = {
4763 "BPF program name", probe_kern_prog_name,
4764 },
4765 [FEAT_GLOBAL_DATA] = {
4766 "global variables", probe_kern_global_data,
4767 },
68b08647
AN
4768 [FEAT_BTF] = {
4769 "minimal BTF", probe_kern_btf,
4770 },
47b6cb4d
AN
4771 [FEAT_BTF_FUNC] = {
4772 "BTF functions", probe_kern_btf_func,
4773 },
4774 [FEAT_BTF_GLOBAL_FUNC] = {
4775 "BTF global function", probe_kern_btf_func_global,
4776 },
4777 [FEAT_BTF_DATASEC] = {
4778 "BTF data section and variable", probe_kern_btf_datasec,
4779 },
4780 [FEAT_ARRAY_MMAP] = {
4781 "ARRAY map mmap()", probe_kern_array_mmap,
4782 },
4783 [FEAT_EXP_ATTACH_TYPE] = {
4784 "BPF_PROG_LOAD expected_attach_type attribute",
4785 probe_kern_exp_attach_type,
4786 },
109cea5a
AN
4787 [FEAT_PROBE_READ_KERN] = {
4788 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5d23328d
YZ
4789 },
4790 [FEAT_PROG_BIND_MAP] = {
4791 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4f33a53d
AN
4792 },
4793 [FEAT_MODULE_BTF] = {
4794 "module BTF support", probe_module_btf,
4795 },
22541a9e
IL
4796 [FEAT_BTF_FLOAT] = {
4797 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4798 },
668ace0e
AN
4799 [FEAT_PERF_LINK] = {
4800 "BPF perf link support", probe_perf_link,
4801 },
223f903e
YS
4802 [FEAT_BTF_DECL_TAG] = {
4803 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5b84bd10 4804 },
2dc1e488
YS
4805 [FEAT_BTF_TYPE_TAG] = {
4806 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4807 },
e542f2c4
AN
4808 [FEAT_MEMCG_ACCOUNT] = {
4809 "memcg-based memory accounting", probe_memcg_account,
4810 },
2e4913e0
AN
4811 [FEAT_BPF_COOKIE] = {
4812 "BPF cookie support", probe_kern_bpf_cookie,
4813 },
47b6cb4d 4814};
8837fe5d 4815
e542f2c4 4816bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
47b6cb4d
AN
4817{
4818 struct kern_feature_desc *feat = &feature_probes[feat_id];
4819 int ret;
4820
e542f2c4 4821 if (obj && obj->gen_loader)
67234743
AS
4822 /* To generate loader program assume the latest kernel
4823 * to avoid doing extra prog_load, map_create syscalls.
4824 */
4825 return true;
4826
47b6cb4d
AN
4827 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4828 ret = feat->probe();
4829 if (ret > 0) {
4830 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4831 } else if (ret == 0) {
4832 WRITE_ONCE(feat->res, FEAT_MISSING);
4833 } else {
4834 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4835 WRITE_ONCE(feat->res, FEAT_MISSING);
4836 }
8837fe5d
DB
4837 }
4838
47b6cb4d 4839 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
47eff617
SF
4840}
4841
57a00f41
THJ
4842static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4843{
4844 struct bpf_map_info map_info = {};
4845 char msg[STRERR_BUFSIZE];
4846 __u32 map_info_len;
97eb3138 4847 int err;
57a00f41
THJ
4848
4849 map_info_len = sizeof(map_info);
4850
97eb3138
MP
4851 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4852 if (err && errno == EINVAL)
4853 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4854 if (err) {
4855 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4856 libbpf_strerror_r(errno, msg, sizeof(msg)));
57a00f41
THJ
4857 return false;
4858 }
4859
4860 return (map_info.type == map->def.type &&
4861 map_info.key_size == map->def.key_size &&
4862 map_info.value_size == map->def.value_size &&
4863 map_info.max_entries == map->def.max_entries &&
47512102
JK
4864 map_info.map_flags == map->def.map_flags &&
4865 map_info.map_extra == map->map_extra);
57a00f41
THJ
4866}
4867
4868static int
4869bpf_object__reuse_map(struct bpf_map *map)
4870{
4871 char *cp, errmsg[STRERR_BUFSIZE];
4872 int err, pin_fd;
4873
4874 pin_fd = bpf_obj_get(map->pin_path);
4875 if (pin_fd < 0) {
4876 err = -errno;
4877 if (err == -ENOENT) {
4878 pr_debug("found no pinned map to reuse at '%s'\n",
4879 map->pin_path);
4880 return 0;
4881 }
4882
4883 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4884 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4885 map->pin_path, cp);
4886 return err;
4887 }
4888
4889 if (!map_is_reuse_compat(map, pin_fd)) {
4890 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4891 map->pin_path);
4892 close(pin_fd);
4893 return -EINVAL;
4894 }
4895
4896 err = bpf_map__reuse_fd(map, pin_fd);
d0f325c3 4897 close(pin_fd);
57a00f41 4898 if (err) {
57a00f41
THJ
4899 return err;
4900 }
4901 map->pinned = true;
4902 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4903
4904 return 0;
4905}
4906
d859900c
DB
4907static int
4908bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4909{
166750bc 4910 enum libbpf_map_type map_type = map->libbpf_type;
d859900c
DB
4911 char *cp, errmsg[STRERR_BUFSIZE];
4912 int err, zero = 0;
d859900c 4913
67234743
AS
4914 if (obj->gen_loader) {
4915 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4916 map->mmaped, map->def.value_size);
4917 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4918 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4919 return 0;
4920 }
eba9c5f4
AN
4921 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4922 if (err) {
4923 err = -errno;
4924 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4925 pr_warn("Error setting initial map(%s) contents: %s\n",
4926 map->name, cp);
4927 return err;
4928 }
d859900c 4929
81bfdd08
AN
4930 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4931 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
d859900c
DB
4932 err = bpf_map_freeze(map->fd);
4933 if (err) {
eba9c5f4
AN
4934 err = -errno;
4935 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e
KW
4936 pr_warn("Error freezing map(%s) as read-only: %s\n",
4937 map->name, cp);
eba9c5f4 4938 return err;
d859900c
DB
4939 }
4940 }
eba9c5f4 4941 return 0;
d859900c
DB
4942}
4943
2d39d7c5
AN
4944static void bpf_map__destroy(struct bpf_map *map);
4945
67234743 4946static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
2d39d7c5 4947{
992c4225 4948 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
2d39d7c5 4949 struct bpf_map_def *def = &map->def;
992c4225 4950 const char *map_name = NULL;
a21ab4c5 4951 int err = 0;
2d39d7c5 4952
9ca1f56a 4953 if (kernel_supports(obj, FEAT_PROG_NAME))
992c4225 4954 map_name = map->name;
2d39d7c5 4955 create_attr.map_ifindex = map->map_ifindex;
2d39d7c5 4956 create_attr.map_flags = def->map_flags;
1bdb6c9a 4957 create_attr.numa_node = map->numa_node;
47512102 4958 create_attr.map_extra = map->map_extra;
2d39d7c5 4959
2d39d7c5 4960 if (bpf_map__is_struct_ops(map))
992c4225 4961 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
2d39d7c5 4962
262cfb74 4963 if (obj->btf && btf__fd(obj->btf) >= 0) {
2d39d7c5
AN
4964 create_attr.btf_fd = btf__fd(obj->btf);
4965 create_attr.btf_key_type_id = map->btf_key_type_id;
4966 create_attr.btf_value_type_id = map->btf_value_type_id;
4967 }
4968
646f02ff
AN
4969 if (bpf_map_type__is_map_in_map(def->type)) {
4970 if (map->inner_map) {
67234743 4971 err = bpf_object__create_map(obj, map->inner_map, true);
646f02ff
AN
4972 if (err) {
4973 pr_warn("map '%s': failed to create inner map: %d\n",
4974 map->name, err);
4975 return err;
4976 }
4977 map->inner_map_fd = bpf_map__fd(map->inner_map);
4978 }
4979 if (map->inner_map_fd >= 0)
4980 create_attr.inner_map_fd = map->inner_map_fd;
4981 }
4982
f7310523
HC
4983 switch (def->type) {
4984 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4985 case BPF_MAP_TYPE_CGROUP_ARRAY:
4986 case BPF_MAP_TYPE_STACK_TRACE:
4987 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4988 case BPF_MAP_TYPE_HASH_OF_MAPS:
4989 case BPF_MAP_TYPE_DEVMAP:
4990 case BPF_MAP_TYPE_DEVMAP_HASH:
4991 case BPF_MAP_TYPE_CPUMAP:
4992 case BPF_MAP_TYPE_XSKMAP:
4993 case BPF_MAP_TYPE_SOCKMAP:
4994 case BPF_MAP_TYPE_SOCKHASH:
4995 case BPF_MAP_TYPE_QUEUE:
4996 case BPF_MAP_TYPE_STACK:
4997 case BPF_MAP_TYPE_RINGBUF:
4998 create_attr.btf_fd = 0;
4999 create_attr.btf_key_type_id = 0;
5000 create_attr.btf_value_type_id = 0;
5001 map->btf_key_type_id = 0;
5002 map->btf_value_type_id = 0;
5003 default:
5004 break;
5005 }
5006
67234743 5007 if (obj->gen_loader) {
992c4225 5008 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
a4fbfdd7 5009 def->key_size, def->value_size, def->max_entries,
992c4225 5010 &create_attr, is_inner ? -1 : map - obj->maps);
67234743
AS
5011 /* Pretend to have valid FD to pass various fd >= 0 checks.
5012 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5013 */
5014 map->fd = 0;
5015 } else {
992c4225
AN
5016 map->fd = bpf_map_create(def->type, map_name,
5017 def->key_size, def->value_size,
a4fbfdd7 5018 def->max_entries, &create_attr);
67234743 5019 }
2d39d7c5
AN
5020 if (map->fd < 0 && (create_attr.btf_key_type_id ||
5021 create_attr.btf_value_type_id)) {
5022 char *cp, errmsg[STRERR_BUFSIZE];
2d39d7c5 5023
a21ab4c5 5024 err = -errno;
2d39d7c5
AN
5025 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5026 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5027 map->name, cp, err);
5028 create_attr.btf_fd = 0;
5029 create_attr.btf_key_type_id = 0;
5030 create_attr.btf_value_type_id = 0;
5031 map->btf_key_type_id = 0;
5032 map->btf_value_type_id = 0;
992c4225
AN
5033 map->fd = bpf_map_create(def->type, map_name,
5034 def->key_size, def->value_size,
a4fbfdd7 5035 def->max_entries, &create_attr);
2d39d7c5
AN
5036 }
5037
a21ab4c5 5038 err = map->fd < 0 ? -errno : 0;
2d39d7c5 5039
646f02ff 5040 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
67234743
AS
5041 if (obj->gen_loader)
5042 map->inner_map->fd = -1;
646f02ff
AN
5043 bpf_map__destroy(map->inner_map);
5044 zfree(&map->inner_map);
5045 }
5046
a21ab4c5 5047 return err;
2d39d7c5
AN
5048}
5049
341ac5ff 5050static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
a0f2b7ac
HL
5051{
5052 const struct bpf_map *targ_map;
5053 unsigned int i;
67234743 5054 int fd, err = 0;
a0f2b7ac
HL
5055
5056 for (i = 0; i < map->init_slots_sz; i++) {
5057 if (!map->init_slots[i])
5058 continue;
5059
5060 targ_map = map->init_slots[i];
5061 fd = bpf_map__fd(targ_map);
341ac5ff 5062
67234743 5063 if (obj->gen_loader) {
be05c944
AS
5064 bpf_gen__populate_outer_map(obj->gen_loader,
5065 map - obj->maps, i,
5066 targ_map - obj->maps);
67234743
AS
5067 } else {
5068 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5069 }
a0f2b7ac
HL
5070 if (err) {
5071 err = -errno;
5072 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
341ac5ff 5073 map->name, i, targ_map->name, fd, err);
a0f2b7ac
HL
5074 return err;
5075 }
5076 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5077 map->name, i, targ_map->name, fd);
5078 }
5079
5080 zfree(&map->init_slots);
5081 map->init_slots_sz = 0;
5082
5083 return 0;
5084}
5085
341ac5ff
HC
5086static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5087{
5088 const struct bpf_program *targ_prog;
5089 unsigned int i;
5090 int fd, err;
5091
5092 if (obj->gen_loader)
5093 return -ENOTSUP;
5094
5095 for (i = 0; i < map->init_slots_sz; i++) {
5096 if (!map->init_slots[i])
5097 continue;
5098
5099 targ_prog = map->init_slots[i];
5100 fd = bpf_program__fd(targ_prog);
5101
5102 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5103 if (err) {
5104 err = -errno;
5105 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5106 map->name, i, targ_prog->name, fd, err);
5107 return err;
5108 }
5109 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5110 map->name, i, targ_prog->name, fd);
5111 }
5112
5113 zfree(&map->init_slots);
5114 map->init_slots_sz = 0;
5115
5116 return 0;
5117}
5118
5119static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5120{
5121 struct bpf_map *map;
5122 int i, err;
5123
5124 for (i = 0; i < obj->nr_maps; i++) {
5125 map = &obj->maps[i];
5126
5127 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5128 continue;
5129
5130 err = init_prog_array_slots(obj, map);
5131 if (err < 0) {
5132 zclose(map->fd);
5133 return err;
5134 }
5135 }
5136 return 0;
5137}
5138
a4fbfdd7
ST
5139static int map_set_def_max_entries(struct bpf_map *map)
5140{
5141 if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5142 int nr_cpus;
5143
5144 nr_cpus = libbpf_num_possible_cpus();
5145 if (nr_cpus < 0) {
5146 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5147 map->name, nr_cpus);
5148 return nr_cpus;
5149 }
5150 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5151 map->def.max_entries = nr_cpus;
5152 }
5153
5154 return 0;
5155}
5156
52d3352e
WN
5157static int
5158bpf_object__create_maps(struct bpf_object *obj)
5159{
2d39d7c5
AN
5160 struct bpf_map *map;
5161 char *cp, errmsg[STRERR_BUFSIZE];
5162 unsigned int i, j;
8a138aed 5163 int err;
043c5bb3 5164 bool retried;
52d3352e 5165
9d759a9b 5166 for (i = 0; i < obj->nr_maps; i++) {
2d39d7c5 5167 map = &obj->maps[i];
8a138aed 5168
16e0c35c
AN
5169 /* To support old kernels, we skip creating global data maps
5170 * (.rodata, .data, .kconfig, etc); later on, during program
5171 * loading, if we detect that at least one of the to-be-loaded
5172 * programs is referencing any global data map, we'll error
5173 * out with program name and relocation index logged.
5174 * This approach allows to accommodate Clang emitting
5175 * unnecessary .rodata.str1.1 sections for string literals,
5176 * but also it allows to have CO-RE applications that use
5177 * global variables in some of BPF programs, but not others.
5178 * If those global variable-using programs are not loaded at
5179 * runtime due to bpf_program__set_autoload(prog, false),
5180 * bpf_object loading will succeed just fine even on old
5181 * kernels.
5182 */
5183 if (bpf_map__is_internal(map) &&
229fae38
SC
5184 !kernel_supports(obj, FEAT_GLOBAL_DATA)) {
5185 map->skipped = true;
16e0c35c 5186 continue;
229fae38 5187 }
16e0c35c 5188
a4fbfdd7
ST
5189 err = map_set_def_max_entries(map);
5190 if (err)
5191 goto err_out;
5192
043c5bb3
MP
5193 retried = false;
5194retry:
57a00f41
THJ
5195 if (map->pin_path) {
5196 err = bpf_object__reuse_map(map);
5197 if (err) {
2d39d7c5 5198 pr_warn("map '%s': error reusing pinned map\n",
57a00f41 5199 map->name);
2d39d7c5 5200 goto err_out;
57a00f41 5201 }
043c5bb3
MP
5202 if (retried && map->fd < 0) {
5203 pr_warn("map '%s': cannot find pinned map\n",
5204 map->name);
5205 err = -ENOENT;
5206 goto err_out;
5207 }
57a00f41
THJ
5208 }
5209
26736eb9 5210 if (map->fd >= 0) {
2d39d7c5 5211 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
26736eb9 5212 map->name, map->fd);
2c193d32 5213 } else {
67234743 5214 err = bpf_object__create_map(obj, map, false);
2c193d32 5215 if (err)
d859900c 5216 goto err_out;
d859900c 5217
2c193d32
HL
5218 pr_debug("map '%s': created successfully, fd=%d\n",
5219 map->name, map->fd);
646f02ff 5220
2c193d32
HL
5221 if (bpf_map__is_internal(map)) {
5222 err = bpf_object__populate_internal_map(obj, map);
5223 if (err < 0) {
5224 zclose(map->fd);
5225 goto err_out;
5226 }
d859900c 5227 }
646f02ff 5228
341ac5ff
HC
5229 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5230 err = init_map_in_map_slots(obj, map);
2c193d32
HL
5231 if (err < 0) {
5232 zclose(map->fd);
646f02ff
AN
5233 goto err_out;
5234 }
646f02ff 5235 }
646f02ff
AN
5236 }
5237
57a00f41
THJ
5238 if (map->pin_path && !map->pinned) {
5239 err = bpf_map__pin(map, NULL);
5240 if (err) {
043c5bb3
MP
5241 zclose(map->fd);
5242 if (!retried && err == -EEXIST) {
5243 retried = true;
5244 goto retry;
5245 }
2d39d7c5
AN
5246 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5247 map->name, map->pin_path, err);
2d39d7c5 5248 goto err_out;
57a00f41
THJ
5249 }
5250 }
52d3352e
WN
5251 }
5252
52d3352e 5253 return 0;
2d39d7c5
AN
5254
5255err_out:
5256 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5257 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5258 pr_perm_msg(err);
5259 for (j = 0; j < i; j++)
5260 zclose(obj->maps[j].fd);
5261 return err;
52d3352e
WN
5262}
5263
ddc7c304
AN
5264static bool bpf_core_is_flavor_sep(const char *s)
5265{
5266 /* check X___Y name pattern, where X and Y are not underscores */
5267 return s[0] != '_' && /* X */
5268 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5269 s[4] != '_'; /* Y */
5270}
5271
5272/* Given 'some_struct_name___with_flavor' return the length of a name prefix
5273 * before last triple underscore. Struct name part after last triple
5274 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5275 */
b0588390 5276size_t bpf_core_essential_name_len(const char *name)
ddc7c304
AN
5277{
5278 size_t n = strlen(name);
5279 int i;
5280
5281 for (i = n - 5; i >= 0; i--) {
5282 if (bpf_core_is_flavor_sep(name + i))
5283 return i + 1;
5284 }
5285 return n;
5286}
5287
8de6cae4 5288void bpf_core_free_cands(struct bpf_core_cand_list *cands)
ddc7c304 5289{
8de6cae4
MV
5290 if (!cands)
5291 return;
5292
0f7515ca
AN
5293 free(cands->cands);
5294 free(cands);
ddc7c304
AN
5295}
5296
8de6cae4
MV
5297int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5298 size_t local_essent_len,
5299 const struct btf *targ_btf,
5300 const char *targ_btf_name,
5301 int targ_start_id,
5302 struct bpf_core_cand_list *cands)
ddc7c304 5303{
301ba4d7 5304 struct bpf_core_cand *new_cands, *cand;
03d5b991
AN
5305 const struct btf_type *t, *local_t;
5306 const char *targ_name, *local_name;
0f7515ca
AN
5307 size_t targ_essent_len;
5308 int n, i;
ddc7c304 5309
03d5b991
AN
5310 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5311 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5312
6a886de0
HC
5313 n = btf__type_cnt(targ_btf);
5314 for (i = targ_start_id; i < n; i++) {
ddc7c304 5315 t = btf__type_by_id(targ_btf, i);
03d5b991 5316 if (btf_kind(t) != btf_kind(local_t))
ddc7c304
AN
5317 continue;
5318
3fc32f40
AN
5319 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5320 if (str_is_empty(targ_name))
d121e1d3
AN
5321 continue;
5322
ddc7c304
AN
5323 targ_essent_len = bpf_core_essential_name_len(targ_name);
5324 if (targ_essent_len != local_essent_len)
5325 continue;
5326
03d5b991 5327 if (strncmp(local_name, targ_name, local_essent_len) != 0)
0f7515ca
AN
5328 continue;
5329
5330 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
03d5b991
AN
5331 local_cand->id, btf_kind_str(local_t),
5332 local_name, i, btf_kind_str(t), targ_name,
0f7515ca
AN
5333 targ_btf_name);
5334 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5335 sizeof(*cands->cands));
5336 if (!new_cands)
5337 return -ENOMEM;
5338
5339 cand = &new_cands[cands->len];
5340 cand->btf = targ_btf;
0f7515ca
AN
5341 cand->id = i;
5342
5343 cands->cands = new_cands;
5344 cands->len++;
ddc7c304 5345 }
0f7515ca
AN
5346 return 0;
5347}
5348
4f33a53d
AN
5349static int load_module_btfs(struct bpf_object *obj)
5350{
5351 struct bpf_btf_info info;
5352 struct module_btf *mod_btf;
5353 struct btf *btf;
5354 char name[64];
5355 __u32 id = 0, len;
5356 int err, fd;
5357
5358 if (obj->btf_modules_loaded)
5359 return 0;
5360
67234743
AS
5361 if (obj->gen_loader)
5362 return 0;
5363
4f33a53d
AN
5364 /* don't do this again, even if we find no module BTFs */
5365 obj->btf_modules_loaded = true;
5366
5367 /* kernel too old to support module BTFs */
9ca1f56a 5368 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4f33a53d
AN
5369 return 0;
5370
5371 while (true) {
5372 err = bpf_btf_get_next_id(id, &id);
5373 if (err && errno == ENOENT)
5374 return 0;
5375 if (err) {
5376 err = -errno;
5377 pr_warn("failed to iterate BTF objects: %d\n", err);
5378 return err;
ddc7c304 5379 }
4f33a53d
AN
5380
5381 fd = bpf_btf_get_fd_by_id(id);
5382 if (fd < 0) {
5383 if (errno == ENOENT)
5384 continue; /* expected race: BTF was unloaded */
5385 err = -errno;
5386 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5387 return err;
5388 }
5389
5390 len = sizeof(info);
5391 memset(&info, 0, sizeof(info));
5392 info.name = ptr_to_u64(name);
5393 info.name_len = sizeof(name);
5394
5395 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5396 if (err) {
5397 err = -errno;
5398 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
91abb4a6 5399 goto err_out;
4f33a53d
AN
5400 }
5401
5402 /* ignore non-module BTFs */
5403 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5404 close(fd);
5405 continue;
5406 }
5407
5408 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
e9fc3ce9
AN
5409 err = libbpf_get_error(btf);
5410 if (err) {
5411 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5412 name, id, err);
91abb4a6 5413 goto err_out;
4f33a53d
AN
5414 }
5415
3b029e06
AN
5416 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5417 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4f33a53d 5418 if (err)
91abb4a6 5419 goto err_out;
4f33a53d
AN
5420
5421 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5422
5423 mod_btf->btf = btf;
5424 mod_btf->id = id;
91abb4a6 5425 mod_btf->fd = fd;
4f33a53d 5426 mod_btf->name = strdup(name);
91abb4a6
AN
5427 if (!mod_btf->name) {
5428 err = -ENOMEM;
5429 goto err_out;
5430 }
5431 continue;
5432
5433err_out:
5434 close(fd);
5435 return err;
ddc7c304 5436 }
4f33a53d
AN
5437
5438 return 0;
5439}
5440
301ba4d7 5441static struct bpf_core_cand_list *
0f7515ca
AN
5442bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5443{
301ba4d7
AS
5444 struct bpf_core_cand local_cand = {};
5445 struct bpf_core_cand_list *cands;
4f33a53d 5446 const struct btf *main_btf;
03d5b991
AN
5447 const struct btf_type *local_t;
5448 const char *local_name;
0f7515ca 5449 size_t local_essent_len;
4f33a53d 5450 int err, i;
0f7515ca
AN
5451
5452 local_cand.btf = local_btf;
03d5b991
AN
5453 local_cand.id = local_type_id;
5454 local_t = btf__type_by_id(local_btf, local_type_id);
5455 if (!local_t)
0f7515ca
AN
5456 return ERR_PTR(-EINVAL);
5457
03d5b991
AN
5458 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5459 if (str_is_empty(local_name))
0f7515ca 5460 return ERR_PTR(-EINVAL);
03d5b991 5461 local_essent_len = bpf_core_essential_name_len(local_name);
0f7515ca
AN
5462
5463 cands = calloc(1, sizeof(*cands));
5464 if (!cands)
5465 return ERR_PTR(-ENOMEM);
5466
5467 /* Attempt to find target candidates in vmlinux BTF first */
4f33a53d
AN
5468 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5469 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5470 if (err)
5471 goto err_out;
5472
5473 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5474 if (cands->len)
5475 return cands;
5476
5477 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5478 if (obj->btf_vmlinux_override)
5479 return cands;
5480
5481 /* now look through module BTFs, trying to still find candidates */
5482 err = load_module_btfs(obj);
5483 if (err)
5484 goto err_out;
5485
5486 for (i = 0; i < obj->btf_module_cnt; i++) {
5487 err = bpf_core_add_cands(&local_cand, local_essent_len,
5488 obj->btf_modules[i].btf,
5489 obj->btf_modules[i].name,
6a886de0 5490 btf__type_cnt(obj->btf_vmlinux),
4f33a53d
AN
5491 cands);
5492 if (err)
5493 goto err_out;
0f7515ca
AN
5494 }
5495
5496 return cands;
ddc7c304 5497err_out:
4f33a53d 5498 bpf_core_free_cands(cands);
ddc7c304
AN
5499 return ERR_PTR(err);
5500}
5501
3fc32f40
AN
5502/* Check local and target types for compatibility. This check is used for
5503 * type-based CO-RE relocations and follow slightly different rules than
5504 * field-based relocations. This function assumes that root types were already
5505 * checked for name match. Beyond that initial root-level name check, names
5506 * are completely ignored. Compatibility rules are as follows:
5507 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5508 * kind should match for local and target types (i.e., STRUCT is not
5509 * compatible with UNION);
5510 * - for ENUMs, the size is ignored;
5511 * - for INT, size and signedness are ignored;
5512 * - for ARRAY, dimensionality is ignored, element types are checked for
5513 * compatibility recursively;
5514 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5515 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5516 * - FUNC_PROTOs are compatible if they have compatible signature: same
5517 * number of input args and compatible return and argument types.
5518 * These rules are not set in stone and probably will be adjusted as we get
5519 * more experience with using BPF CO-RE relocations.
5520 */
b0588390
AS
5521int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5522 const struct btf *targ_btf, __u32 targ_id)
3fc32f40
AN
5523{
5524 const struct btf_type *local_type, *targ_type;
5525 int depth = 32; /* max recursion depth */
5526
5527 /* caller made sure that names match (ignoring flavor suffix) */
5528 local_type = btf__type_by_id(local_btf, local_id);
f872e4bc 5529 targ_type = btf__type_by_id(targ_btf, targ_id);
3fc32f40
AN
5530 if (btf_kind(local_type) != btf_kind(targ_type))
5531 return 0;
5532
5533recur:
5534 depth--;
5535 if (depth < 0)
5536 return -EINVAL;
5537
5538 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5539 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5540 if (!local_type || !targ_type)
5541 return -EINVAL;
5542
5543 if (btf_kind(local_type) != btf_kind(targ_type))
5544 return 0;
5545
5546 switch (btf_kind(local_type)) {
5547 case BTF_KIND_UNKN:
5548 case BTF_KIND_STRUCT:
5549 case BTF_KIND_UNION:
5550 case BTF_KIND_ENUM:
5551 case BTF_KIND_FWD:
5552 return 1;
5553 case BTF_KIND_INT:
5554 /* just reject deprecated bitfield-like integers; all other
5555 * integers are by default compatible between each other
5556 */
5557 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5558 case BTF_KIND_PTR:
5559 local_id = local_type->type;
5560 targ_id = targ_type->type;
5561 goto recur;
5562 case BTF_KIND_ARRAY:
5563 local_id = btf_array(local_type)->type;
5564 targ_id = btf_array(targ_type)->type;
5565 goto recur;
5566 case BTF_KIND_FUNC_PROTO: {
5567 struct btf_param *local_p = btf_params(local_type);
5568 struct btf_param *targ_p = btf_params(targ_type);
5569 __u16 local_vlen = btf_vlen(local_type);
5570 __u16 targ_vlen = btf_vlen(targ_type);
5571 int i, err;
5572
5573 if (local_vlen != targ_vlen)
5574 return 0;
5575
5576 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5577 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5578 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5579 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5580 if (err <= 0)
5581 return err;
5582 }
5583
5584 /* tail recurse for return type check */
5585 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5586 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5587 goto recur;
5588 }
5589 default:
5590 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5591 btf_kind_str(local_type), local_id, targ_id);
5592 return 0;
5593 }
5594}
5595
ddc7c304
AN
5596static size_t bpf_core_hash_fn(const void *key, void *ctx)
5597{
5598 return (size_t)key;
5599}
5600
5601static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5602{
5603 return k1 == k2;
5604}
5605
5606static void *u32_as_hash_key(__u32 x)
5607{
5608 return (void *)(uintptr_t)x;
5609}
5610
d0e92887
AS
5611static int record_relo_core(struct bpf_program *prog,
5612 const struct bpf_core_relo *core_relo, int insn_idx)
5613{
5614 struct reloc_desc *relos, *relo;
5615
5616 relos = libbpf_reallocarray(prog->reloc_desc,
5617 prog->nr_reloc + 1, sizeof(*relos));
5618 if (!relos)
5619 return -ENOMEM;
5620 relo = &relos[prog->nr_reloc];
5621 relo->type = RELO_CORE;
5622 relo->insn_idx = insn_idx;
5623 relo->core_relo = core_relo;
5624 prog->reloc_desc = relos;
5625 prog->nr_reloc++;
5626 return 0;
5627}
5628
adb8fa19
MV
5629static int bpf_core_resolve_relo(struct bpf_program *prog,
5630 const struct bpf_core_relo *relo,
5631 int relo_idx,
5632 const struct btf *local_btf,
5633 struct hashmap *cand_cache,
5634 struct bpf_core_relo_res *targ_res)
3ee4f533 5635{
78c1f8d0 5636 struct bpf_core_spec specs_scratch[3] = {};
3ee4f533 5637 const void *type_key = u32_as_hash_key(relo->type_id);
301ba4d7 5638 struct bpf_core_cand_list *cands = NULL;
3ee4f533
AS
5639 const char *prog_name = prog->name;
5640 const struct btf_type *local_type;
5641 const char *local_name;
5642 __u32 local_id = relo->type_id;
adb8fa19 5643 int err;
3ee4f533
AS
5644
5645 local_type = btf__type_by_id(local_btf, local_id);
5646 if (!local_type)
5647 return -EINVAL;
5648
5649 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5650 if (!local_name)
5651 return -EINVAL;
5652
46334a0c 5653 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
3ee4f533
AS
5654 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5655 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5656 if (IS_ERR(cands)) {
5657 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5658 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5659 local_name, PTR_ERR(cands));
5660 return PTR_ERR(cands);
5661 }
5662 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5663 if (err) {
5664 bpf_core_free_cands(cands);
5665 return err;
5666 }
5667 }
5668
adb8fa19
MV
5669 return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5670 targ_res);
3ee4f533
AS
5671}
5672
ddc7c304 5673static int
28b93c64 5674bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
ddc7c304
AN
5675{
5676 const struct btf_ext_info_sec *sec;
adb8fa19 5677 struct bpf_core_relo_res targ_res;
28b93c64 5678 const struct bpf_core_relo *rec;
ddc7c304
AN
5679 const struct btf_ext_info *seg;
5680 struct hashmap_entry *entry;
5681 struct hashmap *cand_cache = NULL;
5682 struct bpf_program *prog;
adb8fa19 5683 struct bpf_insn *insn;
ddc7c304 5684 const char *sec_name;
11d5daa8 5685 int i, err = 0, insn_idx, sec_idx, sec_num;
ddc7c304 5686
28b93c64
AN
5687 if (obj->btf_ext->core_relo_info.len == 0)
5688 return 0;
5689
0f7515ca
AN
5690 if (targ_btf_path) {
5691 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
e9fc3ce9
AN
5692 err = libbpf_get_error(obj->btf_vmlinux_override);
5693 if (err) {
0f7515ca
AN
5694 pr_warn("failed to parse target BTF: %d\n", err);
5695 return err;
5696 }
ddc7c304
AN
5697 }
5698
5699 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5700 if (IS_ERR(cand_cache)) {
5701 err = PTR_ERR(cand_cache);
5702 goto out;
5703 }
5704
28b93c64 5705 seg = &obj->btf_ext->core_relo_info;
11d5daa8 5706 sec_num = 0;
ddc7c304 5707 for_each_btf_ext_sec(seg, sec) {
11d5daa8
AN
5708 sec_idx = seg->sec_idxs[sec_num];
5709 sec_num++;
5710
ddc7c304
AN
5711 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5712 if (str_is_empty(sec_name)) {
5713 err = -EINVAL;
5714 goto out;
5715 }
ddc7c304 5716
11d5daa8 5717 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
ddc7c304
AN
5718
5719 for_each_btf_ext_rec(seg, sec, i, rec) {
adb8fa19
MV
5720 if (rec->insn_off % BPF_INSN_SZ)
5721 return -EINVAL;
db2b8b06
AN
5722 insn_idx = rec->insn_off / BPF_INSN_SZ;
5723 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5724 if (!prog) {
e89d57d9
AN
5725 /* When __weak subprog is "overridden" by another instance
5726 * of the subprog from a different object file, linker still
5727 * appends all the .BTF.ext info that used to belong to that
5728 * eliminated subprogram.
5729 * This is similar to what x86-64 linker does for relocations.
5730 * So just ignore such relocations just like we ignore
5731 * subprog instructions when discovering subprograms.
5732 */
5733 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5734 sec_name, i, insn_idx);
5735 continue;
db2b8b06 5736 }
47f7cf63
AN
5737 /* no need to apply CO-RE relocation if the program is
5738 * not going to be loaded
5739 */
a3820c48 5740 if (!prog->autoload)
47f7cf63 5741 continue;
db2b8b06 5742
adb8fa19
MV
5743 /* adjust insn_idx from section frame of reference to the local
5744 * program's frame of reference; (sub-)program code is not yet
5745 * relocated, so it's enough to just subtract in-section offset
5746 */
5747 insn_idx = insn_idx - prog->sec_insn_off;
5748 if (insn_idx >= prog->insns_cnt)
5749 return -EINVAL;
5750 insn = &prog->insns[insn_idx];
5751
5752 if (prog->obj->gen_loader) {
5753 err = record_relo_core(prog, rec, insn_idx);
5754 if (err) {
5755 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5756 prog->name, i, err);
5757 goto out;
5758 }
5759 continue;
5760 }
5761
5762 err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
ddc7c304 5763 if (err) {
be18010e 5764 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
9c0f8cbd 5765 prog->name, i, err);
ddc7c304
AN
5766 goto out;
5767 }
adb8fa19
MV
5768
5769 err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5770 if (err) {
5771 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5772 prog->name, i, insn_idx, err);
5773 goto out;
5774 }
ddc7c304
AN
5775 }
5776 }
5777
5778out:
4f33a53d 5779 /* obj->btf_vmlinux and module BTFs are freed after object load */
0f7515ca
AN
5780 btf__free(obj->btf_vmlinux_override);
5781 obj->btf_vmlinux_override = NULL;
5782
ddc7c304
AN
5783 if (!IS_ERR_OR_NULL(cand_cache)) {
5784 hashmap__for_each_entry(cand_cache, entry, i) {
5785 bpf_core_free_cands(entry->value);
5786 }
5787 hashmap__free(cand_cache);
5788 }
5789 return err;
5790}
5791
c3c55696
AN
5792/* Relocate data references within program code:
5793 * - map references;
5794 * - global variable references;
5795 * - extern references.
5796 */
48cca7e4 5797static int
c3c55696 5798bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
8a47a6c5 5799{
c3c55696 5800 int i;
8a47a6c5
WN
5801
5802 for (i = 0; i < prog->nr_reloc; i++) {
53f8dd43 5803 struct reloc_desc *relo = &prog->reloc_desc[i];
166750bc 5804 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
2e33efe3 5805 struct extern_desc *ext;
8a47a6c5 5806
166750bc
AN
5807 switch (relo->type) {
5808 case RELO_LD64:
e2fa0156
AS
5809 if (obj->gen_loader) {
5810 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5811 insn[0].imm = relo->map_idx;
5812 } else {
5813 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5814 insn[0].imm = obj->maps[relo->map_idx].fd;
5815 }
166750bc
AN
5816 break;
5817 case RELO_DATA:
166750bc 5818 insn[1].imm = insn[0].imm + relo->sym_off;
e2fa0156
AS
5819 if (obj->gen_loader) {
5820 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5821 insn[0].imm = relo->map_idx;
5822 } else {
16e0c35c
AN
5823 const struct bpf_map *map = &obj->maps[relo->map_idx];
5824
229fae38 5825 if (map->skipped) {
16e0c35c
AN
5826 pr_warn("prog '%s': relo #%d: kernel doesn't support global data\n",
5827 prog->name, i);
5828 return -ENOTSUP;
5829 }
e2fa0156
AS
5830 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5831 insn[0].imm = obj->maps[relo->map_idx].fd;
5832 }
166750bc 5833 break;
0c091e5c 5834 case RELO_EXTERN_VAR:
2e33efe3 5835 ext = &obj->externs[relo->sym_off];
1c0c7074 5836 if (ext->type == EXT_KCFG) {
e2fa0156
AS
5837 if (obj->gen_loader) {
5838 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5839 insn[0].imm = obj->kconfig_map_idx;
5840 } else {
5841 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5842 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5843 }
1c0c7074
AN
5844 insn[1].imm = ext->kcfg.data_off;
5845 } else /* EXT_KSYM */ {
2211c825 5846 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
d370bbe1 5847 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
284d2587
AN
5848 insn[0].imm = ext->ksym.kernel_btf_id;
5849 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
2211c825 5850 } else { /* typeless ksyms or unresolved typed ksyms */
d370bbe1
HL
5851 insn[0].imm = (__u32)ext->ksym.addr;
5852 insn[1].imm = ext->ksym.addr >> 32;
5853 }
1c0c7074 5854 }
166750bc 5855 break;
5bd022ec
MKL
5856 case RELO_EXTERN_FUNC:
5857 ext = &obj->externs[relo->sym_off];
5858 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
466b2e13
KKD
5859 if (ext->is_set) {
5860 insn[0].imm = ext->ksym.kernel_btf_id;
5861 insn[0].off = ext->ksym.btf_fd_idx;
5862 } else { /* unresolved weak kfunc */
5863 insn[0].imm = 0;
5864 insn[0].off = 0;
5865 }
5bd022ec 5866 break;
53eddb5e 5867 case RELO_SUBPROG_ADDR:
b1268826
AS
5868 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5869 pr_warn("prog '%s': relo #%d: bad insn\n",
5870 prog->name, i);
5871 return -EINVAL;
5872 }
5873 /* handled already */
53eddb5e 5874 break;
166750bc 5875 case RELO_CALL:
b1268826 5876 /* handled already */
166750bc 5877 break;
d0e92887
AS
5878 case RELO_CORE:
5879 /* will be handled by bpf_program_record_relos() */
5880 break;
166750bc 5881 default:
9c0f8cbd
AN
5882 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5883 prog->name, i, relo->type);
166750bc 5884 return -EINVAL;
8a47a6c5 5885 }
8a47a6c5
WN
5886 }
5887
c3c55696
AN
5888 return 0;
5889}
5890
8505e870
AN
5891static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5892 const struct bpf_program *prog,
5893 const struct btf_ext_info *ext_info,
5894 void **prog_info, __u32 *prog_rec_cnt,
5895 __u32 *prog_rec_sz)
5896{
5897 void *copy_start = NULL, *copy_end = NULL;
5898 void *rec, *rec_end, *new_prog_info;
5899 const struct btf_ext_info_sec *sec;
5900 size_t old_sz, new_sz;
11d5daa8 5901 int i, sec_num, sec_idx, off_adj;
8505e870 5902
11d5daa8 5903 sec_num = 0;
8505e870 5904 for_each_btf_ext_sec(ext_info, sec) {
11d5daa8
AN
5905 sec_idx = ext_info->sec_idxs[sec_num];
5906 sec_num++;
5907 if (prog->sec_idx != sec_idx)
8505e870
AN
5908 continue;
5909
5910 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5911 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5912
5913 if (insn_off < prog->sec_insn_off)
5914 continue;
5915 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5916 break;
5917
5918 if (!copy_start)
5919 copy_start = rec;
5920 copy_end = rec + ext_info->rec_size;
5921 }
5922
5923 if (!copy_start)
5924 return -ENOENT;
5925
5926 /* append func/line info of a given (sub-)program to the main
5927 * program func/line info
5928 */
8eb62958 5929 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
8505e870
AN
5930 new_sz = old_sz + (copy_end - copy_start);
5931 new_prog_info = realloc(*prog_info, new_sz);
5932 if (!new_prog_info)
5933 return -ENOMEM;
5934 *prog_info = new_prog_info;
5935 *prog_rec_cnt = new_sz / ext_info->rec_size;
5936 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5937
5938 /* Kernel instruction offsets are in units of 8-byte
5939 * instructions, while .BTF.ext instruction offsets generated
5940 * by Clang are in units of bytes. So convert Clang offsets
5941 * into kernel offsets and adjust offset according to program
5942 * relocated position.
5943 */
5944 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5945 rec = new_prog_info + old_sz;
5946 rec_end = new_prog_info + new_sz;
5947 for (; rec < rec_end; rec += ext_info->rec_size) {
5948 __u32 *insn_off = rec;
5949
5950 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5951 }
5952 *prog_rec_sz = ext_info->rec_size;
5953 return 0;
5954 }
5955
5956 return -ENOENT;
5957}
5958
5959static int
5960reloc_prog_func_and_line_info(const struct bpf_object *obj,
5961 struct bpf_program *main_prog,
5962 const struct bpf_program *prog)
5963{
5964 int err;
5965
5966 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5967 * supprot func/line info
5968 */
9ca1f56a 5969 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
8505e870
AN
5970 return 0;
5971
5972 /* only attempt func info relocation if main program's func_info
5973 * relocation was successful
5974 */
5975 if (main_prog != prog && !main_prog->func_info)
5976 goto line_info;
5977
5978 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5979 &main_prog->func_info,
5980 &main_prog->func_info_cnt,
5981 &main_prog->func_info_rec_size);
5982 if (err) {
5983 if (err != -ENOENT) {
5984 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5985 prog->name, err);
5986 return err;
5987 }
5988 if (main_prog->func_info) {
5989 /*
5990 * Some info has already been found but has problem
5991 * in the last btf_ext reloc. Must have to error out.
5992 */
5993 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5994 return err;
5995 }
5996 /* Have problem loading the very first info. Ignore the rest. */
5997 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5998 prog->name);
5999 }
6000
6001line_info:
6002 /* don't relocate line info if main program's relocation failed */
6003 if (main_prog != prog && !main_prog->line_info)
6004 return 0;
6005
6006 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6007 &main_prog->line_info,
6008 &main_prog->line_info_cnt,
6009 &main_prog->line_info_rec_size);
6010 if (err) {
6011 if (err != -ENOENT) {
6012 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6013 prog->name, err);
6014 return err;
6015 }
6016 if (main_prog->line_info) {
6017 /*
6018 * Some info has already been found but has problem
6019 * in the last btf_ext reloc. Must have to error out.
6020 */
6021 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6022 return err;
6023 }
6024 /* Have problem loading the very first info. Ignore the rest. */
6025 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6026 prog->name);
6027 }
6028 return 0;
6029}
6030
c3c55696
AN
6031static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6032{
6033 size_t insn_idx = *(const size_t *)key;
6034 const struct reloc_desc *relo = elem;
6035
6036 if (insn_idx == relo->insn_idx)
6037 return 0;
6038 return insn_idx < relo->insn_idx ? -1 : 1;
6039}
6040
6041static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6042{
2a6a9bf2
AN
6043 if (!prog->nr_reloc)
6044 return NULL;
c3c55696
AN
6045 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6046 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6047}
6048
b1268826
AS
6049static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6050{
6051 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6052 struct reloc_desc *relos;
6053 int i;
6054
6055 if (main_prog == subprog)
6056 return 0;
6057 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6058 if (!relos)
6059 return -ENOMEM;
2a6a9bf2
AN
6060 if (subprog->nr_reloc)
6061 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6062 sizeof(*relos) * subprog->nr_reloc);
b1268826
AS
6063
6064 for (i = main_prog->nr_reloc; i < new_cnt; i++)
6065 relos[i].insn_idx += subprog->sub_insn_off;
6066 /* After insn_idx adjustment the 'relos' array is still sorted
6067 * by insn_idx and doesn't break bsearch.
6068 */
6069 main_prog->reloc_desc = relos;
6070 main_prog->nr_reloc = new_cnt;
6071 return 0;
6072}
6073
c3c55696
AN
6074static int
6075bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6076 struct bpf_program *prog)
6077{
6078 size_t sub_insn_idx, insn_idx, new_cnt;
6079 struct bpf_program *subprog;
6080 struct bpf_insn *insns, *insn;
6081 struct reloc_desc *relo;
6082 int err;
6083
6084 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6085 if (err)
6086 return err;
6087
6088 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6089 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
53eddb5e 6090 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
c3c55696
AN
6091 continue;
6092
6093 relo = find_prog_insn_relo(prog, insn_idx);
b1268826
AS
6094 if (relo && relo->type == RELO_EXTERN_FUNC)
6095 /* kfunc relocations will be handled later
6096 * in bpf_object__relocate_data()
6097 */
6098 continue;
53eddb5e 6099 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
c3c55696
AN
6100 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6101 prog->name, insn_idx, relo->type);
6102 return -LIBBPF_ERRNO__RELOC;
6103 }
6104 if (relo) {
6105 /* sub-program instruction index is a combination of
6106 * an offset of a symbol pointed to by relocation and
6107 * call instruction's imm field; for global functions,
6108 * call always has imm = -1, but for static functions
6109 * relocation is against STT_SECTION and insn->imm
6110 * points to a start of a static function
53eddb5e
YS
6111 *
6112 * for subprog addr relocation, the relo->sym_off + insn->imm is
6113 * the byte offset in the corresponding section.
c3c55696 6114 */
53eddb5e
YS
6115 if (relo->type == RELO_CALL)
6116 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6117 else
6118 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6119 } else if (insn_is_pseudo_func(insn)) {
6120 /*
6121 * RELO_SUBPROG_ADDR relo is always emitted even if both
6122 * functions are in the same section, so it shouldn't reach here.
6123 */
6124 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6125 prog->name, insn_idx);
6126 return -LIBBPF_ERRNO__RELOC;
c3c55696
AN
6127 } else {
6128 /* if subprogram call is to a static function within
6129 * the same ELF section, there won't be any relocation
6130 * emitted, but it also means there is no additional
6131 * offset necessary, insns->imm is relative to
6132 * instruction's original position within the section
6133 */
6134 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6135 }
6136
6137 /* we enforce that sub-programs should be in .text section */
6138 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6139 if (!subprog) {
6140 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6141 prog->name);
6142 return -LIBBPF_ERRNO__RELOC;
6143 }
6144
6145 /* if it's the first call instruction calling into this
6146 * subprogram (meaning this subprog hasn't been processed
6147 * yet) within the context of current main program:
6148 * - append it at the end of main program's instructions blog;
6149 * - process is recursively, while current program is put on hold;
6150 * - if that subprogram calls some other not yet processes
6151 * subprogram, same thing will happen recursively until
6152 * there are no more unprocesses subprograms left to append
6153 * and relocate.
6154 */
6155 if (subprog->sub_insn_off == 0) {
6156 subprog->sub_insn_off = main_prog->insns_cnt;
6157
6158 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6159 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6160 if (!insns) {
6161 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6162 return -ENOMEM;
6163 }
6164 main_prog->insns = insns;
6165 main_prog->insns_cnt = new_cnt;
6166
6167 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6168 subprog->insns_cnt * sizeof(*insns));
6169
6170 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6171 main_prog->name, subprog->insns_cnt, subprog->name);
6172
b1268826
AS
6173 /* The subprog insns are now appended. Append its relos too. */
6174 err = append_subprog_relos(main_prog, subprog);
6175 if (err)
6176 return err;
c3c55696
AN
6177 err = bpf_object__reloc_code(obj, main_prog, subprog);
6178 if (err)
6179 return err;
6180 }
6181
6182 /* main_prog->insns memory could have been re-allocated, so
6183 * calculate pointer again
6184 */
6185 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6186 /* calculate correct instruction position within current main
6187 * prog; each main prog can have a different set of
6188 * subprograms appended (potentially in different order as
6189 * well), so position of any subprog can be different for
6190 * different main programs */
6191 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6192
c3c55696
AN
6193 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6194 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6195 }
6196
6197 return 0;
6198}
6199
6200/*
6201 * Relocate sub-program calls.
6202 *
6203 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6204 * main prog) is processed separately. For each subprog (non-entry functions,
6205 * that can be called from either entry progs or other subprogs) gets their
6206 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6207 * hasn't been yet appended and relocated within current main prog. Once its
6208 * relocated, sub_insn_off will point at the position within current main prog
6209 * where given subprog was appended. This will further be used to relocate all
6210 * the call instructions jumping into this subprog.
6211 *
6212 * We start with main program and process all call instructions. If the call
6213 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6214 * is zero), subprog instructions are appended at the end of main program's
6215 * instruction array. Then main program is "put on hold" while we recursively
6216 * process newly appended subprogram. If that subprogram calls into another
6217 * subprogram that hasn't been appended, new subprogram is appended again to
6218 * the *main* prog's instructions (subprog's instructions are always left
6219 * untouched, as they need to be in unmodified state for subsequent main progs
6220 * and subprog instructions are always sent only as part of a main prog) and
6221 * the process continues recursively. Once all the subprogs called from a main
6222 * prog or any of its subprogs are appended (and relocated), all their
6223 * positions within finalized instructions array are known, so it's easy to
6224 * rewrite call instructions with correct relative offsets, corresponding to
6225 * desired target subprog.
6226 *
6227 * Its important to realize that some subprogs might not be called from some
6228 * main prog and any of its called/used subprogs. Those will keep their
6229 * subprog->sub_insn_off as zero at all times and won't be appended to current
6230 * main prog and won't be relocated within the context of current main prog.
6231 * They might still be used from other main progs later.
6232 *
6233 * Visually this process can be shown as below. Suppose we have two main
6234 * programs mainA and mainB and BPF object contains three subprogs: subA,
6235 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6236 * subC both call subB:
6237 *
6238 * +--------+ +-------+
6239 * | v v |
6240 * +--+---+ +--+-+-+ +---+--+
6241 * | subA | | subB | | subC |
6242 * +--+---+ +------+ +---+--+
6243 * ^ ^
6244 * | |
6245 * +---+-------+ +------+----+
6246 * | mainA | | mainB |
6247 * +-----------+ +-----------+
6248 *
6249 * We'll start relocating mainA, will find subA, append it and start
6250 * processing sub A recursively:
6251 *
6252 * +-----------+------+
6253 * | mainA | subA |
6254 * +-----------+------+
6255 *
6256 * At this point we notice that subB is used from subA, so we append it and
6257 * relocate (there are no further subcalls from subB):
6258 *
6259 * +-----------+------+------+
6260 * | mainA | subA | subB |
6261 * +-----------+------+------+
6262 *
6263 * At this point, we relocate subA calls, then go one level up and finish with
6264 * relocatin mainA calls. mainA is done.
6265 *
6266 * For mainB process is similar but results in different order. We start with
6267 * mainB and skip subA and subB, as mainB never calls them (at least
6268 * directly), but we see subC is needed, so we append and start processing it:
6269 *
6270 * +-----------+------+
6271 * | mainB | subC |
6272 * +-----------+------+
6273 * Now we see subC needs subB, so we go back to it, append and relocate it:
6274 *
6275 * +-----------+------+------+
6276 * | mainB | subC | subB |
6277 * +-----------+------+------+
6278 *
6279 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6280 */
6281static int
6282bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6283{
6284 struct bpf_program *subprog;
d3d93e34 6285 int i, err;
c3c55696 6286
c3c55696
AN
6287 /* mark all subprogs as not relocated (yet) within the context of
6288 * current main program
6289 */
6290 for (i = 0; i < obj->nr_programs; i++) {
6291 subprog = &obj->programs[i];
6292 if (!prog_is_subprog(obj, subprog))
6293 continue;
6294
6295 subprog->sub_insn_off = 0;
c3c55696
AN
6296 }
6297
6298 err = bpf_object__reloc_code(obj, prog, prog);
6299 if (err)
6300 return err;
6301
6302
8a47a6c5
WN
6303 return 0;
6304}
6305
67234743
AS
6306static void
6307bpf_object__free_relocs(struct bpf_object *obj)
6308{
6309 struct bpf_program *prog;
6310 int i;
6311
6312 /* free up relocation descriptors */
6313 for (i = 0; i < obj->nr_programs; i++) {
6314 prog = &obj->programs[i];
6315 zfree(&prog->reloc_desc);
6316 prog->nr_reloc = 0;
6317 }
6318}
6319
d0e92887
AS
6320static int cmp_relocs(const void *_a, const void *_b)
6321{
6322 const struct reloc_desc *a = _a;
6323 const struct reloc_desc *b = _b;
6324
6325 if (a->insn_idx != b->insn_idx)
6326 return a->insn_idx < b->insn_idx ? -1 : 1;
6327
6328 /* no two relocations should have the same insn_idx, but ... */
6329 if (a->type != b->type)
6330 return a->type < b->type ? -1 : 1;
6331
6332 return 0;
6333}
6334
6335static void bpf_object__sort_relos(struct bpf_object *obj)
6336{
6337 int i;
6338
6339 for (i = 0; i < obj->nr_programs; i++) {
6340 struct bpf_program *p = &obj->programs[i];
6341
6342 if (!p->nr_reloc)
6343 continue;
6344
6345 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6346 }
6347}
6348
8a47a6c5 6349static int
ddc7c304 6350bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
8a47a6c5
WN
6351{
6352 struct bpf_program *prog;
b1268826 6353 size_t i, j;
8a47a6c5
WN
6354 int err;
6355
ddc7c304
AN
6356 if (obj->btf_ext) {
6357 err = bpf_object__relocate_core(obj, targ_btf_path);
6358 if (err) {
be18010e
KW
6359 pr_warn("failed to perform CO-RE relocations: %d\n",
6360 err);
ddc7c304
AN
6361 return err;
6362 }
d0e92887
AS
6363 if (obj->gen_loader)
6364 bpf_object__sort_relos(obj);
ddc7c304 6365 }
b1268826
AS
6366
6367 /* Before relocating calls pre-process relocations and mark
6368 * few ld_imm64 instructions that points to subprogs.
6369 * Otherwise bpf_object__reloc_code() later would have to consider
6370 * all ld_imm64 insns as relocation candidates. That would
6371 * reduce relocation speed, since amount of find_prog_insn_relo()
6372 * would increase and most of them will fail to find a relo.
9173cac3
AN
6373 */
6374 for (i = 0; i < obj->nr_programs; i++) {
6375 prog = &obj->programs[i];
b1268826
AS
6376 for (j = 0; j < prog->nr_reloc; j++) {
6377 struct reloc_desc *relo = &prog->reloc_desc[j];
6378 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6379
6380 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6381 if (relo->type == RELO_SUBPROG_ADDR)
6382 insn[0].src_reg = BPF_PSEUDO_FUNC;
9173cac3 6383 }
9173cac3 6384 }
b1268826
AS
6385
6386 /* relocate subprogram calls and append used subprograms to main
c3c55696
AN
6387 * programs; each copy of subprogram code needs to be relocated
6388 * differently for each main program, because its code location might
b1268826
AS
6389 * have changed.
6390 * Append subprog relos to main programs to allow data relos to be
6391 * processed after text is completely relocated.
9173cac3 6392 */
8a47a6c5
WN
6393 for (i = 0; i < obj->nr_programs; i++) {
6394 prog = &obj->programs[i];
c3c55696
AN
6395 /* sub-program's sub-calls are relocated within the context of
6396 * its main program only
6397 */
6398 if (prog_is_subprog(obj, prog))
9173cac3 6399 continue;
a3820c48 6400 if (!prog->autoload)
16e0c35c 6401 continue;
8a47a6c5 6402
c3c55696 6403 err = bpf_object__relocate_calls(obj, prog);
8a47a6c5 6404 if (err) {
9c0f8cbd
AN
6405 pr_warn("prog '%s': failed to relocate calls: %d\n",
6406 prog->name, err);
8a47a6c5
WN
6407 return err;
6408 }
6409 }
b1268826
AS
6410 /* Process data relos for main programs */
6411 for (i = 0; i < obj->nr_programs; i++) {
6412 prog = &obj->programs[i];
6413 if (prog_is_subprog(obj, prog))
6414 continue;
a3820c48 6415 if (!prog->autoload)
16e0c35c 6416 continue;
b1268826
AS
6417 err = bpf_object__relocate_data(obj, prog);
6418 if (err) {
6419 pr_warn("prog '%s': failed to relocate data references: %d\n",
6420 prog->name, err);
6421 return err;
6422 }
6423 }
67234743
AS
6424 if (!obj->gen_loader)
6425 bpf_object__free_relocs(obj);
8a47a6c5
WN
6426 return 0;
6427}
6428
646f02ff 6429static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 6430 Elf64_Shdr *shdr, Elf_Data *data);
646f02ff
AN
6431
6432static int bpf_object__collect_map_relos(struct bpf_object *obj,
ad23b723 6433 Elf64_Shdr *shdr, Elf_Data *data)
646f02ff 6434{
15728ad3
AN
6435 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6436 int i, j, nrels, new_sz;
063e6881 6437 const struct btf_var_secinfo *vi = NULL;
646f02ff 6438 const struct btf_type *sec, *var, *def;
341ac5ff
HC
6439 struct bpf_map *map = NULL, *targ_map = NULL;
6440 struct bpf_program *targ_prog = NULL;
6441 bool is_prog_array, is_map_in_map;
646f02ff 6442 const struct btf_member *member;
341ac5ff 6443 const char *name, *mname, *type;
646f02ff 6444 unsigned int moff;
ad23b723
AN
6445 Elf64_Sym *sym;
6446 Elf64_Rel *rel;
646f02ff
AN
6447 void *tmp;
6448
6449 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6450 return -EINVAL;
6451 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6452 if (!sec)
6453 return -EINVAL;
6454
646f02ff
AN
6455 nrels = shdr->sh_size / shdr->sh_entsize;
6456 for (i = 0; i < nrels; i++) {
ad23b723
AN
6457 rel = elf_rel_by_idx(data, i);
6458 if (!rel) {
646f02ff
AN
6459 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6460 return -LIBBPF_ERRNO__FORMAT;
6461 }
ad23b723
AN
6462
6463 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6464 if (!sym) {
646f02ff 6465 pr_warn(".maps relo #%d: symbol %zx not found\n",
ad23b723 6466 i, (size_t)ELF64_R_SYM(rel->r_info));
646f02ff
AN
6467 return -LIBBPF_ERRNO__FORMAT;
6468 }
ad23b723 6469 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
646f02ff 6470
ad23b723
AN
6471 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6472 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6473 (size_t)rel->r_offset, sym->st_name, name);
646f02ff
AN
6474
6475 for (j = 0; j < obj->nr_maps; j++) {
6476 map = &obj->maps[j];
6477 if (map->sec_idx != obj->efile.btf_maps_shndx)
6478 continue;
6479
6480 vi = btf_var_secinfos(sec) + map->btf_var_idx;
ad23b723
AN
6481 if (vi->offset <= rel->r_offset &&
6482 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
646f02ff
AN
6483 break;
6484 }
6485 if (j == obj->nr_maps) {
ad23b723
AN
6486 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6487 i, name, (size_t)rel->r_offset);
646f02ff
AN
6488 return -EINVAL;
6489 }
6490
341ac5ff
HC
6491 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6492 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6493 type = is_map_in_map ? "map" : "prog";
6494 if (is_map_in_map) {
6495 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6496 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6497 i, name);
6498 return -LIBBPF_ERRNO__RELOC;
6499 }
6500 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6501 map->def.key_size != sizeof(int)) {
6502 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6503 i, map->name, sizeof(int));
6504 return -EINVAL;
6505 }
6506 targ_map = bpf_object__find_map_by_name(obj, name);
6507 if (!targ_map) {
6508 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6509 i, name);
6510 return -ESRCH;
6511 }
6512 } else if (is_prog_array) {
6513 targ_prog = bpf_object__find_program_by_name(obj, name);
6514 if (!targ_prog) {
6515 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6516 i, name);
6517 return -ESRCH;
6518 }
6519 if (targ_prog->sec_idx != sym->st_shndx ||
6520 targ_prog->sec_insn_off * 8 != sym->st_value ||
6521 prog_is_subprog(obj, targ_prog)) {
6522 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6523 i, name);
6524 return -LIBBPF_ERRNO__RELOC;
6525 }
6526 } else {
646f02ff
AN
6527 return -EINVAL;
6528 }
6529
646f02ff
AN
6530 var = btf__type_by_id(obj->btf, vi->type);
6531 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6532 if (btf_vlen(def) == 0)
6533 return -EINVAL;
6534 member = btf_members(def) + btf_vlen(def) - 1;
6535 mname = btf__name_by_offset(obj->btf, member->name_off);
6536 if (strcmp(mname, "values"))
6537 return -EINVAL;
6538
6539 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
ad23b723 6540 if (rel->r_offset - vi->offset < moff)
646f02ff
AN
6541 return -EINVAL;
6542
ad23b723 6543 moff = rel->r_offset - vi->offset - moff;
15728ad3
AN
6544 /* here we use BPF pointer size, which is always 64 bit, as we
6545 * are parsing ELF that was built for BPF target
6546 */
6547 if (moff % bpf_ptr_sz)
646f02ff 6548 return -EINVAL;
15728ad3 6549 moff /= bpf_ptr_sz;
646f02ff
AN
6550 if (moff >= map->init_slots_sz) {
6551 new_sz = moff + 1;
029258d7 6552 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
646f02ff
AN
6553 if (!tmp)
6554 return -ENOMEM;
6555 map->init_slots = tmp;
6556 memset(map->init_slots + map->init_slots_sz, 0,
15728ad3 6557 (new_sz - map->init_slots_sz) * host_ptr_sz);
646f02ff
AN
6558 map->init_slots_sz = new_sz;
6559 }
341ac5ff 6560 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
646f02ff 6561
341ac5ff
HC
6562 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6563 i, map->name, moff, type, name);
646f02ff
AN
6564 }
6565
6566 return 0;
6567}
590a0088 6568
c3c55696
AN
6569static int bpf_object__collect_relos(struct bpf_object *obj)
6570{
6571 int i, err;
34090915 6572
25bbbd7a
AN
6573 for (i = 0; i < obj->efile.sec_cnt; i++) {
6574 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6575 Elf64_Shdr *shdr;
6576 Elf_Data *data;
6577 int idx;
6578
6579 if (sec_desc->sec_type != SEC_RELO)
6580 continue;
6581
6582 shdr = sec_desc->shdr;
6583 data = sec_desc->data;
6584 idx = shdr->sh_info;
34090915
WN
6585
6586 if (shdr->sh_type != SHT_REL) {
be18010e 6587 pr_warn("internal error at %d\n", __LINE__);
6371ca3b 6588 return -LIBBPF_ERRNO__INTERNAL;
34090915
WN
6589 }
6590
c3c55696 6591 if (idx == obj->efile.st_ops_shndx)
646f02ff 6592 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
c3c55696 6593 else if (idx == obj->efile.btf_maps_shndx)
646f02ff 6594 err = bpf_object__collect_map_relos(obj, shdr, data);
c3c55696
AN
6595 else
6596 err = bpf_object__collect_prog_relos(obj, shdr, data);
34090915 6597 if (err)
6371ca3b 6598 return err;
34090915 6599 }
c3c55696 6600
d0e92887 6601 bpf_object__sort_relos(obj);
34090915
WN
6602 return 0;
6603}
6604
109cea5a
AN
6605static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6606{
9b2f6fec 6607 if (BPF_CLASS(insn->code) == BPF_JMP &&
109cea5a
AN
6608 BPF_OP(insn->code) == BPF_CALL &&
6609 BPF_SRC(insn->code) == BPF_K &&
9b2f6fec
AN
6610 insn->src_reg == 0 &&
6611 insn->dst_reg == 0) {
6612 *func_id = insn->imm;
109cea5a
AN
6613 return true;
6614 }
6615 return false;
6616}
6617
42869d28 6618static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
109cea5a
AN
6619{
6620 struct bpf_insn *insn = prog->insns;
6621 enum bpf_func_id func_id;
6622 int i;
6623
67234743
AS
6624 if (obj->gen_loader)
6625 return 0;
6626
109cea5a
AN
6627 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6628 if (!insn_is_helper_call(insn, &func_id))
6629 continue;
6630
6631 /* on kernels that don't yet support
6632 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6633 * to bpf_probe_read() which works well for old kernels
6634 */
6635 switch (func_id) {
6636 case BPF_FUNC_probe_read_kernel:
6637 case BPF_FUNC_probe_read_user:
9ca1f56a 6638 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6639 insn->imm = BPF_FUNC_probe_read;
6640 break;
6641 case BPF_FUNC_probe_read_kernel_str:
6642 case BPF_FUNC_probe_read_user_str:
9ca1f56a 6643 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6644 insn->imm = BPF_FUNC_probe_read_str;
6645 break;
6646 default:
6647 break;
6648 }
6649 }
6650 return 0;
6651}
6652
15ea31fa
AN
6653static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6654 int *btf_obj_fd, int *btf_type_id);
12d9466d 6655
4fa5bcfe
AN
6656/* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6657static int libbpf_prepare_prog_load(struct bpf_program *prog,
6658 struct bpf_prog_load_opts *opts, long cookie)
12d9466d 6659{
15ea31fa
AN
6660 enum sec_def_flags def = cookie;
6661
12d9466d 6662 /* old kernels might not support specifying expected_attach_type */
15ea31fa 6663 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
d10ef2b8 6664 opts->expected_attach_type = 0;
12d9466d 6665
15ea31fa 6666 if (def & SEC_SLEEPABLE)
d10ef2b8 6667 opts->prog_flags |= BPF_F_SLEEPABLE;
12d9466d 6668
082c4bfb
LB
6669 if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6670 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6671
4a4d4cee
LB
6672 if (def & SEC_DEPRECATED)
6673 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",
6674 prog->sec_name);
6675
12d9466d
AN
6676 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6677 prog->type == BPF_PROG_TYPE_LSM ||
6678 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6679 int btf_obj_fd = 0, btf_type_id = 0, err;
15ea31fa 6680 const char *attach_name;
12d9466d 6681
15ea31fa
AN
6682 attach_name = strchr(prog->sec_name, '/') + 1;
6683 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
12d9466d
AN
6684 if (err)
6685 return err;
6686
6687 /* cache resolved BTF FD and BTF type ID in the prog */
6688 prog->attach_btf_obj_fd = btf_obj_fd;
6689 prog->attach_btf_id = btf_type_id;
6690
6691 /* but by now libbpf common logic is not utilizing
6692 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
d10ef2b8
AN
6693 * this callback is called after opts were populated by
6694 * libbpf, so this callback has to update opts explicitly here
12d9466d 6695 */
d10ef2b8
AN
6696 opts->attach_btf_obj_fd = btf_obj_fd;
6697 opts->attach_btf_id = btf_type_id;
12d9466d
AN
6698 }
6699 return 0;
6700}
6701
be2f2d16
AN
6702static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6703 struct bpf_insn *insns, int insns_cnt,
6704 const char *license, __u32 kern_version,
6705 int *prog_fd)
55cffde2 6706{
d10ef2b8
AN
6707 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6708 const char *prog_name = NULL;
1ce6a9fc 6709 char *cp, errmsg[STRERR_BUFSIZE];
8395f320 6710 size_t log_buf_size = 0;
b3ce9079 6711 char *log_buf = NULL, *tmp;
12d9466d 6712 int btf_fd, ret, err;
b3ce9079
AN
6713 bool own_log_buf = true;
6714 __u32 log_level = prog->log_level;
55cffde2 6715
80b2b5c3
AM
6716 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6717 /*
6718 * The program type must be set. Most likely we couldn't find a proper
6719 * section definition at load time, and thus we didn't infer the type.
6720 */
6721 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6722 prog->name, prog->sec_name);
6723 return -EINVAL;
6724 }
6725
fba01a06
AN
6726 if (!insns || !insns_cnt)
6727 return -EINVAL;
6728
12d9466d 6729 load_attr.expected_attach_type = prog->expected_attach_type;
25bbbd7a 6730 if (kernel_supports(obj, FEAT_PROG_NAME))
d10ef2b8 6731 prog_name = prog->name;
12d9466d
AN
6732 load_attr.attach_prog_fd = prog->attach_prog_fd;
6733 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6aef10a4
AN
6734 load_attr.attach_btf_id = prog->attach_btf_id;
6735 load_attr.kern_version = kern_version;
6736 load_attr.prog_ifindex = prog->prog_ifindex;
6737
0f0e55d8 6738 /* specify func_info/line_info only if kernel supports them */
25bbbd7a
AN
6739 btf_fd = bpf_object__btf_fd(obj);
6740 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
0f0e55d8
AN
6741 load_attr.prog_btf_fd = btf_fd;
6742 load_attr.func_info = prog->func_info;
6743 load_attr.func_info_rec_size = prog->func_info_rec_size;
6744 load_attr.func_info_cnt = prog->func_info_cnt;
6745 load_attr.line_info = prog->line_info;
6746 load_attr.line_info_rec_size = prog->line_info_rec_size;
6747 load_attr.line_info_cnt = prog->line_info_cnt;
6748 }
b3ce9079 6749 load_attr.log_level = log_level;
04656198 6750 load_attr.prog_flags = prog->prog_flags;
25bbbd7a 6751 load_attr.fd_array = obj->fd_array;
55cffde2 6752
12d9466d 6753 /* adjust load_attr if sec_def provides custom preload callback */
4fa5bcfe
AN
6754 if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6755 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
12d9466d
AN
6756 if (err < 0) {
6757 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6758 prog->name, err);
6759 return err;
6760 }
6761 }
6762
25bbbd7a 6763 if (obj->gen_loader) {
d10ef2b8
AN
6764 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6765 license, insns, insns_cnt, &load_attr,
25bbbd7a 6766 prog - obj->programs);
be2f2d16 6767 *prog_fd = -1;
67234743
AS
6768 return 0;
6769 }
8395f320 6770
b3ce9079
AN
6771retry_load:
6772 /* if log_level is zero, we don't request logs initiallly even if
6773 * custom log_buf is specified; if the program load fails, then we'll
6774 * bump log_level to 1 and use either custom log_buf or we'll allocate
6775 * our own and retry the load to get details on what failed
6776 */
6777 if (log_level) {
6778 if (prog->log_buf) {
6779 log_buf = prog->log_buf;
6780 log_buf_size = prog->log_size;
6781 own_log_buf = false;
6782 } else if (obj->log_buf) {
6783 log_buf = obj->log_buf;
6784 log_buf_size = obj->log_size;
6785 own_log_buf = false;
6786 } else {
6787 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6788 tmp = realloc(log_buf, log_buf_size);
6789 if (!tmp) {
6790 ret = -ENOMEM;
6791 goto out;
6792 }
6793 log_buf = tmp;
6794 log_buf[0] = '\0';
6795 own_log_buf = true;
6796 }
8395f320 6797 }
55cffde2 6798
6aef10a4 6799 load_attr.log_buf = log_buf;
d10ef2b8 6800 load_attr.log_size = log_buf_size;
b3ce9079 6801 load_attr.log_level = log_level;
55cffde2 6802
b3ce9079 6803 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
55cffde2 6804 if (ret >= 0) {
b3ce9079 6805 if (log_level && own_log_buf) {
ad9a7f96
AN
6806 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6807 prog->name, log_buf);
6808 }
5d23328d 6809
25bbbd7a
AN
6810 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6811 struct bpf_map *map;
6812 int i;
6813
6814 for (i = 0; i < obj->nr_maps; i++) {
6815 map = &prog->obj->maps[i];
6816 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6817 continue;
5d23328d 6818
25bbbd7a
AN
6819 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6820 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96
AN
6821 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6822 prog->name, map->real_name, cp);
25bbbd7a
AN
6823 /* Don't fail hard if can't bind rodata. */
6824 }
5d23328d
YZ
6825 }
6826 }
6827
be2f2d16 6828 *prog_fd = ret;
55cffde2
WN
6829 ret = 0;
6830 goto out;
6831 }
6832
b3ce9079
AN
6833 if (log_level == 0) {
6834 log_level = 1;
da11b417
AS
6835 goto retry_load;
6836 }
b3ce9079
AN
6837 /* On ENOSPC, increase log buffer size and retry, unless custom
6838 * log_buf is specified.
6839 * Be careful to not overflow u32, though. Kernel's log buf size limit
6840 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6841 * multiply by 2 unless we are sure we'll fit within 32 bits.
6842 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6843 */
6844 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6845 goto retry_load;
2eda2145
AN
6846
6847 ret = -errno;
24d6a808 6848 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96 6849 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
dc3a2d25 6850 pr_perm_msg(ret);
55cffde2 6851
b3ce9079 6852 if (own_log_buf && log_buf && log_buf[0] != '\0') {
ad9a7f96
AN
6853 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6854 prog->name, log_buf);
6855 }
55cffde2
WN
6856
6857out:
b3ce9079
AN
6858 if (own_log_buf)
6859 free(log_buf);
55cffde2
WN
6860 return ret;
6861}
6862
d0e92887 6863static int bpf_program_record_relos(struct bpf_program *prog)
67234743
AS
6864{
6865 struct bpf_object *obj = prog->obj;
6866 int i;
6867
6868 for (i = 0; i < prog->nr_reloc; i++) {
6869 struct reloc_desc *relo = &prog->reloc_desc[i];
6870 struct extern_desc *ext = &obj->externs[relo->sym_off];
6871
6872 switch (relo->type) {
6873 case RELO_EXTERN_VAR:
6874 if (ext->type != EXT_KSYM)
6875 continue;
c24941cd
KKD
6876 bpf_gen__record_extern(obj->gen_loader, ext->name,
6877 ext->is_weak, !ext->ksym.type_id,
18f4fccb 6878 BTF_KIND_VAR, relo->insn_idx);
67234743
AS
6879 break;
6880 case RELO_EXTERN_FUNC:
c24941cd
KKD
6881 bpf_gen__record_extern(obj->gen_loader, ext->name,
6882 ext->is_weak, false, BTF_KIND_FUNC,
67234743
AS
6883 relo->insn_idx);
6884 break;
d0e92887
AS
6885 case RELO_CORE: {
6886 struct bpf_core_relo cr = {
6887 .insn_off = relo->insn_idx * 8,
6888 .type_id = relo->core_relo->type_id,
6889 .access_str_off = relo->core_relo->access_str_off,
6890 .kind = relo->core_relo->kind,
6891 };
6892
6893 bpf_gen__record_relo_core(obj->gen_loader, &cr);
6894 break;
6895 }
67234743
AS
6896 default:
6897 continue;
6898 }
6899 }
6900 return 0;
6901}
6902
be2f2d16
AN
6903static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6904 const char *license, __u32 kern_ver)
55cffde2 6905{
91abb4a6 6906 int err = 0, fd, i;
13acb508 6907
be2f2d16 6908 if (obj->loaded) {
52109584 6909 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
e9fc3ce9 6910 return libbpf_err(-EINVAL);
d9297581
AN
6911 }
6912
b580563e
WN
6913 if (prog->instances.nr < 0 || !prog->instances.fds) {
6914 if (prog->preprocessor) {
be18010e 6915 pr_warn("Internal error: can't load program '%s'\n",
52109584 6916 prog->name);
e9fc3ce9 6917 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
b580563e 6918 }
55cffde2 6919
b580563e
WN
6920 prog->instances.fds = malloc(sizeof(int));
6921 if (!prog->instances.fds) {
be18010e 6922 pr_warn("Not enough memory for BPF fds\n");
e9fc3ce9 6923 return libbpf_err(-ENOMEM);
b580563e
WN
6924 }
6925 prog->instances.nr = 1;
6926 prog->instances.fds[0] = -1;
6927 }
6928
6929 if (!prog->preprocessor) {
6930 if (prog->instances.nr != 1) {
52109584
AN
6931 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6932 prog->name, prog->instances.nr);
b580563e 6933 }
be2f2d16 6934 if (obj->gen_loader)
d0e92887 6935 bpf_program_record_relos(prog);
be2f2d16
AN
6936 err = bpf_object_load_prog_instance(obj, prog,
6937 prog->insns, prog->insns_cnt,
6938 license, kern_ver, &fd);
b580563e
WN
6939 if (!err)
6940 prog->instances.fds[0] = fd;
6941 goto out;
6942 }
6943
6944 for (i = 0; i < prog->instances.nr; i++) {
6945 struct bpf_prog_prep_result result;
6946 bpf_program_prep_t preprocessor = prog->preprocessor;
6947
1ad9cbb8 6948 memset(&result, 0, sizeof(result));
b580563e
WN
6949 err = preprocessor(prog, i, prog->insns,
6950 prog->insns_cnt, &result);
6951 if (err) {
be18010e 6952 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
52109584 6953 i, prog->name);
b580563e
WN
6954 goto out;
6955 }
6956
6957 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6958 pr_debug("Skip loading the %dth instance of program '%s'\n",
52109584 6959 i, prog->name);
b580563e
WN
6960 prog->instances.fds[i] = -1;
6961 if (result.pfd)
6962 *result.pfd = -1;
6963 continue;
6964 }
6965
be2f2d16
AN
6966 err = bpf_object_load_prog_instance(obj, prog,
6967 result.new_insn_ptr, result.new_insn_cnt,
6968 license, kern_ver, &fd);
b580563e 6969 if (err) {
be18010e 6970 pr_warn("Loading the %dth instance of program '%s' failed\n",
52109584 6971 i, prog->name);
b580563e
WN
6972 goto out;
6973 }
6974
6975 if (result.pfd)
6976 *result.pfd = fd;
6977 prog->instances.fds[i] = fd;
6978 }
6979out:
55cffde2 6980 if (err)
52109584 6981 pr_warn("failed to load program '%s'\n", prog->name);
e9fc3ce9 6982 return libbpf_err(err);
55cffde2
WN
6983}
6984
be2f2d16
AN
6985int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
6986{
6987 return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
6988}
6989
55cffde2 6990static int
60276f98 6991bpf_object__load_progs(struct bpf_object *obj, int log_level)
55cffde2 6992{
d9297581 6993 struct bpf_program *prog;
55cffde2
WN
6994 size_t i;
6995 int err;
6996
109cea5a
AN
6997 for (i = 0; i < obj->nr_programs; i++) {
6998 prog = &obj->programs[i];
6999 err = bpf_object__sanitize_prog(obj, prog);
7000 if (err)
7001 return err;
7002 }
7003
55cffde2 7004 for (i = 0; i < obj->nr_programs; i++) {
d9297581 7005 prog = &obj->programs[i];
c3c55696 7006 if (prog_is_subprog(obj, prog))
48cca7e4 7007 continue;
a3820c48 7008 if (!prog->autoload) {
9c0f8cbd 7009 pr_debug("prog '%s': skipped loading\n", prog->name);
d9297581
AN
7010 continue;
7011 }
7012 prog->log_level |= log_level;
be2f2d16 7013 err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
55cffde2
WN
7014 if (err)
7015 return err;
7016 }
67234743
AS
7017 if (obj->gen_loader)
7018 bpf_object__free_relocs(obj);
55cffde2
WN
7019 return 0;
7020}
7021
25498a19
AN
7022static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7023
91b4d1d1
AN
7024static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7025{
7026 struct bpf_program *prog;
12d9466d 7027 int err;
91b4d1d1
AN
7028
7029 bpf_object__for_each_program(prog, obj) {
7030 prog->sec_def = find_sec_def(prog->sec_name);
7031 if (!prog->sec_def) {
7032 /* couldn't guess, but user might manually specify */
7033 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7034 prog->name, prog->sec_name);
7035 continue;
7036 }
7037
df286716
GS
7038 prog->type = prog->sec_def->prog_type;
7039 prog->expected_attach_type = prog->sec_def->expected_attach_type;
91b4d1d1 7040
91b555d7
AN
7041#pragma GCC diagnostic push
7042#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
91b4d1d1
AN
7043 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
7044 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
7045 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
91b555d7 7046#pragma GCC diagnostic pop
12d9466d
AN
7047
7048 /* sec_def can have custom callback which should be called
7049 * after bpf_program is initialized to adjust its properties
7050 */
4fa5bcfe
AN
7051 if (prog->sec_def->prog_setup_fn) {
7052 err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
12d9466d
AN
7053 if (err < 0) {
7054 pr_warn("prog '%s': failed to initialize: %d\n",
7055 prog->name, err);
7056 return err;
7057 }
7058 }
91b4d1d1
AN
7059 }
7060
7061 return 0;
7062}
7063
ad9a7f96
AN
7064static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7065 const struct bpf_object_open_opts *opts)
1a5e3fb1 7066{
1373ff59 7067 const char *obj_name, *kconfig, *btf_tmp_path;
1a5e3fb1 7068 struct bpf_object *obj;
291ee02b 7069 char tmp_name[64];
6371ca3b 7070 int err;
e0e3ea88
AN
7071 char *log_buf;
7072 size_t log_size;
7073 __u32 log_level;
1a5e3fb1
WN
7074
7075 if (elf_version(EV_CURRENT) == EV_NONE) {
be18010e
KW
7076 pr_warn("failed to init libelf for %s\n",
7077 path ? : "(mem buf)");
6371ca3b 7078 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1a5e3fb1
WN
7079 }
7080
291ee02b
AN
7081 if (!OPTS_VALID(opts, bpf_object_open_opts))
7082 return ERR_PTR(-EINVAL);
7083
1aace10f 7084 obj_name = OPTS_GET(opts, object_name, NULL);
291ee02b
AN
7085 if (obj_buf) {
7086 if (!obj_name) {
7087 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7088 (unsigned long)obj_buf,
7089 (unsigned long)obj_buf_sz);
7090 obj_name = tmp_name;
7091 }
7092 path = obj_name;
7093 pr_debug("loading object '%s' from buffer\n", obj_name);
7094 }
7095
e0e3ea88
AN
7096 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7097 log_size = OPTS_GET(opts, kernel_log_size, 0);
7098 log_level = OPTS_GET(opts, kernel_log_level, 0);
7099 if (log_size > UINT_MAX)
7100 return ERR_PTR(-EINVAL);
7101 if (log_size && !log_buf)
7102 return ERR_PTR(-EINVAL);
7103
2ce8450e 7104 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6371ca3b
WN
7105 if (IS_ERR(obj))
7106 return obj;
1a5e3fb1 7107
e0e3ea88
AN
7108 obj->log_buf = log_buf;
7109 obj->log_size = log_size;
7110 obj->log_level = log_level;
7111
1373ff59
SC
7112 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7113 if (btf_tmp_path) {
7114 if (strlen(btf_tmp_path) >= PATH_MAX) {
7115 err = -ENAMETOOLONG;
7116 goto out;
7117 }
7118 obj->btf_custom_path = strdup(btf_tmp_path);
7119 if (!obj->btf_custom_path) {
7120 err = -ENOMEM;
7121 goto out;
7122 }
7123 }
7124
8601fd42
AN
7125 kconfig = OPTS_GET(opts, kconfig, NULL);
7126 if (kconfig) {
7127 obj->kconfig = strdup(kconfig);
18353c87
SC
7128 if (!obj->kconfig) {
7129 err = -ENOMEM;
7130 goto out;
7131 }
166750bc 7132 }
291ee02b 7133
0d13bfce
AN
7134 err = bpf_object__elf_init(obj);
7135 err = err ? : bpf_object__check_endianness(obj);
7136 err = err ? : bpf_object__elf_collect(obj);
166750bc
AN
7137 err = err ? : bpf_object__collect_externs(obj);
7138 err = err ? : bpf_object__finalize_btf(obj);
0d13bfce 7139 err = err ? : bpf_object__init_maps(obj, opts);
91b4d1d1 7140 err = err ? : bpf_object_init_progs(obj, opts);
c3c55696 7141 err = err ? : bpf_object__collect_relos(obj);
0d13bfce
AN
7142 if (err)
7143 goto out;
dd4436bb 7144
91b4d1d1 7145 bpf_object__elf_finish(obj);
dd4436bb 7146
1a5e3fb1
WN
7147 return obj;
7148out:
7149 bpf_object__close(obj);
6371ca3b 7150 return ERR_PTR(err);
1a5e3fb1
WN
7151}
7152
5e61f270
AN
7153static struct bpf_object *
7154__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
1a5e3fb1 7155{
e00aca65 7156 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
291ee02b
AN
7157 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7158 );
7159
1a5e3fb1 7160 /* param validation */
07f2d4ea 7161 if (!attr->file)
1a5e3fb1
WN
7162 return NULL;
7163
07f2d4ea 7164 pr_debug("loading %s\n", attr->file);
ad9a7f96 7165 return bpf_object_open(attr->file, NULL, 0, &opts);
c034a177
JF
7166}
7167
7168struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7169{
e9fc3ce9 7170 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
07f2d4ea
JK
7171}
7172
7173struct bpf_object *bpf_object__open(const char *path)
7174{
7175 struct bpf_object_open_attr attr = {
7176 .file = path,
7177 .prog_type = BPF_PROG_TYPE_UNSPEC,
7178 };
1a5e3fb1 7179
e9fc3ce9 7180 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6c956392
WN
7181}
7182
2ce8450e 7183struct bpf_object *
01af3bf0 7184bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
2ce8450e 7185{
2ce8450e 7186 if (!path)
e9fc3ce9 7187 return libbpf_err_ptr(-EINVAL);
2ce8450e
AN
7188
7189 pr_debug("loading %s\n", path);
7190
ad9a7f96 7191 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
2ce8450e
AN
7192}
7193
7194struct bpf_object *
7195bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
01af3bf0 7196 const struct bpf_object_open_opts *opts)
6c956392 7197{
2ce8450e 7198 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7199 return libbpf_err_ptr(-EINVAL);
6c956392 7200
ad9a7f96 7201 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
2ce8450e
AN
7202}
7203
7204struct bpf_object *
7205bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7206 const char *name)
7207{
e00aca65 7208 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
2ce8450e
AN
7209 .object_name = name,
7210 /* wrong default, but backwards-compatible */
7211 .relaxed_maps = true,
7212 );
7213
7214 /* returning NULL is wrong, but backwards-compatible */
7215 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7216 return errno = EINVAL, NULL;
6c956392 7217
ad9a7f96 7218 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
1a5e3fb1
WN
7219}
7220
4a404a7e 7221static int bpf_object_unload(struct bpf_object *obj)
52d3352e
WN
7222{
7223 size_t i;
7224
7225 if (!obj)
e9fc3ce9 7226 return libbpf_err(-EINVAL);
52d3352e 7227
590a0088 7228 for (i = 0; i < obj->nr_maps; i++) {
9d759a9b 7229 zclose(obj->maps[i].fd);
590a0088
MKL
7230 if (obj->maps[i].st_ops)
7231 zfree(&obj->maps[i].st_ops->kern_vdata);
7232 }
52d3352e 7233
55cffde2
WN
7234 for (i = 0; i < obj->nr_programs; i++)
7235 bpf_program__unload(&obj->programs[i]);
7236
52d3352e
WN
7237 return 0;
7238}
7239
4a404a7e
HC
7240int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7241
0d13bfce
AN
7242static int bpf_object__sanitize_maps(struct bpf_object *obj)
7243{
7244 struct bpf_map *m;
7245
7246 bpf_object__for_each_map(m, obj) {
7247 if (!bpf_map__is_internal(m))
7248 continue;
9ca1f56a 7249 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
0d13bfce
AN
7250 m->def.map_flags ^= BPF_F_MMAPABLE;
7251 }
7252
7253 return 0;
7254}
7255
85153ac0 7256int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
1c0c7074
AN
7257{
7258 char sym_type, sym_name[500];
7259 unsigned long long sym_addr;
1c0c7074
AN
7260 int ret, err = 0;
7261 FILE *f;
7262
7263 f = fopen("/proc/kallsyms", "r");
7264 if (!f) {
7265 err = -errno;
7266 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7267 return err;
7268 }
7269
7270 while (true) {
7271 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7272 &sym_addr, &sym_type, sym_name);
7273 if (ret == EOF && feof(f))
7274 break;
7275 if (ret != 3) {
135c783f 7276 pr_warn("failed to read kallsyms entry: %d\n", ret);
1c0c7074 7277 err = -EINVAL;
85153ac0 7278 break;
1c0c7074
AN
7279 }
7280
85153ac0
JO
7281 err = cb(sym_addr, sym_type, sym_name, ctx);
7282 if (err)
7283 break;
1c0c7074
AN
7284 }
7285
1c0c7074
AN
7286 fclose(f);
7287 return err;
7288}
7289
85153ac0
JO
7290static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7291 const char *sym_name, void *ctx)
7292{
7293 struct bpf_object *obj = ctx;
7294 const struct btf_type *t;
7295 struct extern_desc *ext;
7296
7297 ext = find_extern_by_name(obj, sym_name);
7298 if (!ext || ext->type != EXT_KSYM)
7299 return 0;
7300
7301 t = btf__type_by_id(obj->btf, ext->btf_id);
7302 if (!btf_is_var(t))
7303 return 0;
7304
7305 if (ext->is_set && ext->ksym.addr != sym_addr) {
7306 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7307 sym_name, ext->ksym.addr, sym_addr);
7308 return -EINVAL;
7309 }
7310 if (!ext->is_set) {
7311 ext->is_set = true;
7312 ext->ksym.addr = sym_addr;
7313 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7314 }
7315 return 0;
7316}
7317
7318static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7319{
7320 return libbpf_kallsyms_parse(kallsyms_cb, obj);
7321}
7322
774e132e
MKL
7323static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7324 __u16 kind, struct btf **res_btf,
9dbe6015 7325 struct module_btf **res_mod_btf)
d370bbe1 7326{
9dbe6015 7327 struct module_btf *mod_btf;
284d2587 7328 struct btf *btf;
9dbe6015 7329 int i, id, err;
d370bbe1 7330
933d1aa3 7331 btf = obj->btf_vmlinux;
9dbe6015 7332 mod_btf = NULL;
774e132e
MKL
7333 id = btf__find_by_name_kind(btf, ksym_name, kind);
7334
933d1aa3
MKL
7335 if (id == -ENOENT) {
7336 err = load_module_btfs(obj);
7337 if (err)
7338 return err;
d370bbe1 7339
933d1aa3 7340 for (i = 0; i < obj->btf_module_cnt; i++) {
9dbe6015
KKD
7341 /* we assume module_btf's BTF FD is always >0 */
7342 mod_btf = &obj->btf_modules[i];
7343 btf = mod_btf->btf;
7344 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
933d1aa3
MKL
7345 if (id != -ENOENT)
7346 break;
7347 }
7348 }
2211c825 7349 if (id <= 0)
933d1aa3 7350 return -ESRCH;
d370bbe1 7351
774e132e 7352 *res_btf = btf;
9dbe6015 7353 *res_mod_btf = mod_btf;
774e132e
MKL
7354 return id;
7355}
7356
7357static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7358 struct extern_desc *ext)
7359{
7360 const struct btf_type *targ_var, *targ_type;
7361 __u32 targ_type_id, local_type_id;
9dbe6015 7362 struct module_btf *mod_btf = NULL;
774e132e 7363 const char *targ_var_name;
774e132e 7364 struct btf *btf = NULL;
9dbe6015 7365 int id, err;
774e132e 7366
9dbe6015 7367 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
466b2e13
KKD
7368 if (id < 0) {
7369 if (id == -ESRCH && ext->is_weak)
7370 return 0;
2211c825
HL
7371 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7372 ext->name);
774e132e 7373 return id;
2211c825 7374 }
774e132e 7375
933d1aa3
MKL
7376 /* find local type_id */
7377 local_type_id = ext->ksym.type_id;
284d2587 7378
933d1aa3
MKL
7379 /* find target type_id */
7380 targ_var = btf__type_by_id(btf, id);
7381 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7382 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
d370bbe1 7383
933d1aa3
MKL
7384 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7385 btf, targ_type_id);
7386 if (err <= 0) {
7387 const struct btf_type *local_type;
7388 const char *targ_name, *local_name;
d370bbe1 7389
933d1aa3
MKL
7390 local_type = btf__type_by_id(obj->btf, local_type_id);
7391 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7392 targ_name = btf__name_by_offset(btf, targ_type->name_off);
d370bbe1 7393
933d1aa3
MKL
7394 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7395 ext->name, local_type_id,
7396 btf_kind_str(local_type), local_name, targ_type_id,
7397 btf_kind_str(targ_type), targ_name);
7398 return -EINVAL;
7399 }
d370bbe1 7400
933d1aa3 7401 ext->is_set = true;
9dbe6015 7402 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
933d1aa3
MKL
7403 ext->ksym.kernel_btf_id = id;
7404 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7405 ext->name, id, btf_kind_str(targ_var), targ_var_name);
d370bbe1 7406
933d1aa3
MKL
7407 return 0;
7408}
d370bbe1 7409
5bd022ec
MKL
7410static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7411 struct extern_desc *ext)
7412{
7413 int local_func_proto_id, kfunc_proto_id, kfunc_id;
9dbe6015 7414 struct module_btf *mod_btf = NULL;
5bd022ec
MKL
7415 const struct btf_type *kern_func;
7416 struct btf *kern_btf = NULL;
9dbe6015 7417 int ret;
5bd022ec
MKL
7418
7419 local_func_proto_id = ext->ksym.type_id;
7420
9dbe6015 7421 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
5bd022ec 7422 if (kfunc_id < 0) {
466b2e13
KKD
7423 if (kfunc_id == -ESRCH && ext->is_weak)
7424 return 0;
7425 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
5bd022ec
MKL
7426 ext->name);
7427 return kfunc_id;
7428 }
7429
5bd022ec
MKL
7430 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7431 kfunc_proto_id = kern_func->type;
7432
7433 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7434 kern_btf, kfunc_proto_id);
7435 if (ret <= 0) {
7436 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7437 ext->name, local_func_proto_id, kfunc_proto_id);
7438 return -EINVAL;
7439 }
7440
9dbe6015
KKD
7441 /* set index for module BTF fd in fd_array, if unset */
7442 if (mod_btf && !mod_btf->fd_array_idx) {
7443 /* insn->off is s16 */
7444 if (obj->fd_array_cnt == INT16_MAX) {
7445 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7446 ext->name, mod_btf->fd_array_idx);
7447 return -E2BIG;
7448 }
7449 /* Cannot use index 0 for module BTF fd */
7450 if (!obj->fd_array_cnt)
7451 obj->fd_array_cnt = 1;
7452
7453 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7454 obj->fd_array_cnt + 1);
7455 if (ret)
7456 return ret;
7457 mod_btf->fd_array_idx = obj->fd_array_cnt;
7458 /* we assume module BTF FD is always >0 */
7459 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7460 }
7461
5bd022ec 7462 ext->is_set = true;
5bd022ec 7463 ext->ksym.kernel_btf_id = kfunc_id;
9dbe6015 7464 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
5bd022ec
MKL
7465 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7466 ext->name, kfunc_id);
7467
7468 return 0;
7469}
7470
933d1aa3
MKL
7471static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7472{
5bd022ec 7473 const struct btf_type *t;
933d1aa3
MKL
7474 struct extern_desc *ext;
7475 int i, err;
7476
7477 for (i = 0; i < obj->nr_extern; i++) {
7478 ext = &obj->externs[i];
7479 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7480 continue;
7481
67234743
AS
7482 if (obj->gen_loader) {
7483 ext->is_set = true;
7484 ext->ksym.kernel_btf_obj_fd = 0;
7485 ext->ksym.kernel_btf_id = 0;
7486 continue;
7487 }
5bd022ec
MKL
7488 t = btf__type_by_id(obj->btf, ext->btf_id);
7489 if (btf_is_var(t))
7490 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7491 else
7492 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
933d1aa3
MKL
7493 if (err)
7494 return err;
d370bbe1
HL
7495 }
7496 return 0;
7497}
7498
166750bc 7499static int bpf_object__resolve_externs(struct bpf_object *obj,
8601fd42 7500 const char *extra_kconfig)
166750bc 7501{
1c0c7074 7502 bool need_config = false, need_kallsyms = false;
d370bbe1 7503 bool need_vmlinux_btf = false;
166750bc 7504 struct extern_desc *ext;
2e33efe3 7505 void *kcfg_data = NULL;
166750bc 7506 int err, i;
166750bc
AN
7507
7508 if (obj->nr_extern == 0)
7509 return 0;
7510
2e33efe3
AN
7511 if (obj->kconfig_map_idx >= 0)
7512 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
166750bc
AN
7513
7514 for (i = 0; i < obj->nr_extern; i++) {
7515 ext = &obj->externs[i];
7516
2e33efe3
AN
7517 if (ext->type == EXT_KCFG &&
7518 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7519 void *ext_val = kcfg_data + ext->kcfg.data_off;
166750bc
AN
7520 __u32 kver = get_kernel_version();
7521
7522 if (!kver) {
7523 pr_warn("failed to get kernel version\n");
7524 return -EINVAL;
7525 }
2e33efe3 7526 err = set_kcfg_value_num(ext, ext_val, kver);
166750bc
AN
7527 if (err)
7528 return err;
2e33efe3 7529 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
13d35a0c 7530 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
166750bc 7531 need_config = true;
1c0c7074 7532 } else if (ext->type == EXT_KSYM) {
d370bbe1
HL
7533 if (ext->ksym.type_id)
7534 need_vmlinux_btf = true;
7535 else
7536 need_kallsyms = true;
166750bc
AN
7537 } else {
7538 pr_warn("unrecognized extern '%s'\n", ext->name);
7539 return -EINVAL;
7540 }
7541 }
8601fd42 7542 if (need_config && extra_kconfig) {
2e33efe3 7543 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8601fd42
AN
7544 if (err)
7545 return -EINVAL;
7546 need_config = false;
7547 for (i = 0; i < obj->nr_extern; i++) {
7548 ext = &obj->externs[i];
2e33efe3 7549 if (ext->type == EXT_KCFG && !ext->is_set) {
8601fd42
AN
7550 need_config = true;
7551 break;
7552 }
7553 }
7554 }
166750bc 7555 if (need_config) {
2e33efe3 7556 err = bpf_object__read_kconfig_file(obj, kcfg_data);
166750bc
AN
7557 if (err)
7558 return -EINVAL;
7559 }
1c0c7074
AN
7560 if (need_kallsyms) {
7561 err = bpf_object__read_kallsyms_file(obj);
7562 if (err)
7563 return -EINVAL;
7564 }
d370bbe1
HL
7565 if (need_vmlinux_btf) {
7566 err = bpf_object__resolve_ksyms_btf_id(obj);
7567 if (err)
7568 return -EINVAL;
7569 }
166750bc
AN
7570 for (i = 0; i < obj->nr_extern; i++) {
7571 ext = &obj->externs[i];
7572
7573 if (!ext->is_set && !ext->is_weak) {
7574 pr_warn("extern %s (strong) not resolved\n", ext->name);
7575 return -ESRCH;
7576 } else if (!ext->is_set) {
7577 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7578 ext->name);
7579 }
7580 }
7581
7582 return 0;
7583}
7584
e7b924ca 7585static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
52d3352e 7586{
ec6d5f47 7587 int err, i;
6371ca3b 7588
52d3352e 7589 if (!obj)
e9fc3ce9 7590 return libbpf_err(-EINVAL);
52d3352e
WN
7591
7592 if (obj->loaded) {
d9297581 7593 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
e9fc3ce9 7594 return libbpf_err(-EINVAL);
52d3352e
WN
7595 }
7596
67234743 7597 if (obj->gen_loader)
be315829 7598 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
67234743 7599
fd9eef1a 7600 err = bpf_object__probe_loading(obj);
fe62de31 7601 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8601fd42 7602 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
0d13bfce
AN
7603 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7604 err = err ? : bpf_object__sanitize_maps(obj);
590a0088 7605 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
0d13bfce 7606 err = err ? : bpf_object__create_maps(obj);
e7b924ca
AN
7607 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7608 err = err ? : bpf_object__load_progs(obj, extra_log_level);
341ac5ff 7609 err = err ? : bpf_object_init_prog_arrays(obj);
a6ed02ca 7610
67234743
AS
7611 if (obj->gen_loader) {
7612 /* reset FDs */
4729445b
KKD
7613 if (obj->btf)
7614 btf__set_fd(obj->btf, -1);
67234743
AS
7615 for (i = 0; i < obj->nr_maps; i++)
7616 obj->maps[i].fd = -1;
7617 if (!err)
ba05fd36 7618 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
67234743
AS
7619 }
7620
9dbe6015
KKD
7621 /* clean up fd_array */
7622 zfree(&obj->fd_array);
7623
4f33a53d
AN
7624 /* clean up module BTFs */
7625 for (i = 0; i < obj->btf_module_cnt; i++) {
91abb4a6 7626 close(obj->btf_modules[i].fd);
4f33a53d
AN
7627 btf__free(obj->btf_modules[i].btf);
7628 free(obj->btf_modules[i].name);
7629 }
7630 free(obj->btf_modules);
7631
7632 /* clean up vmlinux BTF */
a6ed02ca
KS
7633 btf__free(obj->btf_vmlinux);
7634 obj->btf_vmlinux = NULL;
7635
d9297581
AN
7636 obj->loaded = true; /* doesn't matter if successfully or not */
7637
0d13bfce
AN
7638 if (err)
7639 goto out;
52d3352e
WN
7640
7641 return 0;
7642out:
ec6d5f47
THJ
7643 /* unpin any maps that were auto-pinned during load */
7644 for (i = 0; i < obj->nr_maps; i++)
7645 if (obj->maps[i].pinned && !obj->maps[i].reused)
7646 bpf_map__unpin(&obj->maps[i], NULL);
7647
4a404a7e 7648 bpf_object_unload(obj);
be18010e 7649 pr_warn("failed to load object '%s'\n", obj->path);
e9fc3ce9 7650 return libbpf_err(err);
52d3352e
WN
7651}
7652
e7b924ca 7653int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
60276f98 7654{
e7b924ca
AN
7655 return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7656}
60276f98 7657
e7b924ca
AN
7658int bpf_object__load(struct bpf_object *obj)
7659{
7660 return bpf_object_load(obj, 0, NULL);
60276f98
QM
7661}
7662
196f8487
THJ
7663static int make_parent_dir(const char *path)
7664{
7665 char *cp, errmsg[STRERR_BUFSIZE];
7666 char *dname, *dir;
7667 int err = 0;
7668
7669 dname = strdup(path);
7670 if (dname == NULL)
7671 return -ENOMEM;
7672
7673 dir = dirname(dname);
7674 if (mkdir(dir, 0700) && errno != EEXIST)
7675 err = -errno;
7676
7677 free(dname);
7678 if (err) {
7679 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7680 pr_warn("failed to mkdir %s: %s\n", path, cp);
7681 }
7682 return err;
7683}
7684
f367540c
JS
7685static int check_path(const char *path)
7686{
1ce6a9fc 7687 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7688 struct statfs st_fs;
7689 char *dname, *dir;
7690 int err = 0;
7691
7692 if (path == NULL)
7693 return -EINVAL;
7694
7695 dname = strdup(path);
7696 if (dname == NULL)
7697 return -ENOMEM;
7698
7699 dir = dirname(dname);
7700 if (statfs(dir, &st_fs)) {
24d6a808 7701 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
be18010e 7702 pr_warn("failed to statfs %s: %s\n", dir, cp);
f367540c
JS
7703 err = -errno;
7704 }
7705 free(dname);
7706
7707 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
be18010e 7708 pr_warn("specified path %s is not on BPF FS\n", path);
f367540c
JS
7709 err = -EINVAL;
7710 }
7711
7712 return err;
7713}
7714
e21d585c 7715static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
f367540c 7716{
1ce6a9fc 7717 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7718 int err;
7719
196f8487
THJ
7720 err = make_parent_dir(path);
7721 if (err)
e9fc3ce9 7722 return libbpf_err(err);
196f8487 7723
f367540c
JS
7724 err = check_path(path);
7725 if (err)
e9fc3ce9 7726 return libbpf_err(err);
f367540c
JS
7727
7728 if (prog == NULL) {
be18010e 7729 pr_warn("invalid program pointer\n");
e9fc3ce9 7730 return libbpf_err(-EINVAL);
f367540c
JS
7731 }
7732
7733 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7734 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7735 instance, prog->name, prog->instances.nr);
e9fc3ce9 7736 return libbpf_err(-EINVAL);
f367540c
JS
7737 }
7738
7739 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
23ab656b
THJ
7740 err = -errno;
7741 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e 7742 pr_warn("failed to pin program: %s\n", cp);
e9fc3ce9 7743 return libbpf_err(err);
f367540c
JS
7744 }
7745 pr_debug("pinned program '%s'\n", path);
7746
7747 return 0;
7748}
7749
e21d585c 7750static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
0c19a9fb
SF
7751{
7752 int err;
7753
7754 err = check_path(path);
7755 if (err)
e9fc3ce9 7756 return libbpf_err(err);
0c19a9fb
SF
7757
7758 if (prog == NULL) {
be18010e 7759 pr_warn("invalid program pointer\n");
e9fc3ce9 7760 return libbpf_err(-EINVAL);
0c19a9fb
SF
7761 }
7762
7763 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7764 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7765 instance, prog->name, prog->instances.nr);
e9fc3ce9 7766 return libbpf_err(-EINVAL);
0c19a9fb
SF
7767 }
7768
7769 err = unlink(path);
7770 if (err != 0)
e9fc3ce9
AN
7771 return libbpf_err(-errno);
7772
0c19a9fb
SF
7773 pr_debug("unpinned program '%s'\n", path);
7774
7775 return 0;
7776}
7777
e21d585c
AN
7778__attribute__((alias("bpf_program_pin_instance")))
7779int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
7780
7781__attribute__((alias("bpf_program_unpin_instance")))
7782int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
7783
f367540c
JS
7784int bpf_program__pin(struct bpf_program *prog, const char *path)
7785{
7786 int i, err;
7787
196f8487
THJ
7788 err = make_parent_dir(path);
7789 if (err)
e9fc3ce9 7790 return libbpf_err(err);
196f8487 7791
f367540c
JS
7792 err = check_path(path);
7793 if (err)
e9fc3ce9 7794 return libbpf_err(err);
f367540c
JS
7795
7796 if (prog == NULL) {
be18010e 7797 pr_warn("invalid program pointer\n");
e9fc3ce9 7798 return libbpf_err(-EINVAL);
f367540c
JS
7799 }
7800
7801 if (prog->instances.nr <= 0) {
52109584 7802 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7803 return libbpf_err(-EINVAL);
f367540c
JS
7804 }
7805
fd734c5c
SF
7806 if (prog->instances.nr == 1) {
7807 /* don't create subdirs when pinning single instance */
e21d585c 7808 return bpf_program_pin_instance(prog, path, 0);
fd734c5c
SF
7809 }
7810
0c19a9fb
SF
7811 for (i = 0; i < prog->instances.nr; i++) {
7812 char buf[PATH_MAX];
7813 int len;
7814
7815 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7816 if (len < 0) {
7817 err = -EINVAL;
7818 goto err_unpin;
7819 } else if (len >= PATH_MAX) {
7820 err = -ENAMETOOLONG;
7821 goto err_unpin;
7822 }
7823
e21d585c 7824 err = bpf_program_pin_instance(prog, buf, i);
0c19a9fb
SF
7825 if (err)
7826 goto err_unpin;
7827 }
7828
7829 return 0;
7830
7831err_unpin:
7832 for (i = i - 1; i >= 0; i--) {
7833 char buf[PATH_MAX];
7834 int len;
7835
7836 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7837 if (len < 0)
7838 continue;
7839 else if (len >= PATH_MAX)
7840 continue;
7841
e21d585c 7842 bpf_program_unpin_instance(prog, buf, i);
0c19a9fb
SF
7843 }
7844
7845 rmdir(path);
7846
e9fc3ce9 7847 return libbpf_err(err);
0c19a9fb
SF
7848}
7849
7850int bpf_program__unpin(struct bpf_program *prog, const char *path)
7851{
7852 int i, err;
7853
7854 err = check_path(path);
7855 if (err)
e9fc3ce9 7856 return libbpf_err(err);
0c19a9fb
SF
7857
7858 if (prog == NULL) {
be18010e 7859 pr_warn("invalid program pointer\n");
e9fc3ce9 7860 return libbpf_err(-EINVAL);
0c19a9fb
SF
7861 }
7862
7863 if (prog->instances.nr <= 0) {
52109584 7864 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7865 return libbpf_err(-EINVAL);
fd734c5c
SF
7866 }
7867
7868 if (prog->instances.nr == 1) {
7869 /* don't create subdirs when pinning single instance */
e21d585c 7870 return bpf_program_unpin_instance(prog, path, 0);
0c19a9fb
SF
7871 }
7872
f367540c
JS
7873 for (i = 0; i < prog->instances.nr; i++) {
7874 char buf[PATH_MAX];
7875 int len;
7876
7877 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7878 if (len < 0)
e9fc3ce9 7879 return libbpf_err(-EINVAL);
f367540c 7880 else if (len >= PATH_MAX)
e9fc3ce9 7881 return libbpf_err(-ENAMETOOLONG);
f367540c 7882
e21d585c 7883 err = bpf_program_unpin_instance(prog, buf, i);
f367540c
JS
7884 if (err)
7885 return err;
7886 }
7887
0c19a9fb
SF
7888 err = rmdir(path);
7889 if (err)
e9fc3ce9 7890 return libbpf_err(-errno);
0c19a9fb 7891
f367540c
JS
7892 return 0;
7893}
7894
b6989f35
JS
7895int bpf_map__pin(struct bpf_map *map, const char *path)
7896{
1ce6a9fc 7897 char *cp, errmsg[STRERR_BUFSIZE];
b6989f35
JS
7898 int err;
7899
b6989f35 7900 if (map == NULL) {
be18010e 7901 pr_warn("invalid map pointer\n");
e9fc3ce9 7902 return libbpf_err(-EINVAL);
b6989f35
JS
7903 }
7904
4580b25f
THJ
7905 if (map->pin_path) {
7906 if (path && strcmp(path, map->pin_path)) {
7907 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7908 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7909 return libbpf_err(-EINVAL);
4580b25f
THJ
7910 } else if (map->pinned) {
7911 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7912 bpf_map__name(map), map->pin_path);
7913 return 0;
7914 }
7915 } else {
7916 if (!path) {
7917 pr_warn("missing a path to pin map '%s' at\n",
7918 bpf_map__name(map));
e9fc3ce9 7919 return libbpf_err(-EINVAL);
4580b25f
THJ
7920 } else if (map->pinned) {
7921 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
e9fc3ce9 7922 return libbpf_err(-EEXIST);
4580b25f
THJ
7923 }
7924
7925 map->pin_path = strdup(path);
7926 if (!map->pin_path) {
7927 err = -errno;
7928 goto out_err;
7929 }
b6989f35
JS
7930 }
7931
196f8487
THJ
7932 err = make_parent_dir(map->pin_path);
7933 if (err)
e9fc3ce9 7934 return libbpf_err(err);
196f8487 7935
4580b25f
THJ
7936 err = check_path(map->pin_path);
7937 if (err)
e9fc3ce9 7938 return libbpf_err(err);
4580b25f
THJ
7939
7940 if (bpf_obj_pin(map->fd, map->pin_path)) {
7941 err = -errno;
7942 goto out_err;
7943 }
7944
7945 map->pinned = true;
7946 pr_debug("pinned map '%s'\n", map->pin_path);
0c19a9fb 7947
b6989f35 7948 return 0;
4580b25f
THJ
7949
7950out_err:
7951 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7952 pr_warn("failed to pin map: %s\n", cp);
e9fc3ce9 7953 return libbpf_err(err);
b6989f35
JS
7954}
7955
0c19a9fb
SF
7956int bpf_map__unpin(struct bpf_map *map, const char *path)
7957{
7958 int err;
7959
0c19a9fb 7960 if (map == NULL) {
be18010e 7961 pr_warn("invalid map pointer\n");
e9fc3ce9 7962 return libbpf_err(-EINVAL);
0c19a9fb
SF
7963 }
7964
4580b25f
THJ
7965 if (map->pin_path) {
7966 if (path && strcmp(path, map->pin_path)) {
7967 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7968 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7969 return libbpf_err(-EINVAL);
4580b25f
THJ
7970 }
7971 path = map->pin_path;
7972 } else if (!path) {
7973 pr_warn("no path to unpin map '%s' from\n",
7974 bpf_map__name(map));
e9fc3ce9 7975 return libbpf_err(-EINVAL);
4580b25f
THJ
7976 }
7977
7978 err = check_path(path);
7979 if (err)
e9fc3ce9 7980 return libbpf_err(err);
4580b25f 7981
0c19a9fb
SF
7982 err = unlink(path);
7983 if (err != 0)
e9fc3ce9 7984 return libbpf_err(-errno);
4580b25f
THJ
7985
7986 map->pinned = false;
7987 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
0c19a9fb
SF
7988
7989 return 0;
7990}
7991
4580b25f
THJ
7992int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7993{
7994 char *new = NULL;
7995
7996 if (path) {
7997 new = strdup(path);
7998 if (!new)
e9fc3ce9 7999 return libbpf_err(-errno);
4580b25f
THJ
8000 }
8001
8002 free(map->pin_path);
8003 map->pin_path = new;
8004 return 0;
8005}
8006
20eccf29
AN
8007__alias(bpf_map__pin_path)
8008const char *bpf_map__get_pin_path(const struct bpf_map *map);
4580b25f 8009
e244d34d
EL
8010const char *bpf_map__pin_path(const struct bpf_map *map)
8011{
8012 return map->pin_path;
8013}
8014
4580b25f
THJ
8015bool bpf_map__is_pinned(const struct bpf_map *map)
8016{
8017 return map->pinned;
8018}
8019
9cf309c5
THJ
8020static void sanitize_pin_path(char *s)
8021{
8022 /* bpffs disallows periods in path names */
8023 while (*s) {
8024 if (*s == '.')
8025 *s = '_';
8026 s++;
8027 }
8028}
8029
0c19a9fb 8030int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
d5148d85 8031{
d5148d85
JS
8032 struct bpf_map *map;
8033 int err;
8034
8035 if (!obj)
e9fc3ce9 8036 return libbpf_err(-ENOENT);
d5148d85
JS
8037
8038 if (!obj->loaded) {
be18010e 8039 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 8040 return libbpf_err(-ENOENT);
d5148d85
JS
8041 }
8042
f74a53d9 8043 bpf_object__for_each_map(map, obj) {
4580b25f 8044 char *pin_path = NULL;
0c19a9fb 8045 char buf[PATH_MAX];
0c19a9fb 8046
229fae38
SC
8047 if (map->skipped)
8048 continue;
8049
4580b25f
THJ
8050 if (path) {
8051 int len;
8052
8053 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8054 bpf_map__name(map));
8055 if (len < 0) {
8056 err = -EINVAL;
8057 goto err_unpin_maps;
8058 } else if (len >= PATH_MAX) {
8059 err = -ENAMETOOLONG;
8060 goto err_unpin_maps;
8061 }
9cf309c5 8062 sanitize_pin_path(buf);
4580b25f
THJ
8063 pin_path = buf;
8064 } else if (!map->pin_path) {
8065 continue;
0c19a9fb
SF
8066 }
8067
4580b25f 8068 err = bpf_map__pin(map, pin_path);
0c19a9fb
SF
8069 if (err)
8070 goto err_unpin_maps;
8071 }
8072
8073 return 0;
8074
8075err_unpin_maps:
bcc40fc0 8076 while ((map = bpf_object__prev_map(obj, map))) {
4580b25f 8077 if (!map->pin_path)
0c19a9fb
SF
8078 continue;
8079
4580b25f 8080 bpf_map__unpin(map, NULL);
0c19a9fb
SF
8081 }
8082
e9fc3ce9 8083 return libbpf_err(err);
0c19a9fb
SF
8084}
8085
8086int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8087{
8088 struct bpf_map *map;
8089 int err;
8090
8091 if (!obj)
e9fc3ce9 8092 return libbpf_err(-ENOENT);
0c19a9fb 8093
f74a53d9 8094 bpf_object__for_each_map(map, obj) {
4580b25f 8095 char *pin_path = NULL;
d5148d85 8096 char buf[PATH_MAX];
d5148d85 8097
4580b25f
THJ
8098 if (path) {
8099 int len;
8100
8101 len = snprintf(buf, PATH_MAX, "%s/%s", path,
8102 bpf_map__name(map));
8103 if (len < 0)
e9fc3ce9 8104 return libbpf_err(-EINVAL);
4580b25f 8105 else if (len >= PATH_MAX)
e9fc3ce9 8106 return libbpf_err(-ENAMETOOLONG);
9cf309c5 8107 sanitize_pin_path(buf);
4580b25f
THJ
8108 pin_path = buf;
8109 } else if (!map->pin_path) {
8110 continue;
8111 }
d5148d85 8112
4580b25f 8113 err = bpf_map__unpin(map, pin_path);
d5148d85 8114 if (err)
e9fc3ce9 8115 return libbpf_err(err);
d5148d85
JS
8116 }
8117
0c19a9fb
SF
8118 return 0;
8119}
8120
8121int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8122{
8123 struct bpf_program *prog;
8124 int err;
8125
8126 if (!obj)
e9fc3ce9 8127 return libbpf_err(-ENOENT);
0c19a9fb
SF
8128
8129 if (!obj->loaded) {
be18010e 8130 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 8131 return libbpf_err(-ENOENT);
0c19a9fb
SF
8132 }
8133
0c19a9fb
SF
8134 bpf_object__for_each_program(prog, obj) {
8135 char buf[PATH_MAX];
8136 int len;
8137
8138 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8139 prog->pin_name);
0c19a9fb
SF
8140 if (len < 0) {
8141 err = -EINVAL;
8142 goto err_unpin_programs;
8143 } else if (len >= PATH_MAX) {
8144 err = -ENAMETOOLONG;
8145 goto err_unpin_programs;
8146 }
8147
8148 err = bpf_program__pin(prog, buf);
8149 if (err)
8150 goto err_unpin_programs;
8151 }
8152
8153 return 0;
8154
8155err_unpin_programs:
bcc40fc0 8156 while ((prog = bpf_object__prev_program(obj, prog))) {
0c19a9fb
SF
8157 char buf[PATH_MAX];
8158 int len;
8159
8160 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8161 prog->pin_name);
0c19a9fb
SF
8162 if (len < 0)
8163 continue;
8164 else if (len >= PATH_MAX)
8165 continue;
8166
8167 bpf_program__unpin(prog, buf);
8168 }
8169
e9fc3ce9 8170 return libbpf_err(err);
0c19a9fb
SF
8171}
8172
8173int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8174{
8175 struct bpf_program *prog;
8176 int err;
8177
8178 if (!obj)
e9fc3ce9 8179 return libbpf_err(-ENOENT);
0c19a9fb 8180
d5148d85
JS
8181 bpf_object__for_each_program(prog, obj) {
8182 char buf[PATH_MAX];
8183 int len;
8184
8185 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8186 prog->pin_name);
d5148d85 8187 if (len < 0)
e9fc3ce9 8188 return libbpf_err(-EINVAL);
d5148d85 8189 else if (len >= PATH_MAX)
e9fc3ce9 8190 return libbpf_err(-ENAMETOOLONG);
d5148d85 8191
0c19a9fb 8192 err = bpf_program__unpin(prog, buf);
d5148d85 8193 if (err)
e9fc3ce9 8194 return libbpf_err(err);
d5148d85
JS
8195 }
8196
8197 return 0;
8198}
8199
0c19a9fb
SF
8200int bpf_object__pin(struct bpf_object *obj, const char *path)
8201{
8202 int err;
8203
8204 err = bpf_object__pin_maps(obj, path);
8205 if (err)
e9fc3ce9 8206 return libbpf_err(err);
0c19a9fb
SF
8207
8208 err = bpf_object__pin_programs(obj, path);
8209 if (err) {
8210 bpf_object__unpin_maps(obj, path);
e9fc3ce9 8211 return libbpf_err(err);
0c19a9fb
SF
8212 }
8213
8214 return 0;
8215}
8216
2d39d7c5
AN
8217static void bpf_map__destroy(struct bpf_map *map)
8218{
8219 if (map->clear_priv)
8220 map->clear_priv(map, map->priv);
8221 map->priv = NULL;
8222 map->clear_priv = NULL;
8223
646f02ff
AN
8224 if (map->inner_map) {
8225 bpf_map__destroy(map->inner_map);
8226 zfree(&map->inner_map);
8227 }
8228
8229 zfree(&map->init_slots);
8230 map->init_slots_sz = 0;
8231
2d39d7c5
AN
8232 if (map->mmaped) {
8233 munmap(map->mmaped, bpf_map_mmap_sz(map));
8234 map->mmaped = NULL;
8235 }
8236
8237 if (map->st_ops) {
8238 zfree(&map->st_ops->data);
8239 zfree(&map->st_ops->progs);
8240 zfree(&map->st_ops->kern_func_off);
8241 zfree(&map->st_ops);
8242 }
8243
8244 zfree(&map->name);
aed65917 8245 zfree(&map->real_name);
2d39d7c5
AN
8246 zfree(&map->pin_path);
8247
8248 if (map->fd >= 0)
8249 zclose(map->fd);
8250}
8251
1a5e3fb1
WN
8252void bpf_object__close(struct bpf_object *obj)
8253{
a5b8bd47
WN
8254 size_t i;
8255
50450fc7 8256 if (IS_ERR_OR_NULL(obj))
1a5e3fb1
WN
8257 return;
8258
10931d24
WN
8259 if (obj->clear_priv)
8260 obj->clear_priv(obj, obj->priv);
8261
2e4913e0
AN
8262 usdt_manager_free(obj->usdt_man);
8263 obj->usdt_man = NULL;
8264
67234743 8265 bpf_gen__free(obj->gen_loader);
1a5e3fb1 8266 bpf_object__elf_finish(obj);
4a404a7e 8267 bpf_object_unload(obj);
8a138aed 8268 btf__free(obj->btf);
2993e051 8269 btf_ext__free(obj->btf_ext);
1a5e3fb1 8270
2d39d7c5
AN
8271 for (i = 0; i < obj->nr_maps; i++)
8272 bpf_map__destroy(&obj->maps[i]);
d859900c 8273
1373ff59 8274 zfree(&obj->btf_custom_path);
8601fd42 8275 zfree(&obj->kconfig);
166750bc
AN
8276 zfree(&obj->externs);
8277 obj->nr_extern = 0;
8278
9d759a9b
WN
8279 zfree(&obj->maps);
8280 obj->nr_maps = 0;
a5b8bd47
WN
8281
8282 if (obj->programs && obj->nr_programs) {
8283 for (i = 0; i < obj->nr_programs; i++)
8284 bpf_program__exit(&obj->programs[i]);
8285 }
8286 zfree(&obj->programs);
8287
9a208eff 8288 list_del(&obj->list);
1a5e3fb1
WN
8289 free(obj);
8290}
aa9b1ac3 8291
9a208eff
WN
8292struct bpf_object *
8293bpf_object__next(struct bpf_object *prev)
8294{
8295 struct bpf_object *next;
689624f0
JB
8296 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8297
8298 if (strict)
8299 return NULL;
9a208eff
WN
8300
8301 if (!prev)
8302 next = list_first_entry(&bpf_objects_list,
8303 struct bpf_object,
8304 list);
8305 else
8306 next = list_next_entry(prev, list);
8307
8308 /* Empty list is noticed here so don't need checking on entry. */
8309 if (&next->list == &bpf_objects_list)
8310 return NULL;
8311
8312 return next;
8313}
8314
a324aae3 8315const char *bpf_object__name(const struct bpf_object *obj)
acf860ae 8316{
e9fc3ce9 8317 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
acf860ae
WN
8318}
8319
a324aae3 8320unsigned int bpf_object__kversion(const struct bpf_object *obj)
45825d8a 8321{
a7fe0450 8322 return obj ? obj->kern_version : 0;
45825d8a
WN
8323}
8324
a324aae3 8325struct btf *bpf_object__btf(const struct bpf_object *obj)
789f6bab
AI
8326{
8327 return obj ? obj->btf : NULL;
8328}
8329
8a138aed
MKL
8330int bpf_object__btf_fd(const struct bpf_object *obj)
8331{
8332 return obj->btf ? btf__fd(obj->btf) : -1;
8333}
8334
155f556d
RDT
8335int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8336{
8337 if (obj->loaded)
e9fc3ce9 8338 return libbpf_err(-EINVAL);
155f556d
RDT
8339
8340 obj->kern_version = kern_version;
8341
8342 return 0;
8343}
8344
10931d24
WN
8345int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8346 bpf_object_clear_priv_t clear_priv)
8347{
8348 if (obj->priv && obj->clear_priv)
8349 obj->clear_priv(obj, obj->priv);
8350
8351 obj->priv = priv;
8352 obj->clear_priv = clear_priv;
8353 return 0;
8354}
8355
a324aae3 8356void *bpf_object__priv(const struct bpf_object *obj)
10931d24 8357{
e9fc3ce9 8358 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
10931d24
WN
8359}
8360
67234743
AS
8361int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8362{
8363 struct bpf_gen *gen;
8364
8365 if (!opts)
8366 return -EFAULT;
8367 if (!OPTS_VALID(opts, gen_loader_opts))
8368 return -EINVAL;
8369 gen = calloc(sizeof(*gen), 1);
8370 if (!gen)
8371 return -ENOMEM;
8372 gen->opts = opts;
8373 obj->gen_loader = gen;
8374 return 0;
8375}
8376
eac7d845 8377static struct bpf_program *
a324aae3
AN
8378__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8379 bool forward)
aa9b1ac3 8380{
a83d6e76 8381 size_t nr_programs = obj->nr_programs;
0c19a9fb 8382 ssize_t idx;
aa9b1ac3 8383
a83d6e76 8384 if (!nr_programs)
aa9b1ac3 8385 return NULL;
aa9b1ac3 8386
a83d6e76
MKL
8387 if (!p)
8388 /* Iter from the beginning */
8389 return forward ? &obj->programs[0] :
8390 &obj->programs[nr_programs - 1];
8391
0c19a9fb 8392 if (p->obj != obj) {
be18010e 8393 pr_warn("error: program handler doesn't match object\n");
e9fc3ce9 8394 return errno = EINVAL, NULL;
aa9b1ac3
WN
8395 }
8396
a83d6e76 8397 idx = (p - obj->programs) + (forward ? 1 : -1);
0c19a9fb 8398 if (idx >= obj->nr_programs || idx < 0)
aa9b1ac3
WN
8399 return NULL;
8400 return &obj->programs[idx];
8401}
8402
eac7d845 8403struct bpf_program *
a324aae3 8404bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
2088a3a7
HC
8405{
8406 return bpf_object__next_program(obj, prev);
8407}
8408
8409struct bpf_program *
8410bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
eac7d845
JK
8411{
8412 struct bpf_program *prog = prev;
8413
8414 do {
a83d6e76 8415 prog = __bpf_program__iter(prog, obj, true);
c3c55696 8416 } while (prog && prog_is_subprog(obj, prog));
0c19a9fb
SF
8417
8418 return prog;
8419}
8420
8421struct bpf_program *
a324aae3 8422bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
2088a3a7
HC
8423{
8424 return bpf_object__prev_program(obj, next);
8425}
8426
8427struct bpf_program *
8428bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
0c19a9fb
SF
8429{
8430 struct bpf_program *prog = next;
8431
0c19a9fb 8432 do {
a83d6e76 8433 prog = __bpf_program__iter(prog, obj, false);
c3c55696 8434 } while (prog && prog_is_subprog(obj, prog));
eac7d845
JK
8435
8436 return prog;
8437}
8438
edb13ed4
ACM
8439int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8440 bpf_program_clear_priv_t clear_priv)
aa9b1ac3
WN
8441{
8442 if (prog->priv && prog->clear_priv)
8443 prog->clear_priv(prog, prog->priv);
8444
8445 prog->priv = priv;
8446 prog->clear_priv = clear_priv;
8447 return 0;
8448}
8449
a324aae3 8450void *bpf_program__priv(const struct bpf_program *prog)
aa9b1ac3 8451{
e9fc3ce9 8452 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
aa9b1ac3
WN
8453}
8454
9aba3613
JK
8455void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8456{
8457 prog->prog_ifindex = ifindex;
8458}
8459
01af3bf0
AN
8460const char *bpf_program__name(const struct bpf_program *prog)
8461{
8462 return prog->name;
8463}
8464
52109584
AN
8465const char *bpf_program__section_name(const struct bpf_program *prog)
8466{
8467 return prog->sec_name;
8468}
8469
a324aae3 8470const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
aa9b1ac3
WN
8471{
8472 const char *title;
8473
52109584 8474 title = prog->sec_name;
715f8db9 8475 if (needs_copy) {
aa9b1ac3
WN
8476 title = strdup(title);
8477 if (!title) {
be18010e 8478 pr_warn("failed to strdup program title\n");
e9fc3ce9 8479 return libbpf_err_ptr(-ENOMEM);
aa9b1ac3
WN
8480 }
8481 }
8482
8483 return title;
8484}
8485
d9297581
AN
8486bool bpf_program__autoload(const struct bpf_program *prog)
8487{
a3820c48 8488 return prog->autoload;
d9297581
AN
8489}
8490
8491int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8492{
8493 if (prog->obj->loaded)
e9fc3ce9 8494 return libbpf_err(-EINVAL);
d9297581 8495
a3820c48 8496 prog->autoload = autoload;
d9297581
AN
8497 return 0;
8498}
8499
bcc40fc0
AN
8500static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8501
a324aae3 8502int bpf_program__fd(const struct bpf_program *prog)
aa9b1ac3 8503{
bcc40fc0 8504 return bpf_program_nth_fd(prog, 0);
b580563e
WN
8505}
8506
1a734efe
THJ
8507size_t bpf_program__size(const struct bpf_program *prog)
8508{
9c0f8cbd 8509 return prog->insns_cnt * BPF_INSN_SZ;
1a734efe
THJ
8510}
8511
65a7fa2e
AN
8512const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8513{
8514 return prog->insns;
8515}
8516
8517size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8518{
8519 return prog->insns_cnt;
8520}
8521
b580563e
WN
8522int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8523 bpf_program_prep_t prep)
8524{
8525 int *instances_fds;
8526
8527 if (nr_instances <= 0 || !prep)
e9fc3ce9 8528 return libbpf_err(-EINVAL);
b580563e
WN
8529
8530 if (prog->instances.nr > 0 || prog->instances.fds) {
be18010e 8531 pr_warn("Can't set pre-processor after loading\n");
e9fc3ce9 8532 return libbpf_err(-EINVAL);
b580563e
WN
8533 }
8534
8535 instances_fds = malloc(sizeof(int) * nr_instances);
8536 if (!instances_fds) {
be18010e 8537 pr_warn("alloc memory failed for fds\n");
e9fc3ce9 8538 return libbpf_err(-ENOMEM);
b580563e
WN
8539 }
8540
8541 /* fill all fd with -1 */
8542 memset(instances_fds, -1, sizeof(int) * nr_instances);
8543
8544 prog->instances.nr = nr_instances;
8545 prog->instances.fds = instances_fds;
8546 prog->preprocessor = prep;
8547 return 0;
8548}
8549
bcc40fc0
AN
8550__attribute__((alias("bpf_program_nth_fd")))
8551int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8552
8553static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
b580563e
WN
8554{
8555 int fd;
8556
1e960043 8557 if (!prog)
e9fc3ce9 8558 return libbpf_err(-EINVAL);
1e960043 8559
b580563e 8560 if (n >= prog->instances.nr || n < 0) {
be18010e 8561 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
52109584 8562 n, prog->name, prog->instances.nr);
e9fc3ce9 8563 return libbpf_err(-EINVAL);
b580563e
WN
8564 }
8565
8566 fd = prog->instances.fds[n];
8567 if (fd < 0) {
be18010e 8568 pr_warn("%dth instance of program '%s' is invalid\n",
52109584 8569 n, prog->name);
e9fc3ce9 8570 return libbpf_err(-ENOENT);
b580563e
WN
8571 }
8572
8573 return fd;
aa9b1ac3 8574}
9d759a9b 8575
20eccf29
AN
8576__alias(bpf_program__type)
8577enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8578
8579enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
f1eead9e
AN
8580{
8581 return prog->type;
8582}
8583
93442f13 8584int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5f44e4c8 8585{
93442f13
GS
8586 if (prog->obj->loaded)
8587 return libbpf_err(-EBUSY);
8588
5f44e4c8 8589 prog->type = type;
93442f13 8590 return 0;
5f44e4c8
WN
8591}
8592
a324aae3 8593static bool bpf_program__is_type(const struct bpf_program *prog,
5f44e4c8
WN
8594 enum bpf_prog_type type)
8595{
8596 return prog ? (prog->type == type) : false;
8597}
8598
a324aae3
AN
8599#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8600int bpf_program__set_##NAME(struct bpf_program *prog) \
8601{ \
8602 if (!prog) \
e9fc3ce9 8603 return libbpf_err(-EINVAL); \
df286716 8604 return bpf_program__set_type(prog, TYPE); \
a324aae3
AN
8605} \
8606 \
8607bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8608{ \
8609 return bpf_program__is_type(prog, TYPE); \
8610} \
ed794073 8611
7803ba73 8612BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1e092a03 8613BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
ed794073 8614BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7803ba73
JS
8615BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8616BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
ed794073 8617BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
e14c93fd 8618BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7803ba73
JS
8619BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8620BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
12a8654b 8621BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
590a0088 8622BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
2db6eab1 8623BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
499dd29d 8624BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
5f44e4c8 8625
20eccf29
AN
8626__alias(bpf_program__expected_attach_type)
8627enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8628
8629enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
f1eead9e
AN
8630{
8631 return prog->expected_attach_type;
8632}
8633
93442f13 8634int bpf_program__set_expected_attach_type(struct bpf_program *prog,
16962b24 8635 enum bpf_attach_type type)
d7be143b 8636{
93442f13
GS
8637 if (prog->obj->loaded)
8638 return libbpf_err(-EBUSY);
8639
d7be143b 8640 prog->expected_attach_type = type;
93442f13 8641 return 0;
d7be143b
AI
8642}
8643
a6ca7158
AN
8644__u32 bpf_program__flags(const struct bpf_program *prog)
8645{
8646 return prog->prog_flags;
8647}
8648
8cccee9e 8649int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
a6ca7158
AN
8650{
8651 if (prog->obj->loaded)
8652 return libbpf_err(-EBUSY);
8653
8cccee9e 8654 prog->prog_flags = flags;
a6ca7158
AN
8655 return 0;
8656}
8657
dbdd2c7f
AN
8658__u32 bpf_program__log_level(const struct bpf_program *prog)
8659{
8660 return prog->log_level;
8661}
8662
8663int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8664{
8665 if (prog->obj->loaded)
8666 return libbpf_err(-EBUSY);
8667
8668 prog->log_level = log_level;
8669 return 0;
8670}
8671
b3ce9079
AN
8672const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8673{
8674 *log_size = prog->log_size;
8675 return prog->log_buf;
8676}
8677
8678int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8679{
8680 if (log_size && !log_buf)
8681 return -EINVAL;
8682 if (prog->log_size > UINT_MAX)
8683 return -EINVAL;
8684 if (prog->obj->loaded)
8685 return -EBUSY;
8686
8687 prog->log_buf = log_buf;
8688 prog->log_size = log_size;
a6ca7158
AN
8689 return 0;
8690}
8691
15ea31fa 8692#define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
697f104d 8693 .sec = (char *)sec_pfx, \
d7a18ea7 8694 .prog_type = BPF_PROG_TYPE_##ptype, \
15ea31fa
AN
8695 .expected_attach_type = atype, \
8696 .cookie = (long)(flags), \
4fa5bcfe 8697 .prog_prepare_load_fn = libbpf_prepare_prog_load, \
d7a18ea7
AN
8698 __VA_ARGS__ \
8699}
8700
4fa5bcfe 8701static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
39f8dc43 8702static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
2e4913e0 8703static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
4fa5bcfe
AN
8704static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8705static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8706static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
ddc6b049 8707static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
4fa5bcfe
AN
8708static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8709static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
d7a18ea7 8710
d7a18ea7 8711static const struct bpf_sec_def section_defs[] = {
dd94d45c
AN
8712 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8713 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8714 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
15ea31fa 8715 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
39f8dc43 8716 SEC_DEF("uprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
15ea31fa 8717 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
39f8dc43 8718 SEC_DEF("uretprobe+", KPROBE, 0, SEC_NONE, attach_uprobe),
ddc6b049
JO
8719 SEC_DEF("kprobe.multi/", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8720 SEC_DEF("kretprobe.multi/", KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
2e4913e0 8721 SEC_DEF("usdt+", KPROBE, 0, SEC_NONE, attach_usdt),
15ea31fa 8722 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
4a4d4cee 8723 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX | SEC_DEPRECATED),
dd94d45c 8724 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
15ea31fa
AN
8725 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8726 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8727 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8728 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
ccaf12d6
HT
8729 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8730 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
15ea31fa
AN
8731 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8732 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8733 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8734 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8735 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8736 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8737 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8738 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8739 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8740 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8741 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
a8b77f74 8742 SEC_DEF("iter.s/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
15ea31fa 8743 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
082c4bfb 8744 SEC_DEF("xdp.frags/devmap", XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
4a4d4cee
LB
8745 SEC_DEF("xdp/devmap", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8746 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
082c4bfb 8747 SEC_DEF("xdp.frags/cpumap", XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
4a4d4cee
LB
8748 SEC_DEF("xdp/cpumap", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8749 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE | SEC_DEPRECATED),
082c4bfb 8750 SEC_DEF("xdp.frags", XDP, BPF_XDP, SEC_XDP_FRAGS),
dd94d45c
AN
8751 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8752 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8753 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8754 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8755 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8756 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8757 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8758 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8759 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8760 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8761 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8762 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8763 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8764 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8765 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8766 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8767 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8768 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8769 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8770 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8771 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8772 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8773 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8774 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8775 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8776 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8777 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8778 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8779 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8780 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8781 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8782 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8783 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8784 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8785 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8786 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8787 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8788 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
7c80c87a 8789 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
583c9009 8790};
d7be143b 8791
697f104d
AN
8792static size_t custom_sec_def_cnt;
8793static struct bpf_sec_def *custom_sec_defs;
8794static struct bpf_sec_def custom_fallback_def;
8795static bool has_custom_fallback_def;
c76e4c22 8796
697f104d
AN
8797static int last_custom_sec_def_handler_id;
8798
8799int libbpf_register_prog_handler(const char *sec,
8800 enum bpf_prog_type prog_type,
8801 enum bpf_attach_type exp_attach_type,
8802 const struct libbpf_prog_handler_opts *opts)
d7a18ea7 8803{
697f104d 8804 struct bpf_sec_def *sec_def;
d7a18ea7 8805
697f104d
AN
8806 if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8807 return libbpf_err(-EINVAL);
dd94d45c 8808
697f104d
AN
8809 if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8810 return libbpf_err(-E2BIG);
dd94d45c 8811
697f104d
AN
8812 if (sec) {
8813 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8814 sizeof(*sec_def));
8815 if (!sec_def)
8816 return libbpf_err(-ENOMEM);
dd94d45c 8817
697f104d
AN
8818 custom_sec_defs = sec_def;
8819 sec_def = &custom_sec_defs[custom_sec_def_cnt];
8820 } else {
8821 if (has_custom_fallback_def)
8822 return libbpf_err(-EBUSY);
dd94d45c 8823
697f104d
AN
8824 sec_def = &custom_fallback_def;
8825 }
8826
8827 sec_def->sec = sec ? strdup(sec) : NULL;
8828 if (sec && !sec_def->sec)
8829 return libbpf_err(-ENOMEM);
8830
8831 sec_def->prog_type = prog_type;
8832 sec_def->expected_attach_type = exp_attach_type;
8833 sec_def->cookie = OPTS_GET(opts, cookie, 0);
8834
8835 sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8836 sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8837 sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8838
8839 sec_def->handler_id = ++last_custom_sec_def_handler_id;
8840
8841 if (sec)
8842 custom_sec_def_cnt++;
8843 else
8844 has_custom_fallback_def = true;
8845
8846 return sec_def->handler_id;
8847}
8848
8849int libbpf_unregister_prog_handler(int handler_id)
8850{
8851 struct bpf_sec_def *sec_defs;
8852 int i;
8853
8854 if (handler_id <= 0)
8855 return libbpf_err(-EINVAL);
8856
8857 if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8858 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8859 has_custom_fallback_def = false;
8860 return 0;
8861 }
8862
8863 for (i = 0; i < custom_sec_def_cnt; i++) {
8864 if (custom_sec_defs[i].handler_id == handler_id)
8865 break;
8866 }
8867
8868 if (i == custom_sec_def_cnt)
8869 return libbpf_err(-ENOENT);
8870
8871 free(custom_sec_defs[i].sec);
8872 for (i = i + 1; i < custom_sec_def_cnt; i++)
8873 custom_sec_defs[i - 1] = custom_sec_defs[i];
8874 custom_sec_def_cnt--;
8875
8876 /* try to shrink the array, but it's ok if we couldn't */
8877 sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8878 if (sec_defs)
8879 custom_sec_defs = sec_defs;
8880
8881 return 0;
8882}
8883
8884static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name,
8885 bool allow_sloppy)
8886{
8887 size_t len = strlen(sec_def->sec);
8888
8889 /* "type/" always has to have proper SEC("type/extras") form */
8890 if (sec_def->sec[len - 1] == '/') {
8891 if (str_has_pfx(sec_name, sec_def->sec))
8892 return true;
8893 return false;
8894 }
8895
8896 /* "type+" means it can be either exact SEC("type") or
8897 * well-formed SEC("type/extras") with proper '/' separator
8898 */
8899 if (sec_def->sec[len - 1] == '+') {
8900 len--;
8901 /* not even a prefix */
8902 if (strncmp(sec_name, sec_def->sec, len) != 0)
8903 return false;
8904 /* exact match or has '/' separator */
8905 if (sec_name[len] == '\0' || sec_name[len] == '/')
8906 return true;
8907 return false;
8908 }
8909
8910 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8911 * matches, unless strict section name mode
8912 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8913 * match has to be exact.
8914 */
8915 if (allow_sloppy && str_has_pfx(sec_name, sec_def->sec))
8916 return true;
8917
8918 /* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8919 * SEC("syscall")) are exact matches in both modes.
8920 */
8921 return strcmp(sec_name, sec_def->sec) == 0;
8922}
8923
8924static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8925{
8926 const struct bpf_sec_def *sec_def;
8927 int i, n;
8928 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME, allow_sloppy;
8929
8930 n = custom_sec_def_cnt;
8931 for (i = 0; i < n; i++) {
8932 sec_def = &custom_sec_defs[i];
8933 if (sec_def_matches(sec_def, sec_name, false))
8934 return sec_def;
8935 }
8936
8937 n = ARRAY_SIZE(section_defs);
8938 for (i = 0; i < n; i++) {
8939 sec_def = &section_defs[i];
8940 allow_sloppy = (sec_def->cookie & SEC_SLOPPY_PFX) && !strict;
8941 if (sec_def_matches(sec_def, sec_name, allow_sloppy))
dd94d45c 8942 return sec_def;
d7a18ea7 8943 }
697f104d
AN
8944
8945 if (has_custom_fallback_def)
8946 return &custom_fallback_def;
8947
d7a18ea7
AN
8948 return NULL;
8949}
8950
697f104d
AN
8951#define MAX_TYPE_NAME_SIZE 32
8952
c76e4c22
TS
8953static char *libbpf_get_type_names(bool attach_type)
8954{
d7a18ea7 8955 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
c76e4c22
TS
8956 char *buf;
8957
8958 buf = malloc(len);
8959 if (!buf)
8960 return NULL;
8961
8962 buf[0] = '\0';
8963 /* Forge string buf with all available names */
d7a18ea7 8964 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
15ea31fa
AN
8965 const struct bpf_sec_def *sec_def = &section_defs[i];
8966
8967 if (attach_type) {
4fa5bcfe 8968 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
15ea31fa
AN
8969 continue;
8970
8971 if (!(sec_def->cookie & SEC_ATTACHABLE))
8972 continue;
8973 }
c76e4c22 8974
d7a18ea7 8975 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
c76e4c22
TS
8976 free(buf);
8977 return NULL;
8978 }
8979 strcat(buf, " ");
d7a18ea7 8980 strcat(buf, section_defs[i].sec);
c76e4c22
TS
8981 }
8982
8983 return buf;
8984}
8985
b60df2a0
JK
8986int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8987 enum bpf_attach_type *expected_attach_type)
583c9009 8988{
d7a18ea7 8989 const struct bpf_sec_def *sec_def;
c76e4c22 8990 char *type_names;
583c9009 8991
b60df2a0 8992 if (!name)
e9fc3ce9 8993 return libbpf_err(-EINVAL);
583c9009 8994
d7a18ea7
AN
8995 sec_def = find_sec_def(name);
8996 if (sec_def) {
8997 *prog_type = sec_def->prog_type;
8998 *expected_attach_type = sec_def->expected_attach_type;
b60df2a0
JK
8999 return 0;
9000 }
d7a18ea7 9001
4a3d6c6a 9002 pr_debug("failed to guess program type from ELF section '%s'\n", name);
c76e4c22
TS
9003 type_names = libbpf_get_type_names(false);
9004 if (type_names != NULL) {
3f519353 9005 pr_debug("supported section(type) names are:%s\n", type_names);
c76e4c22
TS
9006 free(type_names);
9007 }
9008
e9fc3ce9 9009 return libbpf_err(-ESRCH);
b60df2a0 9010}
583c9009 9011
590a0088
MKL
9012static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9013 size_t offset)
9014{
9015 struct bpf_map *map;
9016 size_t i;
9017
9018 for (i = 0; i < obj->nr_maps; i++) {
9019 map = &obj->maps[i];
9020 if (!bpf_map__is_struct_ops(map))
9021 continue;
9022 if (map->sec_offset <= offset &&
9023 offset - map->sec_offset < map->def.value_size)
9024 return map;
9025 }
9026
9027 return NULL;
9028}
9029
9030/* Collect the reloc from ELF and populate the st_ops->progs[] */
646f02ff 9031static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 9032 Elf64_Shdr *shdr, Elf_Data *data)
590a0088
MKL
9033{
9034 const struct btf_member *member;
9035 struct bpf_struct_ops *st_ops;
9036 struct bpf_program *prog;
9037 unsigned int shdr_idx;
9038 const struct btf *btf;
9039 struct bpf_map *map;
7e06aad5 9040 unsigned int moff, insn_idx;
590a0088 9041 const char *name;
1d1a3bcf 9042 __u32 member_idx;
ad23b723
AN
9043 Elf64_Sym *sym;
9044 Elf64_Rel *rel;
590a0088
MKL
9045 int i, nrels;
9046
590a0088
MKL
9047 btf = obj->btf;
9048 nrels = shdr->sh_size / shdr->sh_entsize;
9049 for (i = 0; i < nrels; i++) {
ad23b723
AN
9050 rel = elf_rel_by_idx(data, i);
9051 if (!rel) {
590a0088
MKL
9052 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9053 return -LIBBPF_ERRNO__FORMAT;
9054 }
9055
ad23b723
AN
9056 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9057 if (!sym) {
590a0088 9058 pr_warn("struct_ops reloc: symbol %zx not found\n",
ad23b723 9059 (size_t)ELF64_R_SYM(rel->r_info));
590a0088
MKL
9060 return -LIBBPF_ERRNO__FORMAT;
9061 }
9062
ad23b723
AN
9063 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9064 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
590a0088 9065 if (!map) {
ad23b723
AN
9066 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9067 (size_t)rel->r_offset);
590a0088
MKL
9068 return -EINVAL;
9069 }
9070
ad23b723
AN
9071 moff = rel->r_offset - map->sec_offset;
9072 shdr_idx = sym->st_shndx;
590a0088 9073 st_ops = map->st_ops;
ad23b723 9074 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 9075 map->name,
ad23b723
AN
9076 (long long)(rel->r_info >> 32),
9077 (long long)sym->st_value,
9078 shdr_idx, (size_t)rel->r_offset,
9079 map->sec_offset, sym->st_name, name);
590a0088
MKL
9080
9081 if (shdr_idx >= SHN_LORESERVE) {
ad23b723
AN
9082 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9083 map->name, (size_t)rel->r_offset, shdr_idx);
590a0088
MKL
9084 return -LIBBPF_ERRNO__RELOC;
9085 }
ad23b723 9086 if (sym->st_value % BPF_INSN_SZ) {
7e06aad5 9087 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
ad23b723 9088 map->name, (unsigned long long)sym->st_value);
7e06aad5
AN
9089 return -LIBBPF_ERRNO__FORMAT;
9090 }
ad23b723 9091 insn_idx = sym->st_value / BPF_INSN_SZ;
590a0088
MKL
9092
9093 member = find_member_by_offset(st_ops->type, moff * 8);
9094 if (!member) {
9095 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9096 map->name, moff);
9097 return -EINVAL;
9098 }
9099 member_idx = member - btf_members(st_ops->type);
9100 name = btf__name_by_offset(btf, member->name_off);
9101
9102 if (!resolve_func_ptr(btf, member->type, NULL)) {
9103 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9104 map->name, name);
9105 return -EINVAL;
9106 }
9107
7e06aad5 9108 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
590a0088
MKL
9109 if (!prog) {
9110 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9111 map->name, shdr_idx, name);
9112 return -EINVAL;
9113 }
9114
91b4d1d1
AN
9115 /* prevent the use of BPF prog with invalid type */
9116 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9117 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9118 map->name, prog->name);
9119 return -EINVAL;
9120 }
590a0088 9121
91b4d1d1
AN
9122 /* if we haven't yet processed this BPF program, record proper
9123 * attach_btf_id and member_idx
9124 */
9125 if (!prog->attach_btf_id) {
590a0088
MKL
9126 prog->attach_btf_id = st_ops->type_id;
9127 prog->expected_attach_type = member_idx;
590a0088 9128 }
91b4d1d1
AN
9129
9130 /* struct_ops BPF prog can be re-used between multiple
9131 * .struct_ops as long as it's the same struct_ops struct
9132 * definition and the same function pointer field
9133 */
9134 if (prog->attach_btf_id != st_ops->type_id ||
9135 prog->expected_attach_type != member_idx) {
9136 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",
9137 map->name, prog->name, prog->sec_name, prog->type,
9138 prog->attach_btf_id, prog->expected_attach_type, name);
9139 return -EINVAL;
9140 }
9141
590a0088
MKL
9142 st_ops->progs[member_idx] = prog;
9143 }
9144
9145 return 0;
590a0088
MKL
9146}
9147
a6ed02ca 9148#define BTF_TRACE_PREFIX "btf_trace_"
1e092a03 9149#define BTF_LSM_PREFIX "bpf_lsm_"
21aef70e 9150#define BTF_ITER_PREFIX "bpf_iter_"
a6ed02ca
KS
9151#define BTF_MAX_NAME_SIZE 128
9152
67234743
AS
9153void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9154 const char **prefix, int *kind)
9155{
9156 switch (attach_type) {
9157 case BPF_TRACE_RAW_TP:
9158 *prefix = BTF_TRACE_PREFIX;
9159 *kind = BTF_KIND_TYPEDEF;
9160 break;
9161 case BPF_LSM_MAC:
9162 *prefix = BTF_LSM_PREFIX;
9163 *kind = BTF_KIND_FUNC;
9164 break;
9165 case BPF_TRACE_ITER:
9166 *prefix = BTF_ITER_PREFIX;
9167 *kind = BTF_KIND_FUNC;
9168 break;
9169 default:
9170 *prefix = "";
9171 *kind = BTF_KIND_FUNC;
9172 }
9173}
9174
a6ed02ca
KS
9175static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9176 const char *name, __u32 kind)
9177{
9178 char btf_type_name[BTF_MAX_NAME_SIZE];
9179 int ret;
9180
9181 ret = snprintf(btf_type_name, sizeof(btf_type_name),
9182 "%s%s", prefix, name);
9183 /* snprintf returns the number of characters written excluding the
c139e40a 9184 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
a6ed02ca
KS
9185 * indicates truncation.
9186 */
9187 if (ret < 0 || ret >= sizeof(btf_type_name))
9188 return -ENAMETOOLONG;
9189 return btf__find_by_name_kind(btf, btf_type_name, kind);
9190}
9191
91abb4a6
AN
9192static inline int find_attach_btf_id(struct btf *btf, const char *name,
9193 enum bpf_attach_type attach_type)
a6ed02ca 9194{
67234743
AS
9195 const char *prefix;
9196 int kind;
a6ed02ca 9197
67234743
AS
9198 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9199 return find_btf_by_prefix_kind(btf, prefix, name, kind);
a6ed02ca
KS
9200}
9201
b8c54ea4
AS
9202int libbpf_find_vmlinux_btf_id(const char *name,
9203 enum bpf_attach_type attach_type)
12a8654b 9204{
a6ed02ca 9205 struct btf *btf;
3521ffa2 9206 int err;
12a8654b 9207
a710eed3 9208 btf = btf__load_vmlinux_btf();
e9fc3ce9
AN
9209 err = libbpf_get_error(btf);
9210 if (err) {
12a8654b 9211 pr_warn("vmlinux BTF is not found\n");
e9fc3ce9 9212 return libbpf_err(err);
12a8654b
AS
9213 }
9214
91abb4a6
AN
9215 err = find_attach_btf_id(btf, name, attach_type);
9216 if (err <= 0)
9217 pr_warn("%s is not found in vmlinux BTF\n", name);
9218
3521ffa2 9219 btf__free(btf);
e9fc3ce9 9220 return libbpf_err(err);
b8c54ea4
AS
9221}
9222
e7bf94db
AS
9223static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9224{
ebc7b50a
DM
9225 struct bpf_prog_info info = {};
9226 __u32 info_len = sizeof(info);
6cc93e2f 9227 struct btf *btf;
6d2d73cd 9228 int err;
e7bf94db 9229
ebc7b50a 9230 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
e9fc3ce9 9231 if (err) {
ebc7b50a
DM
9232 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9233 attach_prog_fd, err);
e9fc3ce9 9234 return err;
e7bf94db 9235 }
6d2d73cd
QM
9236
9237 err = -EINVAL;
ebc7b50a 9238 if (!info.btf_id) {
e7bf94db
AS
9239 pr_warn("The target program doesn't have BTF\n");
9240 goto out;
9241 }
ebc7b50a
DM
9242 btf = btf__load_from_kernel_by_id(info.btf_id);
9243 err = libbpf_get_error(btf);
9244 if (err) {
9245 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
e7bf94db
AS
9246 goto out;
9247 }
9248 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9249 btf__free(btf);
9250 if (err <= 0) {
9251 pr_warn("%s is not found in prog's BTF\n", name);
9252 goto out;
9253 }
9254out:
e7bf94db
AS
9255 return err;
9256}
9257
91abb4a6
AN
9258static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9259 enum bpf_attach_type attach_type,
9260 int *btf_obj_fd, int *btf_type_id)
9261{
9262 int ret, i;
9263
9264 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9265 if (ret > 0) {
9266 *btf_obj_fd = 0; /* vmlinux BTF */
9267 *btf_type_id = ret;
9268 return 0;
9269 }
9270 if (ret != -ENOENT)
9271 return ret;
9272
9273 ret = load_module_btfs(obj);
9274 if (ret)
9275 return ret;
9276
9277 for (i = 0; i < obj->btf_module_cnt; i++) {
9278 const struct module_btf *mod = &obj->btf_modules[i];
9279
9280 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9281 if (ret > 0) {
9282 *btf_obj_fd = mod->fd;
9283 *btf_type_id = ret;
9284 return 0;
9285 }
9286 if (ret == -ENOENT)
9287 continue;
9288
9289 return ret;
9290 }
9291
9292 return -ESRCH;
9293}
9294
15ea31fa
AN
9295static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9296 int *btf_obj_fd, int *btf_type_id)
b8c54ea4 9297{
a6ed02ca
KS
9298 enum bpf_attach_type attach_type = prog->expected_attach_type;
9299 __u32 attach_prog_fd = prog->attach_prog_fd;
b6291a6f 9300 int err = 0;
b8c54ea4 9301
91abb4a6
AN
9302 /* BPF program's BTF ID */
9303 if (attach_prog_fd) {
9304 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9305 if (err < 0) {
9306 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9307 attach_prog_fd, attach_name, err);
9308 return err;
9309 }
9310 *btf_obj_fd = 0;
9311 *btf_type_id = err;
9312 return 0;
9313 }
9314
9315 /* kernel/module BTF ID */
67234743
AS
9316 if (prog->obj->gen_loader) {
9317 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9318 *btf_obj_fd = 0;
9319 *btf_type_id = 1;
9320 } else {
9321 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9322 }
91abb4a6
AN
9323 if (err) {
9324 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
b8c54ea4 9325 return err;
12a8654b 9326 }
91abb4a6 9327 return 0;
12a8654b
AS
9328}
9329
956b620f
AI
9330int libbpf_attach_type_by_name(const char *name,
9331 enum bpf_attach_type *attach_type)
9332{
c76e4c22 9333 char *type_names;
b6291a6f 9334 const struct bpf_sec_def *sec_def;
956b620f
AI
9335
9336 if (!name)
e9fc3ce9 9337 return libbpf_err(-EINVAL);
956b620f 9338
b6291a6f
AN
9339 sec_def = find_sec_def(name);
9340 if (!sec_def) {
9341 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9342 type_names = libbpf_get_type_names(true);
9343 if (type_names != NULL) {
9344 pr_debug("attachable section(type) names are:%s\n", type_names);
9345 free(type_names);
9346 }
9347
9348 return libbpf_err(-EINVAL);
c76e4c22
TS
9349 }
9350
4fa5bcfe 9351 if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
15ea31fa
AN
9352 return libbpf_err(-EINVAL);
9353 if (!(sec_def->cookie & SEC_ATTACHABLE))
b6291a6f
AN
9354 return libbpf_err(-EINVAL);
9355
9356 *attach_type = sec_def->expected_attach_type;
9357 return 0;
956b620f
AI
9358}
9359
a324aae3 9360int bpf_map__fd(const struct bpf_map *map)
9d759a9b 9361{
e9fc3ce9 9362 return map ? map->fd : libbpf_err(-EINVAL);
9d759a9b
WN
9363}
9364
a324aae3 9365const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9d759a9b 9366{
e9fc3ce9 9367 return map ? &map->def : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9368}
9369
aed65917
AN
9370static bool map_uses_real_name(const struct bpf_map *map)
9371{
9372 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9373 * their user-visible name differs from kernel-visible name. Users see
9374 * such map's corresponding ELF section name as a map name.
9375 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9376 * maps to know which name has to be returned to the user.
9377 */
9378 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9379 return true;
9380 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9381 return true;
9382 return false;
9383}
9384
a324aae3 9385const char *bpf_map__name(const struct bpf_map *map)
561bbcca 9386{
aed65917
AN
9387 if (!map)
9388 return NULL;
9389
9390 if (map_uses_real_name(map))
9391 return map->real_name;
9392
9393 return map->name;
561bbcca
WN
9394}
9395
1bdb6c9a
AN
9396enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9397{
9398 return map->def.type;
9399}
9400
9401int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9402{
9403 if (map->fd >= 0)
e9fc3ce9 9404 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9405 map->def.type = type;
9406 return 0;
9407}
9408
9409__u32 bpf_map__map_flags(const struct bpf_map *map)
9410{
9411 return map->def.map_flags;
9412}
9413
9414int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9415{
9416 if (map->fd >= 0)
e9fc3ce9 9417 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9418 map->def.map_flags = flags;
9419 return 0;
9420}
9421
47512102
JK
9422__u64 bpf_map__map_extra(const struct bpf_map *map)
9423{
9424 return map->map_extra;
9425}
9426
9427int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9428{
9429 if (map->fd >= 0)
9430 return libbpf_err(-EBUSY);
9431 map->map_extra = map_extra;
9432 return 0;
9433}
9434
1bdb6c9a
AN
9435__u32 bpf_map__numa_node(const struct bpf_map *map)
9436{
9437 return map->numa_node;
9438}
9439
9440int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9441{
9442 if (map->fd >= 0)
e9fc3ce9 9443 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9444 map->numa_node = numa_node;
9445 return 0;
9446}
9447
9448__u32 bpf_map__key_size(const struct bpf_map *map)
9449{
9450 return map->def.key_size;
9451}
9452
9453int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9454{
9455 if (map->fd >= 0)
e9fc3ce9 9456 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9457 map->def.key_size = size;
9458 return 0;
9459}
9460
9461__u32 bpf_map__value_size(const struct bpf_map *map)
9462{
9463 return map->def.value_size;
9464}
9465
9466int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9467{
9468 if (map->fd >= 0)
e9fc3ce9 9469 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9470 map->def.value_size = size;
9471 return 0;
9472}
9473
5b891af7 9474__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8a138aed 9475{
61746dbe 9476 return map ? map->btf_key_type_id : 0;
8a138aed
MKL
9477}
9478
5b891af7 9479__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8a138aed 9480{
61746dbe 9481 return map ? map->btf_value_type_id : 0;
8a138aed
MKL
9482}
9483
edb13ed4
ACM
9484int bpf_map__set_priv(struct bpf_map *map, void *priv,
9485 bpf_map_clear_priv_t clear_priv)
9d759a9b
WN
9486{
9487 if (!map)
e9fc3ce9 9488 return libbpf_err(-EINVAL);
9d759a9b
WN
9489
9490 if (map->priv) {
9491 if (map->clear_priv)
9492 map->clear_priv(map, map->priv);
9493 }
9494
9495 map->priv = priv;
9496 map->clear_priv = clear_priv;
9497 return 0;
9498}
9499
a324aae3 9500void *bpf_map__priv(const struct bpf_map *map)
9d759a9b 9501{
e9fc3ce9 9502 return map ? map->priv : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9503}
9504
e2842be5
THJ
9505int bpf_map__set_initial_value(struct bpf_map *map,
9506 const void *data, size_t size)
9507{
9508 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9509 size != map->def.value_size || map->fd >= 0)
e9fc3ce9 9510 return libbpf_err(-EINVAL);
e2842be5
THJ
9511
9512 memcpy(map->mmaped, data, size);
9513 return 0;
9514}
9515
7723256b
AS
9516const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9517{
9518 if (!map->mmaped)
9519 return NULL;
9520 *psize = map->def.value_size;
9521 return map->mmaped;
9522}
9523
a324aae3 9524bool bpf_map__is_offload_neutral(const struct bpf_map *map)
f83fb22c
JK
9525{
9526 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9527}
9528
a324aae3 9529bool bpf_map__is_internal(const struct bpf_map *map)
d859900c
DB
9530{
9531 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9532}
9533
1bdb6c9a
AN
9534__u32 bpf_map__ifindex(const struct bpf_map *map)
9535{
9536 return map->map_ifindex;
9537}
9538
9539int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9aba3613 9540{
1bdb6c9a 9541 if (map->fd >= 0)
e9fc3ce9 9542 return libbpf_err(-EBUSY);
9aba3613 9543 map->map_ifindex = ifindex;
1bdb6c9a 9544 return 0;
9aba3613
JK
9545}
9546
addb9fc9
NS
9547int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9548{
9549 if (!bpf_map_type__is_map_in_map(map->def.type)) {
be18010e 9550 pr_warn("error: unsupported map type\n");
e9fc3ce9 9551 return libbpf_err(-EINVAL);
addb9fc9
NS
9552 }
9553 if (map->inner_map_fd != -1) {
be18010e 9554 pr_warn("error: inner_map_fd already specified\n");
e9fc3ce9 9555 return libbpf_err(-EINVAL);
addb9fc9 9556 }
8f7b239e
AN
9557 if (map->inner_map) {
9558 bpf_map__destroy(map->inner_map);
9559 zfree(&map->inner_map);
9560 }
addb9fc9
NS
9561 map->inner_map_fd = fd;
9562 return 0;
9563}
9564
0c19a9fb 9565static struct bpf_map *
a324aae3 9566__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9d759a9b 9567{
0c19a9fb 9568 ssize_t idx;
9d759a9b
WN
9569 struct bpf_map *s, *e;
9570
9571 if (!obj || !obj->maps)
e9fc3ce9 9572 return errno = EINVAL, NULL;
9d759a9b
WN
9573
9574 s = obj->maps;
9575 e = obj->maps + obj->nr_maps;
9576
0c19a9fb 9577 if ((m < s) || (m >= e)) {
be18010e
KW
9578 pr_warn("error in %s: map handler doesn't belong to object\n",
9579 __func__);
e9fc3ce9 9580 return errno = EINVAL, NULL;
9d759a9b
WN
9581 }
9582
0c19a9fb
SF
9583 idx = (m - obj->maps) + i;
9584 if (idx >= obj->nr_maps || idx < 0)
9d759a9b
WN
9585 return NULL;
9586 return &obj->maps[idx];
9587}
561bbcca 9588
0c19a9fb 9589struct bpf_map *
a324aae3 9590bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
2088a3a7
HC
9591{
9592 return bpf_object__next_map(obj, prev);
9593}
9594
9595struct bpf_map *
9596bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
0c19a9fb
SF
9597{
9598 if (prev == NULL)
9599 return obj->maps;
9600
9601 return __bpf_map__iter(prev, obj, 1);
9602}
9603
9604struct bpf_map *
a324aae3 9605bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
2088a3a7
HC
9606{
9607 return bpf_object__prev_map(obj, next);
9608}
9609
9610struct bpf_map *
9611bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
0c19a9fb
SF
9612{
9613 if (next == NULL) {
9614 if (!obj->nr_maps)
9615 return NULL;
9616 return obj->maps + obj->nr_maps - 1;
9617 }
9618
9619 return __bpf_map__iter(next, obj, -1);
9620}
9621
561bbcca 9622struct bpf_map *
a324aae3 9623bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
561bbcca
WN
9624{
9625 struct bpf_map *pos;
9626
f74a53d9 9627 bpf_object__for_each_map(pos, obj) {
26071635
AN
9628 /* if it's a special internal map name (which always starts
9629 * with dot) then check if that special name matches the
9630 * real map name (ELF section name)
9631 */
9632 if (name[0] == '.') {
9633 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9634 return pos;
9635 continue;
9636 }
9637 /* otherwise map name has to be an exact match */
aed65917
AN
9638 if (map_uses_real_name(pos)) {
9639 if (strcmp(pos->real_name, name) == 0)
9640 return pos;
9641 continue;
9642 }
9643 if (strcmp(pos->name, name) == 0)
561bbcca
WN
9644 return pos;
9645 }
e9fc3ce9 9646 return errno = ENOENT, NULL;
561bbcca 9647}
5a6acad1 9648
f3cea32d 9649int
a324aae3 9650bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
f3cea32d
MF
9651{
9652 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9653}
9654
5a6acad1
WN
9655struct bpf_map *
9656bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9657{
e9fc3ce9 9658 return libbpf_err_ptr(-ENOTSUP);
5a6acad1 9659}
e28ff1a8
JS
9660
9661long libbpf_get_error(const void *ptr)
9662{
e9fc3ce9
AN
9663 if (!IS_ERR_OR_NULL(ptr))
9664 return 0;
9665
9666 if (IS_ERR(ptr))
9667 errno = -PTR_ERR(ptr);
9668
9669 /* If ptr == NULL, then errno should be already set by the failing
9670 * API, because libbpf never returns NULL on success and it now always
9671 * sets errno on error. So no extra errno handling for ptr == NULL
9672 * case.
9673 */
9674 return -errno;
e28ff1a8 9675}
6f6d33f3 9676
e32660ac 9677__attribute__((alias("bpf_prog_load_xattr2")))
d7be143b 9678int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
e32660ac
AN
9679 struct bpf_object **pobj, int *prog_fd);
9680
9681static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
9682 struct bpf_object **pobj, int *prog_fd)
6f6d33f3 9683{
33bae185 9684 struct bpf_object_open_attr open_attr = {};
48cca7e4 9685 struct bpf_program *prog, *first_prog = NULL;
6f6d33f3 9686 struct bpf_object *obj;
f0307a7e 9687 struct bpf_map *map;
6f6d33f3
JF
9688 int err;
9689
d7be143b 9690 if (!attr)
e9fc3ce9 9691 return libbpf_err(-EINVAL);
17387dd5 9692 if (!attr->file)
e9fc3ce9 9693 return libbpf_err(-EINVAL);
d7be143b 9694
33bae185
LY
9695 open_attr.file = attr->file;
9696 open_attr.prog_type = attr->prog_type;
9697
fc763870 9698 obj = __bpf_object__open_xattr(&open_attr, 0);
e9fc3ce9
AN
9699 err = libbpf_get_error(obj);
9700 if (err)
9701 return libbpf_err(-ENOENT);
6f6d33f3 9702
48cca7e4 9703 bpf_object__for_each_program(prog, obj) {
dd4436bb 9704 enum bpf_attach_type attach_type = attr->expected_attach_type;
48cca7e4 9705 /*
dd4436bb
AN
9706 * to preserve backwards compatibility, bpf_prog_load treats
9707 * attr->prog_type, if specified, as an override to whatever
9708 * bpf_object__open guessed
48cca7e4 9709 */
dd4436bb 9710 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
df286716
GS
9711 prog->type = attr->prog_type;
9712 prog->expected_attach_type = attach_type;
dd4436bb 9713 }
20eccf29 9714 if (bpf_program__type(prog) == BPF_PROG_TYPE_UNSPEC) {
dd4436bb
AN
9715 /*
9716 * we haven't guessed from section name and user
9717 * didn't provide a fallback type, too bad...
9718 */
9719 bpf_object__close(obj);
e9fc3ce9 9720 return libbpf_err(-EINVAL);
583c9009 9721 }
48cca7e4 9722
dd4436bb 9723 prog->prog_ifindex = attr->ifindex;
da11b417 9724 prog->log_level = attr->log_level;
2b288740 9725 prog->prog_flags |= attr->prog_flags;
69495d2a 9726 if (!first_prog)
48cca7e4
AS
9727 first_prog = prog;
9728 }
9729
f74a53d9 9730 bpf_object__for_each_map(map, obj) {
a5dd9589 9731 if (map->def.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
f83fb22c 9732 map->map_ifindex = attr->ifindex;
f0307a7e
DB
9733 }
9734
48cca7e4 9735 if (!first_prog) {
be18010e 9736 pr_warn("object file doesn't contain bpf program\n");
48cca7e4 9737 bpf_object__close(obj);
e9fc3ce9 9738 return libbpf_err(-ENOENT);
583c9009
RG
9739 }
9740
6f6d33f3
JF
9741 err = bpf_object__load(obj);
9742 if (err) {
9743 bpf_object__close(obj);
e9fc3ce9 9744 return libbpf_err(err);
6f6d33f3
JF
9745 }
9746
9747 *pobj = obj;
48cca7e4 9748 *prog_fd = bpf_program__fd(first_prog);
6f6d33f3
JF
9749 return 0;
9750}
d0cabbb0 9751
e32660ac
AN
9752COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
9753int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
9754 struct bpf_object **pobj, int *prog_fd)
9755{
9756 struct bpf_prog_load_attr attr;
9757
9758 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9759 attr.file = file;
9760 attr.prog_type = type;
9761 attr.expected_attach_type = 0;
9762
9763 return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
9764}
9765
cc4f864b
AN
9766/* Replace link's underlying BPF program with the new one */
9767int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9768{
e9fc3ce9 9769 int ret;
c139e40a 9770
e9fc3ce9
AN
9771 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9772 return libbpf_err_errno(ret);
cc4f864b
AN
9773}
9774
d6958706
AN
9775/* Release "ownership" of underlying BPF resource (typically, BPF program
9776 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9777 * link, when destructed through bpf_link__destroy() call won't attempt to
9778 * detach/unregisted that BPF resource. This is useful in situations where,
9779 * say, attached BPF program has to outlive userspace program that attached it
9780 * in the system. Depending on type of BPF program, though, there might be
9781 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9782 * exit of userspace program doesn't trigger automatic detachment and clean up
9783 * inside the kernel.
9784 */
9785void bpf_link__disconnect(struct bpf_link *link)
9786{
9787 link->disconnected = true;
9788}
9789
1c2e9efc
AN
9790int bpf_link__destroy(struct bpf_link *link)
9791{
d6958706 9792 int err = 0;
1c2e9efc 9793
50450fc7 9794 if (IS_ERR_OR_NULL(link))
1c2e9efc
AN
9795 return 0;
9796
d6958706
AN
9797 if (!link->disconnected && link->detach)
9798 err = link->detach(link);
c016b68e
AN
9799 if (link->pin_path)
9800 free(link->pin_path);
d88b71d4
AN
9801 if (link->dealloc)
9802 link->dealloc(link);
9803 else
9804 free(link);
1c2e9efc 9805
e9fc3ce9 9806 return libbpf_err(err);
1c2e9efc
AN
9807}
9808
c016b68e
AN
9809int bpf_link__fd(const struct bpf_link *link)
9810{
9811 return link->fd;
9812}
9813
9814const char *bpf_link__pin_path(const struct bpf_link *link)
9815{
9816 return link->pin_path;
9817}
9818
9819static int bpf_link__detach_fd(struct bpf_link *link)
9820{
e9fc3ce9 9821 return libbpf_err_errno(close(link->fd));
c016b68e
AN
9822}
9823
9824struct bpf_link *bpf_link__open(const char *path)
9825{
9826 struct bpf_link *link;
9827 int fd;
9828
9829 fd = bpf_obj_get(path);
9830 if (fd < 0) {
9831 fd = -errno;
9832 pr_warn("failed to open link at %s: %d\n", path, fd);
e9fc3ce9 9833 return libbpf_err_ptr(fd);
c016b68e
AN
9834 }
9835
9836 link = calloc(1, sizeof(*link));
9837 if (!link) {
9838 close(fd);
e9fc3ce9 9839 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9840 }
9841 link->detach = &bpf_link__detach_fd;
9842 link->fd = fd;
9843
9844 link->pin_path = strdup(path);
9845 if (!link->pin_path) {
9846 bpf_link__destroy(link);
e9fc3ce9 9847 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9848 }
9849
9850 return link;
9851}
9852
2e49527e
AN
9853int bpf_link__detach(struct bpf_link *link)
9854{
9855 return bpf_link_detach(link->fd) ? -errno : 0;
9856}
9857
c016b68e
AN
9858int bpf_link__pin(struct bpf_link *link, const char *path)
9859{
9860 int err;
9861
9862 if (link->pin_path)
e9fc3ce9 9863 return libbpf_err(-EBUSY);
c016b68e
AN
9864 err = make_parent_dir(path);
9865 if (err)
e9fc3ce9 9866 return libbpf_err(err);
c016b68e
AN
9867 err = check_path(path);
9868 if (err)
e9fc3ce9 9869 return libbpf_err(err);
c016b68e
AN
9870
9871 link->pin_path = strdup(path);
9872 if (!link->pin_path)
e9fc3ce9 9873 return libbpf_err(-ENOMEM);
c016b68e
AN
9874
9875 if (bpf_obj_pin(link->fd, link->pin_path)) {
9876 err = -errno;
9877 zfree(&link->pin_path);
e9fc3ce9 9878 return libbpf_err(err);
c016b68e
AN
9879 }
9880
9881 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9882 return 0;
9883}
9884
9885int bpf_link__unpin(struct bpf_link *link)
9886{
9887 int err;
9888
9889 if (!link->pin_path)
e9fc3ce9 9890 return libbpf_err(-EINVAL);
c016b68e
AN
9891
9892 err = unlink(link->pin_path);
9893 if (err != 0)
af0efa05 9894 return -errno;
c016b68e
AN
9895
9896 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9897 zfree(&link->pin_path);
9898 return 0;
9899}
63f2f5ee 9900
668ace0e
AN
9901struct bpf_link_perf {
9902 struct bpf_link link;
9903 int perf_event_fd;
ca304b40
RDT
9904 /* legacy kprobe support: keep track of probe identifier and type */
9905 char *legacy_probe_name;
46ed5fc3 9906 bool legacy_is_kprobe;
ca304b40 9907 bool legacy_is_retprobe;
668ace0e
AN
9908};
9909
46ed5fc3 9910static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
cc10623c 9911static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
46ed5fc3 9912
668ace0e 9913static int bpf_link_perf_detach(struct bpf_link *link)
63f2f5ee 9914{
668ace0e
AN
9915 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9916 int err = 0;
63f2f5ee 9917
668ace0e 9918 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
63f2f5ee
AN
9919 err = -errno;
9920
668ace0e
AN
9921 if (perf_link->perf_event_fd != link->fd)
9922 close(perf_link->perf_event_fd);
c016b68e 9923 close(link->fd);
668ace0e 9924
cc10623c 9925 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
46ed5fc3
AN
9926 if (perf_link->legacy_probe_name) {
9927 if (perf_link->legacy_is_kprobe) {
9928 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9929 perf_link->legacy_is_retprobe);
cc10623c
AN
9930 } else {
9931 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9932 perf_link->legacy_is_retprobe);
46ed5fc3
AN
9933 }
9934 }
ca304b40
RDT
9935
9936 return err;
63f2f5ee
AN
9937}
9938
668ace0e
AN
9939static void bpf_link_perf_dealloc(struct bpf_link *link)
9940{
9941 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9942
ca304b40 9943 free(perf_link->legacy_probe_name);
668ace0e
AN
9944 free(perf_link);
9945}
9946
942025c9 9947struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
47faff37 9948 const struct bpf_perf_event_opts *opts)
63f2f5ee
AN
9949{
9950 char errmsg[STRERR_BUFSIZE];
668ace0e
AN
9951 struct bpf_link_perf *link;
9952 int prog_fd, link_fd = -1, err;
63f2f5ee 9953
47faff37
AN
9954 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9955 return libbpf_err_ptr(-EINVAL);
9956
63f2f5ee 9957 if (pfd < 0) {
52109584
AN
9958 pr_warn("prog '%s': invalid perf event FD %d\n",
9959 prog->name, pfd);
e9fc3ce9 9960 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9961 }
9962 prog_fd = bpf_program__fd(prog);
9963 if (prog_fd < 0) {
52109584
AN
9964 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9965 prog->name);
e9fc3ce9 9966 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9967 }
9968
d6958706 9969 link = calloc(1, sizeof(*link));
63f2f5ee 9970 if (!link)
e9fc3ce9 9971 return libbpf_err_ptr(-ENOMEM);
668ace0e
AN
9972 link->link.detach = &bpf_link_perf_detach;
9973 link->link.dealloc = &bpf_link_perf_dealloc;
9974 link->perf_event_fd = pfd;
63f2f5ee 9975
668ace0e 9976 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
47faff37
AN
9977 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9978 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9979
9980 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
668ace0e
AN
9981 if (link_fd < 0) {
9982 err = -errno;
9983 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9984 prog->name, pfd,
9985 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9986 goto err_out;
9987 }
9988 link->link.fd = link_fd;
9989 } else {
47faff37
AN
9990 if (OPTS_GET(opts, bpf_cookie, 0)) {
9991 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9992 err = -EOPNOTSUPP;
9993 goto err_out;
9994 }
9995
668ace0e
AN
9996 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9997 err = -errno;
9998 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9999 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10000 if (err == -EPROTO)
10001 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10002 prog->name, pfd);
10003 goto err_out;
10004 }
10005 link->link.fd = pfd;
63f2f5ee
AN
10006 }
10007 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10008 err = -errno;
668ace0e 10009 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
52109584 10010 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
668ace0e 10011 goto err_out;
63f2f5ee 10012 }
668ace0e
AN
10013
10014 return &link->link;
10015err_out:
10016 if (link_fd >= 0)
10017 close(link_fd);
10018 free(link);
10019 return libbpf_err_ptr(err);
63f2f5ee
AN
10020}
10021
942025c9 10022struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
47faff37
AN
10023{
10024 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10025}
10026
b2650027
AN
10027/*
10028 * this function is expected to parse integer in the range of [0, 2^31-1] from
10029 * given file using scanf format string fmt. If actual parsed value is
10030 * negative, the result might be indistinguishable from error
10031 */
10032static int parse_uint_from_file(const char *file, const char *fmt)
10033{
10034 char buf[STRERR_BUFSIZE];
10035 int err, ret;
10036 FILE *f;
10037
10038 f = fopen(file, "r");
10039 if (!f) {
10040 err = -errno;
10041 pr_debug("failed to open '%s': %s\n", file,
10042 libbpf_strerror_r(err, buf, sizeof(buf)));
10043 return err;
10044 }
10045 err = fscanf(f, fmt, &ret);
10046 if (err != 1) {
10047 err = err == EOF ? -EIO : -errno;
10048 pr_debug("failed to parse '%s': %s\n", file,
10049 libbpf_strerror_r(err, buf, sizeof(buf)));
10050 fclose(f);
10051 return err;
10052 }
10053 fclose(f);
10054 return ret;
10055}
10056
10057static int determine_kprobe_perf_type(void)
10058{
10059 const char *file = "/sys/bus/event_source/devices/kprobe/type";
10060
10061 return parse_uint_from_file(file, "%d\n");
10062}
10063
10064static int determine_uprobe_perf_type(void)
10065{
10066 const char *file = "/sys/bus/event_source/devices/uprobe/type";
10067
10068 return parse_uint_from_file(file, "%d\n");
10069}
10070
10071static int determine_kprobe_retprobe_bit(void)
10072{
10073 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10074
10075 return parse_uint_from_file(file, "config:%d\n");
10076}
10077
10078static int determine_uprobe_retprobe_bit(void)
10079{
10080 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10081
10082 return parse_uint_from_file(file, "config:%d\n");
10083}
10084
5e3b8356
AN
10085#define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10086#define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10087
b2650027 10088static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5e3b8356 10089 uint64_t offset, int pid, size_t ref_ctr_off)
b2650027
AN
10090{
10091 struct perf_event_attr attr = {};
10092 char errmsg[STRERR_BUFSIZE];
10093 int type, pfd, err;
10094
5e3b8356
AN
10095 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10096 return -EINVAL;
10097
b2650027
AN
10098 type = uprobe ? determine_uprobe_perf_type()
10099 : determine_kprobe_perf_type();
10100 if (type < 0) {
be18010e
KW
10101 pr_warn("failed to determine %s perf type: %s\n",
10102 uprobe ? "uprobe" : "kprobe",
10103 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
b2650027
AN
10104 return type;
10105 }
10106 if (retprobe) {
10107 int bit = uprobe ? determine_uprobe_retprobe_bit()
10108 : determine_kprobe_retprobe_bit();
10109
10110 if (bit < 0) {
be18010e
KW
10111 pr_warn("failed to determine %s retprobe bit: %s\n",
10112 uprobe ? "uprobe" : "kprobe",
10113 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
b2650027
AN
10114 return bit;
10115 }
10116 attr.config |= 1 << bit;
10117 }
10118 attr.size = sizeof(attr);
10119 attr.type = type;
5e3b8356 10120 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
36db2a94
AN
10121 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10122 attr.config2 = offset; /* kprobe_addr or probe_offset */
b2650027
AN
10123
10124 /* pid filter is meaningful only for uprobes */
10125 pfd = syscall(__NR_perf_event_open, &attr,
10126 pid < 0 ? -1 : pid /* pid */,
10127 pid == -1 ? 0 : -1 /* cpu */,
10128 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10129 if (pfd < 0) {
10130 err = -errno;
be18010e
KW
10131 pr_warn("%s perf_event_open() failed: %s\n",
10132 uprobe ? "uprobe" : "kprobe",
10133 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
b2650027
AN
10134 return err;
10135 }
10136 return pfd;
10137}
10138
46ed5fc3
AN
10139static int append_to_file(const char *file, const char *fmt, ...)
10140{
10141 int fd, n, err = 0;
10142 va_list ap;
10143
92274e24 10144 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
46ed5fc3
AN
10145 if (fd < 0)
10146 return -errno;
10147
10148 va_start(ap, fmt);
10149 n = vdprintf(fd, fmt, ap);
10150 va_end(ap);
10151
10152 if (n < 0)
10153 err = -errno;
10154
10155 close(fd);
10156 return err;
10157}
10158
10159static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10160 const char *kfunc_name, size_t offset)
10161{
51a33c60
QW
10162 static int index = 0;
10163
10164 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10165 __sync_fetch_and_add(&index, 1));
46ed5fc3
AN
10166}
10167
10168static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10169 const char *kfunc_name, size_t offset)
10170{
10171 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10172
10173 return append_to_file(file, "%c:%s/%s %s+0x%zx",
10174 retprobe ? 'r' : 'p',
10175 retprobe ? "kretprobes" : "kprobes",
10176 probe_name, kfunc_name, offset);
10177}
10178
10179static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10180{
10181 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
10182
10183 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
10184}
10185
10186static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10187{
10188 char file[256];
10189
10190 snprintf(file, sizeof(file),
10191 "/sys/kernel/debug/tracing/events/%s/%s/id",
10192 retprobe ? "kretprobes" : "kprobes", probe_name);
10193
10194 return parse_uint_from_file(file, "%d\n");
10195}
10196
10197static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10198 const char *kfunc_name, size_t offset, int pid)
ca304b40
RDT
10199{
10200 struct perf_event_attr attr = {};
10201 char errmsg[STRERR_BUFSIZE];
10202 int type, pfd, err;
10203
46ed5fc3 10204 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
ca304b40 10205 if (err < 0) {
46ed5fc3
AN
10206 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10207 kfunc_name, offset,
ca304b40
RDT
10208 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10209 return err;
10210 }
46ed5fc3 10211 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
ca304b40 10212 if (type < 0) {
46ed5fc3
AN
10213 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10214 kfunc_name, offset,
ca304b40
RDT
10215 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10216 return type;
10217 }
10218 attr.size = sizeof(attr);
10219 attr.config = type;
10220 attr.type = PERF_TYPE_TRACEPOINT;
10221
10222 pfd = syscall(__NR_perf_event_open, &attr,
10223 pid < 0 ? -1 : pid, /* pid */
10224 pid == -1 ? 0 : -1, /* cpu */
10225 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10226 if (pfd < 0) {
10227 err = -errno;
10228 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10229 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10230 return err;
10231 }
10232 return pfd;
10233}
10234
da97553e 10235struct bpf_link *
942025c9 10236bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
ac0ed488 10237 const char *func_name,
47faff37 10238 const struct bpf_kprobe_opts *opts)
b2650027 10239{
47faff37 10240 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
b2650027 10241 char errmsg[STRERR_BUFSIZE];
ca304b40 10242 char *legacy_probe = NULL;
b2650027 10243 struct bpf_link *link;
46ed5fc3 10244 size_t offset;
ca304b40 10245 bool retprobe, legacy;
b2650027
AN
10246 int pfd, err;
10247
da97553e
JO
10248 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10249 return libbpf_err_ptr(-EINVAL);
10250
10251 retprobe = OPTS_GET(opts, retprobe, false);
10252 offset = OPTS_GET(opts, offset, 0);
47faff37 10253 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
da97553e 10254
ca304b40
RDT
10255 legacy = determine_kprobe_perf_type() < 0;
10256 if (!legacy) {
10257 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10258 func_name, offset,
10259 -1 /* pid */, 0 /* ref_ctr_off */);
10260 } else {
46ed5fc3
AN
10261 char probe_name[256];
10262
10263 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10264 func_name, offset);
10265
71cff670 10266 legacy_probe = strdup(probe_name);
ca304b40
RDT
10267 if (!legacy_probe)
10268 return libbpf_err_ptr(-ENOMEM);
10269
46ed5fc3 10270 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
ca304b40
RDT
10271 offset, -1 /* pid */);
10272 }
b2650027 10273 if (pfd < 0) {
46ed5fc3
AN
10274 err = -errno;
10275 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10276 prog->name, retprobe ? "kretprobe" : "kprobe",
10277 func_name, offset,
303a2572
AN
10278 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10279 goto err_out;
b2650027 10280 }
47faff37 10281 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10282 err = libbpf_get_error(link);
10283 if (err) {
b2650027 10284 close(pfd);
46ed5fc3
AN
10285 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10286 prog->name, retprobe ? "kretprobe" : "kprobe",
10287 func_name, offset,
be18010e 10288 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
303a2572 10289 goto err_out;
b2650027 10290 }
ca304b40
RDT
10291 if (legacy) {
10292 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10293
10294 perf_link->legacy_probe_name = legacy_probe;
46ed5fc3 10295 perf_link->legacy_is_kprobe = true;
ca304b40
RDT
10296 perf_link->legacy_is_retprobe = retprobe;
10297 }
10298
b2650027 10299 return link;
303a2572
AN
10300err_out:
10301 free(legacy_probe);
10302 return libbpf_err_ptr(err);
b2650027
AN
10303}
10304
942025c9 10305struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
ac0ed488
JO
10306 bool retprobe,
10307 const char *func_name)
10308{
da97553e 10309 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
ac0ed488 10310 .retprobe = retprobe,
da97553e 10311 );
ac0ed488
JO
10312
10313 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10314}
10315
ddc6b049
JO
10316/* Adapted from perf/util/string.c */
10317static bool glob_match(const char *str, const char *pat)
10318{
10319 while (*str && *pat && *pat != '*') {
10320 if (*pat == '?') { /* Matches any single character */
10321 str++;
10322 pat++;
10323 continue;
10324 }
10325 if (*str != *pat)
10326 return false;
10327 str++;
10328 pat++;
10329 }
10330 /* Check wild card */
10331 if (*pat == '*') {
10332 while (*pat == '*')
10333 pat++;
10334 if (!*pat) /* Tail wild card matches all */
10335 return true;
10336 while (*str)
10337 if (glob_match(str++, pat))
10338 return true;
10339 }
10340 return !*str && !*pat;
10341}
10342
10343struct kprobe_multi_resolve {
10344 const char *pattern;
10345 unsigned long *addrs;
10346 size_t cap;
10347 size_t cnt;
10348};
10349
10350static int
10351resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10352 const char *sym_name, void *ctx)
10353{
10354 struct kprobe_multi_resolve *res = ctx;
10355 int err;
10356
10357 if (!glob_match(sym_name, res->pattern))
10358 return 0;
10359
10360 err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10361 res->cnt + 1);
10362 if (err)
10363 return err;
10364
10365 res->addrs[res->cnt++] = (unsigned long) sym_addr;
10366 return 0;
10367}
10368
10369struct bpf_link *
10370bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10371 const char *pattern,
10372 const struct bpf_kprobe_multi_opts *opts)
10373{
10374 LIBBPF_OPTS(bpf_link_create_opts, lopts);
10375 struct kprobe_multi_resolve res = {
10376 .pattern = pattern,
10377 };
10378 struct bpf_link *link = NULL;
10379 char errmsg[STRERR_BUFSIZE];
10380 const unsigned long *addrs;
10381 int err, link_fd, prog_fd;
10382 const __u64 *cookies;
10383 const char **syms;
10384 bool retprobe;
10385 size_t cnt;
10386
10387 if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10388 return libbpf_err_ptr(-EINVAL);
10389
10390 syms = OPTS_GET(opts, syms, false);
10391 addrs = OPTS_GET(opts, addrs, false);
10392 cnt = OPTS_GET(opts, cnt, false);
10393 cookies = OPTS_GET(opts, cookies, false);
10394
10395 if (!pattern && !addrs && !syms)
10396 return libbpf_err_ptr(-EINVAL);
10397 if (pattern && (addrs || syms || cookies || cnt))
10398 return libbpf_err_ptr(-EINVAL);
10399 if (!pattern && !cnt)
10400 return libbpf_err_ptr(-EINVAL);
10401 if (addrs && syms)
10402 return libbpf_err_ptr(-EINVAL);
10403
10404 if (pattern) {
10405 err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10406 if (err)
10407 goto error;
10408 if (!res.cnt) {
10409 err = -ENOENT;
10410 goto error;
10411 }
10412 addrs = res.addrs;
10413 cnt = res.cnt;
10414 }
10415
10416 retprobe = OPTS_GET(opts, retprobe, false);
10417
10418 lopts.kprobe_multi.syms = syms;
10419 lopts.kprobe_multi.addrs = addrs;
10420 lopts.kprobe_multi.cookies = cookies;
10421 lopts.kprobe_multi.cnt = cnt;
10422 lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10423
10424 link = calloc(1, sizeof(*link));
10425 if (!link) {
10426 err = -ENOMEM;
10427 goto error;
10428 }
10429 link->detach = &bpf_link__detach_fd;
10430
10431 prog_fd = bpf_program__fd(prog);
10432 link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10433 if (link_fd < 0) {
10434 err = -errno;
10435 pr_warn("prog '%s': failed to attach: %s\n",
10436 prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10437 goto error;
10438 }
10439 link->fd = link_fd;
10440 free(res.addrs);
10441 return link;
10442
10443error:
10444 free(link);
10445 free(res.addrs);
10446 return libbpf_err_ptr(err);
10447}
10448
4fa5bcfe 10449static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 10450{
da97553e 10451 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
a2488b5f 10452 unsigned long offset = 0;
d7a18ea7 10453 const char *func_name;
a2488b5f 10454 char *func;
4fa5bcfe 10455 int n;
d7a18ea7 10456
13d35a0c
AN
10457 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10458 if (opts.retprobe)
10459 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10460 else
10461 func_name = prog->sec_name + sizeof("kprobe/") - 1;
d7a18ea7 10462
e3f9bc35 10463 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
a2488b5f 10464 if (n < 1) {
a2488b5f 10465 pr_warn("kprobe name is invalid: %s\n", func_name);
4fa5bcfe 10466 return -EINVAL;
a2488b5f
AM
10467 }
10468 if (opts.retprobe && offset != 0) {
1f71a468 10469 free(func);
a2488b5f 10470 pr_warn("kretprobes do not support offset specification\n");
4fa5bcfe 10471 return -EINVAL;
a2488b5f 10472 }
d7a18ea7 10473
a2488b5f 10474 opts.offset = offset;
4fa5bcfe 10475 *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
a2488b5f 10476 free(func);
4fa5bcfe 10477 return libbpf_get_error(*link);
d7a18ea7
AN
10478}
10479
ddc6b049
JO
10480static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10481{
10482 LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10483 const char *spec;
10484 char *pattern;
10485 int n;
10486
10487 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10488 if (opts.retprobe)
10489 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10490 else
10491 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10492
10493 n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10494 if (n < 1) {
10495 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10496 return -EINVAL;
10497 }
10498
10499 *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10500 free(pattern);
10501 return libbpf_get_error(*link);
10502}
10503
cc10623c
AN
10504static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10505 const char *binary_path, uint64_t offset)
10506{
10507 int i;
10508
10509 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10510
10511 /* sanitize binary_path in the probe name */
10512 for (i = 0; buf[i]; i++) {
10513 if (!isalnum(buf[i]))
10514 buf[i] = '_';
10515 }
10516}
10517
10518static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10519 const char *binary_path, size_t offset)
10520{
10521 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10522
10523 return append_to_file(file, "%c:%s/%s %s:0x%zx",
10524 retprobe ? 'r' : 'p',
10525 retprobe ? "uretprobes" : "uprobes",
10526 probe_name, binary_path, offset);
10527}
10528
10529static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10530{
10531 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10532
10533 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10534}
10535
10536static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10537{
10538 char file[512];
10539
10540 snprintf(file, sizeof(file),
10541 "/sys/kernel/debug/tracing/events/%s/%s/id",
10542 retprobe ? "uretprobes" : "uprobes", probe_name);
10543
10544 return parse_uint_from_file(file, "%d\n");
10545}
10546
10547static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10548 const char *binary_path, size_t offset, int pid)
10549{
10550 struct perf_event_attr attr;
10551 int type, pfd, err;
10552
10553 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10554 if (err < 0) {
10555 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10556 binary_path, (size_t)offset, err);
10557 return err;
10558 }
10559 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10560 if (type < 0) {
10561 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10562 binary_path, offset, err);
10563 return type;
10564 }
10565
10566 memset(&attr, 0, sizeof(attr));
10567 attr.size = sizeof(attr);
10568 attr.config = type;
10569 attr.type = PERF_TYPE_TRACEPOINT;
10570
10571 pfd = syscall(__NR_perf_event_open, &attr,
10572 pid < 0 ? -1 : pid, /* pid */
10573 pid == -1 ? 0 : -1, /* cpu */
10574 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10575 if (pfd < 0) {
10576 err = -errno;
10577 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10578 return err;
10579 }
10580 return pfd;
10581}
10582
433966e3
AM
10583/* uprobes deal in relative offsets; subtract the base address associated with
10584 * the mapped binary. See Documentation/trace/uprobetracer.rst for more
10585 * details.
10586 */
10587static long elf_find_relative_offset(const char *filename, Elf *elf, long addr)
10588{
10589 size_t n;
10590 int i;
10591
10592 if (elf_getphdrnum(elf, &n)) {
10593 pr_warn("elf: failed to find program headers for '%s': %s\n", filename,
10594 elf_errmsg(-1));
10595 return -ENOENT;
10596 }
10597
10598 for (i = 0; i < n; i++) {
10599 int seg_start, seg_end, seg_offset;
10600 GElf_Phdr phdr;
10601
10602 if (!gelf_getphdr(elf, i, &phdr)) {
10603 pr_warn("elf: failed to get program header %d from '%s': %s\n", i, filename,
10604 elf_errmsg(-1));
10605 return -ENOENT;
10606 }
10607 if (phdr.p_type != PT_LOAD || !(phdr.p_flags & PF_X))
10608 continue;
10609
10610 seg_start = phdr.p_vaddr;
10611 seg_end = seg_start + phdr.p_memsz;
10612 seg_offset = phdr.p_offset;
10613 if (addr >= seg_start && addr < seg_end)
10614 return addr - seg_start + seg_offset;
10615 }
10616 pr_warn("elf: failed to find prog header containing 0x%lx in '%s'\n", addr, filename);
10617 return -ENOENT;
10618}
10619
10620/* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10621static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10622{
10623 while ((scn = elf_nextscn(elf, scn)) != NULL) {
10624 GElf_Shdr sh;
10625
10626 if (!gelf_getshdr(scn, &sh))
10627 continue;
10628 if (sh.sh_type == sh_type)
10629 return scn;
10630 }
10631 return NULL;
10632}
10633
10634/* Find offset of function name in object specified by path. "name" matches
10635 * symbol name or name@@LIB for library functions.
10636 */
10637static long elf_find_func_offset(const char *binary_path, const char *name)
10638{
10639 int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10640 bool is_shared_lib, is_name_qualified;
10641 char errmsg[STRERR_BUFSIZE];
10642 long ret = -ENOENT;
10643 size_t name_len;
10644 GElf_Ehdr ehdr;
10645 Elf *elf;
10646
10647 fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10648 if (fd < 0) {
10649 ret = -errno;
10650 pr_warn("failed to open %s: %s\n", binary_path,
10651 libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10652 return ret;
10653 }
10654 elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10655 if (!elf) {
10656 pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10657 close(fd);
10658 return -LIBBPF_ERRNO__FORMAT;
10659 }
10660 if (!gelf_getehdr(elf, &ehdr)) {
10661 pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10662 ret = -LIBBPF_ERRNO__FORMAT;
10663 goto out;
10664 }
10665 /* for shared lib case, we do not need to calculate relative offset */
10666 is_shared_lib = ehdr.e_type == ET_DYN;
10667
10668 name_len = strlen(name);
10669 /* Does name specify "@@LIB"? */
10670 is_name_qualified = strstr(name, "@@") != NULL;
10671
10672 /* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10673 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10674 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10675 * reported as a warning/error.
10676 */
10677 for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10678 size_t nr_syms, strtabidx, idx;
10679 Elf_Data *symbols = NULL;
10680 Elf_Scn *scn = NULL;
10681 int last_bind = -1;
10682 const char *sname;
10683 GElf_Shdr sh;
10684
10685 scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10686 if (!scn) {
10687 pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10688 binary_path);
10689 continue;
10690 }
10691 if (!gelf_getshdr(scn, &sh))
10692 continue;
10693 strtabidx = sh.sh_link;
10694 symbols = elf_getdata(scn, 0);
10695 if (!symbols) {
10696 pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10697 binary_path, elf_errmsg(-1));
10698 ret = -LIBBPF_ERRNO__FORMAT;
10699 goto out;
10700 }
10701 nr_syms = symbols->d_size / sh.sh_entsize;
10702
10703 for (idx = 0; idx < nr_syms; idx++) {
10704 int curr_bind;
10705 GElf_Sym sym;
10706
10707 if (!gelf_getsym(symbols, idx, &sym))
10708 continue;
10709
10710 if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10711 continue;
10712
10713 sname = elf_strptr(elf, strtabidx, sym.st_name);
10714 if (!sname)
10715 continue;
10716
10717 curr_bind = GELF_ST_BIND(sym.st_info);
10718
10719 /* User can specify func, func@@LIB or func@@LIB_VERSION. */
10720 if (strncmp(sname, name, name_len) != 0)
10721 continue;
10722 /* ...but we don't want a search for "foo" to match 'foo2" also, so any
10723 * additional characters in sname should be of the form "@@LIB".
10724 */
10725 if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10726 continue;
10727
10728 if (ret >= 0) {
10729 /* handle multiple matches */
10730 if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10731 /* Only accept one non-weak bind. */
10732 pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10733 sname, name, binary_path);
10734 ret = -LIBBPF_ERRNO__FORMAT;
10735 goto out;
10736 } else if (curr_bind == STB_WEAK) {
10737 /* already have a non-weak bind, and
10738 * this is a weak bind, so ignore.
10739 */
10740 continue;
10741 }
10742 }
10743 ret = sym.st_value;
10744 last_bind = curr_bind;
10745 }
10746 /* For binaries that are not shared libraries, we need relative offset */
10747 if (ret > 0 && !is_shared_lib)
10748 ret = elf_find_relative_offset(binary_path, elf, ret);
10749 if (ret > 0)
10750 break;
10751 }
10752
10753 if (ret > 0) {
10754 pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10755 ret);
10756 } else {
10757 if (ret == 0) {
10758 pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10759 is_shared_lib ? "should not be 0 in a shared library" :
10760 "try using shared library path instead");
10761 ret = -ENOENT;
10762 } else {
10763 pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10764 }
10765 }
10766out:
10767 elf_end(elf);
10768 close(fd);
10769 return ret;
10770}
10771
56818931
IL
10772static const char *arch_specific_lib_paths(void)
10773{
10774 /*
10775 * Based on https://packages.debian.org/sid/libc6.
10776 *
10777 * Assume that the traced program is built for the same architecture
10778 * as libbpf, which should cover the vast majority of cases.
10779 */
10780#if defined(__x86_64__)
10781 return "/lib/x86_64-linux-gnu";
10782#elif defined(__i386__)
10783 return "/lib/i386-linux-gnu";
10784#elif defined(__s390x__)
10785 return "/lib/s390x-linux-gnu";
10786#elif defined(__s390__)
10787 return "/lib/s390-linux-gnu";
10788#elif defined(__arm__) && defined(__SOFTFP__)
10789 return "/lib/arm-linux-gnueabi";
10790#elif defined(__arm__) && !defined(__SOFTFP__)
10791 return "/lib/arm-linux-gnueabihf";
10792#elif defined(__aarch64__)
10793 return "/lib/aarch64-linux-gnu";
10794#elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10795 return "/lib/mips64el-linux-gnuabi64";
10796#elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10797 return "/lib/mipsel-linux-gnu";
10798#elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10799 return "/lib/powerpc64le-linux-gnu";
10800#elif defined(__sparc__) && defined(__arch64__)
10801 return "/lib/sparc64-linux-gnu";
10802#elif defined(__riscv) && __riscv_xlen == 64
10803 return "/lib/riscv64-linux-gnu";
10804#else
10805 return NULL;
10806#endif
10807}
10808
1ce3a60e
AM
10809/* Get full path to program/shared library. */
10810static int resolve_full_path(const char *file, char *result, size_t result_sz)
10811{
56818931 10812 const char *search_paths[3] = {};
1ce3a60e
AM
10813 int i;
10814
a1c9d61b 10815 if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
1ce3a60e
AM
10816 search_paths[0] = getenv("LD_LIBRARY_PATH");
10817 search_paths[1] = "/usr/lib64:/usr/lib";
56818931 10818 search_paths[2] = arch_specific_lib_paths();
1ce3a60e
AM
10819 } else {
10820 search_paths[0] = getenv("PATH");
10821 search_paths[1] = "/usr/bin:/usr/sbin";
10822 }
10823
10824 for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10825 const char *s;
10826
10827 if (!search_paths[i])
10828 continue;
10829 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10830 char *next_path;
10831 int seg_len;
10832
10833 if (s[0] == ':')
10834 s++;
10835 next_path = strchr(s, ':');
10836 seg_len = next_path ? next_path - s : strlen(s);
10837 if (!seg_len)
10838 continue;
10839 snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10840 /* ensure it is an executable file/link */
10841 if (access(result, R_OK | X_OK) < 0)
10842 continue;
10843 pr_debug("resolved '%s' to '%s'\n", file, result);
10844 return 0;
10845 }
10846 }
10847 return -ENOENT;
10848}
10849
47faff37 10850LIBBPF_API struct bpf_link *
942025c9 10851bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
47faff37
AN
10852 const char *binary_path, size_t func_offset,
10853 const struct bpf_uprobe_opts *opts)
b2650027 10854{
47faff37 10855 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
cc10623c 10856 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
1ce3a60e 10857 char full_binary_path[PATH_MAX];
b2650027 10858 struct bpf_link *link;
5e3b8356 10859 size_t ref_ctr_off;
b2650027 10860 int pfd, err;
cc10623c 10861 bool retprobe, legacy;
433966e3 10862 const char *func_name;
47faff37
AN
10863
10864 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10865 return libbpf_err_ptr(-EINVAL);
10866
10867 retprobe = OPTS_GET(opts, retprobe, false);
5e3b8356 10868 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
47faff37 10869 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
b2650027 10870
1ce3a60e
AM
10871 if (binary_path && !strchr(binary_path, '/')) {
10872 err = resolve_full_path(binary_path, full_binary_path,
10873 sizeof(full_binary_path));
10874 if (err) {
2e4913e0
AN
10875 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10876 prog->name, binary_path, err);
1ce3a60e
AM
10877 return libbpf_err_ptr(err);
10878 }
10879 binary_path = full_binary_path;
10880 }
433966e3
AM
10881 func_name = OPTS_GET(opts, func_name, NULL);
10882 if (func_name) {
10883 long sym_off;
10884
10885 if (!binary_path) {
10886 pr_warn("prog '%s': name-based attach requires binary_path\n",
10887 prog->name);
10888 return libbpf_err_ptr(-EINVAL);
10889 }
10890 sym_off = elf_find_func_offset(binary_path, func_name);
10891 if (sym_off < 0)
10892 return libbpf_err_ptr(sym_off);
10893 func_offset += sym_off;
10894 }
1ce3a60e 10895
cc10623c
AN
10896 legacy = determine_uprobe_perf_type() < 0;
10897 if (!legacy) {
10898 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10899 func_offset, pid, ref_ctr_off);
10900 } else {
1ce3a60e 10901 char probe_name[PATH_MAX + 64];
cc10623c
AN
10902
10903 if (ref_ctr_off)
10904 return libbpf_err_ptr(-EINVAL);
10905
10906 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10907 binary_path, func_offset);
10908
10909 legacy_probe = strdup(probe_name);
10910 if (!legacy_probe)
10911 return libbpf_err_ptr(-ENOMEM);
10912
10913 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10914 binary_path, func_offset, pid);
10915 }
b2650027 10916 if (pfd < 0) {
cc10623c 10917 err = -errno;
52109584
AN
10918 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10919 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e 10920 binary_path, func_offset,
cc10623c
AN
10921 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10922 goto err_out;
b2650027 10923 }
cc10623c 10924
47faff37 10925 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10926 err = libbpf_get_error(link);
10927 if (err) {
b2650027 10928 close(pfd);
52109584
AN
10929 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10930 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e
KW
10931 binary_path, func_offset,
10932 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
cc10623c
AN
10933 goto err_out;
10934 }
10935 if (legacy) {
10936 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10937
10938 perf_link->legacy_probe_name = legacy_probe;
10939 perf_link->legacy_is_kprobe = false;
10940 perf_link->legacy_is_retprobe = retprobe;
b2650027
AN
10941 }
10942 return link;
cc10623c
AN
10943err_out:
10944 free(legacy_probe);
10945 return libbpf_err_ptr(err);
10946
b2650027
AN
10947}
10948
39f8dc43
AM
10949/* Format of u[ret]probe section definition supporting auto-attach:
10950 * u[ret]probe/binary:function[+offset]
10951 *
10952 * binary can be an absolute/relative path or a filename; the latter is resolved to a
10953 * full binary path via bpf_program__attach_uprobe_opts.
10954 *
10955 * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
10956 * specified (and auto-attach is not possible) or the above format is specified for
10957 * auto-attach.
10958 */
10959static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10960{
10961 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
90db26e6
AM
10962 char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
10963 int n, ret = -EINVAL;
10964 long offset = 0;
39f8dc43
AM
10965
10966 *link = NULL;
10967
90db26e6
AM
10968 n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
10969 &probe_type, &binary_path, &func_name, &offset);
10970 switch (n) {
10971 case 1:
10972 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
10973 ret = 0;
10974 break;
10975 case 2:
10976 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
10977 prog->name, prog->sec_name);
10978 break;
10979 case 3:
10980 case 4:
10981 opts.retprobe = strcmp(probe_type, "uretprobe") == 0;
10982 if (opts.retprobe && offset != 0) {
10983 pr_warn("prog '%s': uretprobes do not support offset specification\n",
10984 prog->name);
10985 break;
10986 }
10987 opts.func_name = func_name;
10988 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
10989 ret = libbpf_get_error(*link);
10990 break;
10991 default:
10992 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
39f8dc43 10993 prog->sec_name);
90db26e6 10994 break;
39f8dc43 10995 }
90db26e6
AM
10996 free(probe_type);
10997 free(binary_path);
10998 free(func_name);
39f8dc43 10999
90db26e6 11000 return ret;
39f8dc43
AM
11001}
11002
942025c9 11003struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
47faff37
AN
11004 bool retprobe, pid_t pid,
11005 const char *binary_path,
11006 size_t func_offset)
11007{
11008 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11009
11010 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11011}
11012
2e4913e0
AN
11013struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11014 pid_t pid, const char *binary_path,
11015 const char *usdt_provider, const char *usdt_name,
11016 const struct bpf_usdt_opts *opts)
11017{
11018 char resolved_path[512];
11019 struct bpf_object *obj = prog->obj;
11020 struct bpf_link *link;
5af25a41 11021 __u64 usdt_cookie;
2e4913e0
AN
11022 int err;
11023
11024 if (!OPTS_VALID(opts, bpf_uprobe_opts))
11025 return libbpf_err_ptr(-EINVAL);
11026
11027 if (bpf_program__fd(prog) < 0) {
11028 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11029 prog->name);
11030 return libbpf_err_ptr(-EINVAL);
11031 }
11032
11033 if (!strchr(binary_path, '/')) {
11034 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11035 if (err) {
11036 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11037 prog->name, binary_path, err);
11038 return libbpf_err_ptr(err);
11039 }
11040 binary_path = resolved_path;
11041 }
11042
11043 /* USDT manager is instantiated lazily on first USDT attach. It will
11044 * be destroyed together with BPF object in bpf_object__close().
11045 */
11046 if (IS_ERR(obj->usdt_man))
11047 return libbpf_ptr(obj->usdt_man);
11048 if (!obj->usdt_man) {
11049 obj->usdt_man = usdt_manager_new(obj);
11050 if (IS_ERR(obj->usdt_man))
11051 return libbpf_ptr(obj->usdt_man);
11052 }
11053
11054 usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11055 link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11056 usdt_provider, usdt_name, usdt_cookie);
11057 err = libbpf_get_error(link);
11058 if (err)
11059 return libbpf_err_ptr(err);
11060 return link;
11061}
11062
11063static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11064{
11065 char *path = NULL, *provider = NULL, *name = NULL;
11066 const char *sec_name;
11067 int n, err;
11068
11069 sec_name = bpf_program__section_name(prog);
11070 if (strcmp(sec_name, "usdt") == 0) {
11071 /* no auto-attach for just SEC("usdt") */
11072 *link = NULL;
11073 return 0;
11074 }
11075
11076 n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11077 if (n != 3) {
11078 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11079 sec_name);
11080 err = -EINVAL;
11081 } else {
11082 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11083 provider, name, NULL);
11084 err = libbpf_get_error(*link);
11085 }
11086 free(path);
11087 free(provider);
11088 free(name);
11089 return err;
11090}
11091
f6de59c1
AN
11092static int determine_tracepoint_id(const char *tp_category,
11093 const char *tp_name)
11094{
11095 char file[PATH_MAX];
11096 int ret;
11097
11098 ret = snprintf(file, sizeof(file),
11099 "/sys/kernel/debug/tracing/events/%s/%s/id",
11100 tp_category, tp_name);
11101 if (ret < 0)
11102 return -errno;
11103 if (ret >= sizeof(file)) {
11104 pr_debug("tracepoint %s/%s path is too long\n",
11105 tp_category, tp_name);
11106 return -E2BIG;
11107 }
11108 return parse_uint_from_file(file, "%d\n");
11109}
11110
11111static int perf_event_open_tracepoint(const char *tp_category,
11112 const char *tp_name)
11113{
11114 struct perf_event_attr attr = {};
11115 char errmsg[STRERR_BUFSIZE];
11116 int tp_id, pfd, err;
11117
11118 tp_id = determine_tracepoint_id(tp_category, tp_name);
11119 if (tp_id < 0) {
be18010e
KW
11120 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11121 tp_category, tp_name,
11122 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
f6de59c1
AN
11123 return tp_id;
11124 }
11125
11126 attr.type = PERF_TYPE_TRACEPOINT;
11127 attr.size = sizeof(attr);
11128 attr.config = tp_id;
11129
11130 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11131 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11132 if (pfd < 0) {
11133 err = -errno;
be18010e
KW
11134 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11135 tp_category, tp_name,
11136 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
f6de59c1
AN
11137 return err;
11138 }
11139 return pfd;
11140}
11141
942025c9 11142struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
47faff37
AN
11143 const char *tp_category,
11144 const char *tp_name,
11145 const struct bpf_tracepoint_opts *opts)
f6de59c1 11146{
47faff37 11147 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
f6de59c1
AN
11148 char errmsg[STRERR_BUFSIZE];
11149 struct bpf_link *link;
11150 int pfd, err;
11151
47faff37
AN
11152 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11153 return libbpf_err_ptr(-EINVAL);
11154
11155 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11156
f6de59c1
AN
11157 pfd = perf_event_open_tracepoint(tp_category, tp_name);
11158 if (pfd < 0) {
52109584
AN
11159 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11160 prog->name, tp_category, tp_name,
be18010e 11161 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 11162 return libbpf_err_ptr(pfd);
f6de59c1 11163 }
47faff37 11164 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
11165 err = libbpf_get_error(link);
11166 if (err) {
f6de59c1 11167 close(pfd);
52109584
AN
11168 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11169 prog->name, tp_category, tp_name,
be18010e 11170 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
e9fc3ce9 11171 return libbpf_err_ptr(err);
f6de59c1
AN
11172 }
11173 return link;
11174}
11175
942025c9 11176struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
47faff37
AN
11177 const char *tp_category,
11178 const char *tp_name)
11179{
11180 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11181}
11182
4fa5bcfe 11183static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7
AN
11184{
11185 char *sec_name, *tp_cat, *tp_name;
d7a18ea7 11186
52109584 11187 sec_name = strdup(prog->sec_name);
d7a18ea7 11188 if (!sec_name)
4fa5bcfe 11189 return -ENOMEM;
d7a18ea7 11190
13d35a0c
AN
11191 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11192 if (str_has_pfx(prog->sec_name, "tp/"))
11193 tp_cat = sec_name + sizeof("tp/") - 1;
11194 else
11195 tp_cat = sec_name + sizeof("tracepoint/") - 1;
d7a18ea7
AN
11196 tp_name = strchr(tp_cat, '/');
11197 if (!tp_name) {
e9fc3ce9 11198 free(sec_name);
4fa5bcfe 11199 return -EINVAL;
d7a18ea7
AN
11200 }
11201 *tp_name = '\0';
11202 tp_name++;
11203
4fa5bcfe 11204 *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
d7a18ea7 11205 free(sec_name);
4fa5bcfe 11206 return libbpf_get_error(*link);
d7a18ea7
AN
11207}
11208
942025c9 11209struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
84bf5e1f
AN
11210 const char *tp_name)
11211{
11212 char errmsg[STRERR_BUFSIZE];
c016b68e 11213 struct bpf_link *link;
84bf5e1f
AN
11214 int prog_fd, pfd;
11215
11216 prog_fd = bpf_program__fd(prog);
11217 if (prog_fd < 0) {
52109584 11218 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 11219 return libbpf_err_ptr(-EINVAL);
84bf5e1f
AN
11220 }
11221
d6958706 11222 link = calloc(1, sizeof(*link));
84bf5e1f 11223 if (!link)
e9fc3ce9 11224 return libbpf_err_ptr(-ENOMEM);
c016b68e 11225 link->detach = &bpf_link__detach_fd;
84bf5e1f
AN
11226
11227 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11228 if (pfd < 0) {
11229 pfd = -errno;
11230 free(link);
52109584
AN
11231 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11232 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 11233 return libbpf_err_ptr(pfd);
84bf5e1f
AN
11234 }
11235 link->fd = pfd;
c016b68e 11236 return link;
84bf5e1f
AN
11237}
11238
4fa5bcfe 11239static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 11240{
ccaf12d6
HT
11241 static const char *const prefixes[] = {
11242 "raw_tp/",
11243 "raw_tracepoint/",
11244 "raw_tp.w/",
11245 "raw_tracepoint.w/",
11246 };
11247 size_t i;
11248 const char *tp_name = NULL;
13d35a0c 11249
ccaf12d6
HT
11250 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11251 if (str_has_pfx(prog->sec_name, prefixes[i])) {
11252 tp_name = prog->sec_name + strlen(prefixes[i]);
11253 break;
11254 }
11255 }
11256 if (!tp_name) {
11257 pr_warn("prog '%s': invalid section name '%s'\n",
11258 prog->name, prog->sec_name);
4fa5bcfe 11259 return -EINVAL;
ccaf12d6 11260 }
d7a18ea7 11261
4fa5bcfe
AN
11262 *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11263 return libbpf_get_error(link);
d7a18ea7
AN
11264}
11265
1e092a03 11266/* Common logic for all BPF program types that attach to a btf_id */
942025c9 11267static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
b8c54ea4
AS
11268{
11269 char errmsg[STRERR_BUFSIZE];
c016b68e 11270 struct bpf_link *link;
b8c54ea4
AS
11271 int prog_fd, pfd;
11272
11273 prog_fd = bpf_program__fd(prog);
11274 if (prog_fd < 0) {
52109584 11275 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 11276 return libbpf_err_ptr(-EINVAL);
b8c54ea4
AS
11277 }
11278
d6958706 11279 link = calloc(1, sizeof(*link));
b8c54ea4 11280 if (!link)
e9fc3ce9 11281 return libbpf_err_ptr(-ENOMEM);
c016b68e 11282 link->detach = &bpf_link__detach_fd;
b8c54ea4 11283
8462e0b4
AN
11284 /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11285 pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), NULL);
b8c54ea4
AS
11286 if (pfd < 0) {
11287 pfd = -errno;
11288 free(link);
52109584
AN
11289 pr_warn("prog '%s': failed to attach: %s\n",
11290 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 11291 return libbpf_err_ptr(pfd);
b8c54ea4
AS
11292 }
11293 link->fd = pfd;
003fed59 11294 return link;
b8c54ea4
AS
11295}
11296
942025c9 11297struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
1e092a03
KS
11298{
11299 return bpf_program__attach_btf_id(prog);
11300}
11301
942025c9 11302struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
1e092a03
KS
11303{
11304 return bpf_program__attach_btf_id(prog);
11305}
11306
4fa5bcfe 11307static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
d7a18ea7 11308{
4fa5bcfe
AN
11309 *link = bpf_program__attach_trace(prog);
11310 return libbpf_get_error(*link);
d7a18ea7
AN
11311}
11312
4fa5bcfe 11313static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
1e092a03 11314{
4fa5bcfe
AN
11315 *link = bpf_program__attach_lsm(prog);
11316 return libbpf_get_error(*link);
1e092a03
KS
11317}
11318
d60d81ac 11319static struct bpf_link *
942025c9 11320bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
d60d81ac 11321 const char *target_name)
cc4f864b 11322{
a5359091
THJ
11323 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11324 .target_btf_id = btf_id);
cc4f864b
AN
11325 enum bpf_attach_type attach_type;
11326 char errmsg[STRERR_BUFSIZE];
11327 struct bpf_link *link;
11328 int prog_fd, link_fd;
11329
11330 prog_fd = bpf_program__fd(prog);
11331 if (prog_fd < 0) {
52109584 11332 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 11333 return libbpf_err_ptr(-EINVAL);
cc4f864b
AN
11334 }
11335
11336 link = calloc(1, sizeof(*link));
11337 if (!link)
e9fc3ce9 11338 return libbpf_err_ptr(-ENOMEM);
cc4f864b
AN
11339 link->detach = &bpf_link__detach_fd;
11340
20eccf29 11341 attach_type = bpf_program__expected_attach_type(prog);
a5359091 11342 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
cc4f864b
AN
11343 if (link_fd < 0) {
11344 link_fd = -errno;
11345 free(link);
52109584
AN
11346 pr_warn("prog '%s': failed to attach to %s: %s\n",
11347 prog->name, target_name,
cc4f864b 11348 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 11349 return libbpf_err_ptr(link_fd);
cc4f864b
AN
11350 }
11351 link->fd = link_fd;
11352 return link;
11353}
11354
d60d81ac 11355struct bpf_link *
942025c9 11356bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
d60d81ac 11357{
a5359091 11358 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
d60d81ac
JS
11359}
11360
11361struct bpf_link *
942025c9 11362bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
d60d81ac 11363{
a5359091 11364 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
d60d81ac
JS
11365}
11366
942025c9 11367struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
dc8698ca
AN
11368{
11369 /* target_fd/target_ifindex use the same field in LINK_CREATE */
a5359091
THJ
11370 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11371}
11372
942025c9 11373struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
a5359091
THJ
11374 int target_fd,
11375 const char *attach_func_name)
11376{
11377 int btf_id;
11378
11379 if (!!target_fd != !!attach_func_name) {
11380 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11381 prog->name);
e9fc3ce9 11382 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
11383 }
11384
11385 if (prog->type != BPF_PROG_TYPE_EXT) {
11386 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11387 prog->name);
e9fc3ce9 11388 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
11389 }
11390
11391 if (target_fd) {
11392 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11393 if (btf_id < 0)
e9fc3ce9 11394 return libbpf_err_ptr(btf_id);
a5359091
THJ
11395
11396 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11397 } else {
11398 /* no target, so use raw_tracepoint_open for compatibility
11399 * with old kernels
11400 */
11401 return bpf_program__attach_trace(prog);
11402 }
dc8698ca
AN
11403}
11404
c09add2f 11405struct bpf_link *
942025c9 11406bpf_program__attach_iter(const struct bpf_program *prog,
c09add2f
YS
11407 const struct bpf_iter_attach_opts *opts)
11408{
cd31039a 11409 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
c09add2f
YS
11410 char errmsg[STRERR_BUFSIZE];
11411 struct bpf_link *link;
11412 int prog_fd, link_fd;
cd31039a 11413 __u32 target_fd = 0;
c09add2f
YS
11414
11415 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
e9fc3ce9 11416 return libbpf_err_ptr(-EINVAL);
c09add2f 11417
74fc097d
YS
11418 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11419 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
cd31039a 11420
c09add2f
YS
11421 prog_fd = bpf_program__fd(prog);
11422 if (prog_fd < 0) {
52109584 11423 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 11424 return libbpf_err_ptr(-EINVAL);
c09add2f
YS
11425 }
11426
11427 link = calloc(1, sizeof(*link));
11428 if (!link)
e9fc3ce9 11429 return libbpf_err_ptr(-ENOMEM);
c09add2f
YS
11430 link->detach = &bpf_link__detach_fd;
11431
cd31039a
YS
11432 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11433 &link_create_opts);
c09add2f
YS
11434 if (link_fd < 0) {
11435 link_fd = -errno;
11436 free(link);
52109584
AN
11437 pr_warn("prog '%s': failed to attach to iterator: %s\n",
11438 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 11439 return libbpf_err_ptr(link_fd);
c09add2f
YS
11440 }
11441 link->fd = link_fd;
11442 return link;
11443}
11444
4fa5bcfe 11445static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
e9fc3ce9 11446{
4fa5bcfe
AN
11447 *link = bpf_program__attach_iter(prog, NULL);
11448 return libbpf_get_error(*link);
e9fc3ce9
AN
11449}
11450
942025c9 11451struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
d7a18ea7 11452{
4fa5bcfe
AN
11453 struct bpf_link *link = NULL;
11454 int err;
11455
11456 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11457 return libbpf_err_ptr(-EOPNOTSUPP);
d7a18ea7 11458
4fa5bcfe
AN
11459 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11460 if (err)
11461 return libbpf_err_ptr(err);
11462
11463 /* When calling bpf_program__attach() explicitly, auto-attach support
11464 * is expected to work, so NULL returned link is considered an error.
11465 * This is different for skeleton's attach, see comment in
11466 * bpf_object__attach_skeleton().
11467 */
11468 if (!link)
11469 return libbpf_err_ptr(-EOPNOTSUPP);
11470
11471 return link;
d7a18ea7
AN
11472}
11473
590a0088
MKL
11474static int bpf_link__detach_struct_ops(struct bpf_link *link)
11475{
590a0088
MKL
11476 __u32 zero = 0;
11477
c016b68e 11478 if (bpf_map_delete_elem(link->fd, &zero))
590a0088
MKL
11479 return -errno;
11480
11481 return 0;
11482}
11483
942025c9 11484struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
590a0088
MKL
11485{
11486 struct bpf_struct_ops *st_ops;
c016b68e 11487 struct bpf_link *link;
590a0088
MKL
11488 __u32 i, zero = 0;
11489 int err;
11490
11491 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
e9fc3ce9 11492 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
11493
11494 link = calloc(1, sizeof(*link));
11495 if (!link)
e9fc3ce9 11496 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
11497
11498 st_ops = map->st_ops;
11499 for (i = 0; i < btf_vlen(st_ops->type); i++) {
11500 struct bpf_program *prog = st_ops->progs[i];
11501 void *kern_data;
11502 int prog_fd;
11503
11504 if (!prog)
11505 continue;
11506
11507 prog_fd = bpf_program__fd(prog);
11508 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11509 *(unsigned long *)kern_data = prog_fd;
11510 }
11511
11512 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11513 if (err) {
11514 err = -errno;
11515 free(link);
e9fc3ce9 11516 return libbpf_err_ptr(err);
590a0088
MKL
11517 }
11518
c016b68e 11519 link->detach = bpf_link__detach_struct_ops;
590a0088
MKL
11520 link->fd = map->fd;
11521
c016b68e 11522 return link;
590a0088
MKL
11523}
11524
7218c28c
CL
11525static enum bpf_perf_event_ret
11526perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11527 void **copy_mem, size_t *copy_size,
11528 bpf_perf_event_print_t fn, void *private_data)
d0cabbb0 11529{
3dca2115 11530 struct perf_event_mmap_page *header = mmap_mem;
a64af0ef 11531 __u64 data_head = ring_buffer_read_head(header);
d0cabbb0 11532 __u64 data_tail = header->data_tail;
3dca2115
DB
11533 void *base = ((__u8 *)header) + page_size;
11534 int ret = LIBBPF_PERF_EVENT_CONT;
11535 struct perf_event_header *ehdr;
11536 size_t ehdr_size;
11537
11538 while (data_head != data_tail) {
11539 ehdr = base + (data_tail & (mmap_size - 1));
11540 ehdr_size = ehdr->size;
11541
11542 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11543 void *copy_start = ehdr;
11544 size_t len_first = base + mmap_size - copy_start;
11545 size_t len_secnd = ehdr_size - len_first;
11546
11547 if (*copy_size < ehdr_size) {
11548 free(*copy_mem);
11549 *copy_mem = malloc(ehdr_size);
11550 if (!*copy_mem) {
11551 *copy_size = 0;
d0cabbb0
JK
11552 ret = LIBBPF_PERF_EVENT_ERROR;
11553 break;
11554 }
3dca2115 11555 *copy_size = ehdr_size;
d0cabbb0
JK
11556 }
11557
3dca2115
DB
11558 memcpy(*copy_mem, copy_start, len_first);
11559 memcpy(*copy_mem + len_first, base, len_secnd);
11560 ehdr = *copy_mem;
d0cabbb0
JK
11561 }
11562
3dca2115
DB
11563 ret = fn(ehdr, private_data);
11564 data_tail += ehdr_size;
d0cabbb0
JK
11565 if (ret != LIBBPF_PERF_EVENT_CONT)
11566 break;
d0cabbb0
JK
11567 }
11568
a64af0ef 11569 ring_buffer_write_tail(header, data_tail);
e9fc3ce9 11570 return libbpf_err(ret);
d0cabbb0 11571}
34be1646 11572
7218c28c
CL
11573__attribute__((alias("perf_event_read_simple")))
11574enum bpf_perf_event_ret
11575bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11576 void **copy_mem, size_t *copy_size,
11577 bpf_perf_event_print_t fn, void *private_data);
11578
fb84b822
AN
11579struct perf_buffer;
11580
11581struct perf_buffer_params {
11582 struct perf_event_attr *attr;
11583 /* if event_cb is specified, it takes precendence */
11584 perf_buffer_event_fn event_cb;
11585 /* sample_cb and lost_cb are higher-level common-case callbacks */
11586 perf_buffer_sample_fn sample_cb;
11587 perf_buffer_lost_fn lost_cb;
11588 void *ctx;
11589 int cpu_cnt;
11590 int *cpus;
11591 int *map_keys;
11592};
11593
11594struct perf_cpu_buf {
11595 struct perf_buffer *pb;
11596 void *base; /* mmap()'ed memory */
11597 void *buf; /* for reconstructing segmented data */
11598 size_t buf_size;
11599 int fd;
11600 int cpu;
11601 int map_key;
11602};
11603
11604struct perf_buffer {
11605 perf_buffer_event_fn event_cb;
11606 perf_buffer_sample_fn sample_cb;
11607 perf_buffer_lost_fn lost_cb;
11608 void *ctx; /* passed into callbacks */
11609
11610 size_t page_size;
11611 size_t mmap_size;
11612 struct perf_cpu_buf **cpu_bufs;
11613 struct epoll_event *events;
783b8f01 11614 int cpu_cnt; /* number of allocated CPU buffers */
fb84b822
AN
11615 int epoll_fd; /* perf event FD */
11616 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11617};
11618
11619static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11620 struct perf_cpu_buf *cpu_buf)
11621{
11622 if (!cpu_buf)
11623 return;
11624 if (cpu_buf->base &&
11625 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
be18010e 11626 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
fb84b822
AN
11627 if (cpu_buf->fd >= 0) {
11628 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11629 close(cpu_buf->fd);
11630 }
11631 free(cpu_buf->buf);
11632 free(cpu_buf);
11633}
11634
11635void perf_buffer__free(struct perf_buffer *pb)
11636{
11637 int i;
11638
50450fc7 11639 if (IS_ERR_OR_NULL(pb))
fb84b822
AN
11640 return;
11641 if (pb->cpu_bufs) {
601b05ca 11642 for (i = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
11643 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11644
601b05ca
EC
11645 if (!cpu_buf)
11646 continue;
11647
fb84b822
AN
11648 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11649 perf_buffer__free_cpu_buf(pb, cpu_buf);
11650 }
11651 free(pb->cpu_bufs);
11652 }
11653 if (pb->epoll_fd >= 0)
11654 close(pb->epoll_fd);
11655 free(pb->events);
11656 free(pb);
11657}
11658
11659static struct perf_cpu_buf *
11660perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11661 int cpu, int map_key)
11662{
11663 struct perf_cpu_buf *cpu_buf;
11664 char msg[STRERR_BUFSIZE];
11665 int err;
11666
11667 cpu_buf = calloc(1, sizeof(*cpu_buf));
11668 if (!cpu_buf)
11669 return ERR_PTR(-ENOMEM);
11670
11671 cpu_buf->pb = pb;
11672 cpu_buf->cpu = cpu;
11673 cpu_buf->map_key = map_key;
11674
11675 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11676 -1, PERF_FLAG_FD_CLOEXEC);
11677 if (cpu_buf->fd < 0) {
11678 err = -errno;
be18010e
KW
11679 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11680 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11681 goto error;
11682 }
11683
11684 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11685 PROT_READ | PROT_WRITE, MAP_SHARED,
11686 cpu_buf->fd, 0);
11687 if (cpu_buf->base == MAP_FAILED) {
11688 cpu_buf->base = NULL;
11689 err = -errno;
be18010e
KW
11690 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11691 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11692 goto error;
11693 }
11694
11695 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11696 err = -errno;
be18010e
KW
11697 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11698 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11699 goto error;
11700 }
11701
11702 return cpu_buf;
11703
11704error:
11705 perf_buffer__free_cpu_buf(pb, cpu_buf);
11706 return (struct perf_cpu_buf *)ERR_PTR(err);
11707}
11708
11709static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11710 struct perf_buffer_params *p);
11711
41788934
AN
11712DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
11713struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
11714 perf_buffer_sample_fn sample_cb,
11715 perf_buffer_lost_fn lost_cb,
11716 void *ctx,
11717 const struct perf_buffer_opts *opts)
fb84b822
AN
11718{
11719 struct perf_buffer_params p = {};
41788934
AN
11720 struct perf_event_attr attr = {};
11721
11722 if (!OPTS_VALID(opts, perf_buffer_opts))
11723 return libbpf_err_ptr(-EINVAL);
4be6e05c 11724
65bb2e0f 11725 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
4be6e05c
ACM
11726 attr.type = PERF_TYPE_SOFTWARE;
11727 attr.sample_type = PERF_SAMPLE_RAW;
11728 attr.sample_period = 1;
11729 attr.wakeup_events = 1;
fb84b822
AN
11730
11731 p.attr = &attr;
41788934
AN
11732 p.sample_cb = sample_cb;
11733 p.lost_cb = lost_cb;
11734 p.ctx = ctx;
fb84b822 11735
e9fc3ce9 11736 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
11737}
11738
41788934
AN
11739COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
11740struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
11741 const struct perf_buffer_opts *opts)
11742{
11743 return perf_buffer__new_v0_6_0(map_fd, page_cnt,
11744 opts ? opts->sample_cb : NULL,
11745 opts ? opts->lost_cb : NULL,
11746 opts ? opts->ctx : NULL,
11747 NULL);
11748}
11749
11750DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
11751struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
11752 struct perf_event_attr *attr,
11753 perf_buffer_event_fn event_cb, void *ctx,
11754 const struct perf_buffer_raw_opts *opts)
fb84b822
AN
11755{
11756 struct perf_buffer_params p = {};
11757
41332d6e 11758 if (!attr)
41788934
AN
11759 return libbpf_err_ptr(-EINVAL);
11760
11761 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11762 return libbpf_err_ptr(-EINVAL);
11763
11764 p.attr = attr;
11765 p.event_cb = event_cb;
11766 p.ctx = ctx;
11767 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11768 p.cpus = OPTS_GET(opts, cpus, NULL);
11769 p.map_keys = OPTS_GET(opts, map_keys, NULL);
fb84b822 11770
e9fc3ce9 11771 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
11772}
11773
41788934
AN
11774COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
11775struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
11776 const struct perf_buffer_raw_opts *opts)
11777{
11778 LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
11779 .cpu_cnt = opts->cpu_cnt,
11780 .cpus = opts->cpus,
11781 .map_keys = opts->map_keys,
11782 );
11783
11784 return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
11785 opts->event_cb, opts->ctx, &inner_opts);
11786}
11787
fb84b822
AN
11788static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11789 struct perf_buffer_params *p)
11790{
783b8f01 11791 const char *online_cpus_file = "/sys/devices/system/cpu/online";
0e289487 11792 struct bpf_map_info map;
fb84b822
AN
11793 char msg[STRERR_BUFSIZE];
11794 struct perf_buffer *pb;
783b8f01 11795 bool *online = NULL;
fb84b822 11796 __u32 map_info_len;
783b8f01 11797 int err, i, j, n;
fb84b822 11798
41332d6e 11799 if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
be18010e
KW
11800 pr_warn("page count should be power of two, but is %zu\n",
11801 page_cnt);
fb84b822
AN
11802 return ERR_PTR(-EINVAL);
11803 }
11804
0e289487
AN
11805 /* best-effort sanity checks */
11806 memset(&map, 0, sizeof(map));
fb84b822
AN
11807 map_info_len = sizeof(map);
11808 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11809 if (err) {
11810 err = -errno;
0e289487
AN
11811 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11812 * -EBADFD, -EFAULT, or -E2BIG on real error
11813 */
11814 if (err != -EINVAL) {
11815 pr_warn("failed to get map info for map FD %d: %s\n",
11816 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11817 return ERR_PTR(err);
11818 }
11819 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11820 map_fd);
11821 } else {
11822 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11823 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11824 map.name);
11825 return ERR_PTR(-EINVAL);
11826 }
fb84b822
AN
11827 }
11828
11829 pb = calloc(1, sizeof(*pb));
11830 if (!pb)
11831 return ERR_PTR(-ENOMEM);
11832
11833 pb->event_cb = p->event_cb;
11834 pb->sample_cb = p->sample_cb;
11835 pb->lost_cb = p->lost_cb;
11836 pb->ctx = p->ctx;
11837
11838 pb->page_size = getpagesize();
11839 pb->mmap_size = pb->page_size * page_cnt;
11840 pb->map_fd = map_fd;
11841
11842 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11843 if (pb->epoll_fd < 0) {
11844 err = -errno;
be18010e
KW
11845 pr_warn("failed to create epoll instance: %s\n",
11846 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11847 goto error;
11848 }
11849
11850 if (p->cpu_cnt > 0) {
11851 pb->cpu_cnt = p->cpu_cnt;
11852 } else {
11853 pb->cpu_cnt = libbpf_num_possible_cpus();
11854 if (pb->cpu_cnt < 0) {
11855 err = pb->cpu_cnt;
11856 goto error;
11857 }
0e289487 11858 if (map.max_entries && map.max_entries < pb->cpu_cnt)
fb84b822
AN
11859 pb->cpu_cnt = map.max_entries;
11860 }
11861
11862 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11863 if (!pb->events) {
11864 err = -ENOMEM;
be18010e 11865 pr_warn("failed to allocate events: out of memory\n");
fb84b822
AN
11866 goto error;
11867 }
11868 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11869 if (!pb->cpu_bufs) {
11870 err = -ENOMEM;
be18010e 11871 pr_warn("failed to allocate buffers: out of memory\n");
fb84b822
AN
11872 goto error;
11873 }
11874
783b8f01
AN
11875 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11876 if (err) {
11877 pr_warn("failed to get online CPU mask: %d\n", err);
11878 goto error;
11879 }
11880
11881 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
11882 struct perf_cpu_buf *cpu_buf;
11883 int cpu, map_key;
11884
11885 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11886 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11887
783b8f01
AN
11888 /* in case user didn't explicitly requested particular CPUs to
11889 * be attached to, skip offline/not present CPUs
11890 */
11891 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11892 continue;
11893
fb84b822
AN
11894 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11895 if (IS_ERR(cpu_buf)) {
11896 err = PTR_ERR(cpu_buf);
11897 goto error;
11898 }
11899
783b8f01 11900 pb->cpu_bufs[j] = cpu_buf;
fb84b822
AN
11901
11902 err = bpf_map_update_elem(pb->map_fd, &map_key,
11903 &cpu_buf->fd, 0);
11904 if (err) {
11905 err = -errno;
be18010e
KW
11906 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11907 cpu, map_key, cpu_buf->fd,
11908 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11909 goto error;
11910 }
11911
783b8f01
AN
11912 pb->events[j].events = EPOLLIN;
11913 pb->events[j].data.ptr = cpu_buf;
fb84b822 11914 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
783b8f01 11915 &pb->events[j]) < 0) {
fb84b822 11916 err = -errno;
be18010e
KW
11917 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11918 cpu, cpu_buf->fd,
11919 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11920 goto error;
11921 }
783b8f01 11922 j++;
fb84b822 11923 }
783b8f01
AN
11924 pb->cpu_cnt = j;
11925 free(online);
fb84b822
AN
11926
11927 return pb;
11928
11929error:
783b8f01 11930 free(online);
fb84b822
AN
11931 if (pb)
11932 perf_buffer__free(pb);
11933 return ERR_PTR(err);
11934}
11935
11936struct perf_sample_raw {
11937 struct perf_event_header header;
11938 uint32_t size;
385bbf7b 11939 char data[];
fb84b822
AN
11940};
11941
11942struct perf_sample_lost {
11943 struct perf_event_header header;
11944 uint64_t id;
11945 uint64_t lost;
11946 uint64_t sample_id;
11947};
11948
11949static enum bpf_perf_event_ret
11950perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11951{
11952 struct perf_cpu_buf *cpu_buf = ctx;
11953 struct perf_buffer *pb = cpu_buf->pb;
11954 void *data = e;
11955
11956 /* user wants full control over parsing perf event */
11957 if (pb->event_cb)
11958 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11959
11960 switch (e->type) {
11961 case PERF_RECORD_SAMPLE: {
11962 struct perf_sample_raw *s = data;
11963
11964 if (pb->sample_cb)
11965 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11966 break;
11967 }
11968 case PERF_RECORD_LOST: {
11969 struct perf_sample_lost *s = data;
11970
11971 if (pb->lost_cb)
11972 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11973 break;
11974 }
11975 default:
be18010e 11976 pr_warn("unknown perf sample type %d\n", e->type);
fb84b822
AN
11977 return LIBBPF_PERF_EVENT_ERROR;
11978 }
11979 return LIBBPF_PERF_EVENT_CONT;
11980}
11981
11982static int perf_buffer__process_records(struct perf_buffer *pb,
11983 struct perf_cpu_buf *cpu_buf)
11984{
11985 enum bpf_perf_event_ret ret;
11986
7218c28c
CL
11987 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11988 pb->page_size, &cpu_buf->buf,
11989 &cpu_buf->buf_size,
11990 perf_buffer__process_record, cpu_buf);
fb84b822
AN
11991 if (ret != LIBBPF_PERF_EVENT_CONT)
11992 return ret;
11993 return 0;
11994}
11995
dca5612f
AN
11996int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11997{
11998 return pb->epoll_fd;
11999}
12000
fb84b822
AN
12001int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12002{
12003 int i, cnt, err;
12004
12005 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
e9fc3ce9 12006 if (cnt < 0)
af0efa05 12007 return -errno;
e9fc3ce9 12008
fb84b822
AN
12009 for (i = 0; i < cnt; i++) {
12010 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12011
12012 err = perf_buffer__process_records(pb, cpu_buf);
12013 if (err) {
be18010e 12014 pr_warn("error while processing records: %d\n", err);
e9fc3ce9 12015 return libbpf_err(err);
fb84b822
AN
12016 }
12017 }
e9fc3ce9 12018 return cnt;
fb84b822
AN
12019}
12020
dca5612f
AN
12021/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12022 * manager.
12023 */
12024size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12025{
12026 return pb->cpu_cnt;
12027}
12028
12029/*
12030 * Return perf_event FD of a ring buffer in *buf_idx* slot of
12031 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12032 * select()/poll()/epoll() Linux syscalls.
12033 */
12034int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12035{
12036 struct perf_cpu_buf *cpu_buf;
12037
12038 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 12039 return libbpf_err(-EINVAL);
dca5612f
AN
12040
12041 cpu_buf = pb->cpu_bufs[buf_idx];
12042 if (!cpu_buf)
e9fc3ce9 12043 return libbpf_err(-ENOENT);
dca5612f
AN
12044
12045 return cpu_buf->fd;
12046}
12047
12048/*
12049 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12050 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12051 * consume, do nothing and return success.
12052 * Returns:
12053 * - 0 on success;
12054 * - <0 on failure.
12055 */
12056int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12057{
12058 struct perf_cpu_buf *cpu_buf;
12059
12060 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 12061 return libbpf_err(-EINVAL);
dca5612f
AN
12062
12063 cpu_buf = pb->cpu_bufs[buf_idx];
12064 if (!cpu_buf)
e9fc3ce9 12065 return libbpf_err(-ENOENT);
dca5612f
AN
12066
12067 return perf_buffer__process_records(pb, cpu_buf);
12068}
12069
272d51af
EC
12070int perf_buffer__consume(struct perf_buffer *pb)
12071{
12072 int i, err;
12073
12074 for (i = 0; i < pb->cpu_cnt; i++) {
12075 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12076
12077 if (!cpu_buf)
12078 continue;
12079
12080 err = perf_buffer__process_records(pb, cpu_buf);
12081 if (err) {
dca5612f 12082 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
e9fc3ce9 12083 return libbpf_err(err);
272d51af
EC
12084 }
12085 }
12086 return 0;
12087}
12088
34be1646
SL
12089struct bpf_prog_info_array_desc {
12090 int array_offset; /* e.g. offset of jited_prog_insns */
12091 int count_offset; /* e.g. offset of jited_prog_len */
12092 int size_offset; /* > 0: offset of rec size,
12093 * < 0: fix size of -size_offset
12094 */
12095};
12096
12097static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
12098 [BPF_PROG_INFO_JITED_INSNS] = {
12099 offsetof(struct bpf_prog_info, jited_prog_insns),
12100 offsetof(struct bpf_prog_info, jited_prog_len),
12101 -1,
12102 },
12103 [BPF_PROG_INFO_XLATED_INSNS] = {
12104 offsetof(struct bpf_prog_info, xlated_prog_insns),
12105 offsetof(struct bpf_prog_info, xlated_prog_len),
12106 -1,
12107 },
12108 [BPF_PROG_INFO_MAP_IDS] = {
12109 offsetof(struct bpf_prog_info, map_ids),
12110 offsetof(struct bpf_prog_info, nr_map_ids),
12111 -(int)sizeof(__u32),
12112 },
12113 [BPF_PROG_INFO_JITED_KSYMS] = {
12114 offsetof(struct bpf_prog_info, jited_ksyms),
12115 offsetof(struct bpf_prog_info, nr_jited_ksyms),
12116 -(int)sizeof(__u64),
12117 },
12118 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
12119 offsetof(struct bpf_prog_info, jited_func_lens),
12120 offsetof(struct bpf_prog_info, nr_jited_func_lens),
12121 -(int)sizeof(__u32),
12122 },
12123 [BPF_PROG_INFO_FUNC_INFO] = {
12124 offsetof(struct bpf_prog_info, func_info),
12125 offsetof(struct bpf_prog_info, nr_func_info),
12126 offsetof(struct bpf_prog_info, func_info_rec_size),
12127 },
12128 [BPF_PROG_INFO_LINE_INFO] = {
12129 offsetof(struct bpf_prog_info, line_info),
12130 offsetof(struct bpf_prog_info, nr_line_info),
12131 offsetof(struct bpf_prog_info, line_info_rec_size),
12132 },
12133 [BPF_PROG_INFO_JITED_LINE_INFO] = {
12134 offsetof(struct bpf_prog_info, jited_line_info),
12135 offsetof(struct bpf_prog_info, nr_jited_line_info),
12136 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
12137 },
12138 [BPF_PROG_INFO_PROG_TAGS] = {
12139 offsetof(struct bpf_prog_info, prog_tags),
12140 offsetof(struct bpf_prog_info, nr_prog_tags),
12141 -(int)sizeof(__u8) * BPF_TAG_SIZE,
12142 },
12143
12144};
12145
8983b731
AN
12146static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
12147 int offset)
34be1646
SL
12148{
12149 __u32 *array = (__u32 *)info;
12150
12151 if (offset >= 0)
12152 return array[offset / sizeof(__u32)];
12153 return -(int)offset;
12154}
12155
8983b731
AN
12156static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
12157 int offset)
34be1646
SL
12158{
12159 __u64 *array = (__u64 *)info;
12160
12161 if (offset >= 0)
12162 return array[offset / sizeof(__u64)];
12163 return -(int)offset;
12164}
12165
12166static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
12167 __u32 val)
12168{
12169 __u32 *array = (__u32 *)info;
12170
12171 if (offset >= 0)
12172 array[offset / sizeof(__u32)] = val;
12173}
12174
12175static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
12176 __u64 val)
12177{
12178 __u64 *array = (__u64 *)info;
12179
12180 if (offset >= 0)
12181 array[offset / sizeof(__u64)] = val;
12182}
12183
12184struct bpf_prog_info_linear *
12185bpf_program__get_prog_info_linear(int fd, __u64 arrays)
12186{
12187 struct bpf_prog_info_linear *info_linear;
12188 struct bpf_prog_info info = {};
12189 __u32 info_len = sizeof(info);
12190 __u32 data_len = 0;
12191 int i, err;
12192 void *ptr;
12193
12194 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
e9fc3ce9 12195 return libbpf_err_ptr(-EINVAL);
34be1646
SL
12196
12197 /* step 1: get array dimensions */
12198 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
12199 if (err) {
12200 pr_debug("can't get prog info: %s", strerror(errno));
e9fc3ce9 12201 return libbpf_err_ptr(-EFAULT);
34be1646
SL
12202 }
12203
12204 /* step 2: calculate total size of all arrays */
12205 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12206 bool include_array = (arrays & (1UL << i)) > 0;
12207 struct bpf_prog_info_array_desc *desc;
12208 __u32 count, size;
12209
12210 desc = bpf_prog_info_array_desc + i;
12211
12212 /* kernel is too old to support this field */
12213 if (info_len < desc->array_offset + sizeof(__u32) ||
12214 info_len < desc->count_offset + sizeof(__u32) ||
12215 (desc->size_offset > 0 && info_len < desc->size_offset))
12216 include_array = false;
12217
12218 if (!include_array) {
12219 arrays &= ~(1UL << i); /* clear the bit */
12220 continue;
12221 }
12222
12223 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12224 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12225
12226 data_len += count * size;
12227 }
12228
12229 /* step 3: allocate continuous memory */
12230 data_len = roundup(data_len, sizeof(__u64));
12231 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
12232 if (!info_linear)
e9fc3ce9 12233 return libbpf_err_ptr(-ENOMEM);
34be1646
SL
12234
12235 /* step 4: fill data to info_linear->info */
12236 info_linear->arrays = arrays;
12237 memset(&info_linear->info, 0, sizeof(info));
12238 ptr = info_linear->data;
12239
12240 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12241 struct bpf_prog_info_array_desc *desc;
12242 __u32 count, size;
12243
12244 if ((arrays & (1UL << i)) == 0)
12245 continue;
12246
12247 desc = bpf_prog_info_array_desc + i;
12248 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12249 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12250 bpf_prog_info_set_offset_u32(&info_linear->info,
12251 desc->count_offset, count);
12252 bpf_prog_info_set_offset_u32(&info_linear->info,
12253 desc->size_offset, size);
12254 bpf_prog_info_set_offset_u64(&info_linear->info,
12255 desc->array_offset,
12256 ptr_to_u64(ptr));
12257 ptr += count * size;
12258 }
12259
12260 /* step 5: call syscall again to get required arrays */
12261 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
12262 if (err) {
12263 pr_debug("can't get prog info: %s", strerror(errno));
12264 free(info_linear);
e9fc3ce9 12265 return libbpf_err_ptr(-EFAULT);
34be1646
SL
12266 }
12267
12268 /* step 6: verify the data */
12269 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12270 struct bpf_prog_info_array_desc *desc;
12271 __u32 v1, v2;
12272
12273 if ((arrays & (1UL << i)) == 0)
12274 continue;
12275
12276 desc = bpf_prog_info_array_desc + i;
12277 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
12278 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12279 desc->count_offset);
12280 if (v1 != v2)
be18010e 12281 pr_warn("%s: mismatch in element count\n", __func__);
34be1646
SL
12282
12283 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
12284 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
12285 desc->size_offset);
12286 if (v1 != v2)
be18010e 12287 pr_warn("%s: mismatch in rec size\n", __func__);
34be1646
SL
12288 }
12289
12290 /* step 7: update info_len and data_len */
12291 info_linear->info_len = sizeof(struct bpf_prog_info);
12292 info_linear->data_len = data_len;
12293
12294 return info_linear;
12295}
12296
12297void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
12298{
12299 int i;
12300
12301 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12302 struct bpf_prog_info_array_desc *desc;
12303 __u64 addr, offs;
12304
12305 if ((info_linear->arrays & (1UL << i)) == 0)
12306 continue;
12307
12308 desc = bpf_prog_info_array_desc + i;
12309 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
12310 desc->array_offset);
12311 offs = addr - ptr_to_u64(info_linear->data);
12312 bpf_prog_info_set_offset_u64(&info_linear->info,
12313 desc->array_offset, offs);
12314 }
12315}
12316
12317void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
12318{
12319 int i;
12320
12321 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
12322 struct bpf_prog_info_array_desc *desc;
12323 __u64 addr, offs;
12324
12325 if ((info_linear->arrays & (1UL << i)) == 0)
12326 continue;
12327
12328 desc = bpf_prog_info_array_desc + i;
12329 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
12330 desc->array_offset);
12331 addr = offs + ptr_to_u64(info_linear->data);
12332 bpf_prog_info_set_offset_u64(&info_linear->info,
12333 desc->array_offset, addr);
12334 }
12335}
6446b315 12336
ff26ce5c
EC
12337int bpf_program__set_attach_target(struct bpf_program *prog,
12338 int attach_prog_fd,
12339 const char *attach_func_name)
12340{
fe62de31 12341 int btf_obj_fd = 0, btf_id = 0, err;
ff26ce5c 12342
2d5ec1c6 12343 if (!prog || attach_prog_fd < 0)
e9fc3ce9 12344 return libbpf_err(-EINVAL);
ff26ce5c 12345
fe62de31 12346 if (prog->obj->loaded)
e9fc3ce9 12347 return libbpf_err(-EINVAL);
fe62de31 12348
2d5ec1c6
AN
12349 if (attach_prog_fd && !attach_func_name) {
12350 /* remember attach_prog_fd and let bpf_program__load() find
12351 * BTF ID during the program load
12352 */
12353 prog->attach_prog_fd = attach_prog_fd;
12354 return 0;
12355 }
12356
fe62de31 12357 if (attach_prog_fd) {
ff26ce5c
EC
12358 btf_id = libbpf_find_prog_btf_id(attach_func_name,
12359 attach_prog_fd);
fe62de31 12360 if (btf_id < 0)
e9fc3ce9 12361 return libbpf_err(btf_id);
fe62de31 12362 } else {
2d5ec1c6
AN
12363 if (!attach_func_name)
12364 return libbpf_err(-EINVAL);
12365
fe62de31
AN
12366 /* load btf_vmlinux, if not yet */
12367 err = bpf_object__load_vmlinux_btf(prog->obj, true);
12368 if (err)
e9fc3ce9 12369 return libbpf_err(err);
fe62de31
AN
12370 err = find_kernel_btf_id(prog->obj, attach_func_name,
12371 prog->expected_attach_type,
12372 &btf_obj_fd, &btf_id);
12373 if (err)
e9fc3ce9 12374 return libbpf_err(err);
fe62de31 12375 }
ff26ce5c
EC
12376
12377 prog->attach_btf_id = btf_id;
fe62de31 12378 prog->attach_btf_obj_fd = btf_obj_fd;
ff26ce5c
EC
12379 prog->attach_prog_fd = attach_prog_fd;
12380 return 0;
12381}
12382
6803ee25 12383int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
6446b315 12384{
6803ee25
AN
12385 int err = 0, n, len, start, end = -1;
12386 bool *tmp;
6446b315 12387
6803ee25
AN
12388 *mask = NULL;
12389 *mask_sz = 0;
12390
12391 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12392 while (*s) {
12393 if (*s == ',' || *s == '\n') {
12394 s++;
12395 continue;
12396 }
12397 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12398 if (n <= 0 || n > 2) {
12399 pr_warn("Failed to get CPU range %s: %d\n", s, n);
12400 err = -EINVAL;
12401 goto cleanup;
12402 } else if (n == 1) {
12403 end = start;
12404 }
12405 if (start < 0 || start > end) {
12406 pr_warn("Invalid CPU range [%d,%d] in %s\n",
12407 start, end, s);
12408 err = -EINVAL;
12409 goto cleanup;
12410 }
12411 tmp = realloc(*mask, end + 1);
12412 if (!tmp) {
12413 err = -ENOMEM;
12414 goto cleanup;
12415 }
12416 *mask = tmp;
12417 memset(tmp + *mask_sz, 0, start - *mask_sz);
12418 memset(tmp + start, 1, end - start + 1);
12419 *mask_sz = end + 1;
12420 s += len;
12421 }
12422 if (!*mask_sz) {
12423 pr_warn("Empty CPU range\n");
12424 return -EINVAL;
12425 }
12426 return 0;
12427cleanup:
12428 free(*mask);
12429 *mask = NULL;
12430 return err;
12431}
12432
12433int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12434{
12435 int fd, err = 0, len;
12436 char buf[128];
6446b315 12437
92274e24 12438 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
6446b315 12439 if (fd < 0) {
6803ee25
AN
12440 err = -errno;
12441 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12442 return err;
6446b315
HL
12443 }
12444 len = read(fd, buf, sizeof(buf));
12445 close(fd);
12446 if (len <= 0) {
6803ee25
AN
12447 err = len ? -errno : -EINVAL;
12448 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12449 return err;
6446b315 12450 }
6803ee25
AN
12451 if (len >= sizeof(buf)) {
12452 pr_warn("CPU mask is too big in file %s\n", fcpu);
12453 return -E2BIG;
6446b315
HL
12454 }
12455 buf[len] = '\0';
12456
6803ee25
AN
12457 return parse_cpu_mask_str(buf, mask, mask_sz);
12458}
12459
12460int libbpf_num_possible_cpus(void)
12461{
12462 static const char *fcpu = "/sys/devices/system/cpu/possible";
12463 static int cpus;
12464 int err, n, i, tmp_cpus;
12465 bool *mask;
12466
12467 tmp_cpus = READ_ONCE(cpus);
12468 if (tmp_cpus > 0)
12469 return tmp_cpus;
12470
12471 err = parse_cpu_mask_file(fcpu, &mask, &n);
12472 if (err)
e9fc3ce9 12473 return libbpf_err(err);
6803ee25
AN
12474
12475 tmp_cpus = 0;
12476 for (i = 0; i < n; i++) {
12477 if (mask[i])
12478 tmp_cpus++;
6446b315 12479 }
6803ee25 12480 free(mask);
56fbc241
TC
12481
12482 WRITE_ONCE(cpus, tmp_cpus);
12483 return tmp_cpus;
6446b315 12484}
d66562fb 12485
430025e5
DK
12486static int populate_skeleton_maps(const struct bpf_object *obj,
12487 struct bpf_map_skeleton *maps,
12488 size_t map_cnt)
12489{
12490 int i;
12491
12492 for (i = 0; i < map_cnt; i++) {
12493 struct bpf_map **map = maps[i].map;
12494 const char *name = maps[i].name;
12495 void **mmaped = maps[i].mmaped;
12496
12497 *map = bpf_object__find_map_by_name(obj, name);
12498 if (!*map) {
12499 pr_warn("failed to find skeleton map '%s'\n", name);
12500 return -ESRCH;
12501 }
12502
12503 /* externs shouldn't be pre-setup from user code */
12504 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12505 *mmaped = (*map)->mmaped;
12506 }
12507 return 0;
12508}
12509
12510static int populate_skeleton_progs(const struct bpf_object *obj,
12511 struct bpf_prog_skeleton *progs,
12512 size_t prog_cnt)
12513{
12514 int i;
12515
12516 for (i = 0; i < prog_cnt; i++) {
12517 struct bpf_program **prog = progs[i].prog;
12518 const char *name = progs[i].name;
12519
12520 *prog = bpf_object__find_program_by_name(obj, name);
12521 if (!*prog) {
12522 pr_warn("failed to find skeleton program '%s'\n", name);
12523 return -ESRCH;
12524 }
12525 }
12526 return 0;
12527}
12528
d66562fb
AN
12529int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12530 const struct bpf_object_open_opts *opts)
12531{
12532 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12533 .object_name = s->name,
12534 );
12535 struct bpf_object *obj;
430025e5 12536 int err;
d66562fb
AN
12537
12538 /* Attempt to preserve opts->object_name, unless overriden by user
12539 * explicitly. Overwriting object name for skeletons is discouraged,
12540 * as it breaks global data maps, because they contain object name
12541 * prefix as their own map name prefix. When skeleton is generated,
12542 * bpftool is making an assumption that this name will stay the same.
12543 */
12544 if (opts) {
12545 memcpy(&skel_opts, opts, sizeof(*opts));
12546 if (!opts->object_name)
12547 skel_opts.object_name = s->name;
12548 }
12549
12550 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
e9fc3ce9
AN
12551 err = libbpf_get_error(obj);
12552 if (err) {
12553 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12554 s->name, err);
12555 return libbpf_err(err);
d66562fb
AN
12556 }
12557
12558 *s->obj = obj;
430025e5
DK
12559 err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12560 if (err) {
12561 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12562 return libbpf_err(err);
12563 }
12564
12565 err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12566 if (err) {
12567 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12568 return libbpf_err(err);
12569 }
d66562fb 12570
430025e5
DK
12571 return 0;
12572}
d66562fb 12573
430025e5
DK
12574int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12575{
12576 int err, len, var_idx, i;
12577 const char *var_name;
12578 const struct bpf_map *map;
12579 struct btf *btf;
12580 __u32 map_type_id;
12581 const struct btf_type *map_type, *var_type;
12582 const struct bpf_var_skeleton *var_skel;
12583 struct btf_var_secinfo *var;
d66562fb 12584
430025e5
DK
12585 if (!s->obj)
12586 return libbpf_err(-EINVAL);
12587
12588 btf = bpf_object__btf(s->obj);
12589 if (!btf) {
12590 pr_warn("subskeletons require BTF at runtime (object %s)\n",
12591 bpf_object__name(s->obj));
12592 return libbpf_err(-errno);
d66562fb
AN
12593 }
12594
430025e5
DK
12595 err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12596 if (err) {
12597 pr_warn("failed to populate subskeleton maps: %d\n", err);
12598 return libbpf_err(err);
12599 }
d66562fb 12600
430025e5
DK
12601 err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12602 if (err) {
12603 pr_warn("failed to populate subskeleton maps: %d\n", err);
12604 return libbpf_err(err);
d66562fb
AN
12605 }
12606
430025e5
DK
12607 for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12608 var_skel = &s->vars[var_idx];
12609 map = *var_skel->map;
12610 map_type_id = bpf_map__btf_value_type_id(map);
12611 map_type = btf__type_by_id(btf, map_type_id);
12612
12613 if (!btf_is_datasec(map_type)) {
12614 pr_warn("type for map '%1$s' is not a datasec: %2$s",
12615 bpf_map__name(map),
12616 __btf_kind_str(btf_kind(map_type)));
12617 return libbpf_err(-EINVAL);
12618 }
12619
12620 len = btf_vlen(map_type);
12621 var = btf_var_secinfos(map_type);
12622 for (i = 0; i < len; i++, var++) {
12623 var_type = btf__type_by_id(btf, var->type);
12624 var_name = btf__name_by_offset(btf, var_type->name_off);
12625 if (strcmp(var_name, var_skel->name) == 0) {
12626 *var_skel->addr = map->mmaped + var->offset;
12627 break;
12628 }
12629 }
12630 }
d66562fb
AN
12631 return 0;
12632}
12633
430025e5
DK
12634void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12635{
12636 if (!s)
12637 return;
12638 free(s->maps);
12639 free(s->progs);
12640 free(s->vars);
12641 free(s);
12642}
12643
d66562fb
AN
12644int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12645{
12646 int i, err;
12647
12648 err = bpf_object__load(*s->obj);
12649 if (err) {
12650 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
e9fc3ce9 12651 return libbpf_err(err);
d66562fb
AN
12652 }
12653
12654 for (i = 0; i < s->map_cnt; i++) {
12655 struct bpf_map *map = *s->maps[i].map;
12656 size_t mmap_sz = bpf_map_mmap_sz(map);
12657 int prot, map_fd = bpf_map__fd(map);
12658 void **mmaped = s->maps[i].mmaped;
d66562fb
AN
12659
12660 if (!mmaped)
12661 continue;
12662
12663 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12664 *mmaped = NULL;
12665 continue;
12666 }
12667
12668 if (map->def.map_flags & BPF_F_RDONLY_PROG)
12669 prot = PROT_READ;
12670 else
12671 prot = PROT_READ | PROT_WRITE;
12672
12673 /* Remap anonymous mmap()-ed "map initialization image" as
12674 * a BPF map-backed mmap()-ed memory, but preserving the same
12675 * memory address. This will cause kernel to change process'
12676 * page table to point to a different piece of kernel memory,
12677 * but from userspace point of view memory address (and its
12678 * contents, being identical at this point) will stay the
12679 * same. This mapping will be released by bpf_object__close()
12680 * as per normal clean up procedure, so we don't need to worry
12681 * about it from skeleton's clean up perspective.
12682 */
2ad97d47
AN
12683 *mmaped = mmap(map->mmaped, mmap_sz, prot,
12684 MAP_SHARED | MAP_FIXED, map_fd, 0);
12685 if (*mmaped == MAP_FAILED) {
d66562fb
AN
12686 err = -errno;
12687 *mmaped = NULL;
12688 pr_warn("failed to re-mmap() map '%s': %d\n",
12689 bpf_map__name(map), err);
e9fc3ce9 12690 return libbpf_err(err);
d66562fb
AN
12691 }
12692 }
12693
12694 return 0;
12695}
12696
12697int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12698{
e9fc3ce9 12699 int i, err;
d66562fb
AN
12700
12701 for (i = 0; i < s->prog_cnt; i++) {
12702 struct bpf_program *prog = *s->progs[i].prog;
12703 struct bpf_link **link = s->progs[i].link;
d66562fb 12704
a3820c48 12705 if (!prog->autoload)
d9297581
AN
12706 continue;
12707
5532dfd4 12708 /* auto-attaching not supported for this program */
4fa5bcfe 12709 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
d66562fb
AN
12710 continue;
12711
4fa5bcfe
AN
12712 /* if user already set the link manually, don't attempt auto-attach */
12713 if (*link)
12714 continue;
12715
12716 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
e9fc3ce9 12717 if (err) {
4fa5bcfe 12718 pr_warn("prog '%s': failed to auto-attach: %d\n",
e9fc3ce9
AN
12719 bpf_program__name(prog), err);
12720 return libbpf_err(err);
d66562fb 12721 }
4fa5bcfe
AN
12722
12723 /* It's possible that for some SEC() definitions auto-attach
12724 * is supported in some cases (e.g., if definition completely
12725 * specifies target information), but is not in other cases.
12726 * SEC("uprobe") is one such case. If user specified target
12727 * binary and function name, such BPF program can be
12728 * auto-attached. But if not, it shouldn't trigger skeleton's
12729 * attach to fail. It should just be skipped.
12730 * attach_fn signals such case with returning 0 (no error) and
12731 * setting link to NULL.
12732 */
d66562fb
AN
12733 }
12734
12735 return 0;
12736}
12737
12738void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12739{
12740 int i;
12741
12742 for (i = 0; i < s->prog_cnt; i++) {
12743 struct bpf_link **link = s->progs[i].link;
12744
50450fc7 12745 bpf_link__destroy(*link);
d66562fb
AN
12746 *link = NULL;
12747 }
12748}
12749
12750void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12751{
a32ea51a
YS
12752 if (!s)
12753 return;
12754
d66562fb
AN
12755 if (s->progs)
12756 bpf_object__detach_skeleton(s);
12757 if (s->obj)
12758 bpf_object__close(*s->obj);
12759 free(s->maps);
12760 free(s->progs);
12761 free(s);
12762}