bpf: selftests: update xdp_adjust_tail selftest to include xdp frags
[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{
159 /* __LIBBPF_STRICT_LAST is the last power-of-2 value used + 1, so to
160 * get all possible values we compensate last +1, and then (2*x - 1)
161 * to get the bit mask
162 */
163 if (mode != LIBBPF_STRICT_ALL
164 && (mode & ~((__LIBBPF_STRICT_LAST - 1) * 2 - 1)))
165 return errno = EINVAL, -EINVAL;
166
167 libbpf_mode = mode;
168 return 0;
169}
170
7615209f
AN
171__u32 libbpf_major_version(void)
172{
173 return LIBBPF_MAJOR_VERSION;
174}
175
176__u32 libbpf_minor_version(void)
177{
178 return LIBBPF_MINOR_VERSION;
179}
180
181const char *libbpf_version_string(void)
182{
183#define __S(X) #X
184#define _S(X) __S(X)
185 return "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
186#undef _S
187#undef __S
188}
189
166750bc
AN
190enum reloc_type {
191 RELO_LD64,
192 RELO_CALL,
193 RELO_DATA,
0c091e5c 194 RELO_EXTERN_VAR,
5bd022ec 195 RELO_EXTERN_FUNC,
53eddb5e 196 RELO_SUBPROG_ADDR,
d0e92887 197 RELO_CORE,
166750bc
AN
198};
199
200struct reloc_desc {
201 enum reloc_type type;
202 int insn_idx;
d0e92887
AS
203 union {
204 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
205 struct {
206 int map_idx;
207 int sym_off;
208 };
209 };
166750bc
AN
210};
211
25498a19
AN
212struct bpf_sec_def;
213
12d9466d 214typedef int (*init_fn_t)(struct bpf_program *prog, long cookie);
d10ef2b8 215typedef int (*preload_fn_t)(struct bpf_program *prog, struct bpf_prog_load_opts *opts, long cookie);
12d9466d 216typedef struct bpf_link *(*attach_fn_t)(const struct bpf_program *prog, long cookie);
25498a19 217
15ea31fa
AN
218/* stored as sec_def->cookie for all libbpf-supported SEC()s */
219enum sec_def_flags {
220 SEC_NONE = 0,
221 /* expected_attach_type is optional, if kernel doesn't support that */
222 SEC_EXP_ATTACH_OPT = 1,
223 /* legacy, only used by libbpf_get_type_names() and
224 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
225 * This used to be associated with cgroup (and few other) BPF programs
226 * that were attachable through BPF_PROG_ATTACH command. Pretty
227 * meaningless nowadays, though.
228 */
229 SEC_ATTACHABLE = 2,
230 SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
231 /* attachment target is specified through BTF ID in either kernel or
232 * other BPF program's BTF object */
233 SEC_ATTACH_BTF = 4,
234 /* BPF program type allows sleeping/blocking in kernel */
235 SEC_SLEEPABLE = 8,
dd94d45c
AN
236 /* allow non-strict prefix matching */
237 SEC_SLOPPY_PFX = 16,
15ea31fa
AN
238};
239
25498a19
AN
240struct bpf_sec_def {
241 const char *sec;
25498a19
AN
242 enum bpf_prog_type prog_type;
243 enum bpf_attach_type expected_attach_type;
15ea31fa 244 long cookie;
12d9466d
AN
245
246 init_fn_t init_fn;
247 preload_fn_t preload_fn;
25498a19
AN
248 attach_fn_t attach_fn;
249};
250
a5b8bd47
WN
251/*
252 * bpf_prog should be a better name but it has been used in
253 * linux/filter.h.
254 */
255struct bpf_program {
25498a19 256 const struct bpf_sec_def *sec_def;
52109584 257 char *sec_name;
c1122392
AN
258 size_t sec_idx;
259 /* this program's instruction offset (in number of instructions)
260 * within its containing ELF section
261 */
262 size_t sec_insn_off;
263 /* number of original instructions in ELF section belonging to this
264 * program, not taking into account subprogram instructions possible
265 * appended later during relocation
266 */
267 size_t sec_insn_cnt;
268 /* Offset (in number of instructions) of the start of instruction
269 * belonging to this BPF program within its containing main BPF
270 * program. For the entry-point (main) BPF program, this is always
271 * zero. For a sub-program, this gets reset before each of main BPF
272 * programs are processed and relocated and is used to determined
273 * whether sub-program was already appended to the main program, and
274 * if yes, at which instruction offset.
275 */
276 size_t sub_insn_off;
277
278 char *name;
a77f879b 279 /* name with / replaced by _; makes recursive pinning
33a2c75c
SF
280 * in bpf_object__pin_programs easier
281 */
282 char *pin_name;
c1122392
AN
283
284 /* instructions that belong to BPF program; insns[0] is located at
285 * sec_insn_off instruction within its ELF section in ELF file, so
286 * when mapping ELF file instruction index to the local instruction,
287 * one needs to subtract sec_insn_off; and vice versa.
288 */
a5b8bd47 289 struct bpf_insn *insns;
c1122392
AN
290 /* actual number of instruction in this BPF program's image; for
291 * entry-point BPF programs this includes the size of main program
292 * itself plus all the used sub-programs, appended at the end
293 */
c3c55696 294 size_t insns_cnt;
34090915 295
166750bc 296 struct reloc_desc *reloc_desc;
34090915 297 int nr_reloc;
b3ce9079
AN
298
299 /* BPF verifier log settings */
300 char *log_buf;
301 size_t log_size;
302 __u32 log_level;
55cffde2 303
b580563e
WN
304 struct {
305 int nr;
306 int *fds;
307 } instances;
308 bpf_program_prep_t preprocessor;
aa9b1ac3
WN
309
310 struct bpf_object *obj;
311 void *priv;
312 bpf_program_clear_priv_t clear_priv;
d7be143b 313
c1122392 314 bool load;
aea28a60 315 bool mark_btf_static;
c1122392 316 enum bpf_prog_type type;
d7be143b 317 enum bpf_attach_type expected_attach_type;
c1122392 318 int prog_ifindex;
91abb4a6 319 __u32 attach_btf_obj_fd;
12a8654b 320 __u32 attach_btf_id;
e7bf94db 321 __u32 attach_prog_fd;
2993e051
YS
322 void *func_info;
323 __u32 func_info_rec_size;
f0187f0b 324 __u32 func_info_cnt;
47eff617 325
3d650141
MKL
326 void *line_info;
327 __u32 line_info_rec_size;
328 __u32 line_info_cnt;
04656198 329 __u32 prog_flags;
a5b8bd47
WN
330};
331
590a0088
MKL
332struct bpf_struct_ops {
333 const char *tname;
334 const struct btf_type *type;
335 struct bpf_program **progs;
336 __u32 *kern_func_off;
337 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
338 void *data;
339 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
340 * btf_vmlinux's format.
341 * struct bpf_struct_ops_tcp_congestion_ops {
342 * [... some other kernel fields ...]
343 * struct tcp_congestion_ops data;
344 * }
345 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
346 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
347 * from "data".
348 */
349 void *kern_vdata;
350 __u32 type_id;
351};
352
ac9d1389
AN
353#define DATA_SEC ".data"
354#define BSS_SEC ".bss"
355#define RODATA_SEC ".rodata"
81bfdd08 356#define KCONFIG_SEC ".kconfig"
1c0c7074 357#define KSYMS_SEC ".ksyms"
590a0088 358#define STRUCT_OPS_SEC ".struct_ops"
ac9d1389 359
d859900c
DB
360enum libbpf_map_type {
361 LIBBPF_MAP_UNSPEC,
362 LIBBPF_MAP_DATA,
363 LIBBPF_MAP_BSS,
364 LIBBPF_MAP_RODATA,
81bfdd08 365 LIBBPF_MAP_KCONFIG,
d859900c
DB
366};
367
9d759a9b 368struct bpf_map {
561bbcca 369 char *name;
aed65917
AN
370 /* real_name is defined for special internal maps (.rodata*,
371 * .data*, .bss, .kconfig) and preserves their original ELF section
372 * name. This is important to be be able to find corresponding BTF
373 * DATASEC information.
374 */
375 char *real_name;
01af3bf0 376 int fd;
db48814b
AN
377 int sec_idx;
378 size_t sec_offset;
f0307a7e 379 int map_ifindex;
addb9fc9 380 int inner_map_fd;
9d759a9b 381 struct bpf_map_def def;
1bdb6c9a 382 __u32 numa_node;
646f02ff 383 __u32 btf_var_idx;
5b891af7
MKL
384 __u32 btf_key_type_id;
385 __u32 btf_value_type_id;
590a0088 386 __u32 btf_vmlinux_value_type_id;
9d759a9b
WN
387 void *priv;
388 bpf_map_clear_priv_t clear_priv;
d859900c 389 enum libbpf_map_type libbpf_type;
eba9c5f4 390 void *mmaped;
590a0088 391 struct bpf_struct_ops *st_ops;
646f02ff
AN
392 struct bpf_map *inner_map;
393 void **init_slots;
394 int init_slots_sz;
4580b25f
THJ
395 char *pin_path;
396 bool pinned;
ec6d5f47 397 bool reused;
229fae38 398 bool skipped;
47512102 399 __u64 map_extra;
d859900c
DB
400};
401
166750bc
AN
402enum extern_type {
403 EXT_UNKNOWN,
2e33efe3 404 EXT_KCFG,
1c0c7074 405 EXT_KSYM,
2e33efe3
AN
406};
407
408enum kcfg_type {
409 KCFG_UNKNOWN,
410 KCFG_CHAR,
411 KCFG_BOOL,
412 KCFG_INT,
413 KCFG_TRISTATE,
414 KCFG_CHAR_ARR,
166750bc
AN
415};
416
417struct extern_desc {
2e33efe3 418 enum extern_type type;
166750bc
AN
419 int sym_idx;
420 int btf_id;
2e33efe3
AN
421 int sec_btf_id;
422 const char *name;
166750bc 423 bool is_set;
2e33efe3
AN
424 bool is_weak;
425 union {
426 struct {
427 enum kcfg_type type;
428 int sz;
429 int align;
430 int data_off;
431 bool is_signed;
432 } kcfg;
1c0c7074
AN
433 struct {
434 unsigned long long addr;
d370bbe1
HL
435
436 /* target btf_id of the corresponding kernel var. */
284d2587
AN
437 int kernel_btf_obj_fd;
438 int kernel_btf_id;
d370bbe1
HL
439
440 /* local btf_id of the ksym extern's type. */
441 __u32 type_id;
9dbe6015
KKD
442 /* BTF fd index to be patched in for insn->off, this is
443 * 0 for vmlinux BTF, index in obj->fd_array for module
444 * BTF
445 */
446 __s16 btf_fd_idx;
1c0c7074 447 } ksym;
2e33efe3 448 };
166750bc
AN
449};
450
9a208eff
WN
451static LIST_HEAD(bpf_objects_list);
452
4f33a53d
AN
453struct module_btf {
454 struct btf *btf;
455 char *name;
456 __u32 id;
91abb4a6 457 int fd;
9dbe6015 458 int fd_array_idx;
4f33a53d
AN
459};
460
25bbbd7a
AN
461enum sec_type {
462 SEC_UNUSED = 0,
463 SEC_RELO,
464 SEC_BSS,
465 SEC_DATA,
466 SEC_RODATA,
467};
468
469struct elf_sec_desc {
470 enum sec_type sec_type;
471 Elf64_Shdr *shdr;
472 Elf_Data *data;
473};
474
29a30ff5
AN
475struct elf_state {
476 int fd;
477 const void *obj_buf;
478 size_t obj_buf_sz;
479 Elf *elf;
ad23b723 480 Elf64_Ehdr *ehdr;
29a30ff5 481 Elf_Data *symbols;
29a30ff5
AN
482 Elf_Data *st_ops_data;
483 size_t shstrndx; /* section index for section name strings */
484 size_t strtabidx;
25bbbd7a
AN
485 struct elf_sec_desc *secs;
486 int sec_cnt;
29a30ff5
AN
487 int maps_shndx;
488 int btf_maps_shndx;
489 __u32 btf_maps_sec_btf_id;
490 int text_shndx;
491 int symbols_shndx;
29a30ff5 492 int st_ops_shndx;
4f33a53d
AN
493};
494
1a5e3fb1 495struct bpf_object {
d859900c 496 char name[BPF_OBJ_NAME_LEN];
cb1e5e96 497 char license[64];
438363c0 498 __u32 kern_version;
0b3d1efa 499
a5b8bd47
WN
500 struct bpf_program *programs;
501 size_t nr_programs;
9d759a9b
WN
502 struct bpf_map *maps;
503 size_t nr_maps;
bf829271 504 size_t maps_cap;
9d759a9b 505
8601fd42 506 char *kconfig;
166750bc
AN
507 struct extern_desc *externs;
508 int nr_extern;
81bfdd08 509 int kconfig_map_idx;
166750bc 510
52d3352e 511 bool loaded;
c3c55696 512 bool has_subcalls;
25bbbd7a 513 bool has_rodata;
a5b8bd47 514
e2fa0156
AS
515 struct bpf_gen *gen_loader;
516
29a30ff5
AN
517 /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
518 struct elf_state efile;
1a5e3fb1 519 /*
29a30ff5 520 * All loaded bpf_object are linked in a list, which is
9a208eff
WN
521 * hidden to caller. bpf_objects__<func> handlers deal with
522 * all objects.
523 */
524 struct list_head list;
10931d24 525
8a138aed 526 struct btf *btf;
0f7515ca
AN
527 struct btf_ext *btf_ext;
528
a6ed02ca
KS
529 /* Parse and load BTF vmlinux if any of the programs in the object need
530 * it at load time.
531 */
532 struct btf *btf_vmlinux;
1373ff59
SC
533 /* Path to the custom BTF to be used for BPF CO-RE relocations as an
534 * override for vmlinux BTF.
535 */
536 char *btf_custom_path;
0f7515ca
AN
537 /* vmlinux BTF override for CO-RE relocations */
538 struct btf *btf_vmlinux_override;
4f33a53d
AN
539 /* Lazily initialized kernel module BTFs */
540 struct module_btf *btf_modules;
541 bool btf_modules_loaded;
542 size_t btf_module_cnt;
543 size_t btf_module_cap;
8a138aed 544
e0e3ea88
AN
545 /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
546 char *log_buf;
547 size_t log_size;
548 __u32 log_level;
549
10931d24
WN
550 void *priv;
551 bpf_object_clear_priv_t clear_priv;
552
9dbe6015
KKD
553 int *fd_array;
554 size_t fd_array_cap;
555 size_t fd_array_cnt;
556
1a5e3fb1
WN
557 char path[];
558};
1a5e3fb1 559
88a82120
AN
560static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
561static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
562static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
563static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
ad23b723 564static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
88a82120
AN
565static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
566static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
ad23b723
AN
567static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
568static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
88a82120 569
29cd77f4 570void bpf_program__unload(struct bpf_program *prog)
55cffde2 571{
b580563e
WN
572 int i;
573
55cffde2
WN
574 if (!prog)
575 return;
576
b580563e
WN
577 /*
578 * If the object is opened but the program was never loaded,
579 * it is possible that prog->instances.nr == -1.
580 */
581 if (prog->instances.nr > 0) {
582 for (i = 0; i < prog->instances.nr; i++)
583 zclose(prog->instances.fds[i]);
584 } else if (prog->instances.nr != -1) {
be18010e
KW
585 pr_warn("Internal error: instances.nr is %d\n",
586 prog->instances.nr);
b580563e
WN
587 }
588
589 prog->instances.nr = -1;
590 zfree(&prog->instances.fds);
2993e051 591
2993e051 592 zfree(&prog->func_info);
07a09d1b 593 zfree(&prog->line_info);
55cffde2
WN
594}
595
a5b8bd47
WN
596static void bpf_program__exit(struct bpf_program *prog)
597{
598 if (!prog)
599 return;
600
aa9b1ac3
WN
601 if (prog->clear_priv)
602 prog->clear_priv(prog, prog->priv);
603
604 prog->priv = NULL;
605 prog->clear_priv = NULL;
606
55cffde2 607 bpf_program__unload(prog);
88cda1c9 608 zfree(&prog->name);
52109584 609 zfree(&prog->sec_name);
33a2c75c 610 zfree(&prog->pin_name);
a5b8bd47 611 zfree(&prog->insns);
34090915
WN
612 zfree(&prog->reloc_desc);
613
614 prog->nr_reloc = 0;
a5b8bd47 615 prog->insns_cnt = 0;
c1122392 616 prog->sec_idx = -1;
a5b8bd47
WN
617}
618
33a2c75c
SF
619static char *__bpf_program__pin_name(struct bpf_program *prog)
620{
621 char *name, *p;
622
a77f879b
SF
623 if (libbpf_mode & LIBBPF_STRICT_SEC_NAME)
624 name = strdup(prog->name);
625 else
626 name = strdup(prog->sec_name);
627
628 if (!name)
629 return NULL;
630
631 p = name;
632
33a2c75c
SF
633 while ((p = strchr(p, '/')))
634 *p = '_';
635
636 return name;
637}
638
c3c55696
AN
639static bool insn_is_subprog_call(const struct bpf_insn *insn)
640{
641 return BPF_CLASS(insn->code) == BPF_JMP &&
642 BPF_OP(insn->code) == BPF_CALL &&
643 BPF_SRC(insn->code) == BPF_K &&
644 insn->src_reg == BPF_PSEUDO_CALL &&
645 insn->dst_reg == 0 &&
646 insn->off == 0;
647}
648
aa0b8d43
MKL
649static bool is_call_insn(const struct bpf_insn *insn)
650{
651 return insn->code == (BPF_JMP | BPF_CALL);
652}
653
53eddb5e
YS
654static bool insn_is_pseudo_func(struct bpf_insn *insn)
655{
aa0b8d43 656 return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
53eddb5e
YS
657}
658
a5b8bd47 659static int
c3c55696
AN
660bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
661 const char *name, size_t sec_idx, const char *sec_name,
662 size_t sec_off, void *insn_data, size_t insn_data_sz)
a5b8bd47 663{
c1122392
AN
664 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
665 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
666 sec_name, name, sec_off, insn_data_sz);
a5b8bd47
WN
667 return -EINVAL;
668 }
669
1ad9cbb8 670 memset(prog, 0, sizeof(*prog));
c3c55696
AN
671 prog->obj = obj;
672
c1122392
AN
673 prog->sec_idx = sec_idx;
674 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
675 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
676 /* insns_cnt can later be increased by appending used subprograms */
677 prog->insns_cnt = prog->sec_insn_cnt;
a5b8bd47 678
c1122392
AN
679 prog->type = BPF_PROG_TYPE_UNSPEC;
680 prog->load = true;
a5b8bd47 681
c1122392
AN
682 prog->instances.fds = NULL;
683 prog->instances.nr = -1;
684
b3ce9079
AN
685 /* inherit object's log_level */
686 prog->log_level = obj->log_level;
687
52109584
AN
688 prog->sec_name = strdup(sec_name);
689 if (!prog->sec_name)
c1122392
AN
690 goto errout;
691
692 prog->name = strdup(name);
693 if (!prog->name)
a5b8bd47 694 goto errout;
a5b8bd47 695
33a2c75c 696 prog->pin_name = __bpf_program__pin_name(prog);
c1122392 697 if (!prog->pin_name)
33a2c75c 698 goto errout;
33a2c75c 699
c1122392
AN
700 prog->insns = malloc(insn_data_sz);
701 if (!prog->insns)
a5b8bd47 702 goto errout;
c1122392 703 memcpy(prog->insns, insn_data, insn_data_sz);
a5b8bd47
WN
704
705 return 0;
706errout:
c1122392 707 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
a5b8bd47
WN
708 bpf_program__exit(prog);
709 return -ENOMEM;
710}
711
712static int
c1122392
AN
713bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
714 const char *sec_name, int sec_idx)
a5b8bd47 715{
6245947c 716 Elf_Data *symbols = obj->efile.symbols;
c1122392
AN
717 struct bpf_program *prog, *progs;
718 void *data = sec_data->d_buf;
6245947c
AN
719 size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
720 int nr_progs, err, i;
c1122392 721 const char *name;
ad23b723 722 Elf64_Sym *sym;
a5b8bd47
WN
723
724 progs = obj->programs;
725 nr_progs = obj->nr_programs;
ad23b723 726 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
c1122392 727 sec_off = 0;
a5b8bd47 728
6245947c 729 for (i = 0; i < nr_syms; i++) {
ad23b723
AN
730 sym = elf_sym_by_idx(obj, i);
731
732 if (sym->st_shndx != sec_idx)
6245947c 733 continue;
ad23b723 734 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
6245947c 735 continue;
88cda1c9 736
ad23b723
AN
737 prog_sz = sym->st_size;
738 sec_off = sym->st_value;
88cda1c9 739
ad23b723 740 name = elf_sym_str(obj, sym->st_name);
c1122392
AN
741 if (!name) {
742 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
743 sec_name, sec_off);
744 return -LIBBPF_ERRNO__FORMAT;
745 }
88cda1c9 746
c1122392
AN
747 if (sec_off + prog_sz > sec_sz) {
748 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
749 sec_name, sec_off);
750 return -LIBBPF_ERRNO__FORMAT;
751 }
88cda1c9 752
ad23b723 753 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
513f485c
AN
754 pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
755 return -ENOTSUP;
756 }
757
c3c55696
AN
758 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
759 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
88cda1c9 760
c3c55696 761 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
c1122392
AN
762 if (!progs) {
763 /*
764 * In this case the original obj->programs
765 * is still valid, so don't need special treat for
766 * bpf_close_object().
767 */
768 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
769 sec_name, name);
770 return -ENOMEM;
88cda1c9 771 }
c1122392 772 obj->programs = progs;
88cda1c9 773
c1122392 774 prog = &progs[nr_progs];
9a94f277 775
c3c55696
AN
776 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
777 sec_off, data + sec_off, prog_sz);
c1122392
AN
778 if (err)
779 return err;
9a94f277 780
e5670fa0
AN
781 /* if function is a global/weak symbol, but has restricted
782 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
783 * as static to enable more permissive BPF verification mode
784 * with more outside context available to BPF verifier
aea28a60 785 */
ad23b723
AN
786 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
787 && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
788 || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
aea28a60
AN
789 prog->mark_btf_static = true;
790
c1122392
AN
791 nr_progs++;
792 obj->nr_programs = nr_progs;
88cda1c9
MKL
793 }
794
795 return 0;
796}
797
5b3d7298 798__u32 get_kernel_version(void)
5e61f270 799{
5b3d7298
AN
800 /* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
801 * but Ubuntu provides /proc/version_signature file, as described at
802 * https://ubuntu.com/kernel, with an example contents below, which we
803 * can use to get a proper LINUX_VERSION_CODE.
804 *
805 * Ubuntu 5.4.0-12.15-generic 5.4.8
806 *
807 * In the above, 5.4.8 is what kernel is actually expecting, while
808 * uname() call will return 5.4.0 in info.release.
809 */
810 const char *ubuntu_kver_file = "/proc/version_signature";
5e61f270
AN
811 __u32 major, minor, patch;
812 struct utsname info;
813
5b3d7298
AN
814 if (access(ubuntu_kver_file, R_OK) == 0) {
815 FILE *f;
816
817 f = fopen(ubuntu_kver_file, "r");
818 if (f) {
819 if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
820 fclose(f);
821 return KERNEL_VERSION(major, minor, patch);
822 }
823 fclose(f);
824 }
825 /* something went wrong, fall back to uname() approach */
826 }
827
5e61f270
AN
828 uname(&info);
829 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
830 return 0;
831 return KERNEL_VERSION(major, minor, patch);
832}
833
590a0088
MKL
834static const struct btf_member *
835find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
836{
837 struct btf_member *m;
838 int i;
839
840 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
841 if (btf_member_bit_offset(t, i) == bit_offset)
842 return m;
843 }
844
845 return NULL;
846}
847
848static const struct btf_member *
849find_member_by_name(const struct btf *btf, const struct btf_type *t,
850 const char *name)
851{
852 struct btf_member *m;
853 int i;
854
855 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
856 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
857 return m;
858 }
859
860 return NULL;
861}
862
863#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
a6ed02ca
KS
864static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
865 const char *name, __u32 kind);
590a0088
MKL
866
867static int
868find_struct_ops_kern_types(const struct btf *btf, const char *tname,
869 const struct btf_type **type, __u32 *type_id,
870 const struct btf_type **vtype, __u32 *vtype_id,
871 const struct btf_member **data_member)
872{
873 const struct btf_type *kern_type, *kern_vtype;
874 const struct btf_member *kern_data_member;
875 __s32 kern_vtype_id, kern_type_id;
590a0088
MKL
876 __u32 i;
877
878 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
879 if (kern_type_id < 0) {
880 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
881 tname);
882 return kern_type_id;
883 }
884 kern_type = btf__type_by_id(btf, kern_type_id);
885
886 /* Find the corresponding "map_value" type that will be used
887 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
888 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
889 * btf_vmlinux.
890 */
a6ed02ca
KS
891 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
892 tname, BTF_KIND_STRUCT);
590a0088 893 if (kern_vtype_id < 0) {
a6ed02ca
KS
894 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
895 STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
896 return kern_vtype_id;
897 }
898 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
899
900 /* Find "struct tcp_congestion_ops" from
901 * struct bpf_struct_ops_tcp_congestion_ops {
902 * [ ... ]
903 * struct tcp_congestion_ops data;
904 * }
905 */
906 kern_data_member = btf_members(kern_vtype);
907 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
908 if (kern_data_member->type == kern_type_id)
909 break;
910 }
911 if (i == btf_vlen(kern_vtype)) {
a6ed02ca
KS
912 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
913 tname, STRUCT_OPS_VALUE_PREFIX, tname);
590a0088
MKL
914 return -EINVAL;
915 }
916
917 *type = kern_type;
918 *type_id = kern_type_id;
919 *vtype = kern_vtype;
920 *vtype_id = kern_vtype_id;
921 *data_member = kern_data_member;
922
923 return 0;
924}
925
926static bool bpf_map__is_struct_ops(const struct bpf_map *map)
927{
928 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
929}
930
931/* Init the map's fields that depend on kern_btf */
932static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
933 const struct btf *btf,
934 const struct btf *kern_btf)
935{
936 const struct btf_member *member, *kern_member, *kern_data_member;
937 const struct btf_type *type, *kern_type, *kern_vtype;
938 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
939 struct bpf_struct_ops *st_ops;
940 void *data, *kern_data;
941 const char *tname;
942 int err;
943
944 st_ops = map->st_ops;
945 type = st_ops->type;
946 tname = st_ops->tname;
947 err = find_struct_ops_kern_types(kern_btf, tname,
948 &kern_type, &kern_type_id,
949 &kern_vtype, &kern_vtype_id,
950 &kern_data_member);
951 if (err)
952 return err;
953
954 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
955 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
956
957 map->def.value_size = kern_vtype->size;
958 map->btf_vmlinux_value_type_id = kern_vtype_id;
959
960 st_ops->kern_vdata = calloc(1, kern_vtype->size);
961 if (!st_ops->kern_vdata)
962 return -ENOMEM;
963
964 data = st_ops->data;
965 kern_data_off = kern_data_member->offset / 8;
966 kern_data = st_ops->kern_vdata + kern_data_off;
967
968 member = btf_members(type);
969 for (i = 0; i < btf_vlen(type); i++, member++) {
970 const struct btf_type *mtype, *kern_mtype;
971 __u32 mtype_id, kern_mtype_id;
972 void *mdata, *kern_mdata;
973 __s64 msize, kern_msize;
974 __u32 moff, kern_moff;
975 __u32 kern_member_idx;
976 const char *mname;
977
978 mname = btf__name_by_offset(btf, member->name_off);
979 kern_member = find_member_by_name(kern_btf, kern_type, mname);
980 if (!kern_member) {
981 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
982 map->name, mname);
983 return -ENOTSUP;
984 }
985
986 kern_member_idx = kern_member - btf_members(kern_type);
987 if (btf_member_bitfield_size(type, i) ||
988 btf_member_bitfield_size(kern_type, kern_member_idx)) {
989 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
990 map->name, mname);
991 return -ENOTSUP;
992 }
993
994 moff = member->offset / 8;
995 kern_moff = kern_member->offset / 8;
996
997 mdata = data + moff;
998 kern_mdata = kern_data + kern_moff;
999
1000 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1001 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1002 &kern_mtype_id);
1003 if (BTF_INFO_KIND(mtype->info) !=
1004 BTF_INFO_KIND(kern_mtype->info)) {
1005 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1006 map->name, mname, BTF_INFO_KIND(mtype->info),
1007 BTF_INFO_KIND(kern_mtype->info));
1008 return -ENOTSUP;
1009 }
1010
1011 if (btf_is_ptr(mtype)) {
1012 struct bpf_program *prog;
1013
d2836ddd
MKL
1014 prog = st_ops->progs[i];
1015 if (!prog)
1016 continue;
1017
590a0088
MKL
1018 kern_mtype = skip_mods_and_typedefs(kern_btf,
1019 kern_mtype->type,
1020 &kern_mtype_id);
d2836ddd
MKL
1021
1022 /* mtype->type must be a func_proto which was
1023 * guaranteed in bpf_object__collect_st_ops_relos(),
1024 * so only check kern_mtype for func_proto here.
1025 */
1026 if (!btf_is_func_proto(kern_mtype)) {
1027 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
590a0088
MKL
1028 map->name, mname);
1029 return -ENOTSUP;
1030 }
1031
590a0088
MKL
1032 prog->attach_btf_id = kern_type_id;
1033 prog->expected_attach_type = kern_member_idx;
1034
1035 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1036
1037 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1038 map->name, mname, prog->name, moff,
1039 kern_moff);
1040
1041 continue;
1042 }
1043
1044 msize = btf__resolve_size(btf, mtype_id);
1045 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1046 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1047 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1048 map->name, mname, (ssize_t)msize,
1049 (ssize_t)kern_msize);
1050 return -ENOTSUP;
1051 }
1052
1053 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1054 map->name, mname, (unsigned int)msize,
1055 moff, kern_moff);
1056 memcpy(kern_mdata, mdata, msize);
1057 }
1058
1059 return 0;
1060}
1061
1062static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1063{
590a0088
MKL
1064 struct bpf_map *map;
1065 size_t i;
1066 int err;
1067
1068 for (i = 0; i < obj->nr_maps; i++) {
1069 map = &obj->maps[i];
1070
1071 if (!bpf_map__is_struct_ops(map))
1072 continue;
1073
a6ed02ca
KS
1074 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1075 obj->btf_vmlinux);
1076 if (err)
590a0088 1077 return err;
590a0088
MKL
1078 }
1079
590a0088
MKL
1080 return 0;
1081}
1082
1083static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1084{
1085 const struct btf_type *type, *datasec;
1086 const struct btf_var_secinfo *vsi;
1087 struct bpf_struct_ops *st_ops;
1088 const char *tname, *var_name;
1089 __s32 type_id, datasec_id;
1090 const struct btf *btf;
1091 struct bpf_map *map;
1092 __u32 i;
1093
1094 if (obj->efile.st_ops_shndx == -1)
1095 return 0;
1096
1097 btf = obj->btf;
1098 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1099 BTF_KIND_DATASEC);
1100 if (datasec_id < 0) {
1101 pr_warn("struct_ops init: DATASEC %s not found\n",
1102 STRUCT_OPS_SEC);
1103 return -EINVAL;
1104 }
1105
1106 datasec = btf__type_by_id(btf, datasec_id);
1107 vsi = btf_var_secinfos(datasec);
1108 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1109 type = btf__type_by_id(obj->btf, vsi->type);
1110 var_name = btf__name_by_offset(obj->btf, type->name_off);
1111
1112 type_id = btf__resolve_type(obj->btf, vsi->type);
1113 if (type_id < 0) {
1114 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1115 vsi->type, STRUCT_OPS_SEC);
1116 return -EINVAL;
1117 }
1118
1119 type = btf__type_by_id(obj->btf, type_id);
1120 tname = btf__name_by_offset(obj->btf, type->name_off);
1121 if (!tname[0]) {
1122 pr_warn("struct_ops init: anonymous type is not supported\n");
1123 return -ENOTSUP;
1124 }
1125 if (!btf_is_struct(type)) {
1126 pr_warn("struct_ops init: %s is not a struct\n", tname);
1127 return -EINVAL;
1128 }
1129
1130 map = bpf_object__add_map(obj);
1131 if (IS_ERR(map))
1132 return PTR_ERR(map);
1133
1134 map->sec_idx = obj->efile.st_ops_shndx;
1135 map->sec_offset = vsi->offset;
1136 map->name = strdup(var_name);
1137 if (!map->name)
1138 return -ENOMEM;
1139
1140 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1141 map->def.key_size = sizeof(int);
1142 map->def.value_size = type->size;
1143 map->def.max_entries = 1;
1144
1145 map->st_ops = calloc(1, sizeof(*map->st_ops));
1146 if (!map->st_ops)
1147 return -ENOMEM;
1148 st_ops = map->st_ops;
1149 st_ops->data = malloc(type->size);
1150 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1151 st_ops->kern_func_off = malloc(btf_vlen(type) *
1152 sizeof(*st_ops->kern_func_off));
1153 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1154 return -ENOMEM;
1155
1156 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1157 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1158 var_name, STRUCT_OPS_SEC);
1159 return -EINVAL;
1160 }
1161
1162 memcpy(st_ops->data,
1163 obj->efile.st_ops_data->d_buf + vsi->offset,
1164 type->size);
1165 st_ops->tname = tname;
1166 st_ops->type = type;
1167 st_ops->type_id = type_id;
1168
1169 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1170 tname, type_id, var_name, vsi->offset);
1171 }
1172
1173 return 0;
1174}
1175
6c956392 1176static struct bpf_object *bpf_object__new(const char *path,
5e61f270 1177 const void *obj_buf,
2ce8450e
AN
1178 size_t obj_buf_sz,
1179 const char *obj_name)
1a5e3fb1 1180{
689624f0 1181 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
1a5e3fb1 1182 struct bpf_object *obj;
d859900c 1183 char *end;
1a5e3fb1
WN
1184
1185 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1186 if (!obj) {
be18010e 1187 pr_warn("alloc memory failed for %s\n", path);
6371ca3b 1188 return ERR_PTR(-ENOMEM);
1a5e3fb1
WN
1189 }
1190
1191 strcpy(obj->path, path);
2ce8450e 1192 if (obj_name) {
9fc205b4 1193 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
2ce8450e
AN
1194 } else {
1195 /* Using basename() GNU version which doesn't modify arg. */
9fc205b4 1196 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
2ce8450e
AN
1197 end = strchr(obj->name, '.');
1198 if (end)
1199 *end = 0;
1200 }
6c956392 1201
d859900c 1202 obj->efile.fd = -1;
6c956392 1203 /*
76e1022b 1204 * Caller of this function should also call
6c956392
WN
1205 * bpf_object__elf_finish() after data collection to return
1206 * obj_buf to user. If not, we should duplicate the buffer to
1207 * avoid user freeing them before elf finish.
1208 */
1209 obj->efile.obj_buf = obj_buf;
1210 obj->efile.obj_buf_sz = obj_buf_sz;
666810e8 1211 obj->efile.maps_shndx = -1;
abd29c93 1212 obj->efile.btf_maps_shndx = -1;
590a0088 1213 obj->efile.st_ops_shndx = -1;
81bfdd08 1214 obj->kconfig_map_idx = -1;
6c956392 1215
5e61f270 1216 obj->kern_version = get_kernel_version();
52d3352e 1217 obj->loaded = false;
9a208eff
WN
1218
1219 INIT_LIST_HEAD(&obj->list);
689624f0
JB
1220 if (!strict)
1221 list_add(&obj->list, &bpf_objects_list);
1a5e3fb1
WN
1222 return obj;
1223}
1224
1225static void bpf_object__elf_finish(struct bpf_object *obj)
1226{
29a30ff5 1227 if (!obj->efile.elf)
1a5e3fb1
WN
1228 return;
1229
1230 if (obj->efile.elf) {
1231 elf_end(obj->efile.elf);
1232 obj->efile.elf = NULL;
1233 }
bec7d68c 1234 obj->efile.symbols = NULL;
590a0088 1235 obj->efile.st_ops_data = NULL;
b62f06e8 1236
25bbbd7a
AN
1237 zfree(&obj->efile.secs);
1238 obj->efile.sec_cnt = 0;
1a5e3fb1 1239 zclose(obj->efile.fd);
6c956392
WN
1240 obj->efile.obj_buf = NULL;
1241 obj->efile.obj_buf_sz = 0;
1a5e3fb1
WN
1242}
1243
1244static int bpf_object__elf_init(struct bpf_object *obj)
1245{
ad23b723 1246 Elf64_Ehdr *ehdr;
1a5e3fb1 1247 int err = 0;
ad23b723 1248 Elf *elf;
1a5e3fb1 1249
29a30ff5 1250 if (obj->efile.elf) {
88a82120 1251 pr_warn("elf: init internal error\n");
6371ca3b 1252 return -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1253 }
1254
6c956392
WN
1255 if (obj->efile.obj_buf_sz > 0) {
1256 /*
1257 * obj_buf should have been validated by
1258 * bpf_object__open_buffer().
1259 */
ad23b723 1260 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
6c956392 1261 } else {
92274e24 1262 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
6c956392 1263 if (obj->efile.fd < 0) {
be5c5d4e 1264 char errmsg[STRERR_BUFSIZE], *cp;
1ce6a9fc 1265
be5c5d4e
AN
1266 err = -errno;
1267 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
88a82120 1268 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
be5c5d4e 1269 return err;
6c956392
WN
1270 }
1271
ad23b723 1272 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1a5e3fb1
WN
1273 }
1274
ad23b723 1275 if (!elf) {
88a82120 1276 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1277 err = -LIBBPF_ERRNO__LIBELF;
1a5e3fb1
WN
1278 goto errout;
1279 }
1280
ad23b723
AN
1281 obj->efile.elf = elf;
1282
1283 if (elf_kind(elf) != ELF_K_ELF) {
1284 err = -LIBBPF_ERRNO__FORMAT;
1285 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1286 goto errout;
1287 }
1288
1289 if (gelf_getclass(elf) != ELFCLASS64) {
1290 err = -LIBBPF_ERRNO__FORMAT;
1291 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1292 goto errout;
1293 }
1294
1295 obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1296 if (!obj->efile.ehdr) {
88a82120 1297 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
6371ca3b 1298 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1299 goto errout;
1300 }
1a5e3fb1 1301
ad23b723 1302 if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
88a82120
AN
1303 pr_warn("elf: failed to get section names section index for %s: %s\n",
1304 obj->path, elf_errmsg(-1));
1305 err = -LIBBPF_ERRNO__FORMAT;
1306 goto errout;
1307 }
1308
1309 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
ad23b723 1310 if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
88a82120
AN
1311 pr_warn("elf: failed to get section names strings from %s: %s\n",
1312 obj->path, elf_errmsg(-1));
8f3f5792
NK
1313 err = -LIBBPF_ERRNO__FORMAT;
1314 goto errout;
88a82120
AN
1315 }
1316
9b16137a 1317 /* Old LLVM set e_machine to EM_NONE */
ad23b723 1318 if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
88a82120 1319 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
6371ca3b 1320 err = -LIBBPF_ERRNO__FORMAT;
1a5e3fb1
WN
1321 goto errout;
1322 }
1323
1324 return 0;
1325errout:
1326 bpf_object__elf_finish(obj);
1327 return err;
1328}
1329
12ef5634 1330static int bpf_object__check_endianness(struct bpf_object *obj)
cc4228d5 1331{
3930198d 1332#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
ad23b723 1333 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
12ef5634 1334 return 0;
3930198d 1335#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
ad23b723 1336 if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
12ef5634
AN
1337 return 0;
1338#else
1339# error "Unrecognized __BYTE_ORDER__"
1340#endif
88a82120 1341 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
6371ca3b 1342 return -LIBBPF_ERRNO__ENDIAN;
cc4228d5
WN
1343}
1344
cb1e5e96 1345static int
399dc65e 1346bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
cb1e5e96 1347{
f9798239
AN
1348 /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1349 * go over allowed ELF data section buffer
1350 */
1351 libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
cb1e5e96
WN
1352 pr_debug("license of %s is %s\n", obj->path, obj->license);
1353 return 0;
1354}
1355
54b8625c
JF
1356static int
1357bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1358{
1359 __u32 kver;
1360
1361 if (size != sizeof(kver)) {
be18010e 1362 pr_warn("invalid kver section in %s\n", obj->path);
54b8625c
JF
1363 return -LIBBPF_ERRNO__FORMAT;
1364 }
1365 memcpy(&kver, data, sizeof(kver));
1366 obj->kern_version = kver;
1367 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1368 return 0;
1369}
1370
addb9fc9
NS
1371static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1372{
1373 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1374 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1375 return true;
1376 return false;
1377}
1378
b96c07f3 1379static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1713d68b
DB
1380{
1381 int ret = -ENOENT;
25bbbd7a
AN
1382 Elf_Data *data;
1383 Elf_Scn *scn;
1713d68b
DB
1384
1385 *size = 0;
25bbbd7a 1386 if (!name)
1713d68b 1387 return -EINVAL;
88a82120 1388
25bbbd7a
AN
1389 scn = elf_sec_by_name(obj, name);
1390 data = elf_sec_data(obj, scn);
1391 if (data) {
1392 ret = 0; /* found it */
1393 *size = data->d_size;
1713d68b
DB
1394 }
1395
1396 return *size ? 0 : ret;
1397}
1398
b96c07f3 1399static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1713d68b
DB
1400{
1401 Elf_Data *symbols = obj->efile.symbols;
1402 const char *sname;
1403 size_t si;
1404
1405 if (!name || !off)
1406 return -EINVAL;
1407
ad23b723
AN
1408 for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1409 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1713d68b 1410
ad23b723
AN
1411 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL ||
1412 ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1713d68b
DB
1413 continue;
1414
ad23b723 1415 sname = elf_sym_str(obj, sym->st_name);
1713d68b 1416 if (!sname) {
ad23b723 1417 pr_warn("failed to get sym name string for var %s\n", name);
1713d68b
DB
1418 return -EIO;
1419 }
1420 if (strcmp(name, sname) == 0) {
ad23b723 1421 *off = sym->st_value;
1713d68b
DB
1422 return 0;
1423 }
1424 }
1425
1426 return -ENOENT;
1427}
1428
bf829271 1429static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
d859900c 1430{
bf829271
AN
1431 struct bpf_map *new_maps;
1432 size_t new_cap;
1433 int i;
1434
1435 if (obj->nr_maps < obj->maps_cap)
1436 return &obj->maps[obj->nr_maps++];
1437
95064979 1438 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
029258d7 1439 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
bf829271 1440 if (!new_maps) {
be18010e 1441 pr_warn("alloc maps for object failed\n");
bf829271
AN
1442 return ERR_PTR(-ENOMEM);
1443 }
1444
1445 obj->maps_cap = new_cap;
1446 obj->maps = new_maps;
1447
1448 /* zero out new maps */
1449 memset(obj->maps + obj->nr_maps, 0,
1450 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1451 /*
1452 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1453 * when failure (zclose won't close negative fd)).
1454 */
1455 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1456 obj->maps[i].fd = -1;
1457 obj->maps[i].inner_map_fd = -1;
1458 }
1459
1460 return &obj->maps[obj->nr_maps++];
d859900c
DB
1461}
1462
eba9c5f4
AN
1463static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1464{
1465 long page_sz = sysconf(_SC_PAGE_SIZE);
1466 size_t map_sz;
1467
c701917e 1468 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
eba9c5f4
AN
1469 map_sz = roundup(map_sz, page_sz);
1470 return map_sz;
1471}
1472
aed65917 1473static char *internal_map_name(struct bpf_object *obj, const char *real_name)
81bfdd08 1474{
113e6b7e 1475 char map_name[BPF_OBJ_NAME_LEN], *p;
aed65917
AN
1476 int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1477
1478 /* This is one of the more confusing parts of libbpf for various
1479 * reasons, some of which are historical. The original idea for naming
1480 * internal names was to include as much of BPF object name prefix as
1481 * possible, so that it can be distinguished from similar internal
1482 * maps of a different BPF object.
1483 * As an example, let's say we have bpf_object named 'my_object_name'
1484 * and internal map corresponding to '.rodata' ELF section. The final
1485 * map name advertised to user and to the kernel will be
1486 * 'my_objec.rodata', taking first 8 characters of object name and
1487 * entire 7 characters of '.rodata'.
1488 * Somewhat confusingly, if internal map ELF section name is shorter
1489 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1490 * for the suffix, even though we only have 4 actual characters, and
1491 * resulting map will be called 'my_objec.bss', not even using all 15
1492 * characters allowed by the kernel. Oh well, at least the truncated
1493 * object name is somewhat consistent in this case. But if the map
1494 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1495 * (8 chars) and thus will be left with only first 7 characters of the
1496 * object name ('my_obje'). Happy guessing, user, that the final map
1497 * name will be "my_obje.kconfig".
1498 * Now, with libbpf starting to support arbitrarily named .rodata.*
1499 * and .data.* data sections, it's possible that ELF section name is
1500 * longer than allowed 15 chars, so we now need to be careful to take
1501 * only up to 15 first characters of ELF name, taking no BPF object
1502 * name characters at all. So '.rodata.abracadabra' will result in
1503 * '.rodata.abracad' kernel and user-visible name.
1504 * We need to keep this convoluted logic intact for .data, .bss and
1505 * .rodata maps, but for new custom .data.custom and .rodata.custom
1506 * maps we use their ELF names as is, not prepending bpf_object name
1507 * in front. We still need to truncate them to 15 characters for the
1508 * kernel. Full name can be recovered for such maps by using DATASEC
1509 * BTF type associated with such map's value type, though.
1510 */
1511 if (sfx_len >= BPF_OBJ_NAME_LEN)
1512 sfx_len = BPF_OBJ_NAME_LEN - 1;
1513
1514 /* if there are two or more dots in map name, it's a custom dot map */
1515 if (strchr(real_name + 1, '.') != NULL)
1516 pfx_len = 0;
1517 else
1518 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
81bfdd08
AN
1519
1520 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
aed65917 1521 sfx_len, real_name);
81bfdd08 1522
113e6b7e
THJ
1523 /* sanitise map name to characters allowed by kernel */
1524 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1525 if (!isalnum(*p) && *p != '_' && *p != '.')
1526 *p = '_';
1527
81bfdd08
AN
1528 return strdup(map_name);
1529}
1530
d859900c 1531static int
bf829271 1532bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
aed65917 1533 const char *real_name, int sec_idx, void *data, size_t data_sz)
d859900c 1534{
bf829271
AN
1535 struct bpf_map_def *def;
1536 struct bpf_map *map;
eba9c5f4 1537 int err;
bf829271
AN
1538
1539 map = bpf_object__add_map(obj);
1540 if (IS_ERR(map))
1541 return PTR_ERR(map);
d859900c
DB
1542
1543 map->libbpf_type = type;
db48814b
AN
1544 map->sec_idx = sec_idx;
1545 map->sec_offset = 0;
aed65917
AN
1546 map->real_name = strdup(real_name);
1547 map->name = internal_map_name(obj, real_name);
1548 if (!map->real_name || !map->name) {
1549 zfree(&map->real_name);
1550 zfree(&map->name);
d859900c
DB
1551 return -ENOMEM;
1552 }
1553
bf829271 1554 def = &map->def;
d859900c
DB
1555 def->type = BPF_MAP_TYPE_ARRAY;
1556 def->key_size = sizeof(int);
eba9c5f4 1557 def->value_size = data_sz;
d859900c 1558 def->max_entries = 1;
81bfdd08 1559 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
166750bc 1560 ? BPF_F_RDONLY_PROG : 0;
0d13bfce 1561 def->map_flags |= BPF_F_MMAPABLE;
7fe74b43
AN
1562
1563 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
81bfdd08 1564 map->name, map->sec_idx, map->sec_offset, def->map_flags);
7fe74b43 1565
eba9c5f4
AN
1566 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1567 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1568 if (map->mmaped == MAP_FAILED) {
1569 err = -errno;
1570 map->mmaped = NULL;
1571 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1572 map->name, err);
aed65917 1573 zfree(&map->real_name);
eba9c5f4
AN
1574 zfree(&map->name);
1575 return err;
d859900c
DB
1576 }
1577
166750bc 1578 if (data)
eba9c5f4
AN
1579 memcpy(map->mmaped, data, data_sz);
1580
e1d1dc46 1581 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
d859900c
DB
1582 return 0;
1583}
1584
bf829271
AN
1585static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1586{
25bbbd7a 1587 struct elf_sec_desc *sec_desc;
aed65917 1588 const char *sec_name;
25bbbd7a 1589 int err = 0, sec_idx;
bf829271 1590
bf829271
AN
1591 /*
1592 * Populate obj->maps with libbpf internal maps.
1593 */
25bbbd7a
AN
1594 for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1595 sec_desc = &obj->efile.secs[sec_idx];
1596
1597 switch (sec_desc->sec_type) {
1598 case SEC_DATA:
aed65917 1599 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1600 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
aed65917 1601 sec_name, sec_idx,
25bbbd7a
AN
1602 sec_desc->data->d_buf,
1603 sec_desc->data->d_size);
1604 break;
1605 case SEC_RODATA:
1606 obj->has_rodata = true;
aed65917 1607 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1608 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
aed65917 1609 sec_name, sec_idx,
25bbbd7a
AN
1610 sec_desc->data->d_buf,
1611 sec_desc->data->d_size);
1612 break;
1613 case SEC_BSS:
aed65917 1614 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
25bbbd7a 1615 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
aed65917 1616 sec_name, sec_idx,
25bbbd7a
AN
1617 NULL,
1618 sec_desc->data->d_size);
1619 break;
1620 default:
1621 /* skip */
1622 break;
1623 }
bf829271
AN
1624 if (err)
1625 return err;
1626 }
1627 return 0;
1628}
1629
166750bc
AN
1630
1631static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1632 const void *name)
1633{
1634 int i;
1635
1636 for (i = 0; i < obj->nr_extern; i++) {
1637 if (strcmp(obj->externs[i].name, name) == 0)
1638 return &obj->externs[i];
1639 }
1640 return NULL;
1641}
1642
2e33efe3
AN
1643static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1644 char value)
166750bc 1645{
2e33efe3
AN
1646 switch (ext->kcfg.type) {
1647 case KCFG_BOOL:
166750bc 1648 if (value == 'm') {
2e33efe3 1649 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
166750bc
AN
1650 ext->name, value);
1651 return -EINVAL;
1652 }
1653 *(bool *)ext_val = value == 'y' ? true : false;
1654 break;
2e33efe3 1655 case KCFG_TRISTATE:
166750bc
AN
1656 if (value == 'y')
1657 *(enum libbpf_tristate *)ext_val = TRI_YES;
1658 else if (value == 'm')
1659 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1660 else /* value == 'n' */
1661 *(enum libbpf_tristate *)ext_val = TRI_NO;
1662 break;
2e33efe3 1663 case KCFG_CHAR:
166750bc
AN
1664 *(char *)ext_val = value;
1665 break;
2e33efe3
AN
1666 case KCFG_UNKNOWN:
1667 case KCFG_INT:
1668 case KCFG_CHAR_ARR:
166750bc 1669 default:
2e33efe3 1670 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
166750bc
AN
1671 ext->name, value);
1672 return -EINVAL;
1673 }
1674 ext->is_set = true;
1675 return 0;
1676}
1677
2e33efe3
AN
1678static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1679 const char *value)
166750bc
AN
1680{
1681 size_t len;
1682
2e33efe3
AN
1683 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1684 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
166750bc
AN
1685 return -EINVAL;
1686 }
1687
1688 len = strlen(value);
1689 if (value[len - 1] != '"') {
2e33efe3 1690 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
166750bc
AN
1691 ext->name, value);
1692 return -EINVAL;
1693 }
1694
1695 /* strip quotes */
1696 len -= 2;
2e33efe3
AN
1697 if (len >= ext->kcfg.sz) {
1698 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1699 ext->name, value, len, ext->kcfg.sz - 1);
1700 len = ext->kcfg.sz - 1;
166750bc
AN
1701 }
1702 memcpy(ext_val, value + 1, len);
1703 ext_val[len] = '\0';
1704 ext->is_set = true;
1705 return 0;
1706}
1707
1708static int parse_u64(const char *value, __u64 *res)
1709{
1710 char *value_end;
1711 int err;
1712
1713 errno = 0;
1714 *res = strtoull(value, &value_end, 0);
1715 if (errno) {
1716 err = -errno;
1717 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1718 return err;
1719 }
1720 if (*value_end) {
1721 pr_warn("failed to parse '%s' as integer completely\n", value);
1722 return -EINVAL;
1723 }
1724 return 0;
1725}
1726
2e33efe3 1727static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
166750bc 1728{
2e33efe3 1729 int bit_sz = ext->kcfg.sz * 8;
166750bc 1730
2e33efe3 1731 if (ext->kcfg.sz == 8)
166750bc
AN
1732 return true;
1733
1734 /* Validate that value stored in u64 fits in integer of `ext->sz`
1735 * bytes size without any loss of information. If the target integer
1736 * is signed, we rely on the following limits of integer type of
1737 * Y bits and subsequent transformation:
1738 *
1739 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1740 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1741 * 0 <= X + 2^(Y-1) < 2^Y
1742 *
1743 * For unsigned target integer, check that all the (64 - Y) bits are
1744 * zero.
1745 */
2e33efe3 1746 if (ext->kcfg.is_signed)
166750bc
AN
1747 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1748 else
1749 return (v >> bit_sz) == 0;
1750}
1751
2e33efe3
AN
1752static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1753 __u64 value)
166750bc 1754{
2e33efe3
AN
1755 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1756 pr_warn("extern (kcfg) %s=%llu should be integer\n",
7745ff98 1757 ext->name, (unsigned long long)value);
166750bc
AN
1758 return -EINVAL;
1759 }
2e33efe3
AN
1760 if (!is_kcfg_value_in_range(ext, value)) {
1761 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1762 ext->name, (unsigned long long)value, ext->kcfg.sz);
166750bc
AN
1763 return -ERANGE;
1764 }
2e33efe3 1765 switch (ext->kcfg.sz) {
166750bc
AN
1766 case 1: *(__u8 *)ext_val = value; break;
1767 case 2: *(__u16 *)ext_val = value; break;
1768 case 4: *(__u32 *)ext_val = value; break;
1769 case 8: *(__u64 *)ext_val = value; break;
1770 default:
1771 return -EINVAL;
1772 }
1773 ext->is_set = true;
1774 return 0;
1775}
1776
8601fd42
AN
1777static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1778 char *buf, void *data)
166750bc 1779{
166750bc 1780 struct extern_desc *ext;
8601fd42 1781 char *sep, *value;
166750bc
AN
1782 int len, err = 0;
1783 void *ext_val;
1784 __u64 num;
166750bc 1785
13d35a0c 1786 if (!str_has_pfx(buf, "CONFIG_"))
8601fd42 1787 return 0;
166750bc 1788
8601fd42
AN
1789 sep = strchr(buf, '=');
1790 if (!sep) {
1791 pr_warn("failed to parse '%s': no separator\n", buf);
1792 return -EINVAL;
1793 }
1794
1795 /* Trim ending '\n' */
1796 len = strlen(buf);
1797 if (buf[len - 1] == '\n')
1798 buf[len - 1] = '\0';
1799 /* Split on '=' and ensure that a value is present. */
1800 *sep = '\0';
1801 if (!sep[1]) {
1802 *sep = '=';
1803 pr_warn("failed to parse '%s': no value\n", buf);
1804 return -EINVAL;
1805 }
1806
1807 ext = find_extern_by_name(obj, buf);
1808 if (!ext || ext->is_set)
1809 return 0;
1810
2e33efe3 1811 ext_val = data + ext->kcfg.data_off;
8601fd42
AN
1812 value = sep + 1;
1813
1814 switch (*value) {
1815 case 'y': case 'n': case 'm':
2e33efe3 1816 err = set_kcfg_value_tri(ext, ext_val, *value);
8601fd42
AN
1817 break;
1818 case '"':
2e33efe3 1819 err = set_kcfg_value_str(ext, ext_val, value);
8601fd42
AN
1820 break;
1821 default:
1822 /* assume integer */
1823 err = parse_u64(value, &num);
1824 if (err) {
2e33efe3 1825 pr_warn("extern (kcfg) %s=%s should be integer\n",
8601fd42
AN
1826 ext->name, value);
1827 return err;
1828 }
2e33efe3 1829 err = set_kcfg_value_num(ext, ext_val, num);
8601fd42 1830 break;
166750bc 1831 }
8601fd42
AN
1832 if (err)
1833 return err;
2e33efe3 1834 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
8601fd42
AN
1835 return 0;
1836}
1837
1838static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1839{
1840 char buf[PATH_MAX];
1841 struct utsname uts;
1842 int len, err = 0;
1843 gzFile file;
1844
1845 uname(&uts);
1846 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1847 if (len < 0)
1848 return -EINVAL;
1849 else if (len >= PATH_MAX)
1850 return -ENAMETOOLONG;
1851
1852 /* gzopen also accepts uncompressed files. */
1853 file = gzopen(buf, "r");
1854 if (!file)
1855 file = gzopen("/proc/config.gz", "r");
1856
166750bc 1857 if (!file) {
8601fd42 1858 pr_warn("failed to open system Kconfig\n");
166750bc
AN
1859 return -ENOENT;
1860 }
1861
1862 while (gzgets(file, buf, sizeof(buf))) {
8601fd42
AN
1863 err = bpf_object__process_kconfig_line(obj, buf, data);
1864 if (err) {
1865 pr_warn("error parsing system Kconfig line '%s': %d\n",
1866 buf, err);
166750bc
AN
1867 goto out;
1868 }
8601fd42 1869 }
166750bc 1870
8601fd42
AN
1871out:
1872 gzclose(file);
1873 return err;
1874}
166750bc 1875
8601fd42
AN
1876static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1877 const char *config, void *data)
1878{
1879 char buf[PATH_MAX];
1880 int err = 0;
1881 FILE *file;
166750bc 1882
8601fd42
AN
1883 file = fmemopen((void *)config, strlen(config), "r");
1884 if (!file) {
1885 err = -errno;
1886 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1887 return err;
1888 }
1889
1890 while (fgets(buf, sizeof(buf), file)) {
1891 err = bpf_object__process_kconfig_line(obj, buf, data);
1892 if (err) {
1893 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1894 buf, err);
166750bc
AN
1895 break;
1896 }
166750bc
AN
1897 }
1898
8601fd42 1899 fclose(file);
166750bc
AN
1900 return err;
1901}
1902
81bfdd08 1903static int bpf_object__init_kconfig_map(struct bpf_object *obj)
166750bc 1904{
2e33efe3 1905 struct extern_desc *last_ext = NULL, *ext;
166750bc 1906 size_t map_sz;
2e33efe3 1907 int i, err;
166750bc 1908
2e33efe3
AN
1909 for (i = 0; i < obj->nr_extern; i++) {
1910 ext = &obj->externs[i];
1911 if (ext->type == EXT_KCFG)
1912 last_ext = ext;
1913 }
166750bc 1914
2e33efe3
AN
1915 if (!last_ext)
1916 return 0;
166750bc 1917
2e33efe3 1918 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
81bfdd08 1919 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
aed65917 1920 ".kconfig", obj->efile.symbols_shndx,
166750bc
AN
1921 NULL, map_sz);
1922 if (err)
1923 return err;
1924
81bfdd08 1925 obj->kconfig_map_idx = obj->nr_maps - 1;
166750bc
AN
1926
1927 return 0;
1928}
1929
bf829271 1930static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
561bbcca 1931{
561bbcca 1932 Elf_Data *symbols = obj->efile.symbols;
bf829271 1933 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
d859900c 1934 Elf_Data *data = NULL;
bf829271
AN
1935 Elf_Scn *scn;
1936
1937 if (obj->efile.maps_shndx < 0)
1938 return 0;
561bbcca 1939
93b8952d
AN
1940 if (libbpf_mode & LIBBPF_STRICT_MAP_DEFINITIONS) {
1941 pr_warn("legacy map definitions in SEC(\"maps\") are not supported\n");
1942 return -EOPNOTSUPP;
1943 }
1944
4708bbda
EL
1945 if (!symbols)
1946 return -EINVAL;
1947
88a82120
AN
1948 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1949 data = elf_sec_data(obj, scn);
bf829271 1950 if (!scn || !data) {
88a82120
AN
1951 pr_warn("elf: failed to get legacy map definitions for %s\n",
1952 obj->path);
bf829271 1953 return -EINVAL;
4708bbda 1954 }
561bbcca 1955
4708bbda
EL
1956 /*
1957 * Count number of maps. Each map has a name.
1958 * Array of maps is not supported: only the first element is
1959 * considered.
1960 *
1961 * TODO: Detect array of map and report error.
1962 */
ad23b723 1963 nr_syms = symbols->d_size / sizeof(Elf64_Sym);
bf829271 1964 for (i = 0; i < nr_syms; i++) {
ad23b723 1965 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4708bbda 1966
ad23b723 1967 if (sym->st_shndx != obj->efile.maps_shndx)
4708bbda 1968 continue;
ad23b723 1969 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
161ecd53 1970 continue;
4708bbda
EL
1971 nr_maps++;
1972 }
b13c5c14 1973 /* Assume equally sized map definitions */
88a82120
AN
1974 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1975 nr_maps, data->d_size, obj->path);
bf829271 1976
98e527af 1977 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
88a82120
AN
1978 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1979 obj->path);
bf829271 1980 return -EINVAL;
addb9fc9 1981 }
98e527af 1982 map_def_sz = data->d_size / nr_maps;
4708bbda 1983
bf829271
AN
1984 /* Fill obj->maps using data in "maps" section. */
1985 for (i = 0; i < nr_syms; i++) {
ad23b723 1986 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
561bbcca 1987 const char *map_name;
4708bbda 1988 struct bpf_map_def *def;
bf829271 1989 struct bpf_map *map;
561bbcca 1990
ad23b723 1991 if (sym->st_shndx != obj->efile.maps_shndx)
561bbcca 1992 continue;
ad23b723 1993 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION)
c3e8c44a 1994 continue;
561bbcca 1995
bf829271
AN
1996 map = bpf_object__add_map(obj);
1997 if (IS_ERR(map))
1998 return PTR_ERR(map);
1999
ad23b723 2000 map_name = elf_sym_str(obj, sym->st_name);
c51829bb 2001 if (!map_name) {
be18010e
KW
2002 pr_warn("failed to get map #%d name sym string for obj %s\n",
2003 i, obj->path);
c51829bb
AN
2004 return -LIBBPF_ERRNO__FORMAT;
2005 }
d859900c 2006
93b8952d
AN
2007 pr_warn("map '%s' (legacy): legacy map definitions are deprecated, use BTF-defined maps instead\n", map_name);
2008
ad23b723 2009 if (ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
c1cccec9
AN
2010 pr_warn("map '%s' (legacy): static maps are not supported\n", map_name);
2011 return -ENOTSUP;
2012 }
2013
bf829271 2014 map->libbpf_type = LIBBPF_MAP_UNSPEC;
ad23b723
AN
2015 map->sec_idx = sym->st_shndx;
2016 map->sec_offset = sym->st_value;
db48814b
AN
2017 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
2018 map_name, map->sec_idx, map->sec_offset);
ad23b723 2019 if (sym->st_value + map_def_sz > data->d_size) {
be18010e
KW
2020 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
2021 obj->path, map_name);
4708bbda 2022 return -EINVAL;
561bbcca 2023 }
4708bbda 2024
bf829271
AN
2025 map->name = strdup(map_name);
2026 if (!map->name) {
aed65917 2027 pr_warn("map '%s': failed to alloc map name\n", map_name);
973170e6
WN
2028 return -ENOMEM;
2029 }
bf829271 2030 pr_debug("map %d is \"%s\"\n", i, map->name);
ad23b723 2031 def = (struct bpf_map_def *)(data->d_buf + sym->st_value);
b13c5c14
CG
2032 /*
2033 * If the definition of the map in the object file fits in
2034 * bpf_map_def, copy it. Any extra fields in our version
2035 * of bpf_map_def will default to zero as a result of the
2036 * calloc above.
2037 */
2038 if (map_def_sz <= sizeof(struct bpf_map_def)) {
bf829271 2039 memcpy(&map->def, def, map_def_sz);
b13c5c14
CG
2040 } else {
2041 /*
2042 * Here the map structure being read is bigger than what
2043 * we expect, truncate if the excess bits are all zero.
2044 * If they are not zero, reject this map as
2045 * incompatible.
2046 */
2047 char *b;
8983b731 2048
b13c5c14
CG
2049 for (b = ((char *)def) + sizeof(struct bpf_map_def);
2050 b < ((char *)def) + map_def_sz; b++) {
2051 if (*b != 0) {
8983b731 2052 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
be18010e 2053 obj->path, map_name);
c034a177
JF
2054 if (strict)
2055 return -EINVAL;
b13c5c14
CG
2056 }
2057 }
bf829271 2058 memcpy(&map->def, def, sizeof(struct bpf_map_def));
b13c5c14 2059 }
561bbcca 2060 }
bf829271
AN
2061 return 0;
2062}
4708bbda 2063
42869d28 2064const struct btf_type *
ddc7c304 2065skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
abd29c93
AN
2066{
2067 const struct btf_type *t = btf__type_by_id(btf, id);
8837fe5d 2068
ddc7c304
AN
2069 if (res_id)
2070 *res_id = id;
2071
2072 while (btf_is_mod(t) || btf_is_typedef(t)) {
2073 if (res_id)
2074 *res_id = t->type;
2075 t = btf__type_by_id(btf, t->type);
abd29c93 2076 }
ddc7c304
AN
2077
2078 return t;
abd29c93
AN
2079}
2080
590a0088
MKL
2081static const struct btf_type *
2082resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2083{
2084 const struct btf_type *t;
2085
2086 t = skip_mods_and_typedefs(btf, id, NULL);
2087 if (!btf_is_ptr(t))
2088 return NULL;
2089
2090 t = skip_mods_and_typedefs(btf, t->type, res_id);
2091
2092 return btf_is_func_proto(t) ? t : NULL;
2093}
2094
774e132e 2095static const char *__btf_kind_str(__u16 kind)
81ba0889 2096{
774e132e 2097 switch (kind) {
81ba0889
AN
2098 case BTF_KIND_UNKN: return "void";
2099 case BTF_KIND_INT: return "int";
2100 case BTF_KIND_PTR: return "ptr";
2101 case BTF_KIND_ARRAY: return "array";
2102 case BTF_KIND_STRUCT: return "struct";
2103 case BTF_KIND_UNION: return "union";
2104 case BTF_KIND_ENUM: return "enum";
2105 case BTF_KIND_FWD: return "fwd";
2106 case BTF_KIND_TYPEDEF: return "typedef";
2107 case BTF_KIND_VOLATILE: return "volatile";
2108 case BTF_KIND_CONST: return "const";
2109 case BTF_KIND_RESTRICT: return "restrict";
2110 case BTF_KIND_FUNC: return "func";
2111 case BTF_KIND_FUNC_PROTO: return "func_proto";
2112 case BTF_KIND_VAR: return "var";
2113 case BTF_KIND_DATASEC: return "datasec";
22541a9e 2114 case BTF_KIND_FLOAT: return "float";
223f903e 2115 case BTF_KIND_DECL_TAG: return "decl_tag";
2dc1e488 2116 case BTF_KIND_TYPE_TAG: return "type_tag";
81ba0889
AN
2117 default: return "unknown";
2118 }
2119}
2120
42869d28 2121const char *btf_kind_str(const struct btf_type *t)
774e132e
MKL
2122{
2123 return __btf_kind_str(btf_kind(t));
2124}
2125
ef99b02b
AN
2126/*
2127 * Fetch integer attribute of BTF map definition. Such attributes are
2128 * represented using a pointer to an array, in which dimensionality of array
2129 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2130 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2131 * type definition, while using only sizeof(void *) space in ELF data section.
2132 */
2133static bool get_map_field_int(const char *map_name, const struct btf *btf,
8983b731
AN
2134 const struct btf_member *m, __u32 *res)
2135{
ddc7c304 2136 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
abd29c93 2137 const char *name = btf__name_by_offset(btf, m->name_off);
ef99b02b
AN
2138 const struct btf_array *arr_info;
2139 const struct btf_type *arr_t;
abd29c93 2140
b03bc685 2141 if (!btf_is_ptr(t)) {
81ba0889
AN
2142 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2143 map_name, name, btf_kind_str(t));
abd29c93
AN
2144 return false;
2145 }
ef99b02b
AN
2146
2147 arr_t = btf__type_by_id(btf, t->type);
2148 if (!arr_t) {
be18010e
KW
2149 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2150 map_name, name, t->type);
abd29c93
AN
2151 return false;
2152 }
b03bc685 2153 if (!btf_is_array(arr_t)) {
81ba0889
AN
2154 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2155 map_name, name, btf_kind_str(arr_t));
abd29c93
AN
2156 return false;
2157 }
b03bc685 2158 arr_info = btf_array(arr_t);
ef99b02b 2159 *res = arr_info->nelems;
abd29c93
AN
2160 return true;
2161}
2162
57a00f41
THJ
2163static int build_map_pin_path(struct bpf_map *map, const char *path)
2164{
2165 char buf[PATH_MAX];
6e9cab2e 2166 int len;
57a00f41
THJ
2167
2168 if (!path)
2169 path = "/sys/fs/bpf";
2170
2171 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2172 if (len < 0)
2173 return -EINVAL;
2174 else if (len >= PATH_MAX)
2175 return -ENAMETOOLONG;
2176
6e9cab2e 2177 return bpf_map__set_pin_path(map, buf);
57a00f41
THJ
2178}
2179
c7ef5ec9
AN
2180int parse_btf_map_def(const char *map_name, struct btf *btf,
2181 const struct btf_type *def_t, bool strict,
2182 struct btf_map_def *map_def, struct btf_map_def *inner_def)
abd29c93 2183{
41017e56 2184 const struct btf_type *t;
abd29c93 2185 const struct btf_member *m;
c7ef5ec9 2186 bool is_inner = inner_def == NULL;
abd29c93
AN
2187 int vlen, i;
2188
c7ef5ec9
AN
2189 vlen = btf_vlen(def_t);
2190 m = btf_members(def_t);
abd29c93 2191 for (i = 0; i < vlen; i++, m++) {
c7ef5ec9 2192 const char *name = btf__name_by_offset(btf, m->name_off);
abd29c93
AN
2193
2194 if (!name) {
c7ef5ec9 2195 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
abd29c93
AN
2196 return -EINVAL;
2197 }
2198 if (strcmp(name, "type") == 0) {
c7ef5ec9 2199 if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
abd29c93 2200 return -EINVAL;
c7ef5ec9 2201 map_def->parts |= MAP_DEF_MAP_TYPE;
abd29c93 2202 } else if (strcmp(name, "max_entries") == 0) {
c7ef5ec9 2203 if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
abd29c93 2204 return -EINVAL;
c7ef5ec9 2205 map_def->parts |= MAP_DEF_MAX_ENTRIES;
abd29c93 2206 } else if (strcmp(name, "map_flags") == 0) {
c7ef5ec9 2207 if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
abd29c93 2208 return -EINVAL;
c7ef5ec9 2209 map_def->parts |= MAP_DEF_MAP_FLAGS;
1bdb6c9a 2210 } else if (strcmp(name, "numa_node") == 0) {
c7ef5ec9 2211 if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
1bdb6c9a 2212 return -EINVAL;
c7ef5ec9 2213 map_def->parts |= MAP_DEF_NUMA_NODE;
abd29c93
AN
2214 } else if (strcmp(name, "key_size") == 0) {
2215 __u32 sz;
2216
c7ef5ec9 2217 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2218 return -EINVAL;
c7ef5ec9 2219 if (map_def->key_size && map_def->key_size != sz) {
be18010e 2220 pr_warn("map '%s': conflicting key size %u != %u.\n",
c7ef5ec9 2221 map_name, map_def->key_size, sz);
abd29c93
AN
2222 return -EINVAL;
2223 }
c7ef5ec9
AN
2224 map_def->key_size = sz;
2225 map_def->parts |= MAP_DEF_KEY_SIZE;
abd29c93
AN
2226 } else if (strcmp(name, "key") == 0) {
2227 __s64 sz;
2228
c7ef5ec9 2229 t = btf__type_by_id(btf, m->type);
abd29c93 2230 if (!t) {
be18010e 2231 pr_warn("map '%s': key type [%d] not found.\n",
c7ef5ec9 2232 map_name, m->type);
abd29c93
AN
2233 return -EINVAL;
2234 }
b03bc685 2235 if (!btf_is_ptr(t)) {
81ba0889 2236 pr_warn("map '%s': key spec is not PTR: %s.\n",
c7ef5ec9 2237 map_name, btf_kind_str(t));
abd29c93
AN
2238 return -EINVAL;
2239 }
c7ef5ec9 2240 sz = btf__resolve_size(btf, t->type);
abd29c93 2241 if (sz < 0) {
679152d3 2242 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
c7ef5ec9 2243 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2244 return sz;
2245 }
c7ef5ec9 2246 if (map_def->key_size && map_def->key_size != sz) {
679152d3 2247 pr_warn("map '%s': conflicting key size %u != %zd.\n",
c7ef5ec9 2248 map_name, map_def->key_size, (ssize_t)sz);
abd29c93
AN
2249 return -EINVAL;
2250 }
c7ef5ec9
AN
2251 map_def->key_size = sz;
2252 map_def->key_type_id = t->type;
2253 map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
abd29c93
AN
2254 } else if (strcmp(name, "value_size") == 0) {
2255 __u32 sz;
2256
c7ef5ec9 2257 if (!get_map_field_int(map_name, btf, m, &sz))
abd29c93 2258 return -EINVAL;
c7ef5ec9 2259 if (map_def->value_size && map_def->value_size != sz) {
be18010e 2260 pr_warn("map '%s': conflicting value size %u != %u.\n",
c7ef5ec9 2261 map_name, map_def->value_size, sz);
abd29c93
AN
2262 return -EINVAL;
2263 }
c7ef5ec9
AN
2264 map_def->value_size = sz;
2265 map_def->parts |= MAP_DEF_VALUE_SIZE;
abd29c93
AN
2266 } else if (strcmp(name, "value") == 0) {
2267 __s64 sz;
2268
c7ef5ec9 2269 t = btf__type_by_id(btf, m->type);
abd29c93 2270 if (!t) {
be18010e 2271 pr_warn("map '%s': value type [%d] not found.\n",
c7ef5ec9 2272 map_name, m->type);
abd29c93
AN
2273 return -EINVAL;
2274 }
b03bc685 2275 if (!btf_is_ptr(t)) {
81ba0889 2276 pr_warn("map '%s': value spec is not PTR: %s.\n",
c7ef5ec9 2277 map_name, btf_kind_str(t));
abd29c93
AN
2278 return -EINVAL;
2279 }
c7ef5ec9 2280 sz = btf__resolve_size(btf, t->type);
abd29c93 2281 if (sz < 0) {
679152d3 2282 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
c7ef5ec9 2283 map_name, t->type, (ssize_t)sz);
abd29c93
AN
2284 return sz;
2285 }
c7ef5ec9 2286 if (map_def->value_size && map_def->value_size != sz) {
679152d3 2287 pr_warn("map '%s': conflicting value size %u != %zd.\n",
c7ef5ec9 2288 map_name, map_def->value_size, (ssize_t)sz);
abd29c93
AN
2289 return -EINVAL;
2290 }
c7ef5ec9
AN
2291 map_def->value_size = sz;
2292 map_def->value_type_id = t->type;
2293 map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
646f02ff
AN
2294 }
2295 else if (strcmp(name, "values") == 0) {
341ac5ff
HC
2296 bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2297 bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2298 const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
c7ef5ec9 2299 char inner_map_name[128];
646f02ff
AN
2300 int err;
2301
2302 if (is_inner) {
2303 pr_warn("map '%s': multi-level inner maps not supported.\n",
c7ef5ec9 2304 map_name);
646f02ff
AN
2305 return -ENOTSUP;
2306 }
2307 if (i != vlen - 1) {
2308 pr_warn("map '%s': '%s' member should be last.\n",
c7ef5ec9 2309 map_name, name);
646f02ff
AN
2310 return -EINVAL;
2311 }
341ac5ff
HC
2312 if (!is_map_in_map && !is_prog_array) {
2313 pr_warn("map '%s': should be map-in-map or prog-array.\n",
c7ef5ec9 2314 map_name);
646f02ff
AN
2315 return -ENOTSUP;
2316 }
c7ef5ec9 2317 if (map_def->value_size && map_def->value_size != 4) {
646f02ff 2318 pr_warn("map '%s': conflicting value size %u != 4.\n",
c7ef5ec9 2319 map_name, map_def->value_size);
646f02ff
AN
2320 return -EINVAL;
2321 }
c7ef5ec9
AN
2322 map_def->value_size = 4;
2323 t = btf__type_by_id(btf, m->type);
646f02ff 2324 if (!t) {
341ac5ff
HC
2325 pr_warn("map '%s': %s type [%d] not found.\n",
2326 map_name, desc, m->type);
646f02ff
AN
2327 return -EINVAL;
2328 }
2329 if (!btf_is_array(t) || btf_array(t)->nelems) {
341ac5ff
HC
2330 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2331 map_name, desc);
646f02ff
AN
2332 return -EINVAL;
2333 }
c7ef5ec9 2334 t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
646f02ff 2335 if (!btf_is_ptr(t)) {
341ac5ff
HC
2336 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2337 map_name, desc, btf_kind_str(t));
646f02ff
AN
2338 return -EINVAL;
2339 }
c7ef5ec9 2340 t = skip_mods_and_typedefs(btf, t->type, NULL);
341ac5ff
HC
2341 if (is_prog_array) {
2342 if (!btf_is_func_proto(t)) {
2343 pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2344 map_name, btf_kind_str(t));
2345 return -EINVAL;
2346 }
2347 continue;
2348 }
646f02ff 2349 if (!btf_is_struct(t)) {
81ba0889 2350 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
c7ef5ec9 2351 map_name, btf_kind_str(t));
646f02ff
AN
2352 return -EINVAL;
2353 }
2354
c7ef5ec9
AN
2355 snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2356 err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
646f02ff
AN
2357 if (err)
2358 return err;
c7ef5ec9
AN
2359
2360 map_def->parts |= MAP_DEF_INNER_MAP;
57a00f41
THJ
2361 } else if (strcmp(name, "pinning") == 0) {
2362 __u32 val;
57a00f41 2363
646f02ff 2364 if (is_inner) {
c7ef5ec9 2365 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
646f02ff
AN
2366 return -EINVAL;
2367 }
c7ef5ec9 2368 if (!get_map_field_int(map_name, btf, m, &val))
57a00f41 2369 return -EINVAL;
c7ef5ec9 2370 if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
57a00f41 2371 pr_warn("map '%s': invalid pinning value %u.\n",
c7ef5ec9 2372 map_name, val);
57a00f41
THJ
2373 return -EINVAL;
2374 }
c7ef5ec9
AN
2375 map_def->pinning = val;
2376 map_def->parts |= MAP_DEF_PINNING;
47512102
JK
2377 } else if (strcmp(name, "map_extra") == 0) {
2378 __u32 map_extra;
2379
2380 if (!get_map_field_int(map_name, btf, m, &map_extra))
2381 return -EINVAL;
2382 map_def->map_extra = map_extra;
2383 map_def->parts |= MAP_DEF_MAP_EXTRA;
abd29c93
AN
2384 } else {
2385 if (strict) {
c7ef5ec9 2386 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
abd29c93
AN
2387 return -ENOTSUP;
2388 }
c7ef5ec9 2389 pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
abd29c93
AN
2390 }
2391 }
2392
c7ef5ec9
AN
2393 if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2394 pr_warn("map '%s': map type isn't specified.\n", map_name);
abd29c93
AN
2395 return -EINVAL;
2396 }
2397
2398 return 0;
2399}
2400
c7ef5ec9
AN
2401static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2402{
2403 map->def.type = def->map_type;
2404 map->def.key_size = def->key_size;
2405 map->def.value_size = def->value_size;
2406 map->def.max_entries = def->max_entries;
2407 map->def.map_flags = def->map_flags;
47512102 2408 map->map_extra = def->map_extra;
c7ef5ec9
AN
2409
2410 map->numa_node = def->numa_node;
2411 map->btf_key_type_id = def->key_type_id;
2412 map->btf_value_type_id = def->value_type_id;
2413
2414 if (def->parts & MAP_DEF_MAP_TYPE)
2415 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2416
2417 if (def->parts & MAP_DEF_KEY_TYPE)
2418 pr_debug("map '%s': found key [%u], sz = %u.\n",
2419 map->name, def->key_type_id, def->key_size);
2420 else if (def->parts & MAP_DEF_KEY_SIZE)
2421 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2422
2423 if (def->parts & MAP_DEF_VALUE_TYPE)
2424 pr_debug("map '%s': found value [%u], sz = %u.\n",
2425 map->name, def->value_type_id, def->value_size);
2426 else if (def->parts & MAP_DEF_VALUE_SIZE)
2427 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2428
2429 if (def->parts & MAP_DEF_MAX_ENTRIES)
2430 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2431 if (def->parts & MAP_DEF_MAP_FLAGS)
47512102
JK
2432 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2433 if (def->parts & MAP_DEF_MAP_EXTRA)
2434 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2435 (unsigned long long)def->map_extra);
c7ef5ec9
AN
2436 if (def->parts & MAP_DEF_PINNING)
2437 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2438 if (def->parts & MAP_DEF_NUMA_NODE)
2439 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2440
2441 if (def->parts & MAP_DEF_INNER_MAP)
2442 pr_debug("map '%s': found inner map definition.\n", map->name);
2443}
2444
c1cccec9
AN
2445static const char *btf_var_linkage_str(__u32 linkage)
2446{
2447 switch (linkage) {
2448 case BTF_VAR_STATIC: return "static";
2449 case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2450 case BTF_VAR_GLOBAL_EXTERN: return "extern";
2451 default: return "unknown";
2452 }
2453}
2454
41017e56
AN
2455static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2456 const struct btf_type *sec,
2457 int var_idx, int sec_idx,
2458 const Elf_Data *data, bool strict,
2459 const char *pin_root_path)
2460{
c7ef5ec9 2461 struct btf_map_def map_def = {}, inner_def = {};
41017e56
AN
2462 const struct btf_type *var, *def;
2463 const struct btf_var_secinfo *vi;
2464 const struct btf_var *var_extra;
2465 const char *map_name;
2466 struct bpf_map *map;
c7ef5ec9 2467 int err;
41017e56
AN
2468
2469 vi = btf_var_secinfos(sec) + var_idx;
2470 var = btf__type_by_id(obj->btf, vi->type);
2471 var_extra = btf_var(var);
2472 map_name = btf__name_by_offset(obj->btf, var->name_off);
2473
2474 if (map_name == NULL || map_name[0] == '\0') {
2475 pr_warn("map #%d: empty name.\n", var_idx);
2476 return -EINVAL;
2477 }
2478 if ((__u64)vi->offset + vi->size > data->d_size) {
2479 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2480 return -EINVAL;
2481 }
2482 if (!btf_is_var(var)) {
81ba0889
AN
2483 pr_warn("map '%s': unexpected var kind %s.\n",
2484 map_name, btf_kind_str(var));
41017e56
AN
2485 return -EINVAL;
2486 }
c1cccec9
AN
2487 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2488 pr_warn("map '%s': unsupported map linkage %s.\n",
2489 map_name, btf_var_linkage_str(var_extra->linkage));
41017e56
AN
2490 return -EOPNOTSUPP;
2491 }
2492
2493 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2494 if (!btf_is_struct(def)) {
81ba0889
AN
2495 pr_warn("map '%s': unexpected def kind %s.\n",
2496 map_name, btf_kind_str(var));
41017e56
AN
2497 return -EINVAL;
2498 }
2499 if (def->size > vi->size) {
2500 pr_warn("map '%s': invalid def size.\n", map_name);
2501 return -EINVAL;
2502 }
2503
2504 map = bpf_object__add_map(obj);
2505 if (IS_ERR(map))
2506 return PTR_ERR(map);
2507 map->name = strdup(map_name);
2508 if (!map->name) {
2509 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2510 return -ENOMEM;
2511 }
2512 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2513 map->def.type = BPF_MAP_TYPE_UNSPEC;
2514 map->sec_idx = sec_idx;
2515 map->sec_offset = vi->offset;
646f02ff 2516 map->btf_var_idx = var_idx;
41017e56
AN
2517 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2518 map_name, map->sec_idx, map->sec_offset);
2519
c7ef5ec9
AN
2520 err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2521 if (err)
2522 return err;
2523
2524 fill_map_from_def(map, &map_def);
2525
2526 if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2527 err = build_map_pin_path(map, pin_root_path);
2528 if (err) {
2529 pr_warn("map '%s': couldn't build pin path.\n", map->name);
2530 return err;
2531 }
2532 }
2533
2534 if (map_def.parts & MAP_DEF_INNER_MAP) {
2535 map->inner_map = calloc(1, sizeof(*map->inner_map));
2536 if (!map->inner_map)
2537 return -ENOMEM;
2538 map->inner_map->fd = -1;
2539 map->inner_map->sec_idx = sec_idx;
2540 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2541 if (!map->inner_map->name)
2542 return -ENOMEM;
2543 sprintf(map->inner_map->name, "%s.inner", map_name);
2544
2545 fill_map_from_def(map->inner_map, &inner_def);
2546 }
2547
2548 return 0;
41017e56
AN
2549}
2550
57a00f41
THJ
2551static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2552 const char *pin_root_path)
abd29c93
AN
2553{
2554 const struct btf_type *sec = NULL;
2555 int nr_types, i, vlen, err;
2556 const struct btf_type *t;
2557 const char *name;
2558 Elf_Data *data;
2559 Elf_Scn *scn;
2560
2561 if (obj->efile.btf_maps_shndx < 0)
2562 return 0;
2563
88a82120
AN
2564 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2565 data = elf_sec_data(obj, scn);
abd29c93 2566 if (!scn || !data) {
88a82120
AN
2567 pr_warn("elf: failed to get %s map definitions for %s\n",
2568 MAPS_ELF_SEC, obj->path);
abd29c93
AN
2569 return -EINVAL;
2570 }
2571
6a886de0
HC
2572 nr_types = btf__type_cnt(obj->btf);
2573 for (i = 1; i < nr_types; i++) {
abd29c93 2574 t = btf__type_by_id(obj->btf, i);
b03bc685 2575 if (!btf_is_datasec(t))
abd29c93
AN
2576 continue;
2577 name = btf__name_by_offset(obj->btf, t->name_off);
2578 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2579 sec = t;
646f02ff 2580 obj->efile.btf_maps_sec_btf_id = i;
abd29c93
AN
2581 break;
2582 }
2583 }
2584
2585 if (!sec) {
be18010e 2586 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
abd29c93
AN
2587 return -ENOENT;
2588 }
2589
b03bc685 2590 vlen = btf_vlen(sec);
abd29c93
AN
2591 for (i = 0; i < vlen; i++) {
2592 err = bpf_object__init_user_btf_map(obj, sec, i,
2593 obj->efile.btf_maps_shndx,
8983b731
AN
2594 data, strict,
2595 pin_root_path);
abd29c93
AN
2596 if (err)
2597 return err;
2598 }
2599
2600 return 0;
2601}
2602
0d13bfce 2603static int bpf_object__init_maps(struct bpf_object *obj,
01af3bf0 2604 const struct bpf_object_open_opts *opts)
bf829271 2605{
166750bc
AN
2606 const char *pin_root_path;
2607 bool strict;
bf829271 2608 int err;
8837fe5d 2609
166750bc
AN
2610 strict = !OPTS_GET(opts, relaxed_maps, false);
2611 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
bf829271 2612
166750bc
AN
2613 err = bpf_object__init_user_maps(obj, strict);
2614 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2615 err = err ?: bpf_object__init_global_data_maps(obj);
81bfdd08 2616 err = err ?: bpf_object__init_kconfig_map(obj);
590a0088 2617 err = err ?: bpf_object__init_struct_ops_maps(obj);
bf829271 2618
3b3af91c 2619 return err;
561bbcca
WN
2620}
2621
e3d91b0c
JDB
2622static bool section_have_execinstr(struct bpf_object *obj, int idx)
2623{
ad23b723 2624 Elf64_Shdr *sh;
e3d91b0c 2625
ad23b723
AN
2626 sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2627 if (!sh)
e3d91b0c
JDB
2628 return false;
2629
ad23b723 2630 return sh->sh_flags & SHF_EXECINSTR;
e3d91b0c
JDB
2631}
2632
0f0e55d8
AN
2633static bool btf_needs_sanitization(struct bpf_object *obj)
2634{
9ca1f56a
AS
2635 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2636 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2637 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2638 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2639 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2640 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
0f0e55d8 2641
2dc1e488
YS
2642 return !has_func || !has_datasec || !has_func_global || !has_float ||
2643 !has_decl_tag || !has_type_tag;
0f0e55d8
AN
2644}
2645
2646static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
d7c4b398 2647{
9ca1f56a
AS
2648 bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2649 bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2650 bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2651 bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
223f903e 2652 bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2dc1e488 2653 bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
d7c4b398
AN
2654 struct btf_type *t;
2655 int i, j, vlen;
d7c4b398 2656
6a886de0 2657 for (i = 1; i < btf__type_cnt(btf); i++) {
d7c4b398 2658 t = (struct btf_type *)btf__type_by_id(btf, i);
d7c4b398 2659
223f903e
YS
2660 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2661 /* replace VAR/DECL_TAG with INT */
d7c4b398 2662 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
1d4126c4
AN
2663 /*
2664 * using size = 1 is the safest choice, 4 will be too
2665 * big and cause kernel BTF validation failure if
2666 * original variable took less than 4 bytes
2667 */
2668 t->size = 1;
708852dc 2669 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
b03bc685 2670 } else if (!has_datasec && btf_is_datasec(t)) {
d7c4b398 2671 /* replace DATASEC with STRUCT */
b03bc685
AN
2672 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2673 struct btf_member *m = btf_members(t);
d7c4b398
AN
2674 struct btf_type *vt;
2675 char *name;
2676
2677 name = (char *)btf__name_by_offset(btf, t->name_off);
2678 while (*name) {
2679 if (*name == '.')
2680 *name = '_';
2681 name++;
2682 }
2683
b03bc685 2684 vlen = btf_vlen(t);
d7c4b398
AN
2685 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2686 for (j = 0; j < vlen; j++, v++, m++) {
2687 /* order of field assignments is important */
2688 m->offset = v->offset * 8;
2689 m->type = v->type;
2690 /* preserve variable name as member name */
2691 vt = (void *)btf__type_by_id(btf, v->type);
2692 m->name_off = vt->name_off;
2693 }
b03bc685 2694 } else if (!has_func && btf_is_func_proto(t)) {
d7c4b398 2695 /* replace FUNC_PROTO with ENUM */
b03bc685 2696 vlen = btf_vlen(t);
d7c4b398
AN
2697 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2698 t->size = sizeof(__u32); /* kernel enforced */
b03bc685 2699 } else if (!has_func && btf_is_func(t)) {
d7c4b398
AN
2700 /* replace FUNC with TYPEDEF */
2701 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2d3eb67f
AS
2702 } else if (!has_func_global && btf_is_func(t)) {
2703 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2704 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
22541a9e
IL
2705 } else if (!has_float && btf_is_float(t)) {
2706 /* replace FLOAT with an equally-sized empty STRUCT;
2707 * since C compilers do not accept e.g. "float" as a
2708 * valid struct name, make it anonymous
2709 */
2710 t->name_off = 0;
2711 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2dc1e488
YS
2712 } else if (!has_type_tag && btf_is_type_tag(t)) {
2713 /* replace TYPE_TAG with a CONST */
2714 t->name_off = 0;
2715 t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
d7c4b398
AN
2716 }
2717 }
2718}
2719
b35f14f4 2720static bool libbpf_needs_btf(const struct bpf_object *obj)
abd29c93 2721{
b35f14f4
AN
2722 return obj->efile.btf_maps_shndx >= 0 ||
2723 obj->efile.st_ops_shndx >= 0 ||
2724 obj->nr_extern > 0;
2725}
2726
2727static bool kernel_needs_btf(const struct bpf_object *obj)
2728{
2729 return obj->efile.st_ops_shndx >= 0;
abd29c93
AN
2730}
2731
063183bf 2732static int bpf_object__init_btf(struct bpf_object *obj,
9c6660d0
AN
2733 Elf_Data *btf_data,
2734 Elf_Data *btf_ext_data)
2735{
b7d7f3e1 2736 int err = -ENOENT;
9c6660d0
AN
2737
2738 if (btf_data) {
2739 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
e9fc3ce9
AN
2740 err = libbpf_get_error(obj->btf);
2741 if (err) {
b7d7f3e1 2742 obj->btf = NULL;
e9fc3ce9 2743 pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
9c6660d0
AN
2744 goto out;
2745 }
4c01925f
AN
2746 /* enforce 8-byte pointers for BPF-targeted BTFs */
2747 btf__set_pointer_size(obj->btf, 8);
9c6660d0
AN
2748 }
2749 if (btf_ext_data) {
2750 if (!obj->btf) {
2751 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2752 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2753 goto out;
2754 }
e9fc3ce9
AN
2755 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2756 err = libbpf_get_error(obj->btf_ext);
2757 if (err) {
2758 pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2759 BTF_EXT_ELF_SEC, err);
9c6660d0
AN
2760 obj->btf_ext = NULL;
2761 goto out;
2762 }
9c6660d0
AN
2763 }
2764out:
b35f14f4 2765 if (err && libbpf_needs_btf(obj)) {
be18010e 2766 pr_warn("BTF is required, but is missing or corrupted.\n");
b7d7f3e1 2767 return err;
abd29c93 2768 }
9c6660d0
AN
2769 return 0;
2770}
2771
b96c07f3
AN
2772static int compare_vsi_off(const void *_a, const void *_b)
2773{
2774 const struct btf_var_secinfo *a = _a;
2775 const struct btf_var_secinfo *b = _b;
2776
2777 return a->offset - b->offset;
2778}
2779
2780static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2781 struct btf_type *t)
2782{
2783 __u32 size = 0, off = 0, i, vars = btf_vlen(t);
2784 const char *name = btf__name_by_offset(btf, t->name_off);
2785 const struct btf_type *t_var;
2786 struct btf_var_secinfo *vsi;
2787 const struct btf_var *var;
2788 int ret;
2789
2790 if (!name) {
2791 pr_debug("No name found in string section for DATASEC kind.\n");
2792 return -ENOENT;
2793 }
2794
2795 /* .extern datasec size and var offsets were set correctly during
2796 * extern collection step, so just skip straight to sorting variables
2797 */
2798 if (t->size)
2799 goto sort_vars;
2800
2801 ret = find_elf_sec_sz(obj, name, &size);
2802 if (ret || !size || (t->size && t->size != size)) {
2803 pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2804 return -ENOENT;
2805 }
2806
2807 t->size = size;
2808
2809 for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2810 t_var = btf__type_by_id(btf, vsi->type);
88918dc1 2811 if (!t_var || !btf_is_var(t_var)) {
b96c07f3
AN
2812 pr_debug("Non-VAR type seen in section %s\n", name);
2813 return -EINVAL;
2814 }
2815
88918dc1 2816 var = btf_var(t_var);
b96c07f3
AN
2817 if (var->linkage == BTF_VAR_STATIC)
2818 continue;
2819
2820 name = btf__name_by_offset(btf, t_var->name_off);
2821 if (!name) {
2822 pr_debug("No name found in string section for VAR kind\n");
2823 return -ENOENT;
2824 }
2825
2826 ret = find_elf_var_offset(obj, name, &off);
2827 if (ret) {
2828 pr_debug("No offset found in symbol table for VAR %s\n",
2829 name);
2830 return -ENOENT;
2831 }
2832
2833 vsi->offset = off;
2834 }
2835
2836sort_vars:
2837 qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2838 return 0;
2839}
2840
2841static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2842{
2843 int err = 0;
6a886de0 2844 __u32 i, n = btf__type_cnt(btf);
b96c07f3 2845
6a886de0 2846 for (i = 1; i < n; i++) {
b96c07f3
AN
2847 struct btf_type *t = btf_type_by_id(btf, i);
2848
2849 /* Loader needs to fix up some of the things compiler
2850 * couldn't get its hands on while emitting BTF. This
2851 * is section size and global variable offset. We use
2852 * the info from the ELF itself for this purpose.
2853 */
2854 if (btf_is_datasec(t)) {
2855 err = btf_fixup_datasec(obj, btf, t);
2856 if (err)
2857 break;
2858 }
2859 }
2860
2861 return libbpf_err(err);
2862}
2863
2864int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
2865{
2866 return btf_finalize_data(obj, btf);
2867}
2868
166750bc
AN
2869static int bpf_object__finalize_btf(struct bpf_object *obj)
2870{
2871 int err;
2872
2873 if (!obj->btf)
2874 return 0;
2875
b96c07f3 2876 err = btf_finalize_data(obj, obj->btf);
bfc96656
AN
2877 if (err) {
2878 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2879 return err;
166750bc 2880 }
bfc96656 2881
166750bc
AN
2882 return 0;
2883}
2884
fe62de31 2885static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
a6ed02ca 2886{
1e092a03
KS
2887 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2888 prog->type == BPF_PROG_TYPE_LSM)
a6ed02ca
KS
2889 return true;
2890
2891 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2892 * also need vmlinux BTF
2893 */
2894 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2895 return true;
2896
2897 return false;
2898}
2899
fe62de31 2900static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
a6ed02ca
KS
2901{
2902 struct bpf_program *prog;
fe62de31 2903 int i;
a6ed02ca 2904
1373ff59
SC
2905 /* CO-RE relocations need kernel BTF, only when btf_custom_path
2906 * is not specified
2907 */
2908 if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
fe62de31 2909 return true;
192b6638 2910
d370bbe1
HL
2911 /* Support for typed ksyms needs kernel BTF */
2912 for (i = 0; i < obj->nr_extern; i++) {
2913 const struct extern_desc *ext;
2914
2915 ext = &obj->externs[i];
fe62de31
AN
2916 if (ext->type == EXT_KSYM && ext->ksym.type_id)
2917 return true;
d370bbe1
HL
2918 }
2919
a6ed02ca 2920 bpf_object__for_each_program(prog, obj) {
d9297581
AN
2921 if (!prog->load)
2922 continue;
fe62de31
AN
2923 if (prog_needs_vmlinux_btf(prog))
2924 return true;
a6ed02ca
KS
2925 }
2926
fe62de31
AN
2927 return false;
2928}
2929
2930static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2931{
2932 int err;
2933
2934 /* btf_vmlinux could be loaded earlier */
67234743 2935 if (obj->btf_vmlinux || obj->gen_loader)
fe62de31
AN
2936 return 0;
2937
2938 if (!force && !obj_needs_vmlinux_btf(obj))
192b6638
AN
2939 return 0;
2940
a710eed3 2941 obj->btf_vmlinux = btf__load_vmlinux_btf();
e9fc3ce9
AN
2942 err = libbpf_get_error(obj->btf_vmlinux);
2943 if (err) {
192b6638
AN
2944 pr_warn("Error loading vmlinux BTF: %d\n", err);
2945 obj->btf_vmlinux = NULL;
2946 return err;
2947 }
a6ed02ca
KS
2948 return 0;
2949}
2950
063183bf
AN
2951static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2952{
0f0e55d8
AN
2953 struct btf *kern_btf = obj->btf;
2954 bool btf_mandatory, sanitize;
aea28a60 2955 int i, err = 0;
063183bf
AN
2956
2957 if (!obj->btf)
2958 return 0;
2959
9ca1f56a 2960 if (!kernel_supports(obj, FEAT_BTF)) {
68b08647
AN
2961 if (kernel_needs_btf(obj)) {
2962 err = -EOPNOTSUPP;
2963 goto report;
2964 }
2965 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2966 return 0;
2967 }
2968
aea28a60
AN
2969 /* Even though some subprogs are global/weak, user might prefer more
2970 * permissive BPF verification process that BPF verifier performs for
2971 * static functions, taking into account more context from the caller
2972 * functions. In such case, they need to mark such subprogs with
2973 * __attribute__((visibility("hidden"))) and libbpf will adjust
2974 * corresponding FUNC BTF type to be marked as static and trigger more
2975 * involved BPF verification process.
2976 */
2977 for (i = 0; i < obj->nr_programs; i++) {
2978 struct bpf_program *prog = &obj->programs[i];
2979 struct btf_type *t;
2980 const char *name;
2981 int j, n;
2982
2983 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
2984 continue;
2985
6a886de0
HC
2986 n = btf__type_cnt(obj->btf);
2987 for (j = 1; j < n; j++) {
aea28a60
AN
2988 t = btf_type_by_id(obj->btf, j);
2989 if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
2990 continue;
2991
2992 name = btf__str_by_offset(obj->btf, t->name_off);
2993 if (strcmp(name, prog->name) != 0)
2994 continue;
2995
2996 t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
2997 break;
2998 }
2999 }
3000
0f0e55d8
AN
3001 sanitize = btf_needs_sanitization(obj);
3002 if (sanitize) {
5c3320d7 3003 const void *raw_data;
0f0e55d8 3004 __u32 sz;
063183bf 3005
0f0e55d8 3006 /* clone BTF to sanitize a copy and leave the original intact */
6a886de0 3007 raw_data = btf__raw_data(obj->btf, &sz);
5c3320d7 3008 kern_btf = btf__new(raw_data, sz);
e9fc3ce9
AN
3009 err = libbpf_get_error(kern_btf);
3010 if (err)
3011 return err;
04efe591 3012
4c01925f
AN
3013 /* enforce 8-byte pointers for BPF-targeted BTFs */
3014 btf__set_pointer_size(obj->btf, 8);
0f0e55d8 3015 bpf_object__sanitize_btf(obj, kern_btf);
063183bf 3016 }
0f0e55d8 3017
67234743
AS
3018 if (obj->gen_loader) {
3019 __u32 raw_size = 0;
6a886de0 3020 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
67234743
AS
3021
3022 if (!raw_data)
3023 return -ENOMEM;
3024 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3025 /* Pretend to have valid FD to pass various fd >= 0 checks.
3026 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3027 */
3028 btf__set_fd(kern_btf, 0);
3029 } else {
e0e3ea88
AN
3030 /* currently BPF_BTF_LOAD only supports log_level 1 */
3031 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3032 obj->log_level ? 1 : 0);
67234743 3033 }
0f0e55d8
AN
3034 if (sanitize) {
3035 if (!err) {
3036 /* move fd to libbpf's BTF */
3037 btf__set_fd(obj->btf, btf__fd(kern_btf));
3038 btf__set_fd(kern_btf, -1);
3039 }
3040 btf__free(kern_btf);
3041 }
68b08647 3042report:
0f0e55d8
AN
3043 if (err) {
3044 btf_mandatory = kernel_needs_btf(obj);
3045 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3046 btf_mandatory ? "BTF is mandatory, can't proceed."
3047 : "BTF is optional, ignoring.");
3048 if (!btf_mandatory)
3049 err = 0;
3050 }
3051 return err;
063183bf
AN
3052}
3053
88a82120
AN
3054static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3055{
3056 const char *name;
3057
3058 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3059 if (!name) {
3060 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3061 off, obj->path, elf_errmsg(-1));
3062 return NULL;
3063 }
3064
3065 return name;
3066}
3067
3068static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3069{
3070 const char *name;
3071
3072 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3073 if (!name) {
3074 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3075 off, obj->path, elf_errmsg(-1));
3076 return NULL;
3077 }
3078
3079 return name;
3080}
3081
3082static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3083{
3084 Elf_Scn *scn;
3085
3086 scn = elf_getscn(obj->efile.elf, idx);
3087 if (!scn) {
3088 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3089 idx, obj->path, elf_errmsg(-1));
3090 return NULL;
3091 }
3092 return scn;
3093}
3094
3095static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3096{
3097 Elf_Scn *scn = NULL;
3098 Elf *elf = obj->efile.elf;
3099 const char *sec_name;
3100
3101 while ((scn = elf_nextscn(elf, scn)) != NULL) {
3102 sec_name = elf_sec_name(obj, scn);
3103 if (!sec_name)
3104 return NULL;
3105
3106 if (strcmp(sec_name, name) != 0)
3107 continue;
3108
3109 return scn;
3110 }
3111 return NULL;
3112}
3113
ad23b723 3114static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
88a82120 3115{
ad23b723
AN
3116 Elf64_Shdr *shdr;
3117
88a82120 3118 if (!scn)
ad23b723 3119 return NULL;
88a82120 3120
ad23b723
AN
3121 shdr = elf64_getshdr(scn);
3122 if (!shdr) {
88a82120
AN
3123 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3124 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
ad23b723 3125 return NULL;
88a82120
AN
3126 }
3127
ad23b723 3128 return shdr;
88a82120
AN
3129}
3130
3131static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3132{
3133 const char *name;
ad23b723 3134 Elf64_Shdr *sh;
88a82120
AN
3135
3136 if (!scn)
3137 return NULL;
3138
ad23b723
AN
3139 sh = elf_sec_hdr(obj, scn);
3140 if (!sh)
88a82120
AN
3141 return NULL;
3142
ad23b723 3143 name = elf_sec_str(obj, sh->sh_name);
88a82120
AN
3144 if (!name) {
3145 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3146 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3147 return NULL;
3148 }
3149
3150 return name;
3151}
3152
3153static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3154{
3155 Elf_Data *data;
3156
3157 if (!scn)
3158 return NULL;
3159
3160 data = elf_getdata(scn, 0);
3161 if (!data) {
3162 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3163 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3164 obj->path, elf_errmsg(-1));
3165 return NULL;
3166 }
3167
3168 return data;
3169}
3170
ad23b723
AN
3171static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3172{
3173 if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3174 return NULL;
3175
3176 return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3177}
3178
3179static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3180{
3181 if (idx >= data->d_size / sizeof(Elf64_Rel))
3182 return NULL;
3183
3184 return (Elf64_Rel *)data->d_buf + idx;
3185}
3186
50e09460
AN
3187static bool is_sec_name_dwarf(const char *name)
3188{
3189 /* approximation, but the actual list is too long */
13d35a0c 3190 return str_has_pfx(name, ".debug_");
50e09460
AN
3191}
3192
ad23b723 3193static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
50e09460
AN
3194{
3195 /* no special handling of .strtab */
3196 if (hdr->sh_type == SHT_STRTAB)
3197 return true;
3198
3199 /* ignore .llvm_addrsig section as well */
faf6ed32 3200 if (hdr->sh_type == SHT_LLVM_ADDRSIG)
50e09460
AN
3201 return true;
3202
3203 /* no subprograms will lead to an empty .text section, ignore it */
3204 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3205 strcmp(name, ".text") == 0)
3206 return true;
3207
3208 /* DWARF sections */
3209 if (is_sec_name_dwarf(name))
3210 return true;
3211
13d35a0c 3212 if (str_has_pfx(name, ".rel")) {
50e09460
AN
3213 name += sizeof(".rel") - 1;
3214 /* DWARF section relocations */
3215 if (is_sec_name_dwarf(name))
3216 return true;
3217
3218 /* .BTF and .BTF.ext don't need relocations */
3219 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3220 strcmp(name, BTF_EXT_ELF_SEC) == 0)
3221 return true;
3222 }
3223
3224 return false;
3225}
3226
db2b8b06
AN
3227static int cmp_progs(const void *_a, const void *_b)
3228{
3229 const struct bpf_program *a = _a;
3230 const struct bpf_program *b = _b;
3231
3232 if (a->sec_idx != b->sec_idx)
3233 return a->sec_idx < b->sec_idx ? -1 : 1;
3234
3235 /* sec_insn_off can't be the same within the section */
3236 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3237}
3238
0d13bfce 3239static int bpf_object__elf_collect(struct bpf_object *obj)
29603665 3240{
25bbbd7a 3241 struct elf_sec_desc *sec_desc;
29603665 3242 Elf *elf = obj->efile.elf;
f0187f0b 3243 Elf_Data *btf_ext_data = NULL;
1713d68b 3244 Elf_Data *btf_data = NULL;
666810e8 3245 int idx = 0, err = 0;
0201c575
AN
3246 const char *name;
3247 Elf_Data *data;
3248 Elf_Scn *scn;
ad23b723 3249 Elf64_Shdr *sh;
29603665 3250
0d6988e1
AN
3251 /* ELF section indices are 0-based, but sec #0 is special "invalid"
3252 * section. e_shnum does include sec #0, so e_shnum is the necessary
3253 * size of an array to keep all the sections.
25bbbd7a 3254 */
0d6988e1 3255 obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
25bbbd7a
AN
3256 obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3257 if (!obj->efile.secs)
3258 return -ENOMEM;
29603665 3259
0201c575
AN
3260 /* a bunch of ELF parsing functionality depends on processing symbols,
3261 * so do the first pass and find the symbol table
3262 */
3263 scn = NULL;
29603665 3264 while ((scn = elf_nextscn(elf, scn)) != NULL) {
ad23b723
AN
3265 sh = elf_sec_hdr(obj, scn);
3266 if (!sh)
0201c575
AN
3267 return -LIBBPF_ERRNO__FORMAT;
3268
ad23b723 3269 if (sh->sh_type == SHT_SYMTAB) {
0201c575
AN
3270 if (obj->efile.symbols) {
3271 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3272 return -LIBBPF_ERRNO__FORMAT;
3273 }
29603665 3274
0201c575
AN
3275 data = elf_sec_data(obj, scn);
3276 if (!data)
3277 return -LIBBPF_ERRNO__FORMAT;
3278
25bbbd7a
AN
3279 idx = elf_ndxscn(scn);
3280
0201c575 3281 obj->efile.symbols = data;
25bbbd7a 3282 obj->efile.symbols_shndx = idx;
ad23b723 3283 obj->efile.strtabidx = sh->sh_link;
0201c575
AN
3284 }
3285 }
3286
03e601f4
THJ
3287 if (!obj->efile.symbols) {
3288 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3289 obj->path);
3290 return -ENOENT;
3291 }
3292
0201c575
AN
3293 scn = NULL;
3294 while ((scn = elf_nextscn(elf, scn)) != NULL) {
25bbbd7a
AN
3295 idx = elf_ndxscn(scn);
3296 sec_desc = &obj->efile.secs[idx];
88a82120 3297
ad23b723
AN
3298 sh = elf_sec_hdr(obj, scn);
3299 if (!sh)
01b29d1d 3300 return -LIBBPF_ERRNO__FORMAT;
29603665 3301
ad23b723 3302 name = elf_sec_str(obj, sh->sh_name);
88a82120 3303 if (!name)
01b29d1d 3304 return -LIBBPF_ERRNO__FORMAT;
29603665 3305
ad23b723 3306 if (ignore_elf_section(sh, name))
50e09460
AN
3307 continue;
3308
88a82120
AN
3309 data = elf_sec_data(obj, scn);
3310 if (!data)
01b29d1d 3311 return -LIBBPF_ERRNO__FORMAT;
88a82120
AN
3312
3313 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
077c066a 3314 idx, name, (unsigned long)data->d_size,
ad23b723
AN
3315 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3316 (int)sh->sh_type);
cb1e5e96 3317
1713d68b 3318 if (strcmp(name, "license") == 0) {
88a82120 3319 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
01b29d1d
AN
3320 if (err)
3321 return err;
1713d68b 3322 } else if (strcmp(name, "version") == 0) {
88a82120 3323 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
54b8625c
JF
3324 if (err)
3325 return err;
1713d68b 3326 } else if (strcmp(name, "maps") == 0) {
666810e8 3327 obj->efile.maps_shndx = idx;
abd29c93
AN
3328 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3329 obj->efile.btf_maps_shndx = idx;
1713d68b 3330 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
62554d52
AN
3331 if (sh->sh_type != SHT_PROGBITS)
3332 return -LIBBPF_ERRNO__FORMAT;
1713d68b 3333 btf_data = data;
2993e051 3334 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
62554d52
AN
3335 if (sh->sh_type != SHT_PROGBITS)
3336 return -LIBBPF_ERRNO__FORMAT;
f0187f0b 3337 btf_ext_data = data;
ad23b723 3338 } else if (sh->sh_type == SHT_SYMTAB) {
0201c575 3339 /* already processed during the first pass above */
ad23b723
AN
3340 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3341 if (sh->sh_flags & SHF_EXECINSTR) {
f8c7a4d4
JS
3342 if (strcmp(name, ".text") == 0)
3343 obj->efile.text_shndx = idx;
c1122392 3344 err = bpf_object__add_programs(obj, data, name, idx);
88a82120 3345 if (err)
01b29d1d 3346 return err;
aed65917
AN
3347 } else if (strcmp(name, DATA_SEC) == 0 ||
3348 str_has_pfx(name, DATA_SEC ".")) {
25bbbd7a
AN
3349 sec_desc->sec_type = SEC_DATA;
3350 sec_desc->shdr = sh;
3351 sec_desc->data = data;
aed65917
AN
3352 } else if (strcmp(name, RODATA_SEC) == 0 ||
3353 str_has_pfx(name, RODATA_SEC ".")) {
25bbbd7a
AN
3354 sec_desc->sec_type = SEC_RODATA;
3355 sec_desc->shdr = sh;
3356 sec_desc->data = data;
590a0088
MKL
3357 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3358 obj->efile.st_ops_data = data;
3359 obj->efile.st_ops_shndx = idx;
d859900c 3360 } else {
50e09460
AN
3361 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3362 idx, name);
a5b8bd47 3363 }
ad23b723 3364 } else if (sh->sh_type == SHT_REL) {
25bbbd7a 3365 int targ_sec_idx = sh->sh_info; /* points to other section */
e3d91b0c 3366
b7332d28
AN
3367 if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3368 targ_sec_idx >= obj->efile.sec_cnt)
3369 return -LIBBPF_ERRNO__FORMAT;
3370
e3d91b0c 3371 /* Only do relo for section with exec instructions */
25bbbd7a 3372 if (!section_have_execinstr(obj, targ_sec_idx) &&
646f02ff
AN
3373 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3374 strcmp(name, ".rel" MAPS_ELF_SEC)) {
50e09460 3375 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
25bbbd7a
AN
3376 idx, name, targ_sec_idx,
3377 elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
e3d91b0c
JDB
3378 continue;
3379 }
b62f06e8 3380
25bbbd7a
AN
3381 sec_desc->sec_type = SEC_RELO;
3382 sec_desc->shdr = sh;
3383 sec_desc->data = data;
ad23b723 3384 } else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
25bbbd7a
AN
3385 sec_desc->sec_type = SEC_BSS;
3386 sec_desc->shdr = sh;
3387 sec_desc->data = data;
077c066a 3388 } else {
2e80be60 3389 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
ad23b723 3390 (size_t)sh->sh_size);
bec7d68c 3391 }
29603665 3392 }
561bbcca 3393
d3a3aa0c 3394 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
88a82120 3395 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
f102154d 3396 return -LIBBPF_ERRNO__FORMAT;
77ba9a5b 3397 }
db2b8b06
AN
3398
3399 /* sort BPF programs by section name and in-section instruction offset
3400 * for faster search */
2a6a9bf2
AN
3401 if (obj->nr_programs)
3402 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
db2b8b06 3403
0d13bfce 3404 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
29603665
WN
3405}
3406
ad23b723 3407static bool sym_is_extern(const Elf64_Sym *sym)
166750bc 3408{
ad23b723 3409 int bind = ELF64_ST_BIND(sym->st_info);
166750bc
AN
3410 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3411 return sym->st_shndx == SHN_UNDEF &&
3412 (bind == STB_GLOBAL || bind == STB_WEAK) &&
ad23b723 3413 ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
166750bc
AN
3414}
3415
ad23b723 3416static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
53eddb5e 3417{
ad23b723
AN
3418 int bind = ELF64_ST_BIND(sym->st_info);
3419 int type = ELF64_ST_TYPE(sym->st_info);
53eddb5e
YS
3420
3421 /* in .text section */
3422 if (sym->st_shndx != text_shndx)
3423 return false;
3424
3425 /* local function */
3426 if (bind == STB_LOCAL && type == STT_SECTION)
3427 return true;
3428
3429 /* global function */
3430 return bind == STB_GLOBAL && type == STT_FUNC;
3431}
3432
166750bc
AN
3433static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3434{
3435 const struct btf_type *t;
5bd022ec 3436 const char *tname;
166750bc
AN
3437 int i, n;
3438
3439 if (!btf)
3440 return -ESRCH;
3441
6a886de0
HC
3442 n = btf__type_cnt(btf);
3443 for (i = 1; i < n; i++) {
166750bc
AN
3444 t = btf__type_by_id(btf, i);
3445
5bd022ec 3446 if (!btf_is_var(t) && !btf_is_func(t))
166750bc
AN
3447 continue;
3448
5bd022ec
MKL
3449 tname = btf__name_by_offset(btf, t->name_off);
3450 if (strcmp(tname, ext_name))
166750bc
AN
3451 continue;
3452
5bd022ec
MKL
3453 if (btf_is_var(t) &&
3454 btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3455 return -EINVAL;
3456
3457 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
166750bc
AN
3458 return -EINVAL;
3459
3460 return i;
3461 }
3462
3463 return -ENOENT;
3464}
3465
2e33efe3
AN
3466static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3467 const struct btf_var_secinfo *vs;
3468 const struct btf_type *t;
3469 int i, j, n;
3470
3471 if (!btf)
3472 return -ESRCH;
3473
6a886de0
HC
3474 n = btf__type_cnt(btf);
3475 for (i = 1; i < n; i++) {
2e33efe3
AN
3476 t = btf__type_by_id(btf, i);
3477
3478 if (!btf_is_datasec(t))
3479 continue;
3480
3481 vs = btf_var_secinfos(t);
3482 for (j = 0; j < btf_vlen(t); j++, vs++) {
3483 if (vs->type == ext_btf_id)
3484 return i;
3485 }
3486 }
3487
3488 return -ENOENT;
3489}
3490
3491static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3492 bool *is_signed)
166750bc
AN
3493{
3494 const struct btf_type *t;
3495 const char *name;
3496
3497 t = skip_mods_and_typedefs(btf, id, NULL);
3498 name = btf__name_by_offset(btf, t->name_off);
3499
3500 if (is_signed)
3501 *is_signed = false;
3502 switch (btf_kind(t)) {
3503 case BTF_KIND_INT: {
3504 int enc = btf_int_encoding(t);
3505
3506 if (enc & BTF_INT_BOOL)
2e33efe3 3507 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
166750bc
AN
3508 if (is_signed)
3509 *is_signed = enc & BTF_INT_SIGNED;
3510 if (t->size == 1)
2e33efe3 3511 return KCFG_CHAR;
166750bc 3512 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2e33efe3
AN
3513 return KCFG_UNKNOWN;
3514 return KCFG_INT;
166750bc
AN
3515 }
3516 case BTF_KIND_ENUM:
3517 if (t->size != 4)
2e33efe3 3518 return KCFG_UNKNOWN;
166750bc 3519 if (strcmp(name, "libbpf_tristate"))
2e33efe3
AN
3520 return KCFG_UNKNOWN;
3521 return KCFG_TRISTATE;
166750bc
AN
3522 case BTF_KIND_ARRAY:
3523 if (btf_array(t)->nelems == 0)
2e33efe3
AN
3524 return KCFG_UNKNOWN;
3525 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3526 return KCFG_UNKNOWN;
3527 return KCFG_CHAR_ARR;
166750bc 3528 default:
2e33efe3 3529 return KCFG_UNKNOWN;
166750bc
AN
3530 }
3531}
3532
3533static int cmp_externs(const void *_a, const void *_b)
3534{
3535 const struct extern_desc *a = _a;
3536 const struct extern_desc *b = _b;
3537
2e33efe3
AN
3538 if (a->type != b->type)
3539 return a->type < b->type ? -1 : 1;
3540
3541 if (a->type == EXT_KCFG) {
3542 /* descending order by alignment requirements */
3543 if (a->kcfg.align != b->kcfg.align)
3544 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3545 /* ascending order by size, within same alignment class */
3546 if (a->kcfg.sz != b->kcfg.sz)
3547 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3548 }
3549
166750bc
AN
3550 /* resolve ties by name */
3551 return strcmp(a->name, b->name);
3552}
3553
1c0c7074
AN
3554static int find_int_btf_id(const struct btf *btf)
3555{
3556 const struct btf_type *t;
3557 int i, n;
3558
6a886de0
HC
3559 n = btf__type_cnt(btf);
3560 for (i = 1; i < n; i++) {
1c0c7074
AN
3561 t = btf__type_by_id(btf, i);
3562
3563 if (btf_is_int(t) && btf_int_bits(t) == 32)
3564 return i;
3565 }
3566
3567 return 0;
3568}
3569
5bd022ec
MKL
3570static int add_dummy_ksym_var(struct btf *btf)
3571{
3572 int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3573 const struct btf_var_secinfo *vs;
3574 const struct btf_type *sec;
3575
9683e577
IR
3576 if (!btf)
3577 return 0;
3578
5bd022ec
MKL
3579 sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3580 BTF_KIND_DATASEC);
3581 if (sec_btf_id < 0)
3582 return 0;
3583
3584 sec = btf__type_by_id(btf, sec_btf_id);
3585 vs = btf_var_secinfos(sec);
3586 for (i = 0; i < btf_vlen(sec); i++, vs++) {
3587 const struct btf_type *vt;
3588
3589 vt = btf__type_by_id(btf, vs->type);
3590 if (btf_is_func(vt))
3591 break;
3592 }
3593
3594 /* No func in ksyms sec. No need to add dummy var. */
3595 if (i == btf_vlen(sec))
3596 return 0;
3597
3598 int_btf_id = find_int_btf_id(btf);
3599 dummy_var_btf_id = btf__add_var(btf,
3600 "dummy_ksym",
3601 BTF_VAR_GLOBAL_ALLOCATED,
3602 int_btf_id);
3603 if (dummy_var_btf_id < 0)
3604 pr_warn("cannot create a dummy_ksym var\n");
3605
3606 return dummy_var_btf_id;
3607}
3608
166750bc
AN
3609static int bpf_object__collect_externs(struct bpf_object *obj)
3610{
1c0c7074 3611 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
166750bc
AN
3612 const struct btf_type *t;
3613 struct extern_desc *ext;
5bd022ec 3614 int i, n, off, dummy_var_btf_id;
2e33efe3 3615 const char *ext_name, *sec_name;
166750bc 3616 Elf_Scn *scn;
ad23b723 3617 Elf64_Shdr *sh;
166750bc
AN
3618
3619 if (!obj->efile.symbols)
3620 return 0;
3621
88a82120 3622 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
ad23b723 3623 sh = elf_sec_hdr(obj, scn);
83390787 3624 if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
166750bc 3625 return -LIBBPF_ERRNO__FORMAT;
166750bc 3626
5bd022ec
MKL
3627 dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3628 if (dummy_var_btf_id < 0)
3629 return dummy_var_btf_id;
3630
ad23b723 3631 n = sh->sh_size / sh->sh_entsize;
166750bc 3632 pr_debug("looking for externs among %d symbols...\n", n);
88a82120 3633
166750bc 3634 for (i = 0; i < n; i++) {
ad23b723 3635 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
166750bc 3636
ad23b723 3637 if (!sym)
166750bc 3638 return -LIBBPF_ERRNO__FORMAT;
ad23b723 3639 if (!sym_is_extern(sym))
166750bc 3640 continue;
ad23b723 3641 ext_name = elf_sym_str(obj, sym->st_name);
166750bc
AN
3642 if (!ext_name || !ext_name[0])
3643 continue;
3644
3645 ext = obj->externs;
029258d7 3646 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
166750bc
AN
3647 if (!ext)
3648 return -ENOMEM;
3649 obj->externs = ext;
3650 ext = &ext[obj->nr_extern];
3651 memset(ext, 0, sizeof(*ext));
3652 obj->nr_extern++;
3653
3654 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3655 if (ext->btf_id <= 0) {
3656 pr_warn("failed to find BTF for extern '%s': %d\n",
3657 ext_name, ext->btf_id);
3658 return ext->btf_id;
3659 }
3660 t = btf__type_by_id(obj->btf, ext->btf_id);
3661 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3662 ext->sym_idx = i;
ad23b723 3663 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
2e33efe3
AN
3664
3665 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3666 if (ext->sec_btf_id <= 0) {
3667 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3668 ext_name, ext->btf_id, ext->sec_btf_id);
3669 return ext->sec_btf_id;
166750bc 3670 }
2e33efe3
AN
3671 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3672 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3673
3674 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
5bd022ec
MKL
3675 if (btf_is_func(t)) {
3676 pr_warn("extern function %s is unsupported under %s section\n",
3677 ext->name, KCONFIG_SEC);
3678 return -ENOTSUP;
3679 }
2e33efe3
AN
3680 kcfg_sec = sec;
3681 ext->type = EXT_KCFG;
3682 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3683 if (ext->kcfg.sz <= 0) {
3684 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3685 ext_name, ext->kcfg.sz);
3686 return ext->kcfg.sz;
3687 }
3688 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3689 if (ext->kcfg.align <= 0) {
3690 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3691 ext_name, ext->kcfg.align);
3692 return -EINVAL;
3693 }
3694 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3695 &ext->kcfg.is_signed);
3696 if (ext->kcfg.type == KCFG_UNKNOWN) {
3697 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3698 return -ENOTSUP;
3699 }
1c0c7074 3700 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
1c0c7074
AN
3701 ksym_sec = sec;
3702 ext->type = EXT_KSYM;
d370bbe1
HL
3703 skip_mods_and_typedefs(obj->btf, t->type,
3704 &ext->ksym.type_id);
2e33efe3
AN
3705 } else {
3706 pr_warn("unrecognized extern section '%s'\n", sec_name);
166750bc
AN
3707 return -ENOTSUP;
3708 }
3709 }
3710 pr_debug("collected %d externs total\n", obj->nr_extern);
3711
3712 if (!obj->nr_extern)
3713 return 0;
3714
2e33efe3 3715 /* sort externs by type, for kcfg ones also by (align, size, name) */
166750bc 3716 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
166750bc 3717
1c0c7074
AN
3718 /* for .ksyms section, we need to turn all externs into allocated
3719 * variables in BTF to pass kernel verification; we do this by
3720 * pretending that each extern is a 8-byte variable
3721 */
3722 if (ksym_sec) {
3723 /* find existing 4-byte integer type in BTF to use for fake
3724 * extern variables in DATASEC
3725 */
3726 int int_btf_id = find_int_btf_id(obj->btf);
5bd022ec
MKL
3727 /* For extern function, a dummy_var added earlier
3728 * will be used to replace the vs->type and
3729 * its name string will be used to refill
3730 * the missing param's name.
3731 */
3732 const struct btf_type *dummy_var;
1c0c7074 3733
5bd022ec 3734 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
1c0c7074
AN
3735 for (i = 0; i < obj->nr_extern; i++) {
3736 ext = &obj->externs[i];
3737 if (ext->type != EXT_KSYM)
3738 continue;
3739 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3740 i, ext->sym_idx, ext->name);
3741 }
3742
3743 sec = ksym_sec;
3744 n = btf_vlen(sec);
3745 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3746 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3747 struct btf_type *vt;
3748
3749 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3750 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3751 ext = find_extern_by_name(obj, ext_name);
3752 if (!ext) {
5bd022ec
MKL
3753 pr_warn("failed to find extern definition for BTF %s '%s'\n",
3754 btf_kind_str(vt), ext_name);
1c0c7074
AN
3755 return -ESRCH;
3756 }
5bd022ec
MKL
3757 if (btf_is_func(vt)) {
3758 const struct btf_type *func_proto;
3759 struct btf_param *param;
3760 int j;
3761
3762 func_proto = btf__type_by_id(obj->btf,
3763 vt->type);
3764 param = btf_params(func_proto);
3765 /* Reuse the dummy_var string if the
3766 * func proto does not have param name.
3767 */
3768 for (j = 0; j < btf_vlen(func_proto); j++)
3769 if (param[j].type && !param[j].name_off)
3770 param[j].name_off =
3771 dummy_var->name_off;
3772 vs->type = dummy_var_btf_id;
3773 vt->info &= ~0xffff;
3774 vt->info |= BTF_FUNC_GLOBAL;
3775 } else {
3776 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3777 vt->type = int_btf_id;
3778 }
1c0c7074
AN
3779 vs->offset = off;
3780 vs->size = sizeof(int);
3781 }
3782 sec->size = off;
3783 }
3784
2e33efe3
AN
3785 if (kcfg_sec) {
3786 sec = kcfg_sec;
3787 /* for kcfg externs calculate their offsets within a .kconfig map */
3788 off = 0;
3789 for (i = 0; i < obj->nr_extern; i++) {
3790 ext = &obj->externs[i];
3791 if (ext->type != EXT_KCFG)
3792 continue;
166750bc 3793
2e33efe3
AN
3794 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3795 off = ext->kcfg.data_off + ext->kcfg.sz;
1c0c7074 3796 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
2e33efe3
AN
3797 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3798 }
3799 sec->size = off;
3800 n = btf_vlen(sec);
3801 for (i = 0; i < n; i++) {
3802 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3803
3804 t = btf__type_by_id(obj->btf, vs->type);
3805 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3806 ext = find_extern_by_name(obj, ext_name);
3807 if (!ext) {
3808 pr_warn("failed to find extern definition for BTF var '%s'\n",
3809 ext_name);
3810 return -ESRCH;
3811 }
3812 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3813 vs->offset = ext->kcfg.data_off;
166750bc 3814 }
166750bc 3815 }
166750bc
AN
3816 return 0;
3817}
3818
6d4b198b 3819struct bpf_program *
a324aae3
AN
3820bpf_object__find_program_by_title(const struct bpf_object *obj,
3821 const char *title)
6d4b198b
JK
3822{
3823 struct bpf_program *pos;
3824
3825 bpf_object__for_each_program(pos, obj) {
52109584 3826 if (pos->sec_name && !strcmp(pos->sec_name, title))
6d4b198b
JK
3827 return pos;
3828 }
e9fc3ce9 3829 return errno = ENOENT, NULL;
6d4b198b
JK
3830}
3831
c3c55696
AN
3832static bool prog_is_subprog(const struct bpf_object *obj,
3833 const struct bpf_program *prog)
3834{
197afc63
AN
3835 /* For legacy reasons, libbpf supports an entry-point BPF programs
3836 * without SEC() attribute, i.e., those in the .text section. But if
3837 * there are 2 or more such programs in the .text section, they all
3838 * must be subprograms called from entry-point BPF programs in
3839 * designated SEC()'tions, otherwise there is no way to distinguish
3840 * which of those programs should be loaded vs which are a subprogram.
3841 * Similarly, if there is a function/program in .text and at least one
3842 * other BPF program with custom SEC() attribute, then we just assume
3843 * .text programs are subprograms (even if they are not called from
3844 * other programs), because libbpf never explicitly supported mixing
3845 * SEC()-designated BPF programs and .text entry-point BPF programs.
3846 */
3847 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
c3c55696
AN
3848}
3849
01af3bf0
AN
3850struct bpf_program *
3851bpf_object__find_program_by_name(const struct bpf_object *obj,
3852 const char *name)
3853{
3854 struct bpf_program *prog;
3855
3856 bpf_object__for_each_program(prog, obj) {
c3c55696
AN
3857 if (prog_is_subprog(obj, prog))
3858 continue;
01af3bf0
AN
3859 if (!strcmp(prog->name, name))
3860 return prog;
3861 }
e9fc3ce9 3862 return errno = ENOENT, NULL;
01af3bf0
AN
3863}
3864
d859900c
DB
3865static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3866 int shndx)
3867{
25bbbd7a
AN
3868 switch (obj->efile.secs[shndx].sec_type) {
3869 case SEC_BSS:
3870 case SEC_DATA:
3871 case SEC_RODATA:
3872 return true;
3873 default:
3874 return false;
3875 }
d859900c
DB
3876}
3877
3878static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3879 int shndx)
3880{
abd29c93
AN
3881 return shndx == obj->efile.maps_shndx ||
3882 shndx == obj->efile.btf_maps_shndx;
d859900c
DB
3883}
3884
d859900c
DB
3885static enum libbpf_map_type
3886bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3887{
25bbbd7a
AN
3888 if (shndx == obj->efile.symbols_shndx)
3889 return LIBBPF_MAP_KCONFIG;
3890
3891 switch (obj->efile.secs[shndx].sec_type) {
3892 case SEC_BSS:
d859900c 3893 return LIBBPF_MAP_BSS;
25bbbd7a
AN
3894 case SEC_DATA:
3895 return LIBBPF_MAP_DATA;
3896 case SEC_RODATA:
d859900c 3897 return LIBBPF_MAP_RODATA;
25bbbd7a 3898 default:
d859900c 3899 return LIBBPF_MAP_UNSPEC;
25bbbd7a 3900 }
d859900c
DB
3901}
3902
1f8e2bcb
AN
3903static int bpf_program__record_reloc(struct bpf_program *prog,
3904 struct reloc_desc *reloc_desc,
9c0f8cbd 3905 __u32 insn_idx, const char *sym_name,
ad23b723 3906 const Elf64_Sym *sym, const Elf64_Rel *rel)
1f8e2bcb
AN
3907{
3908 struct bpf_insn *insn = &prog->insns[insn_idx];
3909 size_t map_idx, nr_maps = prog->obj->nr_maps;
3910 struct bpf_object *obj = prog->obj;
3911 __u32 shdr_idx = sym->st_shndx;
3912 enum libbpf_map_type type;
9c0f8cbd 3913 const char *sym_sec_name;
1f8e2bcb
AN
3914 struct bpf_map *map;
3915
aa0b8d43 3916 if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
9c0f8cbd
AN
3917 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3918 prog->name, sym_name, insn_idx, insn->code);
1f8e2bcb
AN
3919 return -LIBBPF_ERRNO__RELOC;
3920 }
166750bc
AN
3921
3922 if (sym_is_extern(sym)) {
ad23b723 3923 int sym_idx = ELF64_R_SYM(rel->r_info);
166750bc
AN
3924 int i, n = obj->nr_extern;
3925 struct extern_desc *ext;
3926
3927 for (i = 0; i < n; i++) {
3928 ext = &obj->externs[i];
3929 if (ext->sym_idx == sym_idx)
3930 break;
3931 }
3932 if (i >= n) {
9c0f8cbd
AN
3933 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3934 prog->name, sym_name, sym_idx);
166750bc
AN
3935 return -LIBBPF_ERRNO__RELOC;
3936 }
9c0f8cbd
AN
3937 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3938 prog->name, i, ext->name, ext->sym_idx, insn_idx);
5bd022ec
MKL
3939 if (insn->code == (BPF_JMP | BPF_CALL))
3940 reloc_desc->type = RELO_EXTERN_FUNC;
3941 else
3942 reloc_desc->type = RELO_EXTERN_VAR;
166750bc 3943 reloc_desc->insn_idx = insn_idx;
2e33efe3 3944 reloc_desc->sym_off = i; /* sym_off stores extern index */
166750bc
AN
3945 return 0;
3946 }
3947
aa0b8d43
MKL
3948 /* sub-program call relocation */
3949 if (is_call_insn(insn)) {
3950 if (insn->src_reg != BPF_PSEUDO_CALL) {
3951 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3952 return -LIBBPF_ERRNO__RELOC;
3953 }
3954 /* text_shndx can be 0, if no default "main" program exists */
3955 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3956 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3957 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3958 prog->name, sym_name, sym_sec_name);
3959 return -LIBBPF_ERRNO__RELOC;
3960 }
3961 if (sym->st_value % BPF_INSN_SZ) {
3962 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3963 prog->name, sym_name, (size_t)sym->st_value);
3964 return -LIBBPF_ERRNO__RELOC;
3965 }
3966 reloc_desc->type = RELO_CALL;
3967 reloc_desc->insn_idx = insn_idx;
3968 reloc_desc->sym_off = sym->st_value;
3969 return 0;
3970 }
3971
1f8e2bcb 3972 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
9c0f8cbd
AN
3973 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3974 prog->name, sym_name, shdr_idx);
1f8e2bcb
AN
3975 return -LIBBPF_ERRNO__RELOC;
3976 }
3977
53eddb5e
YS
3978 /* loading subprog addresses */
3979 if (sym_is_subprog(sym, obj->efile.text_shndx)) {
3980 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
3981 * local_func: sym->st_value = 0, insn->imm = offset in the section.
3982 */
3983 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
3984 pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
3985 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
3986 return -LIBBPF_ERRNO__RELOC;
3987 }
3988
3989 reloc_desc->type = RELO_SUBPROG_ADDR;
3990 reloc_desc->insn_idx = insn_idx;
3991 reloc_desc->sym_off = sym->st_value;
3992 return 0;
3993 }
3994
1f8e2bcb 3995 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
9c0f8cbd 3996 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
1f8e2bcb
AN
3997
3998 /* generic map reference relocation */
3999 if (type == LIBBPF_MAP_UNSPEC) {
4000 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
9c0f8cbd
AN
4001 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4002 prog->name, sym_name, sym_sec_name);
1f8e2bcb
AN
4003 return -LIBBPF_ERRNO__RELOC;
4004 }
4005 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4006 map = &obj->maps[map_idx];
4007 if (map->libbpf_type != type ||
4008 map->sec_idx != sym->st_shndx ||
4009 map->sec_offset != sym->st_value)
4010 continue;
9c0f8cbd
AN
4011 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4012 prog->name, map_idx, map->name, map->sec_idx,
1f8e2bcb
AN
4013 map->sec_offset, insn_idx);
4014 break;
4015 }
4016 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4017 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4018 prog->name, sym_sec_name, (size_t)sym->st_value);
1f8e2bcb
AN
4019 return -LIBBPF_ERRNO__RELOC;
4020 }
4021 reloc_desc->type = RELO_LD64;
4022 reloc_desc->insn_idx = insn_idx;
4023 reloc_desc->map_idx = map_idx;
53f8dd43 4024 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
1f8e2bcb
AN
4025 return 0;
4026 }
4027
4028 /* global data map relocation */
4029 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
9c0f8cbd
AN
4030 pr_warn("prog '%s': bad data relo against section '%s'\n",
4031 prog->name, sym_sec_name);
1f8e2bcb 4032 return -LIBBPF_ERRNO__RELOC;
1f8e2bcb 4033 }
1f8e2bcb
AN
4034 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4035 map = &obj->maps[map_idx];
25bbbd7a 4036 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
1f8e2bcb 4037 continue;
9c0f8cbd
AN
4038 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4039 prog->name, map_idx, map->name, map->sec_idx,
4040 map->sec_offset, insn_idx);
1f8e2bcb
AN
4041 break;
4042 }
4043 if (map_idx >= nr_maps) {
9c0f8cbd
AN
4044 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4045 prog->name, sym_sec_name);
1f8e2bcb
AN
4046 return -LIBBPF_ERRNO__RELOC;
4047 }
4048
4049 reloc_desc->type = RELO_DATA;
4050 reloc_desc->insn_idx = insn_idx;
4051 reloc_desc->map_idx = map_idx;
53f8dd43 4052 reloc_desc->sym_off = sym->st_value;
1f8e2bcb
AN
4053 return 0;
4054}
4055
db2b8b06
AN
4056static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4057{
4058 return insn_idx >= prog->sec_insn_off &&
4059 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4060}
4061
4062static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4063 size_t sec_idx, size_t insn_idx)
4064{
4065 int l = 0, r = obj->nr_programs - 1, m;
4066 struct bpf_program *prog;
4067
4068 while (l < r) {
4069 m = l + (r - l + 1) / 2;
4070 prog = &obj->programs[m];
4071
4072 if (prog->sec_idx < sec_idx ||
4073 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4074 l = m;
4075 else
4076 r = m - 1;
4077 }
4078 /* matching program could be at index l, but it still might be the
4079 * wrong one, so we need to double check conditions for the last time
4080 */
4081 prog = &obj->programs[l];
4082 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4083 return prog;
4084 return NULL;
4085}
4086
34090915 4087static int
ad23b723 4088bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
34090915 4089{
9c0f8cbd 4090 const char *relo_sec_name, *sec_name;
b7332d28 4091 size_t sec_idx = shdr->sh_info, sym_idx;
c3c55696
AN
4092 struct bpf_program *prog;
4093 struct reloc_desc *relos;
1f8e2bcb 4094 int err, i, nrels;
c3c55696
AN
4095 const char *sym_name;
4096 __u32 insn_idx;
6245947c
AN
4097 Elf_Scn *scn;
4098 Elf_Data *scn_data;
ad23b723
AN
4099 Elf64_Sym *sym;
4100 Elf64_Rel *rel;
34090915 4101
b7332d28
AN
4102 if (sec_idx >= obj->efile.sec_cnt)
4103 return -EINVAL;
4104
6245947c
AN
4105 scn = elf_sec_by_idx(obj, sec_idx);
4106 scn_data = elf_sec_data(obj, scn);
4107
9c0f8cbd 4108 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
6245947c 4109 sec_name = elf_sec_name(obj, scn);
9c0f8cbd
AN
4110 if (!relo_sec_name || !sec_name)
4111 return -EINVAL;
4112
4113 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4114 relo_sec_name, sec_idx, sec_name);
34090915
WN
4115 nrels = shdr->sh_size / shdr->sh_entsize;
4116
34090915 4117 for (i = 0; i < nrels; i++) {
ad23b723
AN
4118 rel = elf_rel_by_idx(data, i);
4119 if (!rel) {
9c0f8cbd 4120 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
6371ca3b 4121 return -LIBBPF_ERRNO__FORMAT;
34090915 4122 }
ad23b723 4123
b7332d28
AN
4124 sym_idx = ELF64_R_SYM(rel->r_info);
4125 sym = elf_sym_by_idx(obj, sym_idx);
ad23b723 4126 if (!sym) {
b7332d28
AN
4127 pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4128 relo_sec_name, sym_idx, i);
4129 return -LIBBPF_ERRNO__FORMAT;
4130 }
4131
4132 if (sym->st_shndx >= obj->efile.sec_cnt) {
4133 pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4134 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
6371ca3b 4135 return -LIBBPF_ERRNO__FORMAT;
34090915 4136 }
6245947c 4137
ad23b723 4138 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
9c0f8cbd 4139 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
b7332d28 4140 relo_sec_name, (size_t)rel->r_offset, i);
1f8e2bcb 4141 return -LIBBPF_ERRNO__FORMAT;
9c0f8cbd 4142 }
d859900c 4143
ad23b723 4144 insn_idx = rel->r_offset / BPF_INSN_SZ;
c3c55696
AN
4145 /* relocations against static functions are recorded as
4146 * relocations against the section that contains a function;
4147 * in such case, symbol will be STT_SECTION and sym.st_name
4148 * will point to empty string (0), so fetch section name
4149 * instead
4150 */
ad23b723
AN
4151 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4152 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
c3c55696 4153 else
ad23b723 4154 sym_name = elf_sym_str(obj, sym->st_name);
c3c55696 4155 sym_name = sym_name ?: "<?";
d859900c 4156
9c0f8cbd
AN
4157 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4158 relo_sec_name, i, insn_idx, sym_name);
666810e8 4159
c3c55696
AN
4160 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4161 if (!prog) {
6245947c 4162 pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
c3c55696 4163 relo_sec_name, i, sec_name, insn_idx);
6245947c 4164 continue;
c3c55696
AN
4165 }
4166
4167 relos = libbpf_reallocarray(prog->reloc_desc,
4168 prog->nr_reloc + 1, sizeof(*relos));
4169 if (!relos)
4170 return -ENOMEM;
4171 prog->reloc_desc = relos;
4172
4173 /* adjust insn_idx to local BPF program frame of reference */
4174 insn_idx -= prog->sec_insn_off;
4175 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
ad23b723 4176 insn_idx, sym_name, sym, rel);
1f8e2bcb
AN
4177 if (err)
4178 return err;
c3c55696
AN
4179
4180 prog->nr_reloc++;
34090915
WN
4181 }
4182 return 0;
4183}
4184
abd29c93 4185static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
8a138aed
MKL
4186{
4187 struct bpf_map_def *def = &map->def;
d859900c 4188 __u32 key_type_id = 0, value_type_id = 0;
96408c43 4189 int ret;
8a138aed 4190
590a0088
MKL
4191 /* if it's BTF-defined map, we don't need to search for type IDs.
4192 * For struct_ops map, it does not need btf_key_type_id and
4193 * btf_value_type_id.
4194 */
4195 if (map->sec_idx == obj->efile.btf_maps_shndx ||
4196 bpf_map__is_struct_ops(map))
abd29c93
AN
4197 return 0;
4198
d859900c 4199 if (!bpf_map__is_internal(map)) {
93b8952d 4200 pr_warn("Use of BPF_ANNOTATE_KV_PAIR is deprecated, use BTF-defined maps in .maps section instead\n");
abd29c93 4201 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
d859900c
DB
4202 def->value_size, &key_type_id,
4203 &value_type_id);
4204 } else {
4205 /*
4206 * LLVM annotates global data differently in BTF, that is,
4207 * only as '.data', '.bss' or '.rodata'.
4208 */
aed65917 4209 ret = btf__find_by_name(obj->btf, map->real_name);
d859900c
DB
4210 }
4211 if (ret < 0)
96408c43 4212 return ret;
8a138aed 4213
96408c43 4214 map->btf_key_type_id = key_type_id;
d859900c
DB
4215 map->btf_value_type_id = bpf_map__is_internal(map) ?
4216 ret : value_type_id;
8a138aed
MKL
4217 return 0;
4218}
4219
97eb3138
MP
4220static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4221{
4222 char file[PATH_MAX], buff[4096];
4223 FILE *fp;
4224 __u32 val;
4225 int err;
4226
4227 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4228 memset(info, 0, sizeof(*info));
4229
4230 fp = fopen(file, "r");
4231 if (!fp) {
4232 err = -errno;
4233 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4234 err);
4235 return err;
4236 }
4237
4238 while (fgets(buff, sizeof(buff), fp)) {
4239 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4240 info->type = val;
4241 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4242 info->key_size = val;
4243 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4244 info->value_size = val;
4245 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4246 info->max_entries = val;
4247 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4248 info->map_flags = val;
4249 }
4250
4251 fclose(fp);
4252
4253 return 0;
4254}
4255
26736eb9
JK
4256int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4257{
4258 struct bpf_map_info info = {};
4259 __u32 len = sizeof(info);
4260 int new_fd, err;
4261 char *new_name;
4262
4263 err = bpf_obj_get_info_by_fd(fd, &info, &len);
97eb3138
MP
4264 if (err && errno == EINVAL)
4265 err = bpf_get_map_info_from_fdinfo(fd, &info);
26736eb9 4266 if (err)
e9fc3ce9 4267 return libbpf_err(err);
26736eb9
JK
4268
4269 new_name = strdup(info.name);
4270 if (!new_name)
e9fc3ce9 4271 return libbpf_err(-errno);
26736eb9
JK
4272
4273 new_fd = open("/", O_RDONLY | O_CLOEXEC);
d1b4574a
THJ
4274 if (new_fd < 0) {
4275 err = -errno;
26736eb9 4276 goto err_free_new_name;
d1b4574a 4277 }
26736eb9
JK
4278
4279 new_fd = dup3(fd, new_fd, O_CLOEXEC);
d1b4574a
THJ
4280 if (new_fd < 0) {
4281 err = -errno;
26736eb9 4282 goto err_close_new_fd;
d1b4574a 4283 }
26736eb9
JK
4284
4285 err = zclose(map->fd);
d1b4574a
THJ
4286 if (err) {
4287 err = -errno;
26736eb9 4288 goto err_close_new_fd;
d1b4574a 4289 }
26736eb9
JK
4290 free(map->name);
4291
4292 map->fd = new_fd;
4293 map->name = new_name;
4294 map->def.type = info.type;
4295 map->def.key_size = info.key_size;
4296 map->def.value_size = info.value_size;
4297 map->def.max_entries = info.max_entries;
4298 map->def.map_flags = info.map_flags;
4299 map->btf_key_type_id = info.btf_key_type_id;
4300 map->btf_value_type_id = info.btf_value_type_id;
ec6d5f47 4301 map->reused = true;
47512102 4302 map->map_extra = info.map_extra;
26736eb9
JK
4303
4304 return 0;
4305
4306err_close_new_fd:
4307 close(new_fd);
4308err_free_new_name:
4309 free(new_name);
e9fc3ce9 4310 return libbpf_err(err);
26736eb9
JK
4311}
4312
1bdb6c9a 4313__u32 bpf_map__max_entries(const struct bpf_map *map)
1a11a4c7 4314{
1bdb6c9a
AN
4315 return map->def.max_entries;
4316}
1a11a4c7 4317
b3278099
AN
4318struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4319{
4320 if (!bpf_map_type__is_map_in_map(map->def.type))
e9fc3ce9 4321 return errno = EINVAL, NULL;
b3278099
AN
4322
4323 return map->inner_map;
4324}
4325
1bdb6c9a
AN
4326int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4327{
1a11a4c7 4328 if (map->fd >= 0)
e9fc3ce9 4329 return libbpf_err(-EBUSY);
1a11a4c7 4330 map->def.max_entries = max_entries;
1a11a4c7
AI
4331 return 0;
4332}
4333
1bdb6c9a
AN
4334int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
4335{
4336 if (!map || !max_entries)
e9fc3ce9 4337 return libbpf_err(-EINVAL);
1bdb6c9a
AN
4338
4339 return bpf_map__set_max_entries(map, max_entries);
4340}
4341
47eff617 4342static int
fd9eef1a 4343bpf_object__probe_loading(struct bpf_object *obj)
47eff617 4344{
47eff617
SF
4345 char *cp, errmsg[STRERR_BUFSIZE];
4346 struct bpf_insn insns[] = {
4347 BPF_MOV64_IMM(BPF_REG_0, 0),
4348 BPF_EXIT_INSN(),
4349 };
e32660ac 4350 int ret, insn_cnt = ARRAY_SIZE(insns);
47eff617 4351
f9bceaa5
SF
4352 if (obj->gen_loader)
4353 return 0;
4354
e542f2c4
AN
4355 ret = bump_rlimit_memlock();
4356 if (ret)
4357 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4358
47eff617 4359 /* make sure basic loading works */
e32660ac
AN
4360 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4361 if (ret < 0)
4362 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
47eff617 4363 if (ret < 0) {
fd9eef1a
EC
4364 ret = errno;
4365 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4366 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4367 "program. Make sure your kernel supports BPF "
4368 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4369 "set to big enough value.\n", __func__, cp, ret);
4370 return -ret;
47eff617
SF
4371 }
4372 close(ret);
4373
fd9eef1a
EC
4374 return 0;
4375}
4376
bb180fb2
AN
4377static int probe_fd(int fd)
4378{
4379 if (fd >= 0)
4380 close(fd);
4381 return fd >= 0;
4382}
4383
47b6cb4d 4384static int probe_kern_prog_name(void)
fd9eef1a 4385{
fd9eef1a
EC
4386 struct bpf_insn insns[] = {
4387 BPF_MOV64_IMM(BPF_REG_0, 0),
4388 BPF_EXIT_INSN(),
4389 };
e32660ac 4390 int ret, insn_cnt = ARRAY_SIZE(insns);
fd9eef1a
EC
4391
4392 /* make sure loading with name works */
e32660ac 4393 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, "test", "GPL", insns, insn_cnt, NULL);
bb180fb2 4394 return probe_fd(ret);
47eff617
SF
4395}
4396
47b6cb4d 4397static int probe_kern_global_data(void)
8837fe5d 4398{
8837fe5d
DB
4399 char *cp, errmsg[STRERR_BUFSIZE];
4400 struct bpf_insn insns[] = {
4401 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4402 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4403 BPF_MOV64_IMM(BPF_REG_0, 0),
4404 BPF_EXIT_INSN(),
4405 };
e32660ac 4406 int ret, map, insn_cnt = ARRAY_SIZE(insns);
8837fe5d 4407
a9606f40 4408 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
8837fe5d 4409 if (map < 0) {
23ab656b
THJ
4410 ret = -errno;
4411 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
be18010e 4412 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
23ab656b
THJ
4413 __func__, cp, -ret);
4414 return ret;
8837fe5d
DB
4415 }
4416
4417 insns[0].imm = map;
4418
e32660ac 4419 ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
47b6cb4d 4420 close(map);
bb180fb2 4421 return probe_fd(ret);
8837fe5d
DB
4422}
4423
68b08647
AN
4424static int probe_kern_btf(void)
4425{
4426 static const char strs[] = "\0int";
4427 __u32 types[] = {
4428 /* int */
4429 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4430 };
4431
4432 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4433 strs, sizeof(strs)));
4434}
4435
47b6cb4d 4436static int probe_kern_btf_func(void)
d7c4b398 4437{
8983b731 4438 static const char strs[] = "\0int\0x\0a";
d7c4b398
AN
4439 /* void x(int a) {} */
4440 __u32 types[] = {
4441 /* int */
4442 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4443 /* FUNC_PROTO */ /* [2] */
4444 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4445 BTF_PARAM_ENC(7, 1),
4446 /* FUNC x */ /* [3] */
4447 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4448 };
d7c4b398 4449
bb180fb2
AN
4450 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4451 strs, sizeof(strs)));
d7c4b398
AN
4452}
4453
47b6cb4d 4454static int probe_kern_btf_func_global(void)
2d3eb67f
AS
4455{
4456 static const char strs[] = "\0int\0x\0a";
4457 /* static void x(int a) {} */
4458 __u32 types[] = {
4459 /* int */
4460 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4461 /* FUNC_PROTO */ /* [2] */
4462 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4463 BTF_PARAM_ENC(7, 1),
4464 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
4465 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4466 };
2d3eb67f 4467
bb180fb2
AN
4468 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4469 strs, sizeof(strs)));
2d3eb67f
AS
4470}
4471
47b6cb4d 4472static int probe_kern_btf_datasec(void)
d7c4b398 4473{
8983b731 4474 static const char strs[] = "\0x\0.data";
d7c4b398
AN
4475 /* static int a; */
4476 __u32 types[] = {
4477 /* int */
4478 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4479 /* VAR x */ /* [2] */
4480 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4481 BTF_VAR_STATIC,
4482 /* DATASEC val */ /* [3] */
4483 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4484 BTF_VAR_SECINFO_ENC(2, 0, 4),
4485 };
cfd49210 4486
bb180fb2
AN
4487 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4488 strs, sizeof(strs)));
d7c4b398
AN
4489}
4490
22541a9e
IL
4491static int probe_kern_btf_float(void)
4492{
4493 static const char strs[] = "\0float";
4494 __u32 types[] = {
4495 /* float */
4496 BTF_TYPE_FLOAT_ENC(1, 4),
4497 };
4498
4499 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4500 strs, sizeof(strs)));
4501}
4502
223f903e 4503static int probe_kern_btf_decl_tag(void)
5b84bd10
YS
4504{
4505 static const char strs[] = "\0tag";
4506 __u32 types[] = {
4507 /* int */
4508 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4509 /* VAR x */ /* [2] */
4510 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4511 BTF_VAR_STATIC,
4512 /* attr */
223f903e 4513 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
5b84bd10
YS
4514 };
4515
4516 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4517 strs, sizeof(strs)));
4518}
4519
2dc1e488
YS
4520static int probe_kern_btf_type_tag(void)
4521{
4522 static const char strs[] = "\0tag";
4523 __u32 types[] = {
4524 /* int */
4525 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
4526 /* attr */
4527 BTF_TYPE_TYPE_TAG_ENC(1, 1), /* [2] */
4528 /* ptr */
4529 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2), /* [3] */
4530 };
4531
4532 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4533 strs, sizeof(strs)));
4534}
4535
47b6cb4d 4536static int probe_kern_array_mmap(void)
7fe74b43 4537{
a9606f40
AN
4538 LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4539 int fd;
7fe74b43 4540
a9606f40
AN
4541 fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), sizeof(int), 1, &opts);
4542 return probe_fd(fd);
7fe74b43
AN
4543}
4544
47b6cb4d 4545static int probe_kern_exp_attach_type(void)
25498a19 4546{
e32660ac 4547 LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
25498a19
AN
4548 struct bpf_insn insns[] = {
4549 BPF_MOV64_IMM(BPF_REG_0, 0),
4550 BPF_EXIT_INSN(),
4551 };
e32660ac 4552 int fd, insn_cnt = ARRAY_SIZE(insns);
25498a19 4553
25498a19
AN
4554 /* use any valid combination of program type and (optional)
4555 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4556 * to see if kernel supports expected_attach_type field for
4557 * BPF_PROG_LOAD command
4558 */
e32660ac
AN
4559 fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4560 return probe_fd(fd);
25498a19
AN
4561}
4562
109cea5a
AN
4563static int probe_kern_probe_read_kernel(void)
4564{
109cea5a
AN
4565 struct bpf_insn insns[] = {
4566 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
4567 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
4568 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
4569 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
4570 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4571 BPF_EXIT_INSN(),
4572 };
e32660ac 4573 int fd, insn_cnt = ARRAY_SIZE(insns);
109cea5a 4574
e32660ac
AN
4575 fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4576 return probe_fd(fd);
109cea5a
AN
4577}
4578
5d23328d
YZ
4579static int probe_prog_bind_map(void)
4580{
5d23328d
YZ
4581 char *cp, errmsg[STRERR_BUFSIZE];
4582 struct bpf_insn insns[] = {
4583 BPF_MOV64_IMM(BPF_REG_0, 0),
4584 BPF_EXIT_INSN(),
4585 };
e32660ac 4586 int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
5d23328d 4587
a9606f40 4588 map = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, sizeof(int), 32, 1, NULL);
5d23328d
YZ
4589 if (map < 0) {
4590 ret = -errno;
4591 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4592 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4593 __func__, cp, -ret);
4594 return ret;
4595 }
4596
e32660ac 4597 prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5d23328d
YZ
4598 if (prog < 0) {
4599 close(map);
4600 return 0;
4601 }
4602
4603 ret = bpf_prog_bind_map(prog, map, NULL);
4604
4605 close(map);
4606 close(prog);
4607
4608 return ret >= 0;
4609}
4610
4f33a53d
AN
4611static int probe_module_btf(void)
4612{
4613 static const char strs[] = "\0int";
4614 __u32 types[] = {
4615 /* int */
4616 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4617 };
4618 struct bpf_btf_info info;
4619 __u32 len = sizeof(info);
4620 char name[16];
4621 int fd, err;
4622
4623 fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4624 if (fd < 0)
4625 return 0; /* BTF not supported at all */
4626
4627 memset(&info, 0, sizeof(info));
4628 info.name = ptr_to_u64(name);
4629 info.name_len = sizeof(name);
4630
4631 /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4632 * kernel's module BTF support coincides with support for
4633 * name/name_len fields in struct bpf_btf_info.
4634 */
4635 err = bpf_obj_get_info_by_fd(fd, &info, &len);
4636 close(fd);
4637 return !err;
4638}
4639
668ace0e
AN
4640static int probe_perf_link(void)
4641{
668ace0e
AN
4642 struct bpf_insn insns[] = {
4643 BPF_MOV64_IMM(BPF_REG_0, 0),
4644 BPF_EXIT_INSN(),
4645 };
4646 int prog_fd, link_fd, err;
4647
e32660ac
AN
4648 prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4649 insns, ARRAY_SIZE(insns), NULL);
668ace0e
AN
4650 if (prog_fd < 0)
4651 return -errno;
4652
4653 /* use invalid perf_event FD to get EBADF, if link is supported;
4654 * otherwise EINVAL should be returned
4655 */
4656 link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4657 err = -errno; /* close() can clobber errno */
4658
4659 if (link_fd >= 0)
4660 close(link_fd);
4661 close(prog_fd);
4662
4663 return link_fd < 0 && err == -EBADF;
4664}
4665
47b6cb4d
AN
4666enum kern_feature_result {
4667 FEAT_UNKNOWN = 0,
4668 FEAT_SUPPORTED = 1,
4669 FEAT_MISSING = 2,
4670};
4671
4672typedef int (*feature_probe_fn)(void);
4673
4674static struct kern_feature_desc {
4675 const char *desc;
4676 feature_probe_fn probe;
4677 enum kern_feature_result res;
4678} feature_probes[__FEAT_CNT] = {
4679 [FEAT_PROG_NAME] = {
4680 "BPF program name", probe_kern_prog_name,
4681 },
4682 [FEAT_GLOBAL_DATA] = {
4683 "global variables", probe_kern_global_data,
4684 },
68b08647
AN
4685 [FEAT_BTF] = {
4686 "minimal BTF", probe_kern_btf,
4687 },
47b6cb4d
AN
4688 [FEAT_BTF_FUNC] = {
4689 "BTF functions", probe_kern_btf_func,
4690 },
4691 [FEAT_BTF_GLOBAL_FUNC] = {
4692 "BTF global function", probe_kern_btf_func_global,
4693 },
4694 [FEAT_BTF_DATASEC] = {
4695 "BTF data section and variable", probe_kern_btf_datasec,
4696 },
4697 [FEAT_ARRAY_MMAP] = {
4698 "ARRAY map mmap()", probe_kern_array_mmap,
4699 },
4700 [FEAT_EXP_ATTACH_TYPE] = {
4701 "BPF_PROG_LOAD expected_attach_type attribute",
4702 probe_kern_exp_attach_type,
4703 },
109cea5a
AN
4704 [FEAT_PROBE_READ_KERN] = {
4705 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5d23328d
YZ
4706 },
4707 [FEAT_PROG_BIND_MAP] = {
4708 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4f33a53d
AN
4709 },
4710 [FEAT_MODULE_BTF] = {
4711 "module BTF support", probe_module_btf,
4712 },
22541a9e
IL
4713 [FEAT_BTF_FLOAT] = {
4714 "BTF_KIND_FLOAT support", probe_kern_btf_float,
4715 },
668ace0e
AN
4716 [FEAT_PERF_LINK] = {
4717 "BPF perf link support", probe_perf_link,
4718 },
223f903e
YS
4719 [FEAT_BTF_DECL_TAG] = {
4720 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5b84bd10 4721 },
2dc1e488
YS
4722 [FEAT_BTF_TYPE_TAG] = {
4723 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4724 },
e542f2c4
AN
4725 [FEAT_MEMCG_ACCOUNT] = {
4726 "memcg-based memory accounting", probe_memcg_account,
4727 },
47b6cb4d 4728};
8837fe5d 4729
e542f2c4 4730bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
47b6cb4d
AN
4731{
4732 struct kern_feature_desc *feat = &feature_probes[feat_id];
4733 int ret;
4734
e542f2c4 4735 if (obj && obj->gen_loader)
67234743
AS
4736 /* To generate loader program assume the latest kernel
4737 * to avoid doing extra prog_load, map_create syscalls.
4738 */
4739 return true;
4740
47b6cb4d
AN
4741 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4742 ret = feat->probe();
4743 if (ret > 0) {
4744 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4745 } else if (ret == 0) {
4746 WRITE_ONCE(feat->res, FEAT_MISSING);
4747 } else {
4748 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4749 WRITE_ONCE(feat->res, FEAT_MISSING);
4750 }
8837fe5d
DB
4751 }
4752
47b6cb4d 4753 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
47eff617
SF
4754}
4755
57a00f41
THJ
4756static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4757{
4758 struct bpf_map_info map_info = {};
4759 char msg[STRERR_BUFSIZE];
4760 __u32 map_info_len;
97eb3138 4761 int err;
57a00f41
THJ
4762
4763 map_info_len = sizeof(map_info);
4764
97eb3138
MP
4765 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4766 if (err && errno == EINVAL)
4767 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4768 if (err) {
4769 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4770 libbpf_strerror_r(errno, msg, sizeof(msg)));
57a00f41
THJ
4771 return false;
4772 }
4773
4774 return (map_info.type == map->def.type &&
4775 map_info.key_size == map->def.key_size &&
4776 map_info.value_size == map->def.value_size &&
4777 map_info.max_entries == map->def.max_entries &&
47512102
JK
4778 map_info.map_flags == map->def.map_flags &&
4779 map_info.map_extra == map->map_extra);
57a00f41
THJ
4780}
4781
4782static int
4783bpf_object__reuse_map(struct bpf_map *map)
4784{
4785 char *cp, errmsg[STRERR_BUFSIZE];
4786 int err, pin_fd;
4787
4788 pin_fd = bpf_obj_get(map->pin_path);
4789 if (pin_fd < 0) {
4790 err = -errno;
4791 if (err == -ENOENT) {
4792 pr_debug("found no pinned map to reuse at '%s'\n",
4793 map->pin_path);
4794 return 0;
4795 }
4796
4797 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4798 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4799 map->pin_path, cp);
4800 return err;
4801 }
4802
4803 if (!map_is_reuse_compat(map, pin_fd)) {
4804 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4805 map->pin_path);
4806 close(pin_fd);
4807 return -EINVAL;
4808 }
4809
4810 err = bpf_map__reuse_fd(map, pin_fd);
4811 if (err) {
4812 close(pin_fd);
4813 return err;
4814 }
4815 map->pinned = true;
4816 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4817
4818 return 0;
4819}
4820
d859900c
DB
4821static int
4822bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4823{
166750bc 4824 enum libbpf_map_type map_type = map->libbpf_type;
d859900c
DB
4825 char *cp, errmsg[STRERR_BUFSIZE];
4826 int err, zero = 0;
d859900c 4827
67234743
AS
4828 if (obj->gen_loader) {
4829 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4830 map->mmaped, map->def.value_size);
4831 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4832 bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4833 return 0;
4834 }
eba9c5f4
AN
4835 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4836 if (err) {
4837 err = -errno;
4838 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4839 pr_warn("Error setting initial map(%s) contents: %s\n",
4840 map->name, cp);
4841 return err;
4842 }
d859900c 4843
81bfdd08
AN
4844 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4845 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
d859900c
DB
4846 err = bpf_map_freeze(map->fd);
4847 if (err) {
eba9c5f4
AN
4848 err = -errno;
4849 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e
KW
4850 pr_warn("Error freezing map(%s) as read-only: %s\n",
4851 map->name, cp);
eba9c5f4 4852 return err;
d859900c
DB
4853 }
4854 }
eba9c5f4 4855 return 0;
d859900c
DB
4856}
4857
2d39d7c5
AN
4858static void bpf_map__destroy(struct bpf_map *map);
4859
67234743 4860static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
2d39d7c5 4861{
992c4225 4862 LIBBPF_OPTS(bpf_map_create_opts, create_attr);
2d39d7c5 4863 struct bpf_map_def *def = &map->def;
992c4225
AN
4864 const char *map_name = NULL;
4865 __u32 max_entries;
a21ab4c5 4866 int err = 0;
2d39d7c5 4867
9ca1f56a 4868 if (kernel_supports(obj, FEAT_PROG_NAME))
992c4225 4869 map_name = map->name;
2d39d7c5 4870 create_attr.map_ifindex = map->map_ifindex;
2d39d7c5 4871 create_attr.map_flags = def->map_flags;
1bdb6c9a 4872 create_attr.numa_node = map->numa_node;
47512102 4873 create_attr.map_extra = map->map_extra;
2d39d7c5
AN
4874
4875 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4876 int nr_cpus;
4877
4878 nr_cpus = libbpf_num_possible_cpus();
4879 if (nr_cpus < 0) {
4880 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4881 map->name, nr_cpus);
4882 return nr_cpus;
4883 }
4884 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
992c4225 4885 max_entries = nr_cpus;
2d39d7c5 4886 } else {
992c4225 4887 max_entries = def->max_entries;
2d39d7c5
AN
4888 }
4889
4890 if (bpf_map__is_struct_ops(map))
992c4225 4891 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
2d39d7c5 4892
0f0e55d8 4893 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
2d39d7c5
AN
4894 create_attr.btf_fd = btf__fd(obj->btf);
4895 create_attr.btf_key_type_id = map->btf_key_type_id;
4896 create_attr.btf_value_type_id = map->btf_value_type_id;
4897 }
4898
646f02ff
AN
4899 if (bpf_map_type__is_map_in_map(def->type)) {
4900 if (map->inner_map) {
67234743 4901 err = bpf_object__create_map(obj, map->inner_map, true);
646f02ff
AN
4902 if (err) {
4903 pr_warn("map '%s': failed to create inner map: %d\n",
4904 map->name, err);
4905 return err;
4906 }
4907 map->inner_map_fd = bpf_map__fd(map->inner_map);
4908 }
4909 if (map->inner_map_fd >= 0)
4910 create_attr.inner_map_fd = map->inner_map_fd;
4911 }
4912
f7310523
HC
4913 switch (def->type) {
4914 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4915 case BPF_MAP_TYPE_CGROUP_ARRAY:
4916 case BPF_MAP_TYPE_STACK_TRACE:
4917 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4918 case BPF_MAP_TYPE_HASH_OF_MAPS:
4919 case BPF_MAP_TYPE_DEVMAP:
4920 case BPF_MAP_TYPE_DEVMAP_HASH:
4921 case BPF_MAP_TYPE_CPUMAP:
4922 case BPF_MAP_TYPE_XSKMAP:
4923 case BPF_MAP_TYPE_SOCKMAP:
4924 case BPF_MAP_TYPE_SOCKHASH:
4925 case BPF_MAP_TYPE_QUEUE:
4926 case BPF_MAP_TYPE_STACK:
4927 case BPF_MAP_TYPE_RINGBUF:
4928 create_attr.btf_fd = 0;
4929 create_attr.btf_key_type_id = 0;
4930 create_attr.btf_value_type_id = 0;
4931 map->btf_key_type_id = 0;
4932 map->btf_value_type_id = 0;
4933 default:
4934 break;
4935 }
4936
67234743 4937 if (obj->gen_loader) {
992c4225
AN
4938 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
4939 def->key_size, def->value_size, max_entries,
4940 &create_attr, is_inner ? -1 : map - obj->maps);
67234743
AS
4941 /* Pretend to have valid FD to pass various fd >= 0 checks.
4942 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
4943 */
4944 map->fd = 0;
4945 } else {
992c4225
AN
4946 map->fd = bpf_map_create(def->type, map_name,
4947 def->key_size, def->value_size,
4948 max_entries, &create_attr);
67234743 4949 }
2d39d7c5
AN
4950 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4951 create_attr.btf_value_type_id)) {
4952 char *cp, errmsg[STRERR_BUFSIZE];
2d39d7c5 4953
a21ab4c5 4954 err = -errno;
2d39d7c5
AN
4955 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4956 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4957 map->name, cp, err);
4958 create_attr.btf_fd = 0;
4959 create_attr.btf_key_type_id = 0;
4960 create_attr.btf_value_type_id = 0;
4961 map->btf_key_type_id = 0;
4962 map->btf_value_type_id = 0;
992c4225
AN
4963 map->fd = bpf_map_create(def->type, map_name,
4964 def->key_size, def->value_size,
4965 max_entries, &create_attr);
2d39d7c5
AN
4966 }
4967
a21ab4c5 4968 err = map->fd < 0 ? -errno : 0;
2d39d7c5 4969
646f02ff 4970 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
67234743
AS
4971 if (obj->gen_loader)
4972 map->inner_map->fd = -1;
646f02ff
AN
4973 bpf_map__destroy(map->inner_map);
4974 zfree(&map->inner_map);
4975 }
4976
a21ab4c5 4977 return err;
2d39d7c5
AN
4978}
4979
341ac5ff 4980static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
a0f2b7ac
HL
4981{
4982 const struct bpf_map *targ_map;
4983 unsigned int i;
67234743 4984 int fd, err = 0;
a0f2b7ac
HL
4985
4986 for (i = 0; i < map->init_slots_sz; i++) {
4987 if (!map->init_slots[i])
4988 continue;
4989
4990 targ_map = map->init_slots[i];
4991 fd = bpf_map__fd(targ_map);
341ac5ff 4992
67234743 4993 if (obj->gen_loader) {
be05c944
AS
4994 bpf_gen__populate_outer_map(obj->gen_loader,
4995 map - obj->maps, i,
4996 targ_map - obj->maps);
67234743
AS
4997 } else {
4998 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4999 }
a0f2b7ac
HL
5000 if (err) {
5001 err = -errno;
5002 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
341ac5ff 5003 map->name, i, targ_map->name, fd, err);
a0f2b7ac
HL
5004 return err;
5005 }
5006 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5007 map->name, i, targ_map->name, fd);
5008 }
5009
5010 zfree(&map->init_slots);
5011 map->init_slots_sz = 0;
5012
5013 return 0;
5014}
5015
341ac5ff
HC
5016static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5017{
5018 const struct bpf_program *targ_prog;
5019 unsigned int i;
5020 int fd, err;
5021
5022 if (obj->gen_loader)
5023 return -ENOTSUP;
5024
5025 for (i = 0; i < map->init_slots_sz; i++) {
5026 if (!map->init_slots[i])
5027 continue;
5028
5029 targ_prog = map->init_slots[i];
5030 fd = bpf_program__fd(targ_prog);
5031
5032 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5033 if (err) {
5034 err = -errno;
5035 pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5036 map->name, i, targ_prog->name, fd, err);
5037 return err;
5038 }
5039 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5040 map->name, i, targ_prog->name, fd);
5041 }
5042
5043 zfree(&map->init_slots);
5044 map->init_slots_sz = 0;
5045
5046 return 0;
5047}
5048
5049static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5050{
5051 struct bpf_map *map;
5052 int i, err;
5053
5054 for (i = 0; i < obj->nr_maps; i++) {
5055 map = &obj->maps[i];
5056
5057 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5058 continue;
5059
5060 err = init_prog_array_slots(obj, map);
5061 if (err < 0) {
5062 zclose(map->fd);
5063 return err;
5064 }
5065 }
5066 return 0;
5067}
5068
52d3352e
WN
5069static int
5070bpf_object__create_maps(struct bpf_object *obj)
5071{
2d39d7c5
AN
5072 struct bpf_map *map;
5073 char *cp, errmsg[STRERR_BUFSIZE];
5074 unsigned int i, j;
8a138aed 5075 int err;
043c5bb3 5076 bool retried;
52d3352e 5077
9d759a9b 5078 for (i = 0; i < obj->nr_maps; i++) {
2d39d7c5 5079 map = &obj->maps[i];
8a138aed 5080
16e0c35c
AN
5081 /* To support old kernels, we skip creating global data maps
5082 * (.rodata, .data, .kconfig, etc); later on, during program
5083 * loading, if we detect that at least one of the to-be-loaded
5084 * programs is referencing any global data map, we'll error
5085 * out with program name and relocation index logged.
5086 * This approach allows to accommodate Clang emitting
5087 * unnecessary .rodata.str1.1 sections for string literals,
5088 * but also it allows to have CO-RE applications that use
5089 * global variables in some of BPF programs, but not others.
5090 * If those global variable-using programs are not loaded at
5091 * runtime due to bpf_program__set_autoload(prog, false),
5092 * bpf_object loading will succeed just fine even on old
5093 * kernels.
5094 */
5095 if (bpf_map__is_internal(map) &&
229fae38
SC
5096 !kernel_supports(obj, FEAT_GLOBAL_DATA)) {
5097 map->skipped = true;
16e0c35c 5098 continue;
229fae38 5099 }
16e0c35c 5100
043c5bb3
MP
5101 retried = false;
5102retry:
57a00f41
THJ
5103 if (map->pin_path) {
5104 err = bpf_object__reuse_map(map);
5105 if (err) {
2d39d7c5 5106 pr_warn("map '%s': error reusing pinned map\n",
57a00f41 5107 map->name);
2d39d7c5 5108 goto err_out;
57a00f41 5109 }
043c5bb3
MP
5110 if (retried && map->fd < 0) {
5111 pr_warn("map '%s': cannot find pinned map\n",
5112 map->name);
5113 err = -ENOENT;
5114 goto err_out;
5115 }
57a00f41
THJ
5116 }
5117
26736eb9 5118 if (map->fd >= 0) {
2d39d7c5 5119 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
26736eb9 5120 map->name, map->fd);
2c193d32 5121 } else {
67234743 5122 err = bpf_object__create_map(obj, map, false);
2c193d32 5123 if (err)
d859900c 5124 goto err_out;
d859900c 5125
2c193d32
HL
5126 pr_debug("map '%s': created successfully, fd=%d\n",
5127 map->name, map->fd);
646f02ff 5128
2c193d32
HL
5129 if (bpf_map__is_internal(map)) {
5130 err = bpf_object__populate_internal_map(obj, map);
5131 if (err < 0) {
5132 zclose(map->fd);
5133 goto err_out;
5134 }
d859900c 5135 }
646f02ff 5136
341ac5ff
HC
5137 if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5138 err = init_map_in_map_slots(obj, map);
2c193d32
HL
5139 if (err < 0) {
5140 zclose(map->fd);
646f02ff
AN
5141 goto err_out;
5142 }
646f02ff 5143 }
646f02ff
AN
5144 }
5145
57a00f41
THJ
5146 if (map->pin_path && !map->pinned) {
5147 err = bpf_map__pin(map, NULL);
5148 if (err) {
043c5bb3
MP
5149 zclose(map->fd);
5150 if (!retried && err == -EEXIST) {
5151 retried = true;
5152 goto retry;
5153 }
2d39d7c5
AN
5154 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5155 map->name, map->pin_path, err);
2d39d7c5 5156 goto err_out;
57a00f41
THJ
5157 }
5158 }
52d3352e
WN
5159 }
5160
52d3352e 5161 return 0;
2d39d7c5
AN
5162
5163err_out:
5164 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5165 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5166 pr_perm_msg(err);
5167 for (j = 0; j < i; j++)
5168 zclose(obj->maps[j].fd);
5169 return err;
52d3352e
WN
5170}
5171
ddc7c304
AN
5172static bool bpf_core_is_flavor_sep(const char *s)
5173{
5174 /* check X___Y name pattern, where X and Y are not underscores */
5175 return s[0] != '_' && /* X */
5176 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
5177 s[4] != '_'; /* Y */
5178}
5179
5180/* Given 'some_struct_name___with_flavor' return the length of a name prefix
5181 * before last triple underscore. Struct name part after last triple
5182 * underscore is ignored by BPF CO-RE relocation during relocation matching.
5183 */
b0588390 5184size_t bpf_core_essential_name_len(const char *name)
ddc7c304
AN
5185{
5186 size_t n = strlen(name);
5187 int i;
5188
5189 for (i = n - 5; i >= 0; i--) {
5190 if (bpf_core_is_flavor_sep(name + i))
5191 return i + 1;
5192 }
5193 return n;
5194}
5195
301ba4d7 5196static void bpf_core_free_cands(struct bpf_core_cand_list *cands)
ddc7c304 5197{
0f7515ca
AN
5198 free(cands->cands);
5199 free(cands);
ddc7c304
AN
5200}
5201
301ba4d7 5202static int bpf_core_add_cands(struct bpf_core_cand *local_cand,
0f7515ca
AN
5203 size_t local_essent_len,
5204 const struct btf *targ_btf,
5205 const char *targ_btf_name,
5206 int targ_start_id,
301ba4d7 5207 struct bpf_core_cand_list *cands)
ddc7c304 5208{
301ba4d7 5209 struct bpf_core_cand *new_cands, *cand;
03d5b991
AN
5210 const struct btf_type *t, *local_t;
5211 const char *targ_name, *local_name;
0f7515ca
AN
5212 size_t targ_essent_len;
5213 int n, i;
ddc7c304 5214
03d5b991
AN
5215 local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5216 local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5217
6a886de0
HC
5218 n = btf__type_cnt(targ_btf);
5219 for (i = targ_start_id; i < n; i++) {
ddc7c304 5220 t = btf__type_by_id(targ_btf, i);
03d5b991 5221 if (btf_kind(t) != btf_kind(local_t))
ddc7c304
AN
5222 continue;
5223
3fc32f40
AN
5224 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5225 if (str_is_empty(targ_name))
d121e1d3
AN
5226 continue;
5227
ddc7c304
AN
5228 targ_essent_len = bpf_core_essential_name_len(targ_name);
5229 if (targ_essent_len != local_essent_len)
5230 continue;
5231
03d5b991 5232 if (strncmp(local_name, targ_name, local_essent_len) != 0)
0f7515ca
AN
5233 continue;
5234
5235 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
03d5b991
AN
5236 local_cand->id, btf_kind_str(local_t),
5237 local_name, i, btf_kind_str(t), targ_name,
0f7515ca
AN
5238 targ_btf_name);
5239 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5240 sizeof(*cands->cands));
5241 if (!new_cands)
5242 return -ENOMEM;
5243
5244 cand = &new_cands[cands->len];
5245 cand->btf = targ_btf;
0f7515ca
AN
5246 cand->id = i;
5247
5248 cands->cands = new_cands;
5249 cands->len++;
ddc7c304 5250 }
0f7515ca
AN
5251 return 0;
5252}
5253
4f33a53d
AN
5254static int load_module_btfs(struct bpf_object *obj)
5255{
5256 struct bpf_btf_info info;
5257 struct module_btf *mod_btf;
5258 struct btf *btf;
5259 char name[64];
5260 __u32 id = 0, len;
5261 int err, fd;
5262
5263 if (obj->btf_modules_loaded)
5264 return 0;
5265
67234743
AS
5266 if (obj->gen_loader)
5267 return 0;
5268
4f33a53d
AN
5269 /* don't do this again, even if we find no module BTFs */
5270 obj->btf_modules_loaded = true;
5271
5272 /* kernel too old to support module BTFs */
9ca1f56a 5273 if (!kernel_supports(obj, FEAT_MODULE_BTF))
4f33a53d
AN
5274 return 0;
5275
5276 while (true) {
5277 err = bpf_btf_get_next_id(id, &id);
5278 if (err && errno == ENOENT)
5279 return 0;
5280 if (err) {
5281 err = -errno;
5282 pr_warn("failed to iterate BTF objects: %d\n", err);
5283 return err;
ddc7c304 5284 }
4f33a53d
AN
5285
5286 fd = bpf_btf_get_fd_by_id(id);
5287 if (fd < 0) {
5288 if (errno == ENOENT)
5289 continue; /* expected race: BTF was unloaded */
5290 err = -errno;
5291 pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5292 return err;
5293 }
5294
5295 len = sizeof(info);
5296 memset(&info, 0, sizeof(info));
5297 info.name = ptr_to_u64(name);
5298 info.name_len = sizeof(name);
5299
5300 err = bpf_obj_get_info_by_fd(fd, &info, &len);
5301 if (err) {
5302 err = -errno;
5303 pr_warn("failed to get BTF object #%d info: %d\n", id, err);
91abb4a6 5304 goto err_out;
4f33a53d
AN
5305 }
5306
5307 /* ignore non-module BTFs */
5308 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5309 close(fd);
5310 continue;
5311 }
5312
5313 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
e9fc3ce9
AN
5314 err = libbpf_get_error(btf);
5315 if (err) {
5316 pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5317 name, id, err);
91abb4a6 5318 goto err_out;
4f33a53d
AN
5319 }
5320
3b029e06
AN
5321 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5322 sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
4f33a53d 5323 if (err)
91abb4a6 5324 goto err_out;
4f33a53d
AN
5325
5326 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5327
5328 mod_btf->btf = btf;
5329 mod_btf->id = id;
91abb4a6 5330 mod_btf->fd = fd;
4f33a53d 5331 mod_btf->name = strdup(name);
91abb4a6
AN
5332 if (!mod_btf->name) {
5333 err = -ENOMEM;
5334 goto err_out;
5335 }
5336 continue;
5337
5338err_out:
5339 close(fd);
5340 return err;
ddc7c304 5341 }
4f33a53d
AN
5342
5343 return 0;
5344}
5345
301ba4d7 5346static struct bpf_core_cand_list *
0f7515ca
AN
5347bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5348{
301ba4d7
AS
5349 struct bpf_core_cand local_cand = {};
5350 struct bpf_core_cand_list *cands;
4f33a53d 5351 const struct btf *main_btf;
03d5b991
AN
5352 const struct btf_type *local_t;
5353 const char *local_name;
0f7515ca 5354 size_t local_essent_len;
4f33a53d 5355 int err, i;
0f7515ca
AN
5356
5357 local_cand.btf = local_btf;
03d5b991
AN
5358 local_cand.id = local_type_id;
5359 local_t = btf__type_by_id(local_btf, local_type_id);
5360 if (!local_t)
0f7515ca
AN
5361 return ERR_PTR(-EINVAL);
5362
03d5b991
AN
5363 local_name = btf__name_by_offset(local_btf, local_t->name_off);
5364 if (str_is_empty(local_name))
0f7515ca 5365 return ERR_PTR(-EINVAL);
03d5b991 5366 local_essent_len = bpf_core_essential_name_len(local_name);
0f7515ca
AN
5367
5368 cands = calloc(1, sizeof(*cands));
5369 if (!cands)
5370 return ERR_PTR(-ENOMEM);
5371
5372 /* Attempt to find target candidates in vmlinux BTF first */
4f33a53d
AN
5373 main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5374 err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5375 if (err)
5376 goto err_out;
5377
5378 /* if vmlinux BTF has any candidate, don't got for module BTFs */
5379 if (cands->len)
5380 return cands;
5381
5382 /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5383 if (obj->btf_vmlinux_override)
5384 return cands;
5385
5386 /* now look through module BTFs, trying to still find candidates */
5387 err = load_module_btfs(obj);
5388 if (err)
5389 goto err_out;
5390
5391 for (i = 0; i < obj->btf_module_cnt; i++) {
5392 err = bpf_core_add_cands(&local_cand, local_essent_len,
5393 obj->btf_modules[i].btf,
5394 obj->btf_modules[i].name,
6a886de0 5395 btf__type_cnt(obj->btf_vmlinux),
4f33a53d
AN
5396 cands);
5397 if (err)
5398 goto err_out;
0f7515ca
AN
5399 }
5400
5401 return cands;
ddc7c304 5402err_out:
4f33a53d 5403 bpf_core_free_cands(cands);
ddc7c304
AN
5404 return ERR_PTR(err);
5405}
5406
3fc32f40
AN
5407/* Check local and target types for compatibility. This check is used for
5408 * type-based CO-RE relocations and follow slightly different rules than
5409 * field-based relocations. This function assumes that root types were already
5410 * checked for name match. Beyond that initial root-level name check, names
5411 * are completely ignored. Compatibility rules are as follows:
5412 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5413 * kind should match for local and target types (i.e., STRUCT is not
5414 * compatible with UNION);
5415 * - for ENUMs, the size is ignored;
5416 * - for INT, size and signedness are ignored;
5417 * - for ARRAY, dimensionality is ignored, element types are checked for
5418 * compatibility recursively;
5419 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
5420 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5421 * - FUNC_PROTOs are compatible if they have compatible signature: same
5422 * number of input args and compatible return and argument types.
5423 * These rules are not set in stone and probably will be adjusted as we get
5424 * more experience with using BPF CO-RE relocations.
5425 */
b0588390
AS
5426int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5427 const struct btf *targ_btf, __u32 targ_id)
3fc32f40
AN
5428{
5429 const struct btf_type *local_type, *targ_type;
5430 int depth = 32; /* max recursion depth */
5431
5432 /* caller made sure that names match (ignoring flavor suffix) */
5433 local_type = btf__type_by_id(local_btf, local_id);
f872e4bc 5434 targ_type = btf__type_by_id(targ_btf, targ_id);
3fc32f40
AN
5435 if (btf_kind(local_type) != btf_kind(targ_type))
5436 return 0;
5437
5438recur:
5439 depth--;
5440 if (depth < 0)
5441 return -EINVAL;
5442
5443 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
5444 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
5445 if (!local_type || !targ_type)
5446 return -EINVAL;
5447
5448 if (btf_kind(local_type) != btf_kind(targ_type))
5449 return 0;
5450
5451 switch (btf_kind(local_type)) {
5452 case BTF_KIND_UNKN:
5453 case BTF_KIND_STRUCT:
5454 case BTF_KIND_UNION:
5455 case BTF_KIND_ENUM:
5456 case BTF_KIND_FWD:
5457 return 1;
5458 case BTF_KIND_INT:
5459 /* just reject deprecated bitfield-like integers; all other
5460 * integers are by default compatible between each other
5461 */
5462 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
5463 case BTF_KIND_PTR:
5464 local_id = local_type->type;
5465 targ_id = targ_type->type;
5466 goto recur;
5467 case BTF_KIND_ARRAY:
5468 local_id = btf_array(local_type)->type;
5469 targ_id = btf_array(targ_type)->type;
5470 goto recur;
5471 case BTF_KIND_FUNC_PROTO: {
5472 struct btf_param *local_p = btf_params(local_type);
5473 struct btf_param *targ_p = btf_params(targ_type);
5474 __u16 local_vlen = btf_vlen(local_type);
5475 __u16 targ_vlen = btf_vlen(targ_type);
5476 int i, err;
5477
5478 if (local_vlen != targ_vlen)
5479 return 0;
5480
5481 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
5482 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
5483 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
5484 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
5485 if (err <= 0)
5486 return err;
5487 }
5488
5489 /* tail recurse for return type check */
5490 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
5491 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
5492 goto recur;
5493 }
5494 default:
5495 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
5496 btf_kind_str(local_type), local_id, targ_id);
5497 return 0;
5498 }
5499}
5500
ddc7c304
AN
5501static size_t bpf_core_hash_fn(const void *key, void *ctx)
5502{
5503 return (size_t)key;
5504}
5505
5506static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5507{
5508 return k1 == k2;
5509}
5510
5511static void *u32_as_hash_key(__u32 x)
5512{
5513 return (void *)(uintptr_t)x;
5514}
5515
d0e92887
AS
5516static int record_relo_core(struct bpf_program *prog,
5517 const struct bpf_core_relo *core_relo, int insn_idx)
5518{
5519 struct reloc_desc *relos, *relo;
5520
5521 relos = libbpf_reallocarray(prog->reloc_desc,
5522 prog->nr_reloc + 1, sizeof(*relos));
5523 if (!relos)
5524 return -ENOMEM;
5525 relo = &relos[prog->nr_reloc];
5526 relo->type = RELO_CORE;
5527 relo->insn_idx = insn_idx;
5528 relo->core_relo = core_relo;
5529 prog->reloc_desc = relos;
5530 prog->nr_reloc++;
5531 return 0;
5532}
5533
3ee4f533
AS
5534static int bpf_core_apply_relo(struct bpf_program *prog,
5535 const struct bpf_core_relo *relo,
5536 int relo_idx,
5537 const struct btf *local_btf,
5538 struct hashmap *cand_cache)
5539{
78c1f8d0 5540 struct bpf_core_spec specs_scratch[3] = {};
3ee4f533 5541 const void *type_key = u32_as_hash_key(relo->type_id);
301ba4d7 5542 struct bpf_core_cand_list *cands = NULL;
3ee4f533
AS
5543 const char *prog_name = prog->name;
5544 const struct btf_type *local_type;
5545 const char *local_name;
5546 __u32 local_id = relo->type_id;
5547 struct bpf_insn *insn;
5548 int insn_idx, err;
5549
5550 if (relo->insn_off % BPF_INSN_SZ)
5551 return -EINVAL;
5552 insn_idx = relo->insn_off / BPF_INSN_SZ;
5553 /* adjust insn_idx from section frame of reference to the local
5554 * program's frame of reference; (sub-)program code is not yet
5555 * relocated, so it's enough to just subtract in-section offset
5556 */
5557 insn_idx = insn_idx - prog->sec_insn_off;
de5d0dce 5558 if (insn_idx >= prog->insns_cnt)
3ee4f533
AS
5559 return -EINVAL;
5560 insn = &prog->insns[insn_idx];
5561
5562 local_type = btf__type_by_id(local_btf, local_id);
5563 if (!local_type)
5564 return -EINVAL;
5565
5566 local_name = btf__name_by_offset(local_btf, local_type->name_off);
5567 if (!local_name)
5568 return -EINVAL;
5569
5570 if (prog->obj->gen_loader) {
d0e92887
AS
5571 const char *spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
5572
5573 pr_debug("record_relo_core: prog %td insn[%d] %s %s %s final insn_idx %d\n",
3ee4f533 5574 prog - prog->obj->programs, relo->insn_off / 8,
d0e92887
AS
5575 btf_kind_str(local_type), local_name, spec_str, insn_idx);
5576 return record_relo_core(prog, relo, insn_idx);
3ee4f533
AS
5577 }
5578
46334a0c 5579 if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
3ee4f533
AS
5580 !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5581 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5582 if (IS_ERR(cands)) {
5583 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5584 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5585 local_name, PTR_ERR(cands));
5586 return PTR_ERR(cands);
5587 }
5588 err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5589 if (err) {
5590 bpf_core_free_cands(cands);
5591 return err;
5592 }
5593 }
5594
78c1f8d0
AS
5595 return bpf_core_apply_relo_insn(prog_name, insn, insn_idx, relo,
5596 relo_idx, local_btf, cands, specs_scratch);
3ee4f533
AS
5597}
5598
ddc7c304 5599static int
28b93c64 5600bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
ddc7c304
AN
5601{
5602 const struct btf_ext_info_sec *sec;
28b93c64 5603 const struct bpf_core_relo *rec;
ddc7c304
AN
5604 const struct btf_ext_info *seg;
5605 struct hashmap_entry *entry;
5606 struct hashmap *cand_cache = NULL;
5607 struct bpf_program *prog;
ddc7c304 5608 const char *sec_name;
db2b8b06 5609 int i, err = 0, insn_idx, sec_idx;
ddc7c304 5610
28b93c64
AN
5611 if (obj->btf_ext->core_relo_info.len == 0)
5612 return 0;
5613
0f7515ca
AN
5614 if (targ_btf_path) {
5615 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
e9fc3ce9
AN
5616 err = libbpf_get_error(obj->btf_vmlinux_override);
5617 if (err) {
0f7515ca
AN
5618 pr_warn("failed to parse target BTF: %d\n", err);
5619 return err;
5620 }
ddc7c304
AN
5621 }
5622
5623 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5624 if (IS_ERR(cand_cache)) {
5625 err = PTR_ERR(cand_cache);
5626 goto out;
5627 }
5628
28b93c64 5629 seg = &obj->btf_ext->core_relo_info;
ddc7c304
AN
5630 for_each_btf_ext_sec(seg, sec) {
5631 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5632 if (str_is_empty(sec_name)) {
5633 err = -EINVAL;
5634 goto out;
5635 }
db2b8b06
AN
5636 /* bpf_object's ELF is gone by now so it's not easy to find
5637 * section index by section name, but we can find *any*
5638 * bpf_program within desired section name and use it's
5639 * prog->sec_idx to do a proper search by section index and
5640 * instruction offset
5641 */
9c82a63c
AN
5642 prog = NULL;
5643 for (i = 0; i < obj->nr_programs; i++) {
db2b8b06 5644 prog = &obj->programs[i];
52109584 5645 if (strcmp(prog->sec_name, sec_name) == 0)
9c82a63c 5646 break;
9c82a63c 5647 }
ddc7c304 5648 if (!prog) {
db2b8b06
AN
5649 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5650 return -ENOENT;
ddc7c304 5651 }
db2b8b06 5652 sec_idx = prog->sec_idx;
ddc7c304 5653
9c0f8cbd 5654 pr_debug("sec '%s': found %d CO-RE relocations\n",
ddc7c304
AN
5655 sec_name, sec->num_info);
5656
5657 for_each_btf_ext_rec(seg, sec, i, rec) {
db2b8b06
AN
5658 insn_idx = rec->insn_off / BPF_INSN_SZ;
5659 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5660 if (!prog) {
5661 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5662 sec_name, insn_idx, i);
5663 err = -EINVAL;
5664 goto out;
5665 }
47f7cf63
AN
5666 /* no need to apply CO-RE relocation if the program is
5667 * not going to be loaded
5668 */
5669 if (!prog->load)
5670 continue;
db2b8b06 5671
0f7515ca 5672 err = bpf_core_apply_relo(prog, rec, i, obj->btf, cand_cache);
ddc7c304 5673 if (err) {
be18010e 5674 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
9c0f8cbd 5675 prog->name, i, err);
ddc7c304
AN
5676 goto out;
5677 }
5678 }
5679 }
5680
5681out:
4f33a53d 5682 /* obj->btf_vmlinux and module BTFs are freed after object load */
0f7515ca
AN
5683 btf__free(obj->btf_vmlinux_override);
5684 obj->btf_vmlinux_override = NULL;
5685
ddc7c304
AN
5686 if (!IS_ERR_OR_NULL(cand_cache)) {
5687 hashmap__for_each_entry(cand_cache, entry, i) {
5688 bpf_core_free_cands(entry->value);
5689 }
5690 hashmap__free(cand_cache);
5691 }
5692 return err;
5693}
5694
c3c55696
AN
5695/* Relocate data references within program code:
5696 * - map references;
5697 * - global variable references;
5698 * - extern references.
5699 */
48cca7e4 5700static int
c3c55696 5701bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
8a47a6c5 5702{
c3c55696 5703 int i;
8a47a6c5
WN
5704
5705 for (i = 0; i < prog->nr_reloc; i++) {
53f8dd43 5706 struct reloc_desc *relo = &prog->reloc_desc[i];
166750bc 5707 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
2e33efe3 5708 struct extern_desc *ext;
8a47a6c5 5709
166750bc
AN
5710 switch (relo->type) {
5711 case RELO_LD64:
e2fa0156
AS
5712 if (obj->gen_loader) {
5713 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5714 insn[0].imm = relo->map_idx;
5715 } else {
5716 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5717 insn[0].imm = obj->maps[relo->map_idx].fd;
5718 }
166750bc
AN
5719 break;
5720 case RELO_DATA:
166750bc 5721 insn[1].imm = insn[0].imm + relo->sym_off;
e2fa0156
AS
5722 if (obj->gen_loader) {
5723 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5724 insn[0].imm = relo->map_idx;
5725 } else {
16e0c35c
AN
5726 const struct bpf_map *map = &obj->maps[relo->map_idx];
5727
229fae38 5728 if (map->skipped) {
16e0c35c
AN
5729 pr_warn("prog '%s': relo #%d: kernel doesn't support global data\n",
5730 prog->name, i);
5731 return -ENOTSUP;
5732 }
e2fa0156
AS
5733 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5734 insn[0].imm = obj->maps[relo->map_idx].fd;
5735 }
166750bc 5736 break;
0c091e5c 5737 case RELO_EXTERN_VAR:
2e33efe3 5738 ext = &obj->externs[relo->sym_off];
1c0c7074 5739 if (ext->type == EXT_KCFG) {
e2fa0156
AS
5740 if (obj->gen_loader) {
5741 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5742 insn[0].imm = obj->kconfig_map_idx;
5743 } else {
5744 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5745 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5746 }
1c0c7074
AN
5747 insn[1].imm = ext->kcfg.data_off;
5748 } else /* EXT_KSYM */ {
2211c825 5749 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
d370bbe1 5750 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
284d2587
AN
5751 insn[0].imm = ext->ksym.kernel_btf_id;
5752 insn[1].imm = ext->ksym.kernel_btf_obj_fd;
2211c825 5753 } else { /* typeless ksyms or unresolved typed ksyms */
d370bbe1
HL
5754 insn[0].imm = (__u32)ext->ksym.addr;
5755 insn[1].imm = ext->ksym.addr >> 32;
5756 }
1c0c7074 5757 }
166750bc 5758 break;
5bd022ec
MKL
5759 case RELO_EXTERN_FUNC:
5760 ext = &obj->externs[relo->sym_off];
5761 insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
466b2e13
KKD
5762 if (ext->is_set) {
5763 insn[0].imm = ext->ksym.kernel_btf_id;
5764 insn[0].off = ext->ksym.btf_fd_idx;
5765 } else { /* unresolved weak kfunc */
5766 insn[0].imm = 0;
5767 insn[0].off = 0;
5768 }
5bd022ec 5769 break;
53eddb5e 5770 case RELO_SUBPROG_ADDR:
b1268826
AS
5771 if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5772 pr_warn("prog '%s': relo #%d: bad insn\n",
5773 prog->name, i);
5774 return -EINVAL;
5775 }
5776 /* handled already */
53eddb5e 5777 break;
166750bc 5778 case RELO_CALL:
b1268826 5779 /* handled already */
166750bc 5780 break;
d0e92887
AS
5781 case RELO_CORE:
5782 /* will be handled by bpf_program_record_relos() */
5783 break;
166750bc 5784 default:
9c0f8cbd
AN
5785 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5786 prog->name, i, relo->type);
166750bc 5787 return -EINVAL;
8a47a6c5 5788 }
8a47a6c5
WN
5789 }
5790
c3c55696
AN
5791 return 0;
5792}
5793
8505e870
AN
5794static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5795 const struct bpf_program *prog,
5796 const struct btf_ext_info *ext_info,
5797 void **prog_info, __u32 *prog_rec_cnt,
5798 __u32 *prog_rec_sz)
5799{
5800 void *copy_start = NULL, *copy_end = NULL;
5801 void *rec, *rec_end, *new_prog_info;
5802 const struct btf_ext_info_sec *sec;
5803 size_t old_sz, new_sz;
5804 const char *sec_name;
5805 int i, off_adj;
5806
5807 for_each_btf_ext_sec(ext_info, sec) {
5808 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5809 if (!sec_name)
5810 return -EINVAL;
52109584 5811 if (strcmp(sec_name, prog->sec_name) != 0)
8505e870
AN
5812 continue;
5813
5814 for_each_btf_ext_rec(ext_info, sec, i, rec) {
5815 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5816
5817 if (insn_off < prog->sec_insn_off)
5818 continue;
5819 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5820 break;
5821
5822 if (!copy_start)
5823 copy_start = rec;
5824 copy_end = rec + ext_info->rec_size;
5825 }
5826
5827 if (!copy_start)
5828 return -ENOENT;
5829
5830 /* append func/line info of a given (sub-)program to the main
5831 * program func/line info
5832 */
8eb62958 5833 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
8505e870
AN
5834 new_sz = old_sz + (copy_end - copy_start);
5835 new_prog_info = realloc(*prog_info, new_sz);
5836 if (!new_prog_info)
5837 return -ENOMEM;
5838 *prog_info = new_prog_info;
5839 *prog_rec_cnt = new_sz / ext_info->rec_size;
5840 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5841
5842 /* Kernel instruction offsets are in units of 8-byte
5843 * instructions, while .BTF.ext instruction offsets generated
5844 * by Clang are in units of bytes. So convert Clang offsets
5845 * into kernel offsets and adjust offset according to program
5846 * relocated position.
5847 */
5848 off_adj = prog->sub_insn_off - prog->sec_insn_off;
5849 rec = new_prog_info + old_sz;
5850 rec_end = new_prog_info + new_sz;
5851 for (; rec < rec_end; rec += ext_info->rec_size) {
5852 __u32 *insn_off = rec;
5853
5854 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5855 }
5856 *prog_rec_sz = ext_info->rec_size;
5857 return 0;
5858 }
5859
5860 return -ENOENT;
5861}
5862
5863static int
5864reloc_prog_func_and_line_info(const struct bpf_object *obj,
5865 struct bpf_program *main_prog,
5866 const struct bpf_program *prog)
5867{
5868 int err;
5869
5870 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5871 * supprot func/line info
5872 */
9ca1f56a 5873 if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
8505e870
AN
5874 return 0;
5875
5876 /* only attempt func info relocation if main program's func_info
5877 * relocation was successful
5878 */
5879 if (main_prog != prog && !main_prog->func_info)
5880 goto line_info;
5881
5882 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5883 &main_prog->func_info,
5884 &main_prog->func_info_cnt,
5885 &main_prog->func_info_rec_size);
5886 if (err) {
5887 if (err != -ENOENT) {
5888 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5889 prog->name, err);
5890 return err;
5891 }
5892 if (main_prog->func_info) {
5893 /*
5894 * Some info has already been found but has problem
5895 * in the last btf_ext reloc. Must have to error out.
5896 */
5897 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5898 return err;
5899 }
5900 /* Have problem loading the very first info. Ignore the rest. */
5901 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5902 prog->name);
5903 }
5904
5905line_info:
5906 /* don't relocate line info if main program's relocation failed */
5907 if (main_prog != prog && !main_prog->line_info)
5908 return 0;
5909
5910 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5911 &main_prog->line_info,
5912 &main_prog->line_info_cnt,
5913 &main_prog->line_info_rec_size);
5914 if (err) {
5915 if (err != -ENOENT) {
5916 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5917 prog->name, err);
5918 return err;
5919 }
5920 if (main_prog->line_info) {
5921 /*
5922 * Some info has already been found but has problem
5923 * in the last btf_ext reloc. Must have to error out.
5924 */
5925 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
5926 return err;
5927 }
5928 /* Have problem loading the very first info. Ignore the rest. */
5929 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
5930 prog->name);
5931 }
5932 return 0;
5933}
5934
c3c55696
AN
5935static int cmp_relo_by_insn_idx(const void *key, const void *elem)
5936{
5937 size_t insn_idx = *(const size_t *)key;
5938 const struct reloc_desc *relo = elem;
5939
5940 if (insn_idx == relo->insn_idx)
5941 return 0;
5942 return insn_idx < relo->insn_idx ? -1 : 1;
5943}
5944
5945static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
5946{
2a6a9bf2
AN
5947 if (!prog->nr_reloc)
5948 return NULL;
c3c55696
AN
5949 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
5950 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
5951}
5952
b1268826
AS
5953static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
5954{
5955 int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
5956 struct reloc_desc *relos;
5957 int i;
5958
5959 if (main_prog == subprog)
5960 return 0;
5961 relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
5962 if (!relos)
5963 return -ENOMEM;
2a6a9bf2
AN
5964 if (subprog->nr_reloc)
5965 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
5966 sizeof(*relos) * subprog->nr_reloc);
b1268826
AS
5967
5968 for (i = main_prog->nr_reloc; i < new_cnt; i++)
5969 relos[i].insn_idx += subprog->sub_insn_off;
5970 /* After insn_idx adjustment the 'relos' array is still sorted
5971 * by insn_idx and doesn't break bsearch.
5972 */
5973 main_prog->reloc_desc = relos;
5974 main_prog->nr_reloc = new_cnt;
5975 return 0;
5976}
5977
c3c55696
AN
5978static int
5979bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
5980 struct bpf_program *prog)
5981{
5982 size_t sub_insn_idx, insn_idx, new_cnt;
5983 struct bpf_program *subprog;
5984 struct bpf_insn *insns, *insn;
5985 struct reloc_desc *relo;
5986 int err;
5987
5988 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
5989 if (err)
5990 return err;
5991
5992 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
5993 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
53eddb5e 5994 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
c3c55696
AN
5995 continue;
5996
5997 relo = find_prog_insn_relo(prog, insn_idx);
b1268826
AS
5998 if (relo && relo->type == RELO_EXTERN_FUNC)
5999 /* kfunc relocations will be handled later
6000 * in bpf_object__relocate_data()
6001 */
6002 continue;
53eddb5e 6003 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
c3c55696
AN
6004 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6005 prog->name, insn_idx, relo->type);
6006 return -LIBBPF_ERRNO__RELOC;
6007 }
6008 if (relo) {
6009 /* sub-program instruction index is a combination of
6010 * an offset of a symbol pointed to by relocation and
6011 * call instruction's imm field; for global functions,
6012 * call always has imm = -1, but for static functions
6013 * relocation is against STT_SECTION and insn->imm
6014 * points to a start of a static function
53eddb5e
YS
6015 *
6016 * for subprog addr relocation, the relo->sym_off + insn->imm is
6017 * the byte offset in the corresponding section.
c3c55696 6018 */
53eddb5e
YS
6019 if (relo->type == RELO_CALL)
6020 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6021 else
6022 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6023 } else if (insn_is_pseudo_func(insn)) {
6024 /*
6025 * RELO_SUBPROG_ADDR relo is always emitted even if both
6026 * functions are in the same section, so it shouldn't reach here.
6027 */
6028 pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6029 prog->name, insn_idx);
6030 return -LIBBPF_ERRNO__RELOC;
c3c55696
AN
6031 } else {
6032 /* if subprogram call is to a static function within
6033 * the same ELF section, there won't be any relocation
6034 * emitted, but it also means there is no additional
6035 * offset necessary, insns->imm is relative to
6036 * instruction's original position within the section
6037 */
6038 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6039 }
6040
6041 /* we enforce that sub-programs should be in .text section */
6042 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6043 if (!subprog) {
6044 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6045 prog->name);
6046 return -LIBBPF_ERRNO__RELOC;
6047 }
6048
6049 /* if it's the first call instruction calling into this
6050 * subprogram (meaning this subprog hasn't been processed
6051 * yet) within the context of current main program:
6052 * - append it at the end of main program's instructions blog;
6053 * - process is recursively, while current program is put on hold;
6054 * - if that subprogram calls some other not yet processes
6055 * subprogram, same thing will happen recursively until
6056 * there are no more unprocesses subprograms left to append
6057 * and relocate.
6058 */
6059 if (subprog->sub_insn_off == 0) {
6060 subprog->sub_insn_off = main_prog->insns_cnt;
6061
6062 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6063 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6064 if (!insns) {
6065 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6066 return -ENOMEM;
6067 }
6068 main_prog->insns = insns;
6069 main_prog->insns_cnt = new_cnt;
6070
6071 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6072 subprog->insns_cnt * sizeof(*insns));
6073
6074 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6075 main_prog->name, subprog->insns_cnt, subprog->name);
6076
b1268826
AS
6077 /* The subprog insns are now appended. Append its relos too. */
6078 err = append_subprog_relos(main_prog, subprog);
6079 if (err)
6080 return err;
c3c55696
AN
6081 err = bpf_object__reloc_code(obj, main_prog, subprog);
6082 if (err)
6083 return err;
6084 }
6085
6086 /* main_prog->insns memory could have been re-allocated, so
6087 * calculate pointer again
6088 */
6089 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6090 /* calculate correct instruction position within current main
6091 * prog; each main prog can have a different set of
6092 * subprograms appended (potentially in different order as
6093 * well), so position of any subprog can be different for
6094 * different main programs */
6095 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6096
c3c55696
AN
6097 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6098 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6099 }
6100
6101 return 0;
6102}
6103
6104/*
6105 * Relocate sub-program calls.
6106 *
6107 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6108 * main prog) is processed separately. For each subprog (non-entry functions,
6109 * that can be called from either entry progs or other subprogs) gets their
6110 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6111 * hasn't been yet appended and relocated within current main prog. Once its
6112 * relocated, sub_insn_off will point at the position within current main prog
6113 * where given subprog was appended. This will further be used to relocate all
6114 * the call instructions jumping into this subprog.
6115 *
6116 * We start with main program and process all call instructions. If the call
6117 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6118 * is zero), subprog instructions are appended at the end of main program's
6119 * instruction array. Then main program is "put on hold" while we recursively
6120 * process newly appended subprogram. If that subprogram calls into another
6121 * subprogram that hasn't been appended, new subprogram is appended again to
6122 * the *main* prog's instructions (subprog's instructions are always left
6123 * untouched, as they need to be in unmodified state for subsequent main progs
6124 * and subprog instructions are always sent only as part of a main prog) and
6125 * the process continues recursively. Once all the subprogs called from a main
6126 * prog or any of its subprogs are appended (and relocated), all their
6127 * positions within finalized instructions array are known, so it's easy to
6128 * rewrite call instructions with correct relative offsets, corresponding to
6129 * desired target subprog.
6130 *
6131 * Its important to realize that some subprogs might not be called from some
6132 * main prog and any of its called/used subprogs. Those will keep their
6133 * subprog->sub_insn_off as zero at all times and won't be appended to current
6134 * main prog and won't be relocated within the context of current main prog.
6135 * They might still be used from other main progs later.
6136 *
6137 * Visually this process can be shown as below. Suppose we have two main
6138 * programs mainA and mainB and BPF object contains three subprogs: subA,
6139 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6140 * subC both call subB:
6141 *
6142 * +--------+ +-------+
6143 * | v v |
6144 * +--+---+ +--+-+-+ +---+--+
6145 * | subA | | subB | | subC |
6146 * +--+---+ +------+ +---+--+
6147 * ^ ^
6148 * | |
6149 * +---+-------+ +------+----+
6150 * | mainA | | mainB |
6151 * +-----------+ +-----------+
6152 *
6153 * We'll start relocating mainA, will find subA, append it and start
6154 * processing sub A recursively:
6155 *
6156 * +-----------+------+
6157 * | mainA | subA |
6158 * +-----------+------+
6159 *
6160 * At this point we notice that subB is used from subA, so we append it and
6161 * relocate (there are no further subcalls from subB):
6162 *
6163 * +-----------+------+------+
6164 * | mainA | subA | subB |
6165 * +-----------+------+------+
6166 *
6167 * At this point, we relocate subA calls, then go one level up and finish with
6168 * relocatin mainA calls. mainA is done.
6169 *
6170 * For mainB process is similar but results in different order. We start with
6171 * mainB and skip subA and subB, as mainB never calls them (at least
6172 * directly), but we see subC is needed, so we append and start processing it:
6173 *
6174 * +-----------+------+
6175 * | mainB | subC |
6176 * +-----------+------+
6177 * Now we see subC needs subB, so we go back to it, append and relocate it:
6178 *
6179 * +-----------+------+------+
6180 * | mainB | subC | subB |
6181 * +-----------+------+------+
6182 *
6183 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6184 */
6185static int
6186bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6187{
6188 struct bpf_program *subprog;
d3d93e34 6189 int i, err;
c3c55696 6190
c3c55696
AN
6191 /* mark all subprogs as not relocated (yet) within the context of
6192 * current main program
6193 */
6194 for (i = 0; i < obj->nr_programs; i++) {
6195 subprog = &obj->programs[i];
6196 if (!prog_is_subprog(obj, subprog))
6197 continue;
6198
6199 subprog->sub_insn_off = 0;
c3c55696
AN
6200 }
6201
6202 err = bpf_object__reloc_code(obj, prog, prog);
6203 if (err)
6204 return err;
6205
6206
8a47a6c5
WN
6207 return 0;
6208}
6209
67234743
AS
6210static void
6211bpf_object__free_relocs(struct bpf_object *obj)
6212{
6213 struct bpf_program *prog;
6214 int i;
6215
6216 /* free up relocation descriptors */
6217 for (i = 0; i < obj->nr_programs; i++) {
6218 prog = &obj->programs[i];
6219 zfree(&prog->reloc_desc);
6220 prog->nr_reloc = 0;
6221 }
6222}
6223
d0e92887
AS
6224static int cmp_relocs(const void *_a, const void *_b)
6225{
6226 const struct reloc_desc *a = _a;
6227 const struct reloc_desc *b = _b;
6228
6229 if (a->insn_idx != b->insn_idx)
6230 return a->insn_idx < b->insn_idx ? -1 : 1;
6231
6232 /* no two relocations should have the same insn_idx, but ... */
6233 if (a->type != b->type)
6234 return a->type < b->type ? -1 : 1;
6235
6236 return 0;
6237}
6238
6239static void bpf_object__sort_relos(struct bpf_object *obj)
6240{
6241 int i;
6242
6243 for (i = 0; i < obj->nr_programs; i++) {
6244 struct bpf_program *p = &obj->programs[i];
6245
6246 if (!p->nr_reloc)
6247 continue;
6248
6249 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6250 }
6251}
6252
8a47a6c5 6253static int
ddc7c304 6254bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
8a47a6c5
WN
6255{
6256 struct bpf_program *prog;
b1268826 6257 size_t i, j;
8a47a6c5
WN
6258 int err;
6259
ddc7c304
AN
6260 if (obj->btf_ext) {
6261 err = bpf_object__relocate_core(obj, targ_btf_path);
6262 if (err) {
be18010e
KW
6263 pr_warn("failed to perform CO-RE relocations: %d\n",
6264 err);
ddc7c304
AN
6265 return err;
6266 }
d0e92887
AS
6267 if (obj->gen_loader)
6268 bpf_object__sort_relos(obj);
ddc7c304 6269 }
b1268826
AS
6270
6271 /* Before relocating calls pre-process relocations and mark
6272 * few ld_imm64 instructions that points to subprogs.
6273 * Otherwise bpf_object__reloc_code() later would have to consider
6274 * all ld_imm64 insns as relocation candidates. That would
6275 * reduce relocation speed, since amount of find_prog_insn_relo()
6276 * would increase and most of them will fail to find a relo.
9173cac3
AN
6277 */
6278 for (i = 0; i < obj->nr_programs; i++) {
6279 prog = &obj->programs[i];
b1268826
AS
6280 for (j = 0; j < prog->nr_reloc; j++) {
6281 struct reloc_desc *relo = &prog->reloc_desc[j];
6282 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6283
6284 /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6285 if (relo->type == RELO_SUBPROG_ADDR)
6286 insn[0].src_reg = BPF_PSEUDO_FUNC;
9173cac3 6287 }
9173cac3 6288 }
b1268826
AS
6289
6290 /* relocate subprogram calls and append used subprograms to main
c3c55696
AN
6291 * programs; each copy of subprogram code needs to be relocated
6292 * differently for each main program, because its code location might
b1268826
AS
6293 * have changed.
6294 * Append subprog relos to main programs to allow data relos to be
6295 * processed after text is completely relocated.
9173cac3 6296 */
8a47a6c5
WN
6297 for (i = 0; i < obj->nr_programs; i++) {
6298 prog = &obj->programs[i];
c3c55696
AN
6299 /* sub-program's sub-calls are relocated within the context of
6300 * its main program only
6301 */
6302 if (prog_is_subprog(obj, prog))
9173cac3 6303 continue;
16e0c35c
AN
6304 if (!prog->load)
6305 continue;
8a47a6c5 6306
c3c55696 6307 err = bpf_object__relocate_calls(obj, prog);
8a47a6c5 6308 if (err) {
9c0f8cbd
AN
6309 pr_warn("prog '%s': failed to relocate calls: %d\n",
6310 prog->name, err);
8a47a6c5
WN
6311 return err;
6312 }
6313 }
b1268826
AS
6314 /* Process data relos for main programs */
6315 for (i = 0; i < obj->nr_programs; i++) {
6316 prog = &obj->programs[i];
6317 if (prog_is_subprog(obj, prog))
6318 continue;
16e0c35c
AN
6319 if (!prog->load)
6320 continue;
b1268826
AS
6321 err = bpf_object__relocate_data(obj, prog);
6322 if (err) {
6323 pr_warn("prog '%s': failed to relocate data references: %d\n",
6324 prog->name, err);
6325 return err;
6326 }
6327 }
67234743
AS
6328 if (!obj->gen_loader)
6329 bpf_object__free_relocs(obj);
8a47a6c5
WN
6330 return 0;
6331}
6332
646f02ff 6333static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 6334 Elf64_Shdr *shdr, Elf_Data *data);
646f02ff
AN
6335
6336static int bpf_object__collect_map_relos(struct bpf_object *obj,
ad23b723 6337 Elf64_Shdr *shdr, Elf_Data *data)
646f02ff 6338{
15728ad3
AN
6339 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6340 int i, j, nrels, new_sz;
063e6881 6341 const struct btf_var_secinfo *vi = NULL;
646f02ff 6342 const struct btf_type *sec, *var, *def;
341ac5ff
HC
6343 struct bpf_map *map = NULL, *targ_map = NULL;
6344 struct bpf_program *targ_prog = NULL;
6345 bool is_prog_array, is_map_in_map;
646f02ff 6346 const struct btf_member *member;
341ac5ff 6347 const char *name, *mname, *type;
646f02ff 6348 unsigned int moff;
ad23b723
AN
6349 Elf64_Sym *sym;
6350 Elf64_Rel *rel;
646f02ff
AN
6351 void *tmp;
6352
6353 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6354 return -EINVAL;
6355 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6356 if (!sec)
6357 return -EINVAL;
6358
646f02ff
AN
6359 nrels = shdr->sh_size / shdr->sh_entsize;
6360 for (i = 0; i < nrels; i++) {
ad23b723
AN
6361 rel = elf_rel_by_idx(data, i);
6362 if (!rel) {
646f02ff
AN
6363 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6364 return -LIBBPF_ERRNO__FORMAT;
6365 }
ad23b723
AN
6366
6367 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6368 if (!sym) {
646f02ff 6369 pr_warn(".maps relo #%d: symbol %zx not found\n",
ad23b723 6370 i, (size_t)ELF64_R_SYM(rel->r_info));
646f02ff
AN
6371 return -LIBBPF_ERRNO__FORMAT;
6372 }
ad23b723 6373 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
646f02ff 6374
ad23b723
AN
6375 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6376 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6377 (size_t)rel->r_offset, sym->st_name, name);
646f02ff
AN
6378
6379 for (j = 0; j < obj->nr_maps; j++) {
6380 map = &obj->maps[j];
6381 if (map->sec_idx != obj->efile.btf_maps_shndx)
6382 continue;
6383
6384 vi = btf_var_secinfos(sec) + map->btf_var_idx;
ad23b723
AN
6385 if (vi->offset <= rel->r_offset &&
6386 rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
646f02ff
AN
6387 break;
6388 }
6389 if (j == obj->nr_maps) {
ad23b723
AN
6390 pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6391 i, name, (size_t)rel->r_offset);
646f02ff
AN
6392 return -EINVAL;
6393 }
6394
341ac5ff
HC
6395 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6396 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6397 type = is_map_in_map ? "map" : "prog";
6398 if (is_map_in_map) {
6399 if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6400 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6401 i, name);
6402 return -LIBBPF_ERRNO__RELOC;
6403 }
6404 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6405 map->def.key_size != sizeof(int)) {
6406 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6407 i, map->name, sizeof(int));
6408 return -EINVAL;
6409 }
6410 targ_map = bpf_object__find_map_by_name(obj, name);
6411 if (!targ_map) {
6412 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6413 i, name);
6414 return -ESRCH;
6415 }
6416 } else if (is_prog_array) {
6417 targ_prog = bpf_object__find_program_by_name(obj, name);
6418 if (!targ_prog) {
6419 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6420 i, name);
6421 return -ESRCH;
6422 }
6423 if (targ_prog->sec_idx != sym->st_shndx ||
6424 targ_prog->sec_insn_off * 8 != sym->st_value ||
6425 prog_is_subprog(obj, targ_prog)) {
6426 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6427 i, name);
6428 return -LIBBPF_ERRNO__RELOC;
6429 }
6430 } else {
646f02ff
AN
6431 return -EINVAL;
6432 }
6433
646f02ff
AN
6434 var = btf__type_by_id(obj->btf, vi->type);
6435 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6436 if (btf_vlen(def) == 0)
6437 return -EINVAL;
6438 member = btf_members(def) + btf_vlen(def) - 1;
6439 mname = btf__name_by_offset(obj->btf, member->name_off);
6440 if (strcmp(mname, "values"))
6441 return -EINVAL;
6442
6443 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
ad23b723 6444 if (rel->r_offset - vi->offset < moff)
646f02ff
AN
6445 return -EINVAL;
6446
ad23b723 6447 moff = rel->r_offset - vi->offset - moff;
15728ad3
AN
6448 /* here we use BPF pointer size, which is always 64 bit, as we
6449 * are parsing ELF that was built for BPF target
6450 */
6451 if (moff % bpf_ptr_sz)
646f02ff 6452 return -EINVAL;
15728ad3 6453 moff /= bpf_ptr_sz;
646f02ff
AN
6454 if (moff >= map->init_slots_sz) {
6455 new_sz = moff + 1;
029258d7 6456 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
646f02ff
AN
6457 if (!tmp)
6458 return -ENOMEM;
6459 map->init_slots = tmp;
6460 memset(map->init_slots + map->init_slots_sz, 0,
15728ad3 6461 (new_sz - map->init_slots_sz) * host_ptr_sz);
646f02ff
AN
6462 map->init_slots_sz = new_sz;
6463 }
341ac5ff 6464 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
646f02ff 6465
341ac5ff
HC
6466 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6467 i, map->name, moff, type, name);
646f02ff
AN
6468 }
6469
6470 return 0;
6471}
590a0088 6472
c3c55696
AN
6473static int bpf_object__collect_relos(struct bpf_object *obj)
6474{
6475 int i, err;
34090915 6476
25bbbd7a
AN
6477 for (i = 0; i < obj->efile.sec_cnt; i++) {
6478 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6479 Elf64_Shdr *shdr;
6480 Elf_Data *data;
6481 int idx;
6482
6483 if (sec_desc->sec_type != SEC_RELO)
6484 continue;
6485
6486 shdr = sec_desc->shdr;
6487 data = sec_desc->data;
6488 idx = shdr->sh_info;
34090915
WN
6489
6490 if (shdr->sh_type != SHT_REL) {
be18010e 6491 pr_warn("internal error at %d\n", __LINE__);
6371ca3b 6492 return -LIBBPF_ERRNO__INTERNAL;
34090915
WN
6493 }
6494
c3c55696 6495 if (idx == obj->efile.st_ops_shndx)
646f02ff 6496 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
c3c55696 6497 else if (idx == obj->efile.btf_maps_shndx)
646f02ff 6498 err = bpf_object__collect_map_relos(obj, shdr, data);
c3c55696
AN
6499 else
6500 err = bpf_object__collect_prog_relos(obj, shdr, data);
34090915 6501 if (err)
6371ca3b 6502 return err;
34090915 6503 }
c3c55696 6504
d0e92887 6505 bpf_object__sort_relos(obj);
34090915
WN
6506 return 0;
6507}
6508
109cea5a
AN
6509static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6510{
9b2f6fec 6511 if (BPF_CLASS(insn->code) == BPF_JMP &&
109cea5a
AN
6512 BPF_OP(insn->code) == BPF_CALL &&
6513 BPF_SRC(insn->code) == BPF_K &&
9b2f6fec
AN
6514 insn->src_reg == 0 &&
6515 insn->dst_reg == 0) {
6516 *func_id = insn->imm;
109cea5a
AN
6517 return true;
6518 }
6519 return false;
6520}
6521
42869d28 6522static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
109cea5a
AN
6523{
6524 struct bpf_insn *insn = prog->insns;
6525 enum bpf_func_id func_id;
6526 int i;
6527
67234743
AS
6528 if (obj->gen_loader)
6529 return 0;
6530
109cea5a
AN
6531 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6532 if (!insn_is_helper_call(insn, &func_id))
6533 continue;
6534
6535 /* on kernels that don't yet support
6536 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6537 * to bpf_probe_read() which works well for old kernels
6538 */
6539 switch (func_id) {
6540 case BPF_FUNC_probe_read_kernel:
6541 case BPF_FUNC_probe_read_user:
9ca1f56a 6542 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6543 insn->imm = BPF_FUNC_probe_read;
6544 break;
6545 case BPF_FUNC_probe_read_kernel_str:
6546 case BPF_FUNC_probe_read_user_str:
9ca1f56a 6547 if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
109cea5a
AN
6548 insn->imm = BPF_FUNC_probe_read_str;
6549 break;
6550 default:
6551 break;
6552 }
6553 }
6554 return 0;
6555}
6556
15ea31fa
AN
6557static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6558 int *btf_obj_fd, int *btf_type_id);
12d9466d
AN
6559
6560/* this is called as prog->sec_def->preload_fn for libbpf-supported sec_defs */
6561static int libbpf_preload_prog(struct bpf_program *prog,
d10ef2b8 6562 struct bpf_prog_load_opts *opts, long cookie)
12d9466d 6563{
15ea31fa
AN
6564 enum sec_def_flags def = cookie;
6565
12d9466d 6566 /* old kernels might not support specifying expected_attach_type */
15ea31fa 6567 if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
d10ef2b8 6568 opts->expected_attach_type = 0;
12d9466d 6569
15ea31fa 6570 if (def & SEC_SLEEPABLE)
d10ef2b8 6571 opts->prog_flags |= BPF_F_SLEEPABLE;
12d9466d
AN
6572
6573 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6574 prog->type == BPF_PROG_TYPE_LSM ||
6575 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6576 int btf_obj_fd = 0, btf_type_id = 0, err;
15ea31fa 6577 const char *attach_name;
12d9466d 6578
15ea31fa
AN
6579 attach_name = strchr(prog->sec_name, '/') + 1;
6580 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
12d9466d
AN
6581 if (err)
6582 return err;
6583
6584 /* cache resolved BTF FD and BTF type ID in the prog */
6585 prog->attach_btf_obj_fd = btf_obj_fd;
6586 prog->attach_btf_id = btf_type_id;
6587
6588 /* but by now libbpf common logic is not utilizing
6589 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
d10ef2b8
AN
6590 * this callback is called after opts were populated by
6591 * libbpf, so this callback has to update opts explicitly here
12d9466d 6592 */
d10ef2b8
AN
6593 opts->attach_btf_obj_fd = btf_obj_fd;
6594 opts->attach_btf_id = btf_type_id;
12d9466d
AN
6595 }
6596 return 0;
6597}
6598
be2f2d16
AN
6599static int bpf_object_load_prog_instance(struct bpf_object *obj, struct bpf_program *prog,
6600 struct bpf_insn *insns, int insns_cnt,
6601 const char *license, __u32 kern_version,
6602 int *prog_fd)
55cffde2 6603{
d10ef2b8
AN
6604 LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6605 const char *prog_name = NULL;
1ce6a9fc 6606 char *cp, errmsg[STRERR_BUFSIZE];
8395f320 6607 size_t log_buf_size = 0;
b3ce9079 6608 char *log_buf = NULL, *tmp;
12d9466d 6609 int btf_fd, ret, err;
b3ce9079
AN
6610 bool own_log_buf = true;
6611 __u32 log_level = prog->log_level;
55cffde2 6612
80b2b5c3
AM
6613 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6614 /*
6615 * The program type must be set. Most likely we couldn't find a proper
6616 * section definition at load time, and thus we didn't infer the type.
6617 */
6618 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6619 prog->name, prog->sec_name);
6620 return -EINVAL;
6621 }
6622
fba01a06
AN
6623 if (!insns || !insns_cnt)
6624 return -EINVAL;
6625
12d9466d 6626 load_attr.expected_attach_type = prog->expected_attach_type;
25bbbd7a 6627 if (kernel_supports(obj, FEAT_PROG_NAME))
d10ef2b8 6628 prog_name = prog->name;
12d9466d
AN
6629 load_attr.attach_prog_fd = prog->attach_prog_fd;
6630 load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6aef10a4
AN
6631 load_attr.attach_btf_id = prog->attach_btf_id;
6632 load_attr.kern_version = kern_version;
6633 load_attr.prog_ifindex = prog->prog_ifindex;
6634
0f0e55d8 6635 /* specify func_info/line_info only if kernel supports them */
25bbbd7a
AN
6636 btf_fd = bpf_object__btf_fd(obj);
6637 if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
0f0e55d8
AN
6638 load_attr.prog_btf_fd = btf_fd;
6639 load_attr.func_info = prog->func_info;
6640 load_attr.func_info_rec_size = prog->func_info_rec_size;
6641 load_attr.func_info_cnt = prog->func_info_cnt;
6642 load_attr.line_info = prog->line_info;
6643 load_attr.line_info_rec_size = prog->line_info_rec_size;
6644 load_attr.line_info_cnt = prog->line_info_cnt;
6645 }
b3ce9079 6646 load_attr.log_level = log_level;
04656198 6647 load_attr.prog_flags = prog->prog_flags;
25bbbd7a 6648 load_attr.fd_array = obj->fd_array;
55cffde2 6649
12d9466d
AN
6650 /* adjust load_attr if sec_def provides custom preload callback */
6651 if (prog->sec_def && prog->sec_def->preload_fn) {
6652 err = prog->sec_def->preload_fn(prog, &load_attr, prog->sec_def->cookie);
6653 if (err < 0) {
6654 pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6655 prog->name, err);
6656 return err;
6657 }
6658 }
6659
25bbbd7a 6660 if (obj->gen_loader) {
d10ef2b8
AN
6661 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6662 license, insns, insns_cnt, &load_attr,
25bbbd7a 6663 prog - obj->programs);
be2f2d16 6664 *prog_fd = -1;
67234743
AS
6665 return 0;
6666 }
8395f320 6667
b3ce9079
AN
6668retry_load:
6669 /* if log_level is zero, we don't request logs initiallly even if
6670 * custom log_buf is specified; if the program load fails, then we'll
6671 * bump log_level to 1 and use either custom log_buf or we'll allocate
6672 * our own and retry the load to get details on what failed
6673 */
6674 if (log_level) {
6675 if (prog->log_buf) {
6676 log_buf = prog->log_buf;
6677 log_buf_size = prog->log_size;
6678 own_log_buf = false;
6679 } else if (obj->log_buf) {
6680 log_buf = obj->log_buf;
6681 log_buf_size = obj->log_size;
6682 own_log_buf = false;
6683 } else {
6684 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6685 tmp = realloc(log_buf, log_buf_size);
6686 if (!tmp) {
6687 ret = -ENOMEM;
6688 goto out;
6689 }
6690 log_buf = tmp;
6691 log_buf[0] = '\0';
6692 own_log_buf = true;
6693 }
8395f320 6694 }
55cffde2 6695
6aef10a4 6696 load_attr.log_buf = log_buf;
d10ef2b8 6697 load_attr.log_size = log_buf_size;
b3ce9079 6698 load_attr.log_level = log_level;
55cffde2 6699
b3ce9079 6700 ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
55cffde2 6701 if (ret >= 0) {
b3ce9079 6702 if (log_level && own_log_buf) {
ad9a7f96
AN
6703 pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6704 prog->name, log_buf);
6705 }
5d23328d 6706
25bbbd7a
AN
6707 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6708 struct bpf_map *map;
6709 int i;
6710
6711 for (i = 0; i < obj->nr_maps; i++) {
6712 map = &prog->obj->maps[i];
6713 if (map->libbpf_type != LIBBPF_MAP_RODATA)
6714 continue;
5d23328d 6715
25bbbd7a
AN
6716 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6717 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96
AN
6718 pr_warn("prog '%s': failed to bind map '%s': %s\n",
6719 prog->name, map->real_name, cp);
25bbbd7a
AN
6720 /* Don't fail hard if can't bind rodata. */
6721 }
5d23328d
YZ
6722 }
6723 }
6724
be2f2d16 6725 *prog_fd = ret;
55cffde2
WN
6726 ret = 0;
6727 goto out;
6728 }
6729
b3ce9079
AN
6730 if (log_level == 0) {
6731 log_level = 1;
da11b417
AS
6732 goto retry_load;
6733 }
b3ce9079
AN
6734 /* On ENOSPC, increase log buffer size and retry, unless custom
6735 * log_buf is specified.
6736 * Be careful to not overflow u32, though. Kernel's log buf size limit
6737 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6738 * multiply by 2 unless we are sure we'll fit within 32 bits.
6739 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6740 */
6741 if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6742 goto retry_load;
2eda2145
AN
6743
6744 ret = -errno;
24d6a808 6745 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
ad9a7f96 6746 pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
dc3a2d25 6747 pr_perm_msg(ret);
55cffde2 6748
b3ce9079 6749 if (own_log_buf && log_buf && log_buf[0] != '\0') {
ad9a7f96
AN
6750 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6751 prog->name, log_buf);
6752 }
6753 if (insns_cnt >= BPF_MAXINSNS) {
6754 pr_warn("prog '%s': program too large (%d insns), at most %d insns\n",
6755 prog->name, insns_cnt, BPF_MAXINSNS);
55cffde2
WN
6756 }
6757
6758out:
b3ce9079
AN
6759 if (own_log_buf)
6760 free(log_buf);
55cffde2
WN
6761 return ret;
6762}
6763
d0e92887 6764static int bpf_program_record_relos(struct bpf_program *prog)
67234743
AS
6765{
6766 struct bpf_object *obj = prog->obj;
6767 int i;
6768
6769 for (i = 0; i < prog->nr_reloc; i++) {
6770 struct reloc_desc *relo = &prog->reloc_desc[i];
6771 struct extern_desc *ext = &obj->externs[relo->sym_off];
6772
6773 switch (relo->type) {
6774 case RELO_EXTERN_VAR:
6775 if (ext->type != EXT_KSYM)
6776 continue;
c24941cd
KKD
6777 bpf_gen__record_extern(obj->gen_loader, ext->name,
6778 ext->is_weak, !ext->ksym.type_id,
18f4fccb 6779 BTF_KIND_VAR, relo->insn_idx);
67234743
AS
6780 break;
6781 case RELO_EXTERN_FUNC:
c24941cd
KKD
6782 bpf_gen__record_extern(obj->gen_loader, ext->name,
6783 ext->is_weak, false, BTF_KIND_FUNC,
67234743
AS
6784 relo->insn_idx);
6785 break;
d0e92887
AS
6786 case RELO_CORE: {
6787 struct bpf_core_relo cr = {
6788 .insn_off = relo->insn_idx * 8,
6789 .type_id = relo->core_relo->type_id,
6790 .access_str_off = relo->core_relo->access_str_off,
6791 .kind = relo->core_relo->kind,
6792 };
6793
6794 bpf_gen__record_relo_core(obj->gen_loader, &cr);
6795 break;
6796 }
67234743
AS
6797 default:
6798 continue;
6799 }
6800 }
6801 return 0;
6802}
6803
be2f2d16
AN
6804static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6805 const char *license, __u32 kern_ver)
55cffde2 6806{
91abb4a6 6807 int err = 0, fd, i;
13acb508 6808
be2f2d16 6809 if (obj->loaded) {
52109584 6810 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
e9fc3ce9 6811 return libbpf_err(-EINVAL);
d9297581
AN
6812 }
6813
b580563e
WN
6814 if (prog->instances.nr < 0 || !prog->instances.fds) {
6815 if (prog->preprocessor) {
be18010e 6816 pr_warn("Internal error: can't load program '%s'\n",
52109584 6817 prog->name);
e9fc3ce9 6818 return libbpf_err(-LIBBPF_ERRNO__INTERNAL);
b580563e 6819 }
55cffde2 6820
b580563e
WN
6821 prog->instances.fds = malloc(sizeof(int));
6822 if (!prog->instances.fds) {
be18010e 6823 pr_warn("Not enough memory for BPF fds\n");
e9fc3ce9 6824 return libbpf_err(-ENOMEM);
b580563e
WN
6825 }
6826 prog->instances.nr = 1;
6827 prog->instances.fds[0] = -1;
6828 }
6829
6830 if (!prog->preprocessor) {
6831 if (prog->instances.nr != 1) {
52109584
AN
6832 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6833 prog->name, prog->instances.nr);
b580563e 6834 }
be2f2d16 6835 if (obj->gen_loader)
d0e92887 6836 bpf_program_record_relos(prog);
be2f2d16
AN
6837 err = bpf_object_load_prog_instance(obj, prog,
6838 prog->insns, prog->insns_cnt,
6839 license, kern_ver, &fd);
b580563e
WN
6840 if (!err)
6841 prog->instances.fds[0] = fd;
6842 goto out;
6843 }
6844
6845 for (i = 0; i < prog->instances.nr; i++) {
6846 struct bpf_prog_prep_result result;
6847 bpf_program_prep_t preprocessor = prog->preprocessor;
6848
1ad9cbb8 6849 memset(&result, 0, sizeof(result));
b580563e
WN
6850 err = preprocessor(prog, i, prog->insns,
6851 prog->insns_cnt, &result);
6852 if (err) {
be18010e 6853 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
52109584 6854 i, prog->name);
b580563e
WN
6855 goto out;
6856 }
6857
6858 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6859 pr_debug("Skip loading the %dth instance of program '%s'\n",
52109584 6860 i, prog->name);
b580563e
WN
6861 prog->instances.fds[i] = -1;
6862 if (result.pfd)
6863 *result.pfd = -1;
6864 continue;
6865 }
6866
be2f2d16
AN
6867 err = bpf_object_load_prog_instance(obj, prog,
6868 result.new_insn_ptr, result.new_insn_cnt,
6869 license, kern_ver, &fd);
b580563e 6870 if (err) {
be18010e 6871 pr_warn("Loading the %dth instance of program '%s' failed\n",
52109584 6872 i, prog->name);
b580563e
WN
6873 goto out;
6874 }
6875
6876 if (result.pfd)
6877 *result.pfd = fd;
6878 prog->instances.fds[i] = fd;
6879 }
6880out:
55cffde2 6881 if (err)
52109584 6882 pr_warn("failed to load program '%s'\n", prog->name);
e9fc3ce9 6883 return libbpf_err(err);
55cffde2
WN
6884}
6885
be2f2d16
AN
6886int bpf_program__load(struct bpf_program *prog, const char *license, __u32 kern_ver)
6887{
6888 return bpf_object_load_prog(prog->obj, prog, license, kern_ver);
6889}
6890
55cffde2 6891static int
60276f98 6892bpf_object__load_progs(struct bpf_object *obj, int log_level)
55cffde2 6893{
d9297581 6894 struct bpf_program *prog;
55cffde2
WN
6895 size_t i;
6896 int err;
6897
109cea5a
AN
6898 for (i = 0; i < obj->nr_programs; i++) {
6899 prog = &obj->programs[i];
6900 err = bpf_object__sanitize_prog(obj, prog);
6901 if (err)
6902 return err;
6903 }
6904
55cffde2 6905 for (i = 0; i < obj->nr_programs; i++) {
d9297581 6906 prog = &obj->programs[i];
c3c55696 6907 if (prog_is_subprog(obj, prog))
48cca7e4 6908 continue;
d9297581 6909 if (!prog->load) {
9c0f8cbd 6910 pr_debug("prog '%s': skipped loading\n", prog->name);
d9297581
AN
6911 continue;
6912 }
6913 prog->log_level |= log_level;
be2f2d16 6914 err = bpf_object_load_prog(obj, prog, obj->license, obj->kern_version);
55cffde2
WN
6915 if (err)
6916 return err;
6917 }
67234743
AS
6918 if (obj->gen_loader)
6919 bpf_object__free_relocs(obj);
55cffde2
WN
6920 return 0;
6921}
6922
25498a19
AN
6923static const struct bpf_sec_def *find_sec_def(const char *sec_name);
6924
91b4d1d1
AN
6925static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
6926{
6927 struct bpf_program *prog;
12d9466d 6928 int err;
91b4d1d1
AN
6929
6930 bpf_object__for_each_program(prog, obj) {
6931 prog->sec_def = find_sec_def(prog->sec_name);
6932 if (!prog->sec_def) {
6933 /* couldn't guess, but user might manually specify */
6934 pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
6935 prog->name, prog->sec_name);
6936 continue;
6937 }
6938
91b4d1d1
AN
6939 bpf_program__set_type(prog, prog->sec_def->prog_type);
6940 bpf_program__set_expected_attach_type(prog, prog->sec_def->expected_attach_type);
6941
91b555d7
AN
6942#pragma GCC diagnostic push
6943#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
91b4d1d1
AN
6944 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6945 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6946 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
91b555d7 6947#pragma GCC diagnostic pop
12d9466d
AN
6948
6949 /* sec_def can have custom callback which should be called
6950 * after bpf_program is initialized to adjust its properties
6951 */
6952 if (prog->sec_def->init_fn) {
6953 err = prog->sec_def->init_fn(prog, prog->sec_def->cookie);
6954 if (err < 0) {
6955 pr_warn("prog '%s': failed to initialize: %d\n",
6956 prog->name, err);
6957 return err;
6958 }
6959 }
91b4d1d1
AN
6960 }
6961
6962 return 0;
6963}
6964
ad9a7f96
AN
6965static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6966 const struct bpf_object_open_opts *opts)
1a5e3fb1 6967{
1373ff59 6968 const char *obj_name, *kconfig, *btf_tmp_path;
1a5e3fb1 6969 struct bpf_object *obj;
291ee02b 6970 char tmp_name[64];
6371ca3b 6971 int err;
e0e3ea88
AN
6972 char *log_buf;
6973 size_t log_size;
6974 __u32 log_level;
1a5e3fb1
WN
6975
6976 if (elf_version(EV_CURRENT) == EV_NONE) {
be18010e
KW
6977 pr_warn("failed to init libelf for %s\n",
6978 path ? : "(mem buf)");
6371ca3b 6979 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
1a5e3fb1
WN
6980 }
6981
291ee02b
AN
6982 if (!OPTS_VALID(opts, bpf_object_open_opts))
6983 return ERR_PTR(-EINVAL);
6984
1aace10f 6985 obj_name = OPTS_GET(opts, object_name, NULL);
291ee02b
AN
6986 if (obj_buf) {
6987 if (!obj_name) {
6988 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6989 (unsigned long)obj_buf,
6990 (unsigned long)obj_buf_sz);
6991 obj_name = tmp_name;
6992 }
6993 path = obj_name;
6994 pr_debug("loading object '%s' from buffer\n", obj_name);
6995 }
6996
e0e3ea88
AN
6997 log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
6998 log_size = OPTS_GET(opts, kernel_log_size, 0);
6999 log_level = OPTS_GET(opts, kernel_log_level, 0);
7000 if (log_size > UINT_MAX)
7001 return ERR_PTR(-EINVAL);
7002 if (log_size && !log_buf)
7003 return ERR_PTR(-EINVAL);
7004
2ce8450e 7005 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
6371ca3b
WN
7006 if (IS_ERR(obj))
7007 return obj;
1a5e3fb1 7008
e0e3ea88
AN
7009 obj->log_buf = log_buf;
7010 obj->log_size = log_size;
7011 obj->log_level = log_level;
7012
1373ff59
SC
7013 btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7014 if (btf_tmp_path) {
7015 if (strlen(btf_tmp_path) >= PATH_MAX) {
7016 err = -ENAMETOOLONG;
7017 goto out;
7018 }
7019 obj->btf_custom_path = strdup(btf_tmp_path);
7020 if (!obj->btf_custom_path) {
7021 err = -ENOMEM;
7022 goto out;
7023 }
7024 }
7025
8601fd42
AN
7026 kconfig = OPTS_GET(opts, kconfig, NULL);
7027 if (kconfig) {
7028 obj->kconfig = strdup(kconfig);
18353c87
SC
7029 if (!obj->kconfig) {
7030 err = -ENOMEM;
7031 goto out;
7032 }
166750bc 7033 }
291ee02b 7034
0d13bfce
AN
7035 err = bpf_object__elf_init(obj);
7036 err = err ? : bpf_object__check_endianness(obj);
7037 err = err ? : bpf_object__elf_collect(obj);
166750bc
AN
7038 err = err ? : bpf_object__collect_externs(obj);
7039 err = err ? : bpf_object__finalize_btf(obj);
0d13bfce 7040 err = err ? : bpf_object__init_maps(obj, opts);
91b4d1d1 7041 err = err ? : bpf_object_init_progs(obj, opts);
c3c55696 7042 err = err ? : bpf_object__collect_relos(obj);
0d13bfce
AN
7043 if (err)
7044 goto out;
dd4436bb 7045
91b4d1d1 7046 bpf_object__elf_finish(obj);
dd4436bb 7047
1a5e3fb1
WN
7048 return obj;
7049out:
7050 bpf_object__close(obj);
6371ca3b 7051 return ERR_PTR(err);
1a5e3fb1
WN
7052}
7053
5e61f270
AN
7054static struct bpf_object *
7055__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
1a5e3fb1 7056{
e00aca65 7057 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
291ee02b
AN
7058 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7059 );
7060
1a5e3fb1 7061 /* param validation */
07f2d4ea 7062 if (!attr->file)
1a5e3fb1
WN
7063 return NULL;
7064
07f2d4ea 7065 pr_debug("loading %s\n", attr->file);
ad9a7f96 7066 return bpf_object_open(attr->file, NULL, 0, &opts);
c034a177
JF
7067}
7068
7069struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7070{
e9fc3ce9 7071 return libbpf_ptr(__bpf_object__open_xattr(attr, 0));
07f2d4ea
JK
7072}
7073
7074struct bpf_object *bpf_object__open(const char *path)
7075{
7076 struct bpf_object_open_attr attr = {
7077 .file = path,
7078 .prog_type = BPF_PROG_TYPE_UNSPEC,
7079 };
1a5e3fb1 7080
e9fc3ce9 7081 return libbpf_ptr(__bpf_object__open_xattr(&attr, 0));
6c956392
WN
7082}
7083
2ce8450e 7084struct bpf_object *
01af3bf0 7085bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
2ce8450e 7086{
2ce8450e 7087 if (!path)
e9fc3ce9 7088 return libbpf_err_ptr(-EINVAL);
2ce8450e
AN
7089
7090 pr_debug("loading %s\n", path);
7091
ad9a7f96 7092 return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
2ce8450e
AN
7093}
7094
7095struct bpf_object *
7096bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
01af3bf0 7097 const struct bpf_object_open_opts *opts)
6c956392 7098{
2ce8450e 7099 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7100 return libbpf_err_ptr(-EINVAL);
6c956392 7101
ad9a7f96 7102 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
2ce8450e
AN
7103}
7104
7105struct bpf_object *
7106bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7107 const char *name)
7108{
e00aca65 7109 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
2ce8450e
AN
7110 .object_name = name,
7111 /* wrong default, but backwards-compatible */
7112 .relaxed_maps = true,
7113 );
7114
7115 /* returning NULL is wrong, but backwards-compatible */
7116 if (!obj_buf || obj_buf_sz == 0)
e9fc3ce9 7117 return errno = EINVAL, NULL;
6c956392 7118
ad9a7f96 7119 return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, &opts));
1a5e3fb1
WN
7120}
7121
4a404a7e 7122static int bpf_object_unload(struct bpf_object *obj)
52d3352e
WN
7123{
7124 size_t i;
7125
7126 if (!obj)
e9fc3ce9 7127 return libbpf_err(-EINVAL);
52d3352e 7128
590a0088 7129 for (i = 0; i < obj->nr_maps; i++) {
9d759a9b 7130 zclose(obj->maps[i].fd);
590a0088
MKL
7131 if (obj->maps[i].st_ops)
7132 zfree(&obj->maps[i].st_ops->kern_vdata);
7133 }
52d3352e 7134
55cffde2
WN
7135 for (i = 0; i < obj->nr_programs; i++)
7136 bpf_program__unload(&obj->programs[i]);
7137
52d3352e
WN
7138 return 0;
7139}
7140
4a404a7e
HC
7141int bpf_object__unload(struct bpf_object *obj) __attribute__((alias("bpf_object_unload")));
7142
0d13bfce
AN
7143static int bpf_object__sanitize_maps(struct bpf_object *obj)
7144{
7145 struct bpf_map *m;
7146
7147 bpf_object__for_each_map(m, obj) {
7148 if (!bpf_map__is_internal(m))
7149 continue;
9ca1f56a 7150 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
0d13bfce
AN
7151 m->def.map_flags ^= BPF_F_MMAPABLE;
7152 }
7153
7154 return 0;
7155}
7156
1c0c7074
AN
7157static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7158{
7159 char sym_type, sym_name[500];
7160 unsigned long long sym_addr;
5bd022ec 7161 const struct btf_type *t;
1c0c7074
AN
7162 struct extern_desc *ext;
7163 int ret, err = 0;
7164 FILE *f;
7165
7166 f = fopen("/proc/kallsyms", "r");
7167 if (!f) {
7168 err = -errno;
7169 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7170 return err;
7171 }
7172
7173 while (true) {
7174 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7175 &sym_addr, &sym_type, sym_name);
7176 if (ret == EOF && feof(f))
7177 break;
7178 if (ret != 3) {
135c783f 7179 pr_warn("failed to read kallsyms entry: %d\n", ret);
1c0c7074
AN
7180 err = -EINVAL;
7181 goto out;
7182 }
7183
7184 ext = find_extern_by_name(obj, sym_name);
7185 if (!ext || ext->type != EXT_KSYM)
7186 continue;
7187
5bd022ec
MKL
7188 t = btf__type_by_id(obj->btf, ext->btf_id);
7189 if (!btf_is_var(t))
7190 continue;
7191
1c0c7074
AN
7192 if (ext->is_set && ext->ksym.addr != sym_addr) {
7193 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7194 sym_name, ext->ksym.addr, sym_addr);
7195 err = -EINVAL;
7196 goto out;
7197 }
7198 if (!ext->is_set) {
7199 ext->is_set = true;
7200 ext->ksym.addr = sym_addr;
7201 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7202 }
7203 }
7204
7205out:
7206 fclose(f);
7207 return err;
7208}
7209
774e132e
MKL
7210static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7211 __u16 kind, struct btf **res_btf,
9dbe6015 7212 struct module_btf **res_mod_btf)
d370bbe1 7213{
9dbe6015 7214 struct module_btf *mod_btf;
284d2587 7215 struct btf *btf;
9dbe6015 7216 int i, id, err;
d370bbe1 7217
933d1aa3 7218 btf = obj->btf_vmlinux;
9dbe6015 7219 mod_btf = NULL;
774e132e
MKL
7220 id = btf__find_by_name_kind(btf, ksym_name, kind);
7221
933d1aa3
MKL
7222 if (id == -ENOENT) {
7223 err = load_module_btfs(obj);
7224 if (err)
7225 return err;
d370bbe1 7226
933d1aa3 7227 for (i = 0; i < obj->btf_module_cnt; i++) {
9dbe6015
KKD
7228 /* we assume module_btf's BTF FD is always >0 */
7229 mod_btf = &obj->btf_modules[i];
7230 btf = mod_btf->btf;
7231 id = btf__find_by_name_kind_own(btf, ksym_name, kind);
933d1aa3
MKL
7232 if (id != -ENOENT)
7233 break;
7234 }
7235 }
2211c825 7236 if (id <= 0)
933d1aa3 7237 return -ESRCH;
d370bbe1 7238
774e132e 7239 *res_btf = btf;
9dbe6015 7240 *res_mod_btf = mod_btf;
774e132e
MKL
7241 return id;
7242}
7243
7244static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7245 struct extern_desc *ext)
7246{
7247 const struct btf_type *targ_var, *targ_type;
7248 __u32 targ_type_id, local_type_id;
9dbe6015 7249 struct module_btf *mod_btf = NULL;
774e132e 7250 const char *targ_var_name;
774e132e 7251 struct btf *btf = NULL;
9dbe6015 7252 int id, err;
774e132e 7253
9dbe6015 7254 id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
466b2e13
KKD
7255 if (id < 0) {
7256 if (id == -ESRCH && ext->is_weak)
7257 return 0;
2211c825
HL
7258 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7259 ext->name);
774e132e 7260 return id;
2211c825 7261 }
774e132e 7262
933d1aa3
MKL
7263 /* find local type_id */
7264 local_type_id = ext->ksym.type_id;
284d2587 7265
933d1aa3
MKL
7266 /* find target type_id */
7267 targ_var = btf__type_by_id(btf, id);
7268 targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7269 targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
d370bbe1 7270
933d1aa3
MKL
7271 err = bpf_core_types_are_compat(obj->btf, local_type_id,
7272 btf, targ_type_id);
7273 if (err <= 0) {
7274 const struct btf_type *local_type;
7275 const char *targ_name, *local_name;
d370bbe1 7276
933d1aa3
MKL
7277 local_type = btf__type_by_id(obj->btf, local_type_id);
7278 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7279 targ_name = btf__name_by_offset(btf, targ_type->name_off);
d370bbe1 7280
933d1aa3
MKL
7281 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7282 ext->name, local_type_id,
7283 btf_kind_str(local_type), local_name, targ_type_id,
7284 btf_kind_str(targ_type), targ_name);
7285 return -EINVAL;
7286 }
d370bbe1 7287
933d1aa3 7288 ext->is_set = true;
9dbe6015 7289 ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
933d1aa3
MKL
7290 ext->ksym.kernel_btf_id = id;
7291 pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7292 ext->name, id, btf_kind_str(targ_var), targ_var_name);
d370bbe1 7293
933d1aa3
MKL
7294 return 0;
7295}
d370bbe1 7296
5bd022ec
MKL
7297static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7298 struct extern_desc *ext)
7299{
7300 int local_func_proto_id, kfunc_proto_id, kfunc_id;
9dbe6015 7301 struct module_btf *mod_btf = NULL;
5bd022ec
MKL
7302 const struct btf_type *kern_func;
7303 struct btf *kern_btf = NULL;
9dbe6015 7304 int ret;
5bd022ec
MKL
7305
7306 local_func_proto_id = ext->ksym.type_id;
7307
9dbe6015 7308 kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
5bd022ec 7309 if (kfunc_id < 0) {
466b2e13
KKD
7310 if (kfunc_id == -ESRCH && ext->is_weak)
7311 return 0;
7312 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
5bd022ec
MKL
7313 ext->name);
7314 return kfunc_id;
7315 }
7316
5bd022ec
MKL
7317 kern_func = btf__type_by_id(kern_btf, kfunc_id);
7318 kfunc_proto_id = kern_func->type;
7319
7320 ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7321 kern_btf, kfunc_proto_id);
7322 if (ret <= 0) {
7323 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7324 ext->name, local_func_proto_id, kfunc_proto_id);
7325 return -EINVAL;
7326 }
7327
9dbe6015
KKD
7328 /* set index for module BTF fd in fd_array, if unset */
7329 if (mod_btf && !mod_btf->fd_array_idx) {
7330 /* insn->off is s16 */
7331 if (obj->fd_array_cnt == INT16_MAX) {
7332 pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7333 ext->name, mod_btf->fd_array_idx);
7334 return -E2BIG;
7335 }
7336 /* Cannot use index 0 for module BTF fd */
7337 if (!obj->fd_array_cnt)
7338 obj->fd_array_cnt = 1;
7339
7340 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7341 obj->fd_array_cnt + 1);
7342 if (ret)
7343 return ret;
7344 mod_btf->fd_array_idx = obj->fd_array_cnt;
7345 /* we assume module BTF FD is always >0 */
7346 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7347 }
7348
5bd022ec 7349 ext->is_set = true;
5bd022ec 7350 ext->ksym.kernel_btf_id = kfunc_id;
9dbe6015 7351 ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
5bd022ec
MKL
7352 pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7353 ext->name, kfunc_id);
7354
7355 return 0;
7356}
7357
933d1aa3
MKL
7358static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7359{
5bd022ec 7360 const struct btf_type *t;
933d1aa3
MKL
7361 struct extern_desc *ext;
7362 int i, err;
7363
7364 for (i = 0; i < obj->nr_extern; i++) {
7365 ext = &obj->externs[i];
7366 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7367 continue;
7368
67234743
AS
7369 if (obj->gen_loader) {
7370 ext->is_set = true;
7371 ext->ksym.kernel_btf_obj_fd = 0;
7372 ext->ksym.kernel_btf_id = 0;
7373 continue;
7374 }
5bd022ec
MKL
7375 t = btf__type_by_id(obj->btf, ext->btf_id);
7376 if (btf_is_var(t))
7377 err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7378 else
7379 err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
933d1aa3
MKL
7380 if (err)
7381 return err;
d370bbe1
HL
7382 }
7383 return 0;
7384}
7385
166750bc 7386static int bpf_object__resolve_externs(struct bpf_object *obj,
8601fd42 7387 const char *extra_kconfig)
166750bc 7388{
1c0c7074 7389 bool need_config = false, need_kallsyms = false;
d370bbe1 7390 bool need_vmlinux_btf = false;
166750bc 7391 struct extern_desc *ext;
2e33efe3 7392 void *kcfg_data = NULL;
166750bc 7393 int err, i;
166750bc
AN
7394
7395 if (obj->nr_extern == 0)
7396 return 0;
7397
2e33efe3
AN
7398 if (obj->kconfig_map_idx >= 0)
7399 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
166750bc
AN
7400
7401 for (i = 0; i < obj->nr_extern; i++) {
7402 ext = &obj->externs[i];
7403
2e33efe3
AN
7404 if (ext->type == EXT_KCFG &&
7405 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7406 void *ext_val = kcfg_data + ext->kcfg.data_off;
166750bc
AN
7407 __u32 kver = get_kernel_version();
7408
7409 if (!kver) {
7410 pr_warn("failed to get kernel version\n");
7411 return -EINVAL;
7412 }
2e33efe3 7413 err = set_kcfg_value_num(ext, ext_val, kver);
166750bc
AN
7414 if (err)
7415 return err;
2e33efe3 7416 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
13d35a0c 7417 } else if (ext->type == EXT_KCFG && str_has_pfx(ext->name, "CONFIG_")) {
166750bc 7418 need_config = true;
1c0c7074 7419 } else if (ext->type == EXT_KSYM) {
d370bbe1
HL
7420 if (ext->ksym.type_id)
7421 need_vmlinux_btf = true;
7422 else
7423 need_kallsyms = true;
166750bc
AN
7424 } else {
7425 pr_warn("unrecognized extern '%s'\n", ext->name);
7426 return -EINVAL;
7427 }
7428 }
8601fd42 7429 if (need_config && extra_kconfig) {
2e33efe3 7430 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8601fd42
AN
7431 if (err)
7432 return -EINVAL;
7433 need_config = false;
7434 for (i = 0; i < obj->nr_extern; i++) {
7435 ext = &obj->externs[i];
2e33efe3 7436 if (ext->type == EXT_KCFG && !ext->is_set) {
8601fd42
AN
7437 need_config = true;
7438 break;
7439 }
7440 }
7441 }
166750bc 7442 if (need_config) {
2e33efe3 7443 err = bpf_object__read_kconfig_file(obj, kcfg_data);
166750bc
AN
7444 if (err)
7445 return -EINVAL;
7446 }
1c0c7074
AN
7447 if (need_kallsyms) {
7448 err = bpf_object__read_kallsyms_file(obj);
7449 if (err)
7450 return -EINVAL;
7451 }
d370bbe1
HL
7452 if (need_vmlinux_btf) {
7453 err = bpf_object__resolve_ksyms_btf_id(obj);
7454 if (err)
7455 return -EINVAL;
7456 }
166750bc
AN
7457 for (i = 0; i < obj->nr_extern; i++) {
7458 ext = &obj->externs[i];
7459
7460 if (!ext->is_set && !ext->is_weak) {
7461 pr_warn("extern %s (strong) not resolved\n", ext->name);
7462 return -ESRCH;
7463 } else if (!ext->is_set) {
7464 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7465 ext->name);
7466 }
7467 }
7468
7469 return 0;
7470}
7471
e7b924ca 7472static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
52d3352e 7473{
ec6d5f47 7474 int err, i;
6371ca3b 7475
52d3352e 7476 if (!obj)
e9fc3ce9 7477 return libbpf_err(-EINVAL);
52d3352e
WN
7478
7479 if (obj->loaded) {
d9297581 7480 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
e9fc3ce9 7481 return libbpf_err(-EINVAL);
52d3352e
WN
7482 }
7483
67234743 7484 if (obj->gen_loader)
be315829 7485 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
67234743 7486
fd9eef1a 7487 err = bpf_object__probe_loading(obj);
fe62de31 7488 err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8601fd42 7489 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
0d13bfce
AN
7490 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7491 err = err ? : bpf_object__sanitize_maps(obj);
590a0088 7492 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
0d13bfce 7493 err = err ? : bpf_object__create_maps(obj);
e7b924ca
AN
7494 err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7495 err = err ? : bpf_object__load_progs(obj, extra_log_level);
341ac5ff 7496 err = err ? : bpf_object_init_prog_arrays(obj);
a6ed02ca 7497
67234743
AS
7498 if (obj->gen_loader) {
7499 /* reset FDs */
4729445b
KKD
7500 if (obj->btf)
7501 btf__set_fd(obj->btf, -1);
67234743
AS
7502 for (i = 0; i < obj->nr_maps; i++)
7503 obj->maps[i].fd = -1;
7504 if (!err)
ba05fd36 7505 err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
67234743
AS
7506 }
7507
9dbe6015
KKD
7508 /* clean up fd_array */
7509 zfree(&obj->fd_array);
7510
4f33a53d
AN
7511 /* clean up module BTFs */
7512 for (i = 0; i < obj->btf_module_cnt; i++) {
91abb4a6 7513 close(obj->btf_modules[i].fd);
4f33a53d
AN
7514 btf__free(obj->btf_modules[i].btf);
7515 free(obj->btf_modules[i].name);
7516 }
7517 free(obj->btf_modules);
7518
7519 /* clean up vmlinux BTF */
a6ed02ca
KS
7520 btf__free(obj->btf_vmlinux);
7521 obj->btf_vmlinux = NULL;
7522
d9297581
AN
7523 obj->loaded = true; /* doesn't matter if successfully or not */
7524
0d13bfce
AN
7525 if (err)
7526 goto out;
52d3352e
WN
7527
7528 return 0;
7529out:
ec6d5f47
THJ
7530 /* unpin any maps that were auto-pinned during load */
7531 for (i = 0; i < obj->nr_maps; i++)
7532 if (obj->maps[i].pinned && !obj->maps[i].reused)
7533 bpf_map__unpin(&obj->maps[i], NULL);
7534
4a404a7e 7535 bpf_object_unload(obj);
be18010e 7536 pr_warn("failed to load object '%s'\n", obj->path);
e9fc3ce9 7537 return libbpf_err(err);
52d3352e
WN
7538}
7539
e7b924ca 7540int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
60276f98 7541{
e7b924ca
AN
7542 return bpf_object_load(attr->obj, attr->log_level, attr->target_btf_path);
7543}
60276f98 7544
e7b924ca
AN
7545int bpf_object__load(struct bpf_object *obj)
7546{
7547 return bpf_object_load(obj, 0, NULL);
60276f98
QM
7548}
7549
196f8487
THJ
7550static int make_parent_dir(const char *path)
7551{
7552 char *cp, errmsg[STRERR_BUFSIZE];
7553 char *dname, *dir;
7554 int err = 0;
7555
7556 dname = strdup(path);
7557 if (dname == NULL)
7558 return -ENOMEM;
7559
7560 dir = dirname(dname);
7561 if (mkdir(dir, 0700) && errno != EEXIST)
7562 err = -errno;
7563
7564 free(dname);
7565 if (err) {
7566 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7567 pr_warn("failed to mkdir %s: %s\n", path, cp);
7568 }
7569 return err;
7570}
7571
f367540c
JS
7572static int check_path(const char *path)
7573{
1ce6a9fc 7574 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7575 struct statfs st_fs;
7576 char *dname, *dir;
7577 int err = 0;
7578
7579 if (path == NULL)
7580 return -EINVAL;
7581
7582 dname = strdup(path);
7583 if (dname == NULL)
7584 return -ENOMEM;
7585
7586 dir = dirname(dname);
7587 if (statfs(dir, &st_fs)) {
24d6a808 7588 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
be18010e 7589 pr_warn("failed to statfs %s: %s\n", dir, cp);
f367540c
JS
7590 err = -errno;
7591 }
7592 free(dname);
7593
7594 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
be18010e 7595 pr_warn("specified path %s is not on BPF FS\n", path);
f367540c
JS
7596 err = -EINVAL;
7597 }
7598
7599 return err;
7600}
7601
e21d585c 7602static int bpf_program_pin_instance(struct bpf_program *prog, const char *path, int instance)
f367540c 7603{
1ce6a9fc 7604 char *cp, errmsg[STRERR_BUFSIZE];
f367540c
JS
7605 int err;
7606
196f8487
THJ
7607 err = make_parent_dir(path);
7608 if (err)
e9fc3ce9 7609 return libbpf_err(err);
196f8487 7610
f367540c
JS
7611 err = check_path(path);
7612 if (err)
e9fc3ce9 7613 return libbpf_err(err);
f367540c
JS
7614
7615 if (prog == NULL) {
be18010e 7616 pr_warn("invalid program pointer\n");
e9fc3ce9 7617 return libbpf_err(-EINVAL);
f367540c
JS
7618 }
7619
7620 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7621 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7622 instance, prog->name, prog->instances.nr);
e9fc3ce9 7623 return libbpf_err(-EINVAL);
f367540c
JS
7624 }
7625
7626 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
23ab656b
THJ
7627 err = -errno;
7628 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
be18010e 7629 pr_warn("failed to pin program: %s\n", cp);
e9fc3ce9 7630 return libbpf_err(err);
f367540c
JS
7631 }
7632 pr_debug("pinned program '%s'\n", path);
7633
7634 return 0;
7635}
7636
e21d585c 7637static int bpf_program_unpin_instance(struct bpf_program *prog, const char *path, int instance)
0c19a9fb
SF
7638{
7639 int err;
7640
7641 err = check_path(path);
7642 if (err)
e9fc3ce9 7643 return libbpf_err(err);
0c19a9fb
SF
7644
7645 if (prog == NULL) {
be18010e 7646 pr_warn("invalid program pointer\n");
e9fc3ce9 7647 return libbpf_err(-EINVAL);
0c19a9fb
SF
7648 }
7649
7650 if (instance < 0 || instance >= prog->instances.nr) {
be18010e 7651 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
52109584 7652 instance, prog->name, prog->instances.nr);
e9fc3ce9 7653 return libbpf_err(-EINVAL);
0c19a9fb
SF
7654 }
7655
7656 err = unlink(path);
7657 if (err != 0)
e9fc3ce9
AN
7658 return libbpf_err(-errno);
7659
0c19a9fb
SF
7660 pr_debug("unpinned program '%s'\n", path);
7661
7662 return 0;
7663}
7664
e21d585c
AN
7665__attribute__((alias("bpf_program_pin_instance")))
7666int bpf_object__pin_instance(struct bpf_program *prog, const char *path, int instance);
7667
7668__attribute__((alias("bpf_program_unpin_instance")))
7669int bpf_program__unpin_instance(struct bpf_program *prog, const char *path, int instance);
7670
f367540c
JS
7671int bpf_program__pin(struct bpf_program *prog, const char *path)
7672{
7673 int i, err;
7674
196f8487
THJ
7675 err = make_parent_dir(path);
7676 if (err)
e9fc3ce9 7677 return libbpf_err(err);
196f8487 7678
f367540c
JS
7679 err = check_path(path);
7680 if (err)
e9fc3ce9 7681 return libbpf_err(err);
f367540c
JS
7682
7683 if (prog == NULL) {
be18010e 7684 pr_warn("invalid program pointer\n");
e9fc3ce9 7685 return libbpf_err(-EINVAL);
f367540c
JS
7686 }
7687
7688 if (prog->instances.nr <= 0) {
52109584 7689 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7690 return libbpf_err(-EINVAL);
f367540c
JS
7691 }
7692
fd734c5c
SF
7693 if (prog->instances.nr == 1) {
7694 /* don't create subdirs when pinning single instance */
e21d585c 7695 return bpf_program_pin_instance(prog, path, 0);
fd734c5c
SF
7696 }
7697
0c19a9fb
SF
7698 for (i = 0; i < prog->instances.nr; i++) {
7699 char buf[PATH_MAX];
7700 int len;
7701
7702 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7703 if (len < 0) {
7704 err = -EINVAL;
7705 goto err_unpin;
7706 } else if (len >= PATH_MAX) {
7707 err = -ENAMETOOLONG;
7708 goto err_unpin;
7709 }
7710
e21d585c 7711 err = bpf_program_pin_instance(prog, buf, i);
0c19a9fb
SF
7712 if (err)
7713 goto err_unpin;
7714 }
7715
7716 return 0;
7717
7718err_unpin:
7719 for (i = i - 1; i >= 0; i--) {
7720 char buf[PATH_MAX];
7721 int len;
7722
7723 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7724 if (len < 0)
7725 continue;
7726 else if (len >= PATH_MAX)
7727 continue;
7728
e21d585c 7729 bpf_program_unpin_instance(prog, buf, i);
0c19a9fb
SF
7730 }
7731
7732 rmdir(path);
7733
e9fc3ce9 7734 return libbpf_err(err);
0c19a9fb
SF
7735}
7736
7737int bpf_program__unpin(struct bpf_program *prog, const char *path)
7738{
7739 int i, err;
7740
7741 err = check_path(path);
7742 if (err)
e9fc3ce9 7743 return libbpf_err(err);
0c19a9fb
SF
7744
7745 if (prog == NULL) {
be18010e 7746 pr_warn("invalid program pointer\n");
e9fc3ce9 7747 return libbpf_err(-EINVAL);
0c19a9fb
SF
7748 }
7749
7750 if (prog->instances.nr <= 0) {
52109584 7751 pr_warn("no instances of prog %s to pin\n", prog->name);
e9fc3ce9 7752 return libbpf_err(-EINVAL);
fd734c5c
SF
7753 }
7754
7755 if (prog->instances.nr == 1) {
7756 /* don't create subdirs when pinning single instance */
e21d585c 7757 return bpf_program_unpin_instance(prog, path, 0);
0c19a9fb
SF
7758 }
7759
f367540c
JS
7760 for (i = 0; i < prog->instances.nr; i++) {
7761 char buf[PATH_MAX];
7762 int len;
7763
7764 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7765 if (len < 0)
e9fc3ce9 7766 return libbpf_err(-EINVAL);
f367540c 7767 else if (len >= PATH_MAX)
e9fc3ce9 7768 return libbpf_err(-ENAMETOOLONG);
f367540c 7769
e21d585c 7770 err = bpf_program_unpin_instance(prog, buf, i);
f367540c
JS
7771 if (err)
7772 return err;
7773 }
7774
0c19a9fb
SF
7775 err = rmdir(path);
7776 if (err)
e9fc3ce9 7777 return libbpf_err(-errno);
0c19a9fb 7778
f367540c
JS
7779 return 0;
7780}
7781
b6989f35
JS
7782int bpf_map__pin(struct bpf_map *map, const char *path)
7783{
1ce6a9fc 7784 char *cp, errmsg[STRERR_BUFSIZE];
b6989f35
JS
7785 int err;
7786
b6989f35 7787 if (map == NULL) {
be18010e 7788 pr_warn("invalid map pointer\n");
e9fc3ce9 7789 return libbpf_err(-EINVAL);
b6989f35
JS
7790 }
7791
4580b25f
THJ
7792 if (map->pin_path) {
7793 if (path && strcmp(path, map->pin_path)) {
7794 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7795 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7796 return libbpf_err(-EINVAL);
4580b25f
THJ
7797 } else if (map->pinned) {
7798 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7799 bpf_map__name(map), map->pin_path);
7800 return 0;
7801 }
7802 } else {
7803 if (!path) {
7804 pr_warn("missing a path to pin map '%s' at\n",
7805 bpf_map__name(map));
e9fc3ce9 7806 return libbpf_err(-EINVAL);
4580b25f
THJ
7807 } else if (map->pinned) {
7808 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
e9fc3ce9 7809 return libbpf_err(-EEXIST);
4580b25f
THJ
7810 }
7811
7812 map->pin_path = strdup(path);
7813 if (!map->pin_path) {
7814 err = -errno;
7815 goto out_err;
7816 }
b6989f35
JS
7817 }
7818
196f8487
THJ
7819 err = make_parent_dir(map->pin_path);
7820 if (err)
e9fc3ce9 7821 return libbpf_err(err);
196f8487 7822
4580b25f
THJ
7823 err = check_path(map->pin_path);
7824 if (err)
e9fc3ce9 7825 return libbpf_err(err);
4580b25f
THJ
7826
7827 if (bpf_obj_pin(map->fd, map->pin_path)) {
7828 err = -errno;
7829 goto out_err;
7830 }
7831
7832 map->pinned = true;
7833 pr_debug("pinned map '%s'\n", map->pin_path);
0c19a9fb 7834
b6989f35 7835 return 0;
4580b25f
THJ
7836
7837out_err:
7838 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7839 pr_warn("failed to pin map: %s\n", cp);
e9fc3ce9 7840 return libbpf_err(err);
b6989f35
JS
7841}
7842
0c19a9fb
SF
7843int bpf_map__unpin(struct bpf_map *map, const char *path)
7844{
7845 int err;
7846
0c19a9fb 7847 if (map == NULL) {
be18010e 7848 pr_warn("invalid map pointer\n");
e9fc3ce9 7849 return libbpf_err(-EINVAL);
0c19a9fb
SF
7850 }
7851
4580b25f
THJ
7852 if (map->pin_path) {
7853 if (path && strcmp(path, map->pin_path)) {
7854 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7855 bpf_map__name(map), map->pin_path, path);
e9fc3ce9 7856 return libbpf_err(-EINVAL);
4580b25f
THJ
7857 }
7858 path = map->pin_path;
7859 } else if (!path) {
7860 pr_warn("no path to unpin map '%s' from\n",
7861 bpf_map__name(map));
e9fc3ce9 7862 return libbpf_err(-EINVAL);
4580b25f
THJ
7863 }
7864
7865 err = check_path(path);
7866 if (err)
e9fc3ce9 7867 return libbpf_err(err);
4580b25f 7868
0c19a9fb
SF
7869 err = unlink(path);
7870 if (err != 0)
e9fc3ce9 7871 return libbpf_err(-errno);
4580b25f
THJ
7872
7873 map->pinned = false;
7874 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
0c19a9fb
SF
7875
7876 return 0;
7877}
7878
4580b25f
THJ
7879int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7880{
7881 char *new = NULL;
7882
7883 if (path) {
7884 new = strdup(path);
7885 if (!new)
e9fc3ce9 7886 return libbpf_err(-errno);
4580b25f
THJ
7887 }
7888
7889 free(map->pin_path);
7890 map->pin_path = new;
7891 return 0;
7892}
7893
7894const char *bpf_map__get_pin_path(const struct bpf_map *map)
7895{
7896 return map->pin_path;
7897}
7898
e244d34d
EL
7899const char *bpf_map__pin_path(const struct bpf_map *map)
7900{
7901 return map->pin_path;
7902}
7903
4580b25f
THJ
7904bool bpf_map__is_pinned(const struct bpf_map *map)
7905{
7906 return map->pinned;
7907}
7908
9cf309c5
THJ
7909static void sanitize_pin_path(char *s)
7910{
7911 /* bpffs disallows periods in path names */
7912 while (*s) {
7913 if (*s == '.')
7914 *s = '_';
7915 s++;
7916 }
7917}
7918
0c19a9fb 7919int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
d5148d85 7920{
d5148d85
JS
7921 struct bpf_map *map;
7922 int err;
7923
7924 if (!obj)
e9fc3ce9 7925 return libbpf_err(-ENOENT);
d5148d85
JS
7926
7927 if (!obj->loaded) {
be18010e 7928 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 7929 return libbpf_err(-ENOENT);
d5148d85
JS
7930 }
7931
f74a53d9 7932 bpf_object__for_each_map(map, obj) {
4580b25f 7933 char *pin_path = NULL;
0c19a9fb 7934 char buf[PATH_MAX];
0c19a9fb 7935
229fae38
SC
7936 if (map->skipped)
7937 continue;
7938
4580b25f
THJ
7939 if (path) {
7940 int len;
7941
7942 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7943 bpf_map__name(map));
7944 if (len < 0) {
7945 err = -EINVAL;
7946 goto err_unpin_maps;
7947 } else if (len >= PATH_MAX) {
7948 err = -ENAMETOOLONG;
7949 goto err_unpin_maps;
7950 }
9cf309c5 7951 sanitize_pin_path(buf);
4580b25f
THJ
7952 pin_path = buf;
7953 } else if (!map->pin_path) {
7954 continue;
0c19a9fb
SF
7955 }
7956
4580b25f 7957 err = bpf_map__pin(map, pin_path);
0c19a9fb
SF
7958 if (err)
7959 goto err_unpin_maps;
7960 }
7961
7962 return 0;
7963
7964err_unpin_maps:
bcc40fc0 7965 while ((map = bpf_object__prev_map(obj, map))) {
4580b25f 7966 if (!map->pin_path)
0c19a9fb
SF
7967 continue;
7968
4580b25f 7969 bpf_map__unpin(map, NULL);
0c19a9fb
SF
7970 }
7971
e9fc3ce9 7972 return libbpf_err(err);
0c19a9fb
SF
7973}
7974
7975int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7976{
7977 struct bpf_map *map;
7978 int err;
7979
7980 if (!obj)
e9fc3ce9 7981 return libbpf_err(-ENOENT);
0c19a9fb 7982
f74a53d9 7983 bpf_object__for_each_map(map, obj) {
4580b25f 7984 char *pin_path = NULL;
d5148d85 7985 char buf[PATH_MAX];
d5148d85 7986
4580b25f
THJ
7987 if (path) {
7988 int len;
7989
7990 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7991 bpf_map__name(map));
7992 if (len < 0)
e9fc3ce9 7993 return libbpf_err(-EINVAL);
4580b25f 7994 else if (len >= PATH_MAX)
e9fc3ce9 7995 return libbpf_err(-ENAMETOOLONG);
9cf309c5 7996 sanitize_pin_path(buf);
4580b25f
THJ
7997 pin_path = buf;
7998 } else if (!map->pin_path) {
7999 continue;
8000 }
d5148d85 8001
4580b25f 8002 err = bpf_map__unpin(map, pin_path);
d5148d85 8003 if (err)
e9fc3ce9 8004 return libbpf_err(err);
d5148d85
JS
8005 }
8006
0c19a9fb
SF
8007 return 0;
8008}
8009
8010int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8011{
8012 struct bpf_program *prog;
8013 int err;
8014
8015 if (!obj)
e9fc3ce9 8016 return libbpf_err(-ENOENT);
0c19a9fb
SF
8017
8018 if (!obj->loaded) {
be18010e 8019 pr_warn("object not yet loaded; load it first\n");
e9fc3ce9 8020 return libbpf_err(-ENOENT);
0c19a9fb
SF
8021 }
8022
0c19a9fb
SF
8023 bpf_object__for_each_program(prog, obj) {
8024 char buf[PATH_MAX];
8025 int len;
8026
8027 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8028 prog->pin_name);
0c19a9fb
SF
8029 if (len < 0) {
8030 err = -EINVAL;
8031 goto err_unpin_programs;
8032 } else if (len >= PATH_MAX) {
8033 err = -ENAMETOOLONG;
8034 goto err_unpin_programs;
8035 }
8036
8037 err = bpf_program__pin(prog, buf);
8038 if (err)
8039 goto err_unpin_programs;
8040 }
8041
8042 return 0;
8043
8044err_unpin_programs:
bcc40fc0 8045 while ((prog = bpf_object__prev_program(obj, prog))) {
0c19a9fb
SF
8046 char buf[PATH_MAX];
8047 int len;
8048
8049 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8050 prog->pin_name);
0c19a9fb
SF
8051 if (len < 0)
8052 continue;
8053 else if (len >= PATH_MAX)
8054 continue;
8055
8056 bpf_program__unpin(prog, buf);
8057 }
8058
e9fc3ce9 8059 return libbpf_err(err);
0c19a9fb
SF
8060}
8061
8062int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8063{
8064 struct bpf_program *prog;
8065 int err;
8066
8067 if (!obj)
e9fc3ce9 8068 return libbpf_err(-ENOENT);
0c19a9fb 8069
d5148d85
JS
8070 bpf_object__for_each_program(prog, obj) {
8071 char buf[PATH_MAX];
8072 int len;
8073
8074 len = snprintf(buf, PATH_MAX, "%s/%s", path,
33a2c75c 8075 prog->pin_name);
d5148d85 8076 if (len < 0)
e9fc3ce9 8077 return libbpf_err(-EINVAL);
d5148d85 8078 else if (len >= PATH_MAX)
e9fc3ce9 8079 return libbpf_err(-ENAMETOOLONG);
d5148d85 8080
0c19a9fb 8081 err = bpf_program__unpin(prog, buf);
d5148d85 8082 if (err)
e9fc3ce9 8083 return libbpf_err(err);
d5148d85
JS
8084 }
8085
8086 return 0;
8087}
8088
0c19a9fb
SF
8089int bpf_object__pin(struct bpf_object *obj, const char *path)
8090{
8091 int err;
8092
8093 err = bpf_object__pin_maps(obj, path);
8094 if (err)
e9fc3ce9 8095 return libbpf_err(err);
0c19a9fb
SF
8096
8097 err = bpf_object__pin_programs(obj, path);
8098 if (err) {
8099 bpf_object__unpin_maps(obj, path);
e9fc3ce9 8100 return libbpf_err(err);
0c19a9fb
SF
8101 }
8102
8103 return 0;
8104}
8105
2d39d7c5
AN
8106static void bpf_map__destroy(struct bpf_map *map)
8107{
8108 if (map->clear_priv)
8109 map->clear_priv(map, map->priv);
8110 map->priv = NULL;
8111 map->clear_priv = NULL;
8112
646f02ff
AN
8113 if (map->inner_map) {
8114 bpf_map__destroy(map->inner_map);
8115 zfree(&map->inner_map);
8116 }
8117
8118 zfree(&map->init_slots);
8119 map->init_slots_sz = 0;
8120
2d39d7c5
AN
8121 if (map->mmaped) {
8122 munmap(map->mmaped, bpf_map_mmap_sz(map));
8123 map->mmaped = NULL;
8124 }
8125
8126 if (map->st_ops) {
8127 zfree(&map->st_ops->data);
8128 zfree(&map->st_ops->progs);
8129 zfree(&map->st_ops->kern_func_off);
8130 zfree(&map->st_ops);
8131 }
8132
8133 zfree(&map->name);
aed65917 8134 zfree(&map->real_name);
2d39d7c5
AN
8135 zfree(&map->pin_path);
8136
8137 if (map->fd >= 0)
8138 zclose(map->fd);
8139}
8140
1a5e3fb1
WN
8141void bpf_object__close(struct bpf_object *obj)
8142{
a5b8bd47
WN
8143 size_t i;
8144
50450fc7 8145 if (IS_ERR_OR_NULL(obj))
1a5e3fb1
WN
8146 return;
8147
10931d24
WN
8148 if (obj->clear_priv)
8149 obj->clear_priv(obj, obj->priv);
8150
67234743 8151 bpf_gen__free(obj->gen_loader);
1a5e3fb1 8152 bpf_object__elf_finish(obj);
4a404a7e 8153 bpf_object_unload(obj);
8a138aed 8154 btf__free(obj->btf);
2993e051 8155 btf_ext__free(obj->btf_ext);
1a5e3fb1 8156
2d39d7c5
AN
8157 for (i = 0; i < obj->nr_maps; i++)
8158 bpf_map__destroy(&obj->maps[i]);
d859900c 8159
1373ff59 8160 zfree(&obj->btf_custom_path);
8601fd42 8161 zfree(&obj->kconfig);
166750bc
AN
8162 zfree(&obj->externs);
8163 obj->nr_extern = 0;
8164
9d759a9b
WN
8165 zfree(&obj->maps);
8166 obj->nr_maps = 0;
a5b8bd47
WN
8167
8168 if (obj->programs && obj->nr_programs) {
8169 for (i = 0; i < obj->nr_programs; i++)
8170 bpf_program__exit(&obj->programs[i]);
8171 }
8172 zfree(&obj->programs);
8173
9a208eff 8174 list_del(&obj->list);
1a5e3fb1
WN
8175 free(obj);
8176}
aa9b1ac3 8177
9a208eff
WN
8178struct bpf_object *
8179bpf_object__next(struct bpf_object *prev)
8180{
8181 struct bpf_object *next;
689624f0
JB
8182 bool strict = (libbpf_mode & LIBBPF_STRICT_NO_OBJECT_LIST);
8183
8184 if (strict)
8185 return NULL;
9a208eff
WN
8186
8187 if (!prev)
8188 next = list_first_entry(&bpf_objects_list,
8189 struct bpf_object,
8190 list);
8191 else
8192 next = list_next_entry(prev, list);
8193
8194 /* Empty list is noticed here so don't need checking on entry. */
8195 if (&next->list == &bpf_objects_list)
8196 return NULL;
8197
8198 return next;
8199}
8200
a324aae3 8201const char *bpf_object__name(const struct bpf_object *obj)
acf860ae 8202{
e9fc3ce9 8203 return obj ? obj->name : libbpf_err_ptr(-EINVAL);
acf860ae
WN
8204}
8205
a324aae3 8206unsigned int bpf_object__kversion(const struct bpf_object *obj)
45825d8a 8207{
a7fe0450 8208 return obj ? obj->kern_version : 0;
45825d8a
WN
8209}
8210
a324aae3 8211struct btf *bpf_object__btf(const struct bpf_object *obj)
789f6bab
AI
8212{
8213 return obj ? obj->btf : NULL;
8214}
8215
8a138aed
MKL
8216int bpf_object__btf_fd(const struct bpf_object *obj)
8217{
8218 return obj->btf ? btf__fd(obj->btf) : -1;
8219}
8220
155f556d
RDT
8221int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8222{
8223 if (obj->loaded)
e9fc3ce9 8224 return libbpf_err(-EINVAL);
155f556d
RDT
8225
8226 obj->kern_version = kern_version;
8227
8228 return 0;
8229}
8230
10931d24
WN
8231int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8232 bpf_object_clear_priv_t clear_priv)
8233{
8234 if (obj->priv && obj->clear_priv)
8235 obj->clear_priv(obj, obj->priv);
8236
8237 obj->priv = priv;
8238 obj->clear_priv = clear_priv;
8239 return 0;
8240}
8241
a324aae3 8242void *bpf_object__priv(const struct bpf_object *obj)
10931d24 8243{
e9fc3ce9 8244 return obj ? obj->priv : libbpf_err_ptr(-EINVAL);
10931d24
WN
8245}
8246
67234743
AS
8247int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8248{
8249 struct bpf_gen *gen;
8250
8251 if (!opts)
8252 return -EFAULT;
8253 if (!OPTS_VALID(opts, gen_loader_opts))
8254 return -EINVAL;
8255 gen = calloc(sizeof(*gen), 1);
8256 if (!gen)
8257 return -ENOMEM;
8258 gen->opts = opts;
8259 obj->gen_loader = gen;
8260 return 0;
8261}
8262
eac7d845 8263static struct bpf_program *
a324aae3
AN
8264__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8265 bool forward)
aa9b1ac3 8266{
a83d6e76 8267 size_t nr_programs = obj->nr_programs;
0c19a9fb 8268 ssize_t idx;
aa9b1ac3 8269
a83d6e76 8270 if (!nr_programs)
aa9b1ac3 8271 return NULL;
aa9b1ac3 8272
a83d6e76
MKL
8273 if (!p)
8274 /* Iter from the beginning */
8275 return forward ? &obj->programs[0] :
8276 &obj->programs[nr_programs - 1];
8277
0c19a9fb 8278 if (p->obj != obj) {
be18010e 8279 pr_warn("error: program handler doesn't match object\n");
e9fc3ce9 8280 return errno = EINVAL, NULL;
aa9b1ac3
WN
8281 }
8282
a83d6e76 8283 idx = (p - obj->programs) + (forward ? 1 : -1);
0c19a9fb 8284 if (idx >= obj->nr_programs || idx < 0)
aa9b1ac3
WN
8285 return NULL;
8286 return &obj->programs[idx];
8287}
8288
eac7d845 8289struct bpf_program *
a324aae3 8290bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
2088a3a7
HC
8291{
8292 return bpf_object__next_program(obj, prev);
8293}
8294
8295struct bpf_program *
8296bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
eac7d845
JK
8297{
8298 struct bpf_program *prog = prev;
8299
8300 do {
a83d6e76 8301 prog = __bpf_program__iter(prog, obj, true);
c3c55696 8302 } while (prog && prog_is_subprog(obj, prog));
0c19a9fb
SF
8303
8304 return prog;
8305}
8306
8307struct bpf_program *
a324aae3 8308bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
2088a3a7
HC
8309{
8310 return bpf_object__prev_program(obj, next);
8311}
8312
8313struct bpf_program *
8314bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
0c19a9fb
SF
8315{
8316 struct bpf_program *prog = next;
8317
0c19a9fb 8318 do {
a83d6e76 8319 prog = __bpf_program__iter(prog, obj, false);
c3c55696 8320 } while (prog && prog_is_subprog(obj, prog));
eac7d845
JK
8321
8322 return prog;
8323}
8324
edb13ed4
ACM
8325int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8326 bpf_program_clear_priv_t clear_priv)
aa9b1ac3
WN
8327{
8328 if (prog->priv && prog->clear_priv)
8329 prog->clear_priv(prog, prog->priv);
8330
8331 prog->priv = priv;
8332 prog->clear_priv = clear_priv;
8333 return 0;
8334}
8335
a324aae3 8336void *bpf_program__priv(const struct bpf_program *prog)
aa9b1ac3 8337{
e9fc3ce9 8338 return prog ? prog->priv : libbpf_err_ptr(-EINVAL);
aa9b1ac3
WN
8339}
8340
9aba3613
JK
8341void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8342{
8343 prog->prog_ifindex = ifindex;
8344}
8345
01af3bf0
AN
8346const char *bpf_program__name(const struct bpf_program *prog)
8347{
8348 return prog->name;
8349}
8350
52109584
AN
8351const char *bpf_program__section_name(const struct bpf_program *prog)
8352{
8353 return prog->sec_name;
8354}
8355
a324aae3 8356const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
aa9b1ac3
WN
8357{
8358 const char *title;
8359
52109584 8360 title = prog->sec_name;
715f8db9 8361 if (needs_copy) {
aa9b1ac3
WN
8362 title = strdup(title);
8363 if (!title) {
be18010e 8364 pr_warn("failed to strdup program title\n");
e9fc3ce9 8365 return libbpf_err_ptr(-ENOMEM);
aa9b1ac3
WN
8366 }
8367 }
8368
8369 return title;
8370}
8371
d9297581
AN
8372bool bpf_program__autoload(const struct bpf_program *prog)
8373{
8374 return prog->load;
8375}
8376
8377int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8378{
8379 if (prog->obj->loaded)
e9fc3ce9 8380 return libbpf_err(-EINVAL);
d9297581
AN
8381
8382 prog->load = autoload;
8383 return 0;
8384}
8385
bcc40fc0
AN
8386static int bpf_program_nth_fd(const struct bpf_program *prog, int n);
8387
a324aae3 8388int bpf_program__fd(const struct bpf_program *prog)
aa9b1ac3 8389{
bcc40fc0 8390 return bpf_program_nth_fd(prog, 0);
b580563e
WN
8391}
8392
1a734efe
THJ
8393size_t bpf_program__size(const struct bpf_program *prog)
8394{
9c0f8cbd 8395 return prog->insns_cnt * BPF_INSN_SZ;
1a734efe
THJ
8396}
8397
65a7fa2e
AN
8398const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8399{
8400 return prog->insns;
8401}
8402
8403size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8404{
8405 return prog->insns_cnt;
8406}
8407
b580563e
WN
8408int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8409 bpf_program_prep_t prep)
8410{
8411 int *instances_fds;
8412
8413 if (nr_instances <= 0 || !prep)
e9fc3ce9 8414 return libbpf_err(-EINVAL);
b580563e
WN
8415
8416 if (prog->instances.nr > 0 || prog->instances.fds) {
be18010e 8417 pr_warn("Can't set pre-processor after loading\n");
e9fc3ce9 8418 return libbpf_err(-EINVAL);
b580563e
WN
8419 }
8420
8421 instances_fds = malloc(sizeof(int) * nr_instances);
8422 if (!instances_fds) {
be18010e 8423 pr_warn("alloc memory failed for fds\n");
e9fc3ce9 8424 return libbpf_err(-ENOMEM);
b580563e
WN
8425 }
8426
8427 /* fill all fd with -1 */
8428 memset(instances_fds, -1, sizeof(int) * nr_instances);
8429
8430 prog->instances.nr = nr_instances;
8431 prog->instances.fds = instances_fds;
8432 prog->preprocessor = prep;
8433 return 0;
8434}
8435
bcc40fc0
AN
8436__attribute__((alias("bpf_program_nth_fd")))
8437int bpf_program__nth_fd(const struct bpf_program *prog, int n);
8438
8439static int bpf_program_nth_fd(const struct bpf_program *prog, int n)
b580563e
WN
8440{
8441 int fd;
8442
1e960043 8443 if (!prog)
e9fc3ce9 8444 return libbpf_err(-EINVAL);
1e960043 8445
b580563e 8446 if (n >= prog->instances.nr || n < 0) {
be18010e 8447 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
52109584 8448 n, prog->name, prog->instances.nr);
e9fc3ce9 8449 return libbpf_err(-EINVAL);
b580563e
WN
8450 }
8451
8452 fd = prog->instances.fds[n];
8453 if (fd < 0) {
be18010e 8454 pr_warn("%dth instance of program '%s' is invalid\n",
52109584 8455 n, prog->name);
e9fc3ce9 8456 return libbpf_err(-ENOENT);
b580563e
WN
8457 }
8458
8459 return fd;
aa9b1ac3 8460}
9d759a9b 8461
a46410d5 8462enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog)
f1eead9e
AN
8463{
8464 return prog->type;
8465}
8466
dd26b7f5 8467void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
5f44e4c8
WN
8468{
8469 prog->type = type;
8470}
8471
a324aae3 8472static bool bpf_program__is_type(const struct bpf_program *prog,
5f44e4c8
WN
8473 enum bpf_prog_type type)
8474{
8475 return prog ? (prog->type == type) : false;
8476}
8477
a324aae3
AN
8478#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8479int bpf_program__set_##NAME(struct bpf_program *prog) \
8480{ \
8481 if (!prog) \
e9fc3ce9 8482 return libbpf_err(-EINVAL); \
a324aae3
AN
8483 bpf_program__set_type(prog, TYPE); \
8484 return 0; \
8485} \
8486 \
8487bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8488{ \
8489 return bpf_program__is_type(prog, TYPE); \
8490} \
ed794073 8491
7803ba73 8492BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
1e092a03 8493BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
ed794073 8494BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
7803ba73
JS
8495BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8496BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
ed794073 8497BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
e14c93fd 8498BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
7803ba73
JS
8499BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8500BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
12a8654b 8501BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
590a0088 8502BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
2db6eab1 8503BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
499dd29d 8504BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
5f44e4c8 8505
f1eead9e 8506enum bpf_attach_type
a46410d5 8507bpf_program__get_expected_attach_type(const struct bpf_program *prog)
f1eead9e
AN
8508{
8509 return prog->expected_attach_type;
8510}
8511
16962b24
JF
8512void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8513 enum bpf_attach_type type)
d7be143b
AI
8514{
8515 prog->expected_attach_type = type;
8516}
8517
a6ca7158
AN
8518__u32 bpf_program__flags(const struct bpf_program *prog)
8519{
8520 return prog->prog_flags;
8521}
8522
8cccee9e 8523int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
a6ca7158
AN
8524{
8525 if (prog->obj->loaded)
8526 return libbpf_err(-EBUSY);
8527
8cccee9e 8528 prog->prog_flags = flags;
a6ca7158
AN
8529 return 0;
8530}
8531
dbdd2c7f
AN
8532__u32 bpf_program__log_level(const struct bpf_program *prog)
8533{
8534 return prog->log_level;
8535}
8536
8537int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8538{
8539 if (prog->obj->loaded)
8540 return libbpf_err(-EBUSY);
8541
8542 prog->log_level = log_level;
8543 return 0;
8544}
8545
b3ce9079
AN
8546const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8547{
8548 *log_size = prog->log_size;
8549 return prog->log_buf;
8550}
8551
8552int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8553{
8554 if (log_size && !log_buf)
8555 return -EINVAL;
8556 if (prog->log_size > UINT_MAX)
8557 return -EINVAL;
8558 if (prog->obj->loaded)
8559 return -EBUSY;
8560
8561 prog->log_buf = log_buf;
8562 prog->log_size = log_size;
a6ca7158
AN
8563 return 0;
8564}
8565
15ea31fa 8566#define SEC_DEF(sec_pfx, ptype, atype, flags, ...) { \
d7a18ea7 8567 .sec = sec_pfx, \
d7a18ea7 8568 .prog_type = BPF_PROG_TYPE_##ptype, \
15ea31fa
AN
8569 .expected_attach_type = atype, \
8570 .cookie = (long)(flags), \
12d9466d 8571 .preload_fn = libbpf_preload_prog, \
d7a18ea7
AN
8572 __VA_ARGS__ \
8573}
8574
12d9466d
AN
8575static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie);
8576static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie);
8577static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie);
8578static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie);
8579static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie);
8580static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie);
d7a18ea7 8581
d7a18ea7 8582static const struct bpf_sec_def section_defs[] = {
dd94d45c
AN
8583 SEC_DEF("socket", SOCKET_FILTER, 0, SEC_NONE | SEC_SLOPPY_PFX),
8584 SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8585 SEC_DEF("sk_reuseport", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
15ea31fa
AN
8586 SEC_DEF("kprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8587 SEC_DEF("uprobe/", KPROBE, 0, SEC_NONE),
8588 SEC_DEF("kretprobe/", KPROBE, 0, SEC_NONE, attach_kprobe),
8589 SEC_DEF("uretprobe/", KPROBE, 0, SEC_NONE),
15ea31fa 8590 SEC_DEF("tc", SCHED_CLS, 0, SEC_NONE),
dd94d45c
AN
8591 SEC_DEF("classifier", SCHED_CLS, 0, SEC_NONE | SEC_SLOPPY_PFX),
8592 SEC_DEF("action", SCHED_ACT, 0, SEC_NONE | SEC_SLOPPY_PFX),
15ea31fa
AN
8593 SEC_DEF("tracepoint/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8594 SEC_DEF("tp/", TRACEPOINT, 0, SEC_NONE, attach_tp),
8595 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8596 SEC_DEF("raw_tp/", RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
ccaf12d6
HT
8597 SEC_DEF("raw_tracepoint.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8598 SEC_DEF("raw_tp.w/", RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
15ea31fa
AN
8599 SEC_DEF("tp_btf/", TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8600 SEC_DEF("fentry/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8601 SEC_DEF("fmod_ret/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8602 SEC_DEF("fexit/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8603 SEC_DEF("fentry.s/", TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8604 SEC_DEF("fmod_ret.s/", TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8605 SEC_DEF("fexit.s/", TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8606 SEC_DEF("freplace/", EXT, 0, SEC_ATTACH_BTF, attach_trace),
8607 SEC_DEF("lsm/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8608 SEC_DEF("lsm.s/", LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8609 SEC_DEF("iter/", TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8610 SEC_DEF("syscall", SYSCALL, 0, SEC_SLEEPABLE),
d41ea045
AN
8611 SEC_DEF("xdp_devmap/", XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8612 SEC_DEF("xdp_cpumap/", XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
dd94d45c
AN
8613 SEC_DEF("xdp", XDP, BPF_XDP, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8614 SEC_DEF("perf_event", PERF_EVENT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8615 SEC_DEF("lwt_in", LWT_IN, 0, SEC_NONE | SEC_SLOPPY_PFX),
8616 SEC_DEF("lwt_out", LWT_OUT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8617 SEC_DEF("lwt_xmit", LWT_XMIT, 0, SEC_NONE | SEC_SLOPPY_PFX),
8618 SEC_DEF("lwt_seg6local", LWT_SEG6LOCAL, 0, SEC_NONE | SEC_SLOPPY_PFX),
8619 SEC_DEF("cgroup_skb/ingress", CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8620 SEC_DEF("cgroup_skb/egress", CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8621 SEC_DEF("cgroup/skb", CGROUP_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8622 SEC_DEF("cgroup/sock_create", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8623 SEC_DEF("cgroup/sock_release", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8624 SEC_DEF("cgroup/sock", CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8625 SEC_DEF("cgroup/post_bind4", CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8626 SEC_DEF("cgroup/post_bind6", CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8627 SEC_DEF("cgroup/dev", CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8628 SEC_DEF("sockops", SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8629 SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8630 SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8631 SEC_DEF("sk_skb", SK_SKB, 0, SEC_NONE | SEC_SLOPPY_PFX),
8632 SEC_DEF("sk_msg", SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8633 SEC_DEF("lirc_mode2", LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8634 SEC_DEF("flow_dissector", FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT | SEC_SLOPPY_PFX),
8635 SEC_DEF("cgroup/bind4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8636 SEC_DEF("cgroup/bind6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8637 SEC_DEF("cgroup/connect4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8638 SEC_DEF("cgroup/connect6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8639 SEC_DEF("cgroup/sendmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8640 SEC_DEF("cgroup/sendmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8641 SEC_DEF("cgroup/recvmsg4", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8642 SEC_DEF("cgroup/recvmsg6", CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8643 SEC_DEF("cgroup/getpeername4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8644 SEC_DEF("cgroup/getpeername6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8645 SEC_DEF("cgroup/getsockname4", CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8646 SEC_DEF("cgroup/getsockname6", CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8647 SEC_DEF("cgroup/sysctl", CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8648 SEC_DEF("cgroup/getsockopt", CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8649 SEC_DEF("cgroup/setsockopt", CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
8650 SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE),
7c80c87a 8651 SEC_DEF("sk_lookup", SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE | SEC_SLOPPY_PFX),
583c9009 8652};
d7be143b 8653
c76e4c22
TS
8654#define MAX_TYPE_NAME_SIZE 32
8655
d7a18ea7
AN
8656static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8657{
dd94d45c
AN
8658 const struct bpf_sec_def *sec_def;
8659 enum sec_def_flags sec_flags;
8660 int i, n = ARRAY_SIZE(section_defs), len;
8661 bool strict = libbpf_mode & LIBBPF_STRICT_SEC_NAME;
d7a18ea7
AN
8662
8663 for (i = 0; i < n; i++) {
dd94d45c
AN
8664 sec_def = &section_defs[i];
8665 sec_flags = sec_def->cookie;
8666 len = strlen(sec_def->sec);
8667
8668 /* "type/" always has to have proper SEC("type/extras") form */
8669 if (sec_def->sec[len - 1] == '/') {
8670 if (str_has_pfx(sec_name, sec_def->sec))
8671 return sec_def;
8672 continue;
8673 }
8674
8675 /* "type+" means it can be either exact SEC("type") or
8676 * well-formed SEC("type/extras") with proper '/' separator
8677 */
8678 if (sec_def->sec[len - 1] == '+') {
8679 len--;
8680 /* not even a prefix */
8681 if (strncmp(sec_name, sec_def->sec, len) != 0)
8682 continue;
8683 /* exact match or has '/' separator */
8684 if (sec_name[len] == '\0' || sec_name[len] == '/')
8685 return sec_def;
8686 continue;
8687 }
8688
8689 /* SEC_SLOPPY_PFX definitions are allowed to be just prefix
8690 * matches, unless strict section name mode
8691 * (LIBBPF_STRICT_SEC_NAME) is enabled, in which case the
8692 * match has to be exact.
8693 */
8694 if ((sec_flags & SEC_SLOPPY_PFX) && !strict) {
8695 if (str_has_pfx(sec_name, sec_def->sec))
8696 return sec_def;
8697 continue;
8698 }
8699
8700 /* Definitions not marked SEC_SLOPPY_PFX (e.g.,
8701 * SEC("syscall")) are exact matches in both modes.
8702 */
8703 if (strcmp(sec_name, sec_def->sec) == 0)
8704 return sec_def;
d7a18ea7
AN
8705 }
8706 return NULL;
8707}
8708
c76e4c22
TS
8709static char *libbpf_get_type_names(bool attach_type)
8710{
d7a18ea7 8711 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
c76e4c22
TS
8712 char *buf;
8713
8714 buf = malloc(len);
8715 if (!buf)
8716 return NULL;
8717
8718 buf[0] = '\0';
8719 /* Forge string buf with all available names */
d7a18ea7 8720 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
15ea31fa
AN
8721 const struct bpf_sec_def *sec_def = &section_defs[i];
8722
8723 if (attach_type) {
8724 if (sec_def->preload_fn != libbpf_preload_prog)
8725 continue;
8726
8727 if (!(sec_def->cookie & SEC_ATTACHABLE))
8728 continue;
8729 }
c76e4c22 8730
d7a18ea7 8731 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
c76e4c22
TS
8732 free(buf);
8733 return NULL;
8734 }
8735 strcat(buf, " ");
d7a18ea7 8736 strcat(buf, section_defs[i].sec);
c76e4c22
TS
8737 }
8738
8739 return buf;
8740}
8741
b60df2a0
JK
8742int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8743 enum bpf_attach_type *expected_attach_type)
583c9009 8744{
d7a18ea7 8745 const struct bpf_sec_def *sec_def;
c76e4c22 8746 char *type_names;
583c9009 8747
b60df2a0 8748 if (!name)
e9fc3ce9 8749 return libbpf_err(-EINVAL);
583c9009 8750
d7a18ea7
AN
8751 sec_def = find_sec_def(name);
8752 if (sec_def) {
8753 *prog_type = sec_def->prog_type;
8754 *expected_attach_type = sec_def->expected_attach_type;
b60df2a0
JK
8755 return 0;
8756 }
d7a18ea7 8757
4a3d6c6a 8758 pr_debug("failed to guess program type from ELF section '%s'\n", name);
c76e4c22
TS
8759 type_names = libbpf_get_type_names(false);
8760 if (type_names != NULL) {
3f519353 8761 pr_debug("supported section(type) names are:%s\n", type_names);
c76e4c22
TS
8762 free(type_names);
8763 }
8764
e9fc3ce9 8765 return libbpf_err(-ESRCH);
b60df2a0 8766}
583c9009 8767
590a0088
MKL
8768static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8769 size_t offset)
8770{
8771 struct bpf_map *map;
8772 size_t i;
8773
8774 for (i = 0; i < obj->nr_maps; i++) {
8775 map = &obj->maps[i];
8776 if (!bpf_map__is_struct_ops(map))
8777 continue;
8778 if (map->sec_offset <= offset &&
8779 offset - map->sec_offset < map->def.value_size)
8780 return map;
8781 }
8782
8783 return NULL;
8784}
8785
8786/* Collect the reloc from ELF and populate the st_ops->progs[] */
646f02ff 8787static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
ad23b723 8788 Elf64_Shdr *shdr, Elf_Data *data)
590a0088
MKL
8789{
8790 const struct btf_member *member;
8791 struct bpf_struct_ops *st_ops;
8792 struct bpf_program *prog;
8793 unsigned int shdr_idx;
8794 const struct btf *btf;
8795 struct bpf_map *map;
7e06aad5 8796 unsigned int moff, insn_idx;
590a0088 8797 const char *name;
1d1a3bcf 8798 __u32 member_idx;
ad23b723
AN
8799 Elf64_Sym *sym;
8800 Elf64_Rel *rel;
590a0088
MKL
8801 int i, nrels;
8802
590a0088
MKL
8803 btf = obj->btf;
8804 nrels = shdr->sh_size / shdr->sh_entsize;
8805 for (i = 0; i < nrels; i++) {
ad23b723
AN
8806 rel = elf_rel_by_idx(data, i);
8807 if (!rel) {
590a0088
MKL
8808 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8809 return -LIBBPF_ERRNO__FORMAT;
8810 }
8811
ad23b723
AN
8812 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8813 if (!sym) {
590a0088 8814 pr_warn("struct_ops reloc: symbol %zx not found\n",
ad23b723 8815 (size_t)ELF64_R_SYM(rel->r_info));
590a0088
MKL
8816 return -LIBBPF_ERRNO__FORMAT;
8817 }
8818
ad23b723
AN
8819 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8820 map = find_struct_ops_map_by_offset(obj, rel->r_offset);
590a0088 8821 if (!map) {
ad23b723
AN
8822 pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8823 (size_t)rel->r_offset);
590a0088
MKL
8824 return -EINVAL;
8825 }
8826
ad23b723
AN
8827 moff = rel->r_offset - map->sec_offset;
8828 shdr_idx = sym->st_shndx;
590a0088 8829 st_ops = map->st_ops;
ad23b723 8830 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 8831 map->name,
ad23b723
AN
8832 (long long)(rel->r_info >> 32),
8833 (long long)sym->st_value,
8834 shdr_idx, (size_t)rel->r_offset,
8835 map->sec_offset, sym->st_name, name);
590a0088
MKL
8836
8837 if (shdr_idx >= SHN_LORESERVE) {
ad23b723
AN
8838 pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8839 map->name, (size_t)rel->r_offset, shdr_idx);
590a0088
MKL
8840 return -LIBBPF_ERRNO__RELOC;
8841 }
ad23b723 8842 if (sym->st_value % BPF_INSN_SZ) {
7e06aad5 8843 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
ad23b723 8844 map->name, (unsigned long long)sym->st_value);
7e06aad5
AN
8845 return -LIBBPF_ERRNO__FORMAT;
8846 }
ad23b723 8847 insn_idx = sym->st_value / BPF_INSN_SZ;
590a0088
MKL
8848
8849 member = find_member_by_offset(st_ops->type, moff * 8);
8850 if (!member) {
8851 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8852 map->name, moff);
8853 return -EINVAL;
8854 }
8855 member_idx = member - btf_members(st_ops->type);
8856 name = btf__name_by_offset(btf, member->name_off);
8857
8858 if (!resolve_func_ptr(btf, member->type, NULL)) {
8859 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8860 map->name, name);
8861 return -EINVAL;
8862 }
8863
7e06aad5 8864 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
590a0088
MKL
8865 if (!prog) {
8866 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8867 map->name, shdr_idx, name);
8868 return -EINVAL;
8869 }
8870
91b4d1d1
AN
8871 /* prevent the use of BPF prog with invalid type */
8872 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8873 pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8874 map->name, prog->name);
8875 return -EINVAL;
8876 }
590a0088 8877
91b4d1d1
AN
8878 /* if we haven't yet processed this BPF program, record proper
8879 * attach_btf_id and member_idx
8880 */
8881 if (!prog->attach_btf_id) {
590a0088
MKL
8882 prog->attach_btf_id = st_ops->type_id;
8883 prog->expected_attach_type = member_idx;
590a0088 8884 }
91b4d1d1
AN
8885
8886 /* struct_ops BPF prog can be re-used between multiple
8887 * .struct_ops as long as it's the same struct_ops struct
8888 * definition and the same function pointer field
8889 */
8890 if (prog->attach_btf_id != st_ops->type_id ||
8891 prog->expected_attach_type != member_idx) {
8892 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",
8893 map->name, prog->name, prog->sec_name, prog->type,
8894 prog->attach_btf_id, prog->expected_attach_type, name);
8895 return -EINVAL;
8896 }
8897
590a0088
MKL
8898 st_ops->progs[member_idx] = prog;
8899 }
8900
8901 return 0;
590a0088
MKL
8902}
8903
a6ed02ca 8904#define BTF_TRACE_PREFIX "btf_trace_"
1e092a03 8905#define BTF_LSM_PREFIX "bpf_lsm_"
21aef70e 8906#define BTF_ITER_PREFIX "bpf_iter_"
a6ed02ca
KS
8907#define BTF_MAX_NAME_SIZE 128
8908
67234743
AS
8909void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8910 const char **prefix, int *kind)
8911{
8912 switch (attach_type) {
8913 case BPF_TRACE_RAW_TP:
8914 *prefix = BTF_TRACE_PREFIX;
8915 *kind = BTF_KIND_TYPEDEF;
8916 break;
8917 case BPF_LSM_MAC:
8918 *prefix = BTF_LSM_PREFIX;
8919 *kind = BTF_KIND_FUNC;
8920 break;
8921 case BPF_TRACE_ITER:
8922 *prefix = BTF_ITER_PREFIX;
8923 *kind = BTF_KIND_FUNC;
8924 break;
8925 default:
8926 *prefix = "";
8927 *kind = BTF_KIND_FUNC;
8928 }
8929}
8930
a6ed02ca
KS
8931static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8932 const char *name, __u32 kind)
8933{
8934 char btf_type_name[BTF_MAX_NAME_SIZE];
8935 int ret;
8936
8937 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8938 "%s%s", prefix, name);
8939 /* snprintf returns the number of characters written excluding the
c139e40a 8940 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
a6ed02ca
KS
8941 * indicates truncation.
8942 */
8943 if (ret < 0 || ret >= sizeof(btf_type_name))
8944 return -ENAMETOOLONG;
8945 return btf__find_by_name_kind(btf, btf_type_name, kind);
8946}
8947
91abb4a6
AN
8948static inline int find_attach_btf_id(struct btf *btf, const char *name,
8949 enum bpf_attach_type attach_type)
a6ed02ca 8950{
67234743
AS
8951 const char *prefix;
8952 int kind;
a6ed02ca 8953
67234743
AS
8954 btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8955 return find_btf_by_prefix_kind(btf, prefix, name, kind);
a6ed02ca
KS
8956}
8957
b8c54ea4
AS
8958int libbpf_find_vmlinux_btf_id(const char *name,
8959 enum bpf_attach_type attach_type)
12a8654b 8960{
a6ed02ca 8961 struct btf *btf;
3521ffa2 8962 int err;
12a8654b 8963
a710eed3 8964 btf = btf__load_vmlinux_btf();
e9fc3ce9
AN
8965 err = libbpf_get_error(btf);
8966 if (err) {
12a8654b 8967 pr_warn("vmlinux BTF is not found\n");
e9fc3ce9 8968 return libbpf_err(err);
12a8654b
AS
8969 }
8970
91abb4a6
AN
8971 err = find_attach_btf_id(btf, name, attach_type);
8972 if (err <= 0)
8973 pr_warn("%s is not found in vmlinux BTF\n", name);
8974
3521ffa2 8975 btf__free(btf);
e9fc3ce9 8976 return libbpf_err(err);
b8c54ea4
AS
8977}
8978
e7bf94db
AS
8979static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8980{
ebc7b50a
DM
8981 struct bpf_prog_info info = {};
8982 __u32 info_len = sizeof(info);
6cc93e2f 8983 struct btf *btf;
6d2d73cd 8984 int err;
e7bf94db 8985
ebc7b50a 8986 err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
e9fc3ce9 8987 if (err) {
ebc7b50a
DM
8988 pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
8989 attach_prog_fd, err);
e9fc3ce9 8990 return err;
e7bf94db 8991 }
6d2d73cd
QM
8992
8993 err = -EINVAL;
ebc7b50a 8994 if (!info.btf_id) {
e7bf94db
AS
8995 pr_warn("The target program doesn't have BTF\n");
8996 goto out;
8997 }
ebc7b50a
DM
8998 btf = btf__load_from_kernel_by_id(info.btf_id);
8999 err = libbpf_get_error(btf);
9000 if (err) {
9001 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
e7bf94db
AS
9002 goto out;
9003 }
9004 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9005 btf__free(btf);
9006 if (err <= 0) {
9007 pr_warn("%s is not found in prog's BTF\n", name);
9008 goto out;
9009 }
9010out:
e7bf94db
AS
9011 return err;
9012}
9013
91abb4a6
AN
9014static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9015 enum bpf_attach_type attach_type,
9016 int *btf_obj_fd, int *btf_type_id)
9017{
9018 int ret, i;
9019
9020 ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9021 if (ret > 0) {
9022 *btf_obj_fd = 0; /* vmlinux BTF */
9023 *btf_type_id = ret;
9024 return 0;
9025 }
9026 if (ret != -ENOENT)
9027 return ret;
9028
9029 ret = load_module_btfs(obj);
9030 if (ret)
9031 return ret;
9032
9033 for (i = 0; i < obj->btf_module_cnt; i++) {
9034 const struct module_btf *mod = &obj->btf_modules[i];
9035
9036 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9037 if (ret > 0) {
9038 *btf_obj_fd = mod->fd;
9039 *btf_type_id = ret;
9040 return 0;
9041 }
9042 if (ret == -ENOENT)
9043 continue;
9044
9045 return ret;
9046 }
9047
9048 return -ESRCH;
9049}
9050
15ea31fa
AN
9051static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9052 int *btf_obj_fd, int *btf_type_id)
b8c54ea4 9053{
a6ed02ca
KS
9054 enum bpf_attach_type attach_type = prog->expected_attach_type;
9055 __u32 attach_prog_fd = prog->attach_prog_fd;
b6291a6f 9056 int err = 0;
b8c54ea4 9057
91abb4a6
AN
9058 /* BPF program's BTF ID */
9059 if (attach_prog_fd) {
9060 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9061 if (err < 0) {
9062 pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9063 attach_prog_fd, attach_name, err);
9064 return err;
9065 }
9066 *btf_obj_fd = 0;
9067 *btf_type_id = err;
9068 return 0;
9069 }
9070
9071 /* kernel/module BTF ID */
67234743
AS
9072 if (prog->obj->gen_loader) {
9073 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9074 *btf_obj_fd = 0;
9075 *btf_type_id = 1;
9076 } else {
9077 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9078 }
91abb4a6
AN
9079 if (err) {
9080 pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
b8c54ea4 9081 return err;
12a8654b 9082 }
91abb4a6 9083 return 0;
12a8654b
AS
9084}
9085
956b620f
AI
9086int libbpf_attach_type_by_name(const char *name,
9087 enum bpf_attach_type *attach_type)
9088{
c76e4c22 9089 char *type_names;
b6291a6f 9090 const struct bpf_sec_def *sec_def;
956b620f
AI
9091
9092 if (!name)
e9fc3ce9 9093 return libbpf_err(-EINVAL);
956b620f 9094
b6291a6f
AN
9095 sec_def = find_sec_def(name);
9096 if (!sec_def) {
9097 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9098 type_names = libbpf_get_type_names(true);
9099 if (type_names != NULL) {
9100 pr_debug("attachable section(type) names are:%s\n", type_names);
9101 free(type_names);
9102 }
9103
9104 return libbpf_err(-EINVAL);
c76e4c22
TS
9105 }
9106
15ea31fa
AN
9107 if (sec_def->preload_fn != libbpf_preload_prog)
9108 return libbpf_err(-EINVAL);
9109 if (!(sec_def->cookie & SEC_ATTACHABLE))
b6291a6f
AN
9110 return libbpf_err(-EINVAL);
9111
9112 *attach_type = sec_def->expected_attach_type;
9113 return 0;
956b620f
AI
9114}
9115
a324aae3 9116int bpf_map__fd(const struct bpf_map *map)
9d759a9b 9117{
e9fc3ce9 9118 return map ? map->fd : libbpf_err(-EINVAL);
9d759a9b
WN
9119}
9120
a324aae3 9121const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
9d759a9b 9122{
e9fc3ce9 9123 return map ? &map->def : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9124}
9125
aed65917
AN
9126static bool map_uses_real_name(const struct bpf_map *map)
9127{
9128 /* Since libbpf started to support custom .data.* and .rodata.* maps,
9129 * their user-visible name differs from kernel-visible name. Users see
9130 * such map's corresponding ELF section name as a map name.
9131 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9132 * maps to know which name has to be returned to the user.
9133 */
9134 if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9135 return true;
9136 if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9137 return true;
9138 return false;
9139}
9140
a324aae3 9141const char *bpf_map__name(const struct bpf_map *map)
561bbcca 9142{
aed65917
AN
9143 if (!map)
9144 return NULL;
9145
9146 if (map_uses_real_name(map))
9147 return map->real_name;
9148
9149 return map->name;
561bbcca
WN
9150}
9151
1bdb6c9a
AN
9152enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9153{
9154 return map->def.type;
9155}
9156
9157int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9158{
9159 if (map->fd >= 0)
e9fc3ce9 9160 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9161 map->def.type = type;
9162 return 0;
9163}
9164
9165__u32 bpf_map__map_flags(const struct bpf_map *map)
9166{
9167 return map->def.map_flags;
9168}
9169
9170int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9171{
9172 if (map->fd >= 0)
e9fc3ce9 9173 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9174 map->def.map_flags = flags;
9175 return 0;
9176}
9177
47512102
JK
9178__u64 bpf_map__map_extra(const struct bpf_map *map)
9179{
9180 return map->map_extra;
9181}
9182
9183int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9184{
9185 if (map->fd >= 0)
9186 return libbpf_err(-EBUSY);
9187 map->map_extra = map_extra;
9188 return 0;
9189}
9190
1bdb6c9a
AN
9191__u32 bpf_map__numa_node(const struct bpf_map *map)
9192{
9193 return map->numa_node;
9194}
9195
9196int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9197{
9198 if (map->fd >= 0)
e9fc3ce9 9199 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9200 map->numa_node = numa_node;
9201 return 0;
9202}
9203
9204__u32 bpf_map__key_size(const struct bpf_map *map)
9205{
9206 return map->def.key_size;
9207}
9208
9209int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9210{
9211 if (map->fd >= 0)
e9fc3ce9 9212 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9213 map->def.key_size = size;
9214 return 0;
9215}
9216
9217__u32 bpf_map__value_size(const struct bpf_map *map)
9218{
9219 return map->def.value_size;
9220}
9221
9222int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9223{
9224 if (map->fd >= 0)
e9fc3ce9 9225 return libbpf_err(-EBUSY);
1bdb6c9a
AN
9226 map->def.value_size = size;
9227 return 0;
9228}
9229
5b891af7 9230__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8a138aed 9231{
61746dbe 9232 return map ? map->btf_key_type_id : 0;
8a138aed
MKL
9233}
9234
5b891af7 9235__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8a138aed 9236{
61746dbe 9237 return map ? map->btf_value_type_id : 0;
8a138aed
MKL
9238}
9239
edb13ed4
ACM
9240int bpf_map__set_priv(struct bpf_map *map, void *priv,
9241 bpf_map_clear_priv_t clear_priv)
9d759a9b
WN
9242{
9243 if (!map)
e9fc3ce9 9244 return libbpf_err(-EINVAL);
9d759a9b
WN
9245
9246 if (map->priv) {
9247 if (map->clear_priv)
9248 map->clear_priv(map, map->priv);
9249 }
9250
9251 map->priv = priv;
9252 map->clear_priv = clear_priv;
9253 return 0;
9254}
9255
a324aae3 9256void *bpf_map__priv(const struct bpf_map *map)
9d759a9b 9257{
e9fc3ce9 9258 return map ? map->priv : libbpf_err_ptr(-EINVAL);
9d759a9b
WN
9259}
9260
e2842be5
THJ
9261int bpf_map__set_initial_value(struct bpf_map *map,
9262 const void *data, size_t size)
9263{
9264 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9265 size != map->def.value_size || map->fd >= 0)
e9fc3ce9 9266 return libbpf_err(-EINVAL);
e2842be5
THJ
9267
9268 memcpy(map->mmaped, data, size);
9269 return 0;
9270}
9271
7723256b
AS
9272const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9273{
9274 if (!map->mmaped)
9275 return NULL;
9276 *psize = map->def.value_size;
9277 return map->mmaped;
9278}
9279
a324aae3 9280bool bpf_map__is_offload_neutral(const struct bpf_map *map)
f83fb22c
JK
9281{
9282 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
9283}
9284
a324aae3 9285bool bpf_map__is_internal(const struct bpf_map *map)
d859900c
DB
9286{
9287 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9288}
9289
1bdb6c9a
AN
9290__u32 bpf_map__ifindex(const struct bpf_map *map)
9291{
9292 return map->map_ifindex;
9293}
9294
9295int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9aba3613 9296{
1bdb6c9a 9297 if (map->fd >= 0)
e9fc3ce9 9298 return libbpf_err(-EBUSY);
9aba3613 9299 map->map_ifindex = ifindex;
1bdb6c9a 9300 return 0;
9aba3613
JK
9301}
9302
addb9fc9
NS
9303int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9304{
9305 if (!bpf_map_type__is_map_in_map(map->def.type)) {
be18010e 9306 pr_warn("error: unsupported map type\n");
e9fc3ce9 9307 return libbpf_err(-EINVAL);
addb9fc9
NS
9308 }
9309 if (map->inner_map_fd != -1) {
be18010e 9310 pr_warn("error: inner_map_fd already specified\n");
e9fc3ce9 9311 return libbpf_err(-EINVAL);
addb9fc9 9312 }
8f7b239e
AN
9313 if (map->inner_map) {
9314 bpf_map__destroy(map->inner_map);
9315 zfree(&map->inner_map);
9316 }
addb9fc9
NS
9317 map->inner_map_fd = fd;
9318 return 0;
9319}
9320
0c19a9fb 9321static struct bpf_map *
a324aae3 9322__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9d759a9b 9323{
0c19a9fb 9324 ssize_t idx;
9d759a9b
WN
9325 struct bpf_map *s, *e;
9326
9327 if (!obj || !obj->maps)
e9fc3ce9 9328 return errno = EINVAL, NULL;
9d759a9b
WN
9329
9330 s = obj->maps;
9331 e = obj->maps + obj->nr_maps;
9332
0c19a9fb 9333 if ((m < s) || (m >= e)) {
be18010e
KW
9334 pr_warn("error in %s: map handler doesn't belong to object\n",
9335 __func__);
e9fc3ce9 9336 return errno = EINVAL, NULL;
9d759a9b
WN
9337 }
9338
0c19a9fb
SF
9339 idx = (m - obj->maps) + i;
9340 if (idx >= obj->nr_maps || idx < 0)
9d759a9b
WN
9341 return NULL;
9342 return &obj->maps[idx];
9343}
561bbcca 9344
0c19a9fb 9345struct bpf_map *
a324aae3 9346bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
2088a3a7
HC
9347{
9348 return bpf_object__next_map(obj, prev);
9349}
9350
9351struct bpf_map *
9352bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
0c19a9fb
SF
9353{
9354 if (prev == NULL)
9355 return obj->maps;
9356
9357 return __bpf_map__iter(prev, obj, 1);
9358}
9359
9360struct bpf_map *
a324aae3 9361bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
2088a3a7
HC
9362{
9363 return bpf_object__prev_map(obj, next);
9364}
9365
9366struct bpf_map *
9367bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
0c19a9fb
SF
9368{
9369 if (next == NULL) {
9370 if (!obj->nr_maps)
9371 return NULL;
9372 return obj->maps + obj->nr_maps - 1;
9373 }
9374
9375 return __bpf_map__iter(next, obj, -1);
9376}
9377
561bbcca 9378struct bpf_map *
a324aae3 9379bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
561bbcca
WN
9380{
9381 struct bpf_map *pos;
9382
f74a53d9 9383 bpf_object__for_each_map(pos, obj) {
26071635
AN
9384 /* if it's a special internal map name (which always starts
9385 * with dot) then check if that special name matches the
9386 * real map name (ELF section name)
9387 */
9388 if (name[0] == '.') {
9389 if (pos->real_name && strcmp(pos->real_name, name) == 0)
9390 return pos;
9391 continue;
9392 }
9393 /* otherwise map name has to be an exact match */
aed65917
AN
9394 if (map_uses_real_name(pos)) {
9395 if (strcmp(pos->real_name, name) == 0)
9396 return pos;
9397 continue;
9398 }
9399 if (strcmp(pos->name, name) == 0)
561bbcca
WN
9400 return pos;
9401 }
e9fc3ce9 9402 return errno = ENOENT, NULL;
561bbcca 9403}
5a6acad1 9404
f3cea32d 9405int
a324aae3 9406bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
f3cea32d
MF
9407{
9408 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9409}
9410
5a6acad1
WN
9411struct bpf_map *
9412bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9413{
e9fc3ce9 9414 return libbpf_err_ptr(-ENOTSUP);
5a6acad1 9415}
e28ff1a8
JS
9416
9417long libbpf_get_error(const void *ptr)
9418{
e9fc3ce9
AN
9419 if (!IS_ERR_OR_NULL(ptr))
9420 return 0;
9421
9422 if (IS_ERR(ptr))
9423 errno = -PTR_ERR(ptr);
9424
9425 /* If ptr == NULL, then errno should be already set by the failing
9426 * API, because libbpf never returns NULL on success and it now always
9427 * sets errno on error. So no extra errno handling for ptr == NULL
9428 * case.
9429 */
9430 return -errno;
e28ff1a8 9431}
6f6d33f3 9432
e32660ac 9433__attribute__((alias("bpf_prog_load_xattr2")))
d7be143b 9434int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
e32660ac
AN
9435 struct bpf_object **pobj, int *prog_fd);
9436
9437static int bpf_prog_load_xattr2(const struct bpf_prog_load_attr *attr,
9438 struct bpf_object **pobj, int *prog_fd)
6f6d33f3 9439{
33bae185 9440 struct bpf_object_open_attr open_attr = {};
48cca7e4 9441 struct bpf_program *prog, *first_prog = NULL;
6f6d33f3 9442 struct bpf_object *obj;
f0307a7e 9443 struct bpf_map *map;
6f6d33f3
JF
9444 int err;
9445
d7be143b 9446 if (!attr)
e9fc3ce9 9447 return libbpf_err(-EINVAL);
17387dd5 9448 if (!attr->file)
e9fc3ce9 9449 return libbpf_err(-EINVAL);
d7be143b 9450
33bae185
LY
9451 open_attr.file = attr->file;
9452 open_attr.prog_type = attr->prog_type;
9453
07f2d4ea 9454 obj = bpf_object__open_xattr(&open_attr);
e9fc3ce9
AN
9455 err = libbpf_get_error(obj);
9456 if (err)
9457 return libbpf_err(-ENOENT);
6f6d33f3 9458
48cca7e4 9459 bpf_object__for_each_program(prog, obj) {
dd4436bb 9460 enum bpf_attach_type attach_type = attr->expected_attach_type;
48cca7e4 9461 /*
dd4436bb
AN
9462 * to preserve backwards compatibility, bpf_prog_load treats
9463 * attr->prog_type, if specified, as an override to whatever
9464 * bpf_object__open guessed
48cca7e4 9465 */
dd4436bb
AN
9466 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
9467 bpf_program__set_type(prog, attr->prog_type);
9468 bpf_program__set_expected_attach_type(prog,
9469 attach_type);
9470 }
9471 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
9472 /*
9473 * we haven't guessed from section name and user
9474 * didn't provide a fallback type, too bad...
9475 */
9476 bpf_object__close(obj);
e9fc3ce9 9477 return libbpf_err(-EINVAL);
583c9009 9478 }
48cca7e4 9479
dd4436bb 9480 prog->prog_ifindex = attr->ifindex;
da11b417 9481 prog->log_level = attr->log_level;
2b288740 9482 prog->prog_flags |= attr->prog_flags;
69495d2a 9483 if (!first_prog)
48cca7e4
AS
9484 first_prog = prog;
9485 }
9486
f74a53d9 9487 bpf_object__for_each_map(map, obj) {
f83fb22c
JK
9488 if (!bpf_map__is_offload_neutral(map))
9489 map->map_ifindex = attr->ifindex;
f0307a7e
DB
9490 }
9491
48cca7e4 9492 if (!first_prog) {
be18010e 9493 pr_warn("object file doesn't contain bpf program\n");
48cca7e4 9494 bpf_object__close(obj);
e9fc3ce9 9495 return libbpf_err(-ENOENT);
583c9009
RG
9496 }
9497
6f6d33f3
JF
9498 err = bpf_object__load(obj);
9499 if (err) {
9500 bpf_object__close(obj);
e9fc3ce9 9501 return libbpf_err(err);
6f6d33f3
JF
9502 }
9503
9504 *pobj = obj;
48cca7e4 9505 *prog_fd = bpf_program__fd(first_prog);
6f6d33f3
JF
9506 return 0;
9507}
d0cabbb0 9508
e32660ac
AN
9509COMPAT_VERSION(bpf_prog_load_deprecated, bpf_prog_load, LIBBPF_0.0.1)
9510int bpf_prog_load_deprecated(const char *file, enum bpf_prog_type type,
9511 struct bpf_object **pobj, int *prog_fd)
9512{
9513 struct bpf_prog_load_attr attr;
9514
9515 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9516 attr.file = file;
9517 attr.prog_type = type;
9518 attr.expected_attach_type = 0;
9519
9520 return bpf_prog_load_xattr2(&attr, pobj, prog_fd);
9521}
9522
1c2e9efc 9523struct bpf_link {
d6958706 9524 int (*detach)(struct bpf_link *link);
d88b71d4 9525 void (*dealloc)(struct bpf_link *link);
c016b68e
AN
9526 char *pin_path; /* NULL, if not pinned */
9527 int fd; /* hook FD, -1 if not applicable */
d6958706 9528 bool disconnected;
1c2e9efc
AN
9529};
9530
cc4f864b
AN
9531/* Replace link's underlying BPF program with the new one */
9532int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9533{
e9fc3ce9 9534 int ret;
c139e40a 9535
e9fc3ce9
AN
9536 ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9537 return libbpf_err_errno(ret);
cc4f864b
AN
9538}
9539
d6958706
AN
9540/* Release "ownership" of underlying BPF resource (typically, BPF program
9541 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9542 * link, when destructed through bpf_link__destroy() call won't attempt to
9543 * detach/unregisted that BPF resource. This is useful in situations where,
9544 * say, attached BPF program has to outlive userspace program that attached it
9545 * in the system. Depending on type of BPF program, though, there might be
9546 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9547 * exit of userspace program doesn't trigger automatic detachment and clean up
9548 * inside the kernel.
9549 */
9550void bpf_link__disconnect(struct bpf_link *link)
9551{
9552 link->disconnected = true;
9553}
9554
1c2e9efc
AN
9555int bpf_link__destroy(struct bpf_link *link)
9556{
d6958706 9557 int err = 0;
1c2e9efc 9558
50450fc7 9559 if (IS_ERR_OR_NULL(link))
1c2e9efc
AN
9560 return 0;
9561
d6958706
AN
9562 if (!link->disconnected && link->detach)
9563 err = link->detach(link);
c016b68e
AN
9564 if (link->pin_path)
9565 free(link->pin_path);
d88b71d4
AN
9566 if (link->dealloc)
9567 link->dealloc(link);
9568 else
9569 free(link);
1c2e9efc 9570
e9fc3ce9 9571 return libbpf_err(err);
1c2e9efc
AN
9572}
9573
c016b68e
AN
9574int bpf_link__fd(const struct bpf_link *link)
9575{
9576 return link->fd;
9577}
9578
9579const char *bpf_link__pin_path(const struct bpf_link *link)
9580{
9581 return link->pin_path;
9582}
9583
9584static int bpf_link__detach_fd(struct bpf_link *link)
9585{
e9fc3ce9 9586 return libbpf_err_errno(close(link->fd));
c016b68e
AN
9587}
9588
9589struct bpf_link *bpf_link__open(const char *path)
9590{
9591 struct bpf_link *link;
9592 int fd;
9593
9594 fd = bpf_obj_get(path);
9595 if (fd < 0) {
9596 fd = -errno;
9597 pr_warn("failed to open link at %s: %d\n", path, fd);
e9fc3ce9 9598 return libbpf_err_ptr(fd);
c016b68e
AN
9599 }
9600
9601 link = calloc(1, sizeof(*link));
9602 if (!link) {
9603 close(fd);
e9fc3ce9 9604 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9605 }
9606 link->detach = &bpf_link__detach_fd;
9607 link->fd = fd;
9608
9609 link->pin_path = strdup(path);
9610 if (!link->pin_path) {
9611 bpf_link__destroy(link);
e9fc3ce9 9612 return libbpf_err_ptr(-ENOMEM);
c016b68e
AN
9613 }
9614
9615 return link;
9616}
9617
2e49527e
AN
9618int bpf_link__detach(struct bpf_link *link)
9619{
9620 return bpf_link_detach(link->fd) ? -errno : 0;
9621}
9622
c016b68e
AN
9623int bpf_link__pin(struct bpf_link *link, const char *path)
9624{
9625 int err;
9626
9627 if (link->pin_path)
e9fc3ce9 9628 return libbpf_err(-EBUSY);
c016b68e
AN
9629 err = make_parent_dir(path);
9630 if (err)
e9fc3ce9 9631 return libbpf_err(err);
c016b68e
AN
9632 err = check_path(path);
9633 if (err)
e9fc3ce9 9634 return libbpf_err(err);
c016b68e
AN
9635
9636 link->pin_path = strdup(path);
9637 if (!link->pin_path)
e9fc3ce9 9638 return libbpf_err(-ENOMEM);
c016b68e
AN
9639
9640 if (bpf_obj_pin(link->fd, link->pin_path)) {
9641 err = -errno;
9642 zfree(&link->pin_path);
e9fc3ce9 9643 return libbpf_err(err);
c016b68e
AN
9644 }
9645
9646 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9647 return 0;
9648}
9649
9650int bpf_link__unpin(struct bpf_link *link)
9651{
9652 int err;
9653
9654 if (!link->pin_path)
e9fc3ce9 9655 return libbpf_err(-EINVAL);
c016b68e
AN
9656
9657 err = unlink(link->pin_path);
9658 if (err != 0)
af0efa05 9659 return -errno;
c016b68e
AN
9660
9661 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9662 zfree(&link->pin_path);
9663 return 0;
9664}
63f2f5ee 9665
668ace0e
AN
9666struct bpf_link_perf {
9667 struct bpf_link link;
9668 int perf_event_fd;
ca304b40
RDT
9669 /* legacy kprobe support: keep track of probe identifier and type */
9670 char *legacy_probe_name;
46ed5fc3 9671 bool legacy_is_kprobe;
ca304b40 9672 bool legacy_is_retprobe;
668ace0e
AN
9673};
9674
46ed5fc3 9675static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
cc10623c 9676static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
46ed5fc3 9677
668ace0e 9678static int bpf_link_perf_detach(struct bpf_link *link)
63f2f5ee 9679{
668ace0e
AN
9680 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9681 int err = 0;
63f2f5ee 9682
668ace0e 9683 if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
63f2f5ee
AN
9684 err = -errno;
9685
668ace0e
AN
9686 if (perf_link->perf_event_fd != link->fd)
9687 close(perf_link->perf_event_fd);
c016b68e 9688 close(link->fd);
668ace0e 9689
cc10623c 9690 /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
46ed5fc3
AN
9691 if (perf_link->legacy_probe_name) {
9692 if (perf_link->legacy_is_kprobe) {
9693 err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9694 perf_link->legacy_is_retprobe);
cc10623c
AN
9695 } else {
9696 err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9697 perf_link->legacy_is_retprobe);
46ed5fc3
AN
9698 }
9699 }
ca304b40
RDT
9700
9701 return err;
63f2f5ee
AN
9702}
9703
668ace0e
AN
9704static void bpf_link_perf_dealloc(struct bpf_link *link)
9705{
9706 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9707
ca304b40 9708 free(perf_link->legacy_probe_name);
668ace0e
AN
9709 free(perf_link);
9710}
9711
942025c9 9712struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
47faff37 9713 const struct bpf_perf_event_opts *opts)
63f2f5ee
AN
9714{
9715 char errmsg[STRERR_BUFSIZE];
668ace0e
AN
9716 struct bpf_link_perf *link;
9717 int prog_fd, link_fd = -1, err;
63f2f5ee 9718
47faff37
AN
9719 if (!OPTS_VALID(opts, bpf_perf_event_opts))
9720 return libbpf_err_ptr(-EINVAL);
9721
63f2f5ee 9722 if (pfd < 0) {
52109584
AN
9723 pr_warn("prog '%s': invalid perf event FD %d\n",
9724 prog->name, pfd);
e9fc3ce9 9725 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9726 }
9727 prog_fd = bpf_program__fd(prog);
9728 if (prog_fd < 0) {
52109584
AN
9729 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9730 prog->name);
e9fc3ce9 9731 return libbpf_err_ptr(-EINVAL);
63f2f5ee
AN
9732 }
9733
d6958706 9734 link = calloc(1, sizeof(*link));
63f2f5ee 9735 if (!link)
e9fc3ce9 9736 return libbpf_err_ptr(-ENOMEM);
668ace0e
AN
9737 link->link.detach = &bpf_link_perf_detach;
9738 link->link.dealloc = &bpf_link_perf_dealloc;
9739 link->perf_event_fd = pfd;
63f2f5ee 9740
668ace0e 9741 if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
47faff37
AN
9742 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9743 .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9744
9745 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
668ace0e
AN
9746 if (link_fd < 0) {
9747 err = -errno;
9748 pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9749 prog->name, pfd,
9750 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9751 goto err_out;
9752 }
9753 link->link.fd = link_fd;
9754 } else {
47faff37
AN
9755 if (OPTS_GET(opts, bpf_cookie, 0)) {
9756 pr_warn("prog '%s': user context value is not supported\n", prog->name);
9757 err = -EOPNOTSUPP;
9758 goto err_out;
9759 }
9760
668ace0e
AN
9761 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9762 err = -errno;
9763 pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9764 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9765 if (err == -EPROTO)
9766 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9767 prog->name, pfd);
9768 goto err_out;
9769 }
9770 link->link.fd = pfd;
63f2f5ee
AN
9771 }
9772 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9773 err = -errno;
668ace0e 9774 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
52109584 9775 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
668ace0e 9776 goto err_out;
63f2f5ee 9777 }
668ace0e
AN
9778
9779 return &link->link;
9780err_out:
9781 if (link_fd >= 0)
9782 close(link_fd);
9783 free(link);
9784 return libbpf_err_ptr(err);
63f2f5ee
AN
9785}
9786
942025c9 9787struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
47faff37
AN
9788{
9789 return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9790}
9791
b2650027
AN
9792/*
9793 * this function is expected to parse integer in the range of [0, 2^31-1] from
9794 * given file using scanf format string fmt. If actual parsed value is
9795 * negative, the result might be indistinguishable from error
9796 */
9797static int parse_uint_from_file(const char *file, const char *fmt)
9798{
9799 char buf[STRERR_BUFSIZE];
9800 int err, ret;
9801 FILE *f;
9802
9803 f = fopen(file, "r");
9804 if (!f) {
9805 err = -errno;
9806 pr_debug("failed to open '%s': %s\n", file,
9807 libbpf_strerror_r(err, buf, sizeof(buf)));
9808 return err;
9809 }
9810 err = fscanf(f, fmt, &ret);
9811 if (err != 1) {
9812 err = err == EOF ? -EIO : -errno;
9813 pr_debug("failed to parse '%s': %s\n", file,
9814 libbpf_strerror_r(err, buf, sizeof(buf)));
9815 fclose(f);
9816 return err;
9817 }
9818 fclose(f);
9819 return ret;
9820}
9821
9822static int determine_kprobe_perf_type(void)
9823{
9824 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9825
9826 return parse_uint_from_file(file, "%d\n");
9827}
9828
9829static int determine_uprobe_perf_type(void)
9830{
9831 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9832
9833 return parse_uint_from_file(file, "%d\n");
9834}
9835
9836static int determine_kprobe_retprobe_bit(void)
9837{
9838 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9839
9840 return parse_uint_from_file(file, "config:%d\n");
9841}
9842
9843static int determine_uprobe_retprobe_bit(void)
9844{
9845 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9846
9847 return parse_uint_from_file(file, "config:%d\n");
9848}
9849
5e3b8356
AN
9850#define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9851#define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9852
b2650027 9853static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
5e3b8356 9854 uint64_t offset, int pid, size_t ref_ctr_off)
b2650027
AN
9855{
9856 struct perf_event_attr attr = {};
9857 char errmsg[STRERR_BUFSIZE];
9858 int type, pfd, err;
9859
5e3b8356
AN
9860 if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9861 return -EINVAL;
9862
b2650027
AN
9863 type = uprobe ? determine_uprobe_perf_type()
9864 : determine_kprobe_perf_type();
9865 if (type < 0) {
be18010e
KW
9866 pr_warn("failed to determine %s perf type: %s\n",
9867 uprobe ? "uprobe" : "kprobe",
9868 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
b2650027
AN
9869 return type;
9870 }
9871 if (retprobe) {
9872 int bit = uprobe ? determine_uprobe_retprobe_bit()
9873 : determine_kprobe_retprobe_bit();
9874
9875 if (bit < 0) {
be18010e
KW
9876 pr_warn("failed to determine %s retprobe bit: %s\n",
9877 uprobe ? "uprobe" : "kprobe",
9878 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
b2650027
AN
9879 return bit;
9880 }
9881 attr.config |= 1 << bit;
9882 }
9883 attr.size = sizeof(attr);
9884 attr.type = type;
5e3b8356 9885 attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
36db2a94
AN
9886 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9887 attr.config2 = offset; /* kprobe_addr or probe_offset */
b2650027
AN
9888
9889 /* pid filter is meaningful only for uprobes */
9890 pfd = syscall(__NR_perf_event_open, &attr,
9891 pid < 0 ? -1 : pid /* pid */,
9892 pid == -1 ? 0 : -1 /* cpu */,
9893 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9894 if (pfd < 0) {
9895 err = -errno;
be18010e
KW
9896 pr_warn("%s perf_event_open() failed: %s\n",
9897 uprobe ? "uprobe" : "kprobe",
9898 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
b2650027
AN
9899 return err;
9900 }
9901 return pfd;
9902}
9903
46ed5fc3
AN
9904static int append_to_file(const char *file, const char *fmt, ...)
9905{
9906 int fd, n, err = 0;
9907 va_list ap;
9908
92274e24 9909 fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
46ed5fc3
AN
9910 if (fd < 0)
9911 return -errno;
9912
9913 va_start(ap, fmt);
9914 n = vdprintf(fd, fmt, ap);
9915 va_end(ap);
9916
9917 if (n < 0)
9918 err = -errno;
9919
9920 close(fd);
9921 return err;
9922}
9923
9924static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9925 const char *kfunc_name, size_t offset)
9926{
51a33c60
QW
9927 static int index = 0;
9928
9929 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9930 __sync_fetch_and_add(&index, 1));
46ed5fc3
AN
9931}
9932
9933static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9934 const char *kfunc_name, size_t offset)
9935{
9936 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9937
9938 return append_to_file(file, "%c:%s/%s %s+0x%zx",
9939 retprobe ? 'r' : 'p',
9940 retprobe ? "kretprobes" : "kprobes",
9941 probe_name, kfunc_name, offset);
9942}
9943
9944static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9945{
9946 const char *file = "/sys/kernel/debug/tracing/kprobe_events";
9947
9948 return append_to_file(file, "-:%s/%s", retprobe ? "kretprobes" : "kprobes", probe_name);
9949}
9950
9951static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9952{
9953 char file[256];
9954
9955 snprintf(file, sizeof(file),
9956 "/sys/kernel/debug/tracing/events/%s/%s/id",
9957 retprobe ? "kretprobes" : "kprobes", probe_name);
9958
9959 return parse_uint_from_file(file, "%d\n");
9960}
9961
9962static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9963 const char *kfunc_name, size_t offset, int pid)
ca304b40
RDT
9964{
9965 struct perf_event_attr attr = {};
9966 char errmsg[STRERR_BUFSIZE];
9967 int type, pfd, err;
9968
46ed5fc3 9969 err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
ca304b40 9970 if (err < 0) {
46ed5fc3
AN
9971 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9972 kfunc_name, offset,
ca304b40
RDT
9973 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9974 return err;
9975 }
46ed5fc3 9976 type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
ca304b40 9977 if (type < 0) {
46ed5fc3
AN
9978 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9979 kfunc_name, offset,
ca304b40
RDT
9980 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9981 return type;
9982 }
9983 attr.size = sizeof(attr);
9984 attr.config = type;
9985 attr.type = PERF_TYPE_TRACEPOINT;
9986
9987 pfd = syscall(__NR_perf_event_open, &attr,
9988 pid < 0 ? -1 : pid, /* pid */
9989 pid == -1 ? 0 : -1, /* cpu */
9990 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9991 if (pfd < 0) {
9992 err = -errno;
9993 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
9994 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9995 return err;
9996 }
9997 return pfd;
9998}
9999
da97553e 10000struct bpf_link *
942025c9 10001bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
ac0ed488 10002 const char *func_name,
47faff37 10003 const struct bpf_kprobe_opts *opts)
b2650027 10004{
47faff37 10005 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
b2650027 10006 char errmsg[STRERR_BUFSIZE];
ca304b40 10007 char *legacy_probe = NULL;
b2650027 10008 struct bpf_link *link;
46ed5fc3 10009 size_t offset;
ca304b40 10010 bool retprobe, legacy;
b2650027
AN
10011 int pfd, err;
10012
da97553e
JO
10013 if (!OPTS_VALID(opts, bpf_kprobe_opts))
10014 return libbpf_err_ptr(-EINVAL);
10015
10016 retprobe = OPTS_GET(opts, retprobe, false);
10017 offset = OPTS_GET(opts, offset, 0);
47faff37 10018 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
da97553e 10019
ca304b40
RDT
10020 legacy = determine_kprobe_perf_type() < 0;
10021 if (!legacy) {
10022 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10023 func_name, offset,
10024 -1 /* pid */, 0 /* ref_ctr_off */);
10025 } else {
46ed5fc3
AN
10026 char probe_name[256];
10027
10028 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10029 func_name, offset);
10030
71cff670 10031 legacy_probe = strdup(probe_name);
ca304b40
RDT
10032 if (!legacy_probe)
10033 return libbpf_err_ptr(-ENOMEM);
10034
46ed5fc3 10035 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
ca304b40
RDT
10036 offset, -1 /* pid */);
10037 }
b2650027 10038 if (pfd < 0) {
46ed5fc3
AN
10039 err = -errno;
10040 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10041 prog->name, retprobe ? "kretprobe" : "kprobe",
10042 func_name, offset,
303a2572
AN
10043 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10044 goto err_out;
b2650027 10045 }
47faff37 10046 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10047 err = libbpf_get_error(link);
10048 if (err) {
b2650027 10049 close(pfd);
46ed5fc3
AN
10050 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10051 prog->name, retprobe ? "kretprobe" : "kprobe",
10052 func_name, offset,
be18010e 10053 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
303a2572 10054 goto err_out;
b2650027 10055 }
ca304b40
RDT
10056 if (legacy) {
10057 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10058
10059 perf_link->legacy_probe_name = legacy_probe;
46ed5fc3 10060 perf_link->legacy_is_kprobe = true;
ca304b40
RDT
10061 perf_link->legacy_is_retprobe = retprobe;
10062 }
10063
b2650027 10064 return link;
303a2572
AN
10065err_out:
10066 free(legacy_probe);
10067 return libbpf_err_ptr(err);
b2650027
AN
10068}
10069
942025c9 10070struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
ac0ed488
JO
10071 bool retprobe,
10072 const char *func_name)
10073{
da97553e 10074 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
ac0ed488 10075 .retprobe = retprobe,
da97553e 10076 );
ac0ed488
JO
10077
10078 return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10079}
10080
12d9466d 10081static struct bpf_link *attach_kprobe(const struct bpf_program *prog, long cookie)
d7a18ea7 10082{
da97553e 10083 DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
a2488b5f
AM
10084 unsigned long offset = 0;
10085 struct bpf_link *link;
d7a18ea7 10086 const char *func_name;
a2488b5f
AM
10087 char *func;
10088 int n, err;
d7a18ea7 10089
13d35a0c
AN
10090 opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10091 if (opts.retprobe)
10092 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10093 else
10094 func_name = prog->sec_name + sizeof("kprobe/") - 1;
d7a18ea7 10095
e3f9bc35 10096 n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
a2488b5f
AM
10097 if (n < 1) {
10098 err = -EINVAL;
10099 pr_warn("kprobe name is invalid: %s\n", func_name);
10100 return libbpf_err_ptr(err);
10101 }
10102 if (opts.retprobe && offset != 0) {
1f71a468 10103 free(func);
a2488b5f
AM
10104 err = -EINVAL;
10105 pr_warn("kretprobes do not support offset specification\n");
10106 return libbpf_err_ptr(err);
10107 }
d7a18ea7 10108
a2488b5f
AM
10109 opts.offset = offset;
10110 link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10111 free(func);
10112 return link;
d7a18ea7
AN
10113}
10114
cc10623c
AN
10115static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10116 const char *binary_path, uint64_t offset)
10117{
10118 int i;
10119
10120 snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10121
10122 /* sanitize binary_path in the probe name */
10123 for (i = 0; buf[i]; i++) {
10124 if (!isalnum(buf[i]))
10125 buf[i] = '_';
10126 }
10127}
10128
10129static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10130 const char *binary_path, size_t offset)
10131{
10132 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10133
10134 return append_to_file(file, "%c:%s/%s %s:0x%zx",
10135 retprobe ? 'r' : 'p',
10136 retprobe ? "uretprobes" : "uprobes",
10137 probe_name, binary_path, offset);
10138}
10139
10140static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10141{
10142 const char *file = "/sys/kernel/debug/tracing/uprobe_events";
10143
10144 return append_to_file(file, "-:%s/%s", retprobe ? "uretprobes" : "uprobes", probe_name);
10145}
10146
10147static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10148{
10149 char file[512];
10150
10151 snprintf(file, sizeof(file),
10152 "/sys/kernel/debug/tracing/events/%s/%s/id",
10153 retprobe ? "uretprobes" : "uprobes", probe_name);
10154
10155 return parse_uint_from_file(file, "%d\n");
10156}
10157
10158static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10159 const char *binary_path, size_t offset, int pid)
10160{
10161 struct perf_event_attr attr;
10162 int type, pfd, err;
10163
10164 err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10165 if (err < 0) {
10166 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10167 binary_path, (size_t)offset, err);
10168 return err;
10169 }
10170 type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10171 if (type < 0) {
10172 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10173 binary_path, offset, err);
10174 return type;
10175 }
10176
10177 memset(&attr, 0, sizeof(attr));
10178 attr.size = sizeof(attr);
10179 attr.config = type;
10180 attr.type = PERF_TYPE_TRACEPOINT;
10181
10182 pfd = syscall(__NR_perf_event_open, &attr,
10183 pid < 0 ? -1 : pid, /* pid */
10184 pid == -1 ? 0 : -1, /* cpu */
10185 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10186 if (pfd < 0) {
10187 err = -errno;
10188 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10189 return err;
10190 }
10191 return pfd;
10192}
10193
47faff37 10194LIBBPF_API struct bpf_link *
942025c9 10195bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
47faff37
AN
10196 const char *binary_path, size_t func_offset,
10197 const struct bpf_uprobe_opts *opts)
b2650027 10198{
47faff37 10199 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
cc10623c 10200 char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
b2650027 10201 struct bpf_link *link;
5e3b8356 10202 size_t ref_ctr_off;
b2650027 10203 int pfd, err;
cc10623c 10204 bool retprobe, legacy;
47faff37
AN
10205
10206 if (!OPTS_VALID(opts, bpf_uprobe_opts))
10207 return libbpf_err_ptr(-EINVAL);
10208
10209 retprobe = OPTS_GET(opts, retprobe, false);
5e3b8356 10210 ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
47faff37 10211 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
b2650027 10212
cc10623c
AN
10213 legacy = determine_uprobe_perf_type() < 0;
10214 if (!legacy) {
10215 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10216 func_offset, pid, ref_ctr_off);
10217 } else {
10218 char probe_name[512];
10219
10220 if (ref_ctr_off)
10221 return libbpf_err_ptr(-EINVAL);
10222
10223 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10224 binary_path, func_offset);
10225
10226 legacy_probe = strdup(probe_name);
10227 if (!legacy_probe)
10228 return libbpf_err_ptr(-ENOMEM);
10229
10230 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10231 binary_path, func_offset, pid);
10232 }
b2650027 10233 if (pfd < 0) {
cc10623c 10234 err = -errno;
52109584
AN
10235 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10236 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e 10237 binary_path, func_offset,
cc10623c
AN
10238 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10239 goto err_out;
b2650027 10240 }
cc10623c 10241
47faff37 10242 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10243 err = libbpf_get_error(link);
10244 if (err) {
b2650027 10245 close(pfd);
52109584
AN
10246 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10247 prog->name, retprobe ? "uretprobe" : "uprobe",
be18010e
KW
10248 binary_path, func_offset,
10249 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
cc10623c
AN
10250 goto err_out;
10251 }
10252 if (legacy) {
10253 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10254
10255 perf_link->legacy_probe_name = legacy_probe;
10256 perf_link->legacy_is_kprobe = false;
10257 perf_link->legacy_is_retprobe = retprobe;
b2650027
AN
10258 }
10259 return link;
cc10623c
AN
10260err_out:
10261 free(legacy_probe);
10262 return libbpf_err_ptr(err);
10263
b2650027
AN
10264}
10265
942025c9 10266struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
47faff37
AN
10267 bool retprobe, pid_t pid,
10268 const char *binary_path,
10269 size_t func_offset)
10270{
10271 DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10272
10273 return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10274}
10275
f6de59c1
AN
10276static int determine_tracepoint_id(const char *tp_category,
10277 const char *tp_name)
10278{
10279 char file[PATH_MAX];
10280 int ret;
10281
10282 ret = snprintf(file, sizeof(file),
10283 "/sys/kernel/debug/tracing/events/%s/%s/id",
10284 tp_category, tp_name);
10285 if (ret < 0)
10286 return -errno;
10287 if (ret >= sizeof(file)) {
10288 pr_debug("tracepoint %s/%s path is too long\n",
10289 tp_category, tp_name);
10290 return -E2BIG;
10291 }
10292 return parse_uint_from_file(file, "%d\n");
10293}
10294
10295static int perf_event_open_tracepoint(const char *tp_category,
10296 const char *tp_name)
10297{
10298 struct perf_event_attr attr = {};
10299 char errmsg[STRERR_BUFSIZE];
10300 int tp_id, pfd, err;
10301
10302 tp_id = determine_tracepoint_id(tp_category, tp_name);
10303 if (tp_id < 0) {
be18010e
KW
10304 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
10305 tp_category, tp_name,
10306 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
f6de59c1
AN
10307 return tp_id;
10308 }
10309
10310 attr.type = PERF_TYPE_TRACEPOINT;
10311 attr.size = sizeof(attr);
10312 attr.config = tp_id;
10313
10314 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
10315 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10316 if (pfd < 0) {
10317 err = -errno;
be18010e
KW
10318 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
10319 tp_category, tp_name,
10320 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
f6de59c1
AN
10321 return err;
10322 }
10323 return pfd;
10324}
10325
942025c9 10326struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
47faff37
AN
10327 const char *tp_category,
10328 const char *tp_name,
10329 const struct bpf_tracepoint_opts *opts)
f6de59c1 10330{
47faff37 10331 DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
f6de59c1
AN
10332 char errmsg[STRERR_BUFSIZE];
10333 struct bpf_link *link;
10334 int pfd, err;
10335
47faff37
AN
10336 if (!OPTS_VALID(opts, bpf_tracepoint_opts))
10337 return libbpf_err_ptr(-EINVAL);
10338
10339 pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10340
f6de59c1
AN
10341 pfd = perf_event_open_tracepoint(tp_category, tp_name);
10342 if (pfd < 0) {
52109584
AN
10343 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
10344 prog->name, tp_category, tp_name,
be18010e 10345 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10346 return libbpf_err_ptr(pfd);
f6de59c1 10347 }
47faff37 10348 link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
e9fc3ce9
AN
10349 err = libbpf_get_error(link);
10350 if (err) {
f6de59c1 10351 close(pfd);
52109584
AN
10352 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
10353 prog->name, tp_category, tp_name,
be18010e 10354 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
e9fc3ce9 10355 return libbpf_err_ptr(err);
f6de59c1
AN
10356 }
10357 return link;
10358}
10359
942025c9 10360struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
47faff37
AN
10361 const char *tp_category,
10362 const char *tp_name)
10363{
10364 return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
10365}
10366
12d9466d 10367static struct bpf_link *attach_tp(const struct bpf_program *prog, long cookie)
d7a18ea7
AN
10368{
10369 char *sec_name, *tp_cat, *tp_name;
10370 struct bpf_link *link;
10371
52109584 10372 sec_name = strdup(prog->sec_name);
d7a18ea7 10373 if (!sec_name)
e9fc3ce9 10374 return libbpf_err_ptr(-ENOMEM);
d7a18ea7 10375
13d35a0c
AN
10376 /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
10377 if (str_has_pfx(prog->sec_name, "tp/"))
10378 tp_cat = sec_name + sizeof("tp/") - 1;
10379 else
10380 tp_cat = sec_name + sizeof("tracepoint/") - 1;
d7a18ea7
AN
10381 tp_name = strchr(tp_cat, '/');
10382 if (!tp_name) {
e9fc3ce9
AN
10383 free(sec_name);
10384 return libbpf_err_ptr(-EINVAL);
d7a18ea7
AN
10385 }
10386 *tp_name = '\0';
10387 tp_name++;
10388
10389 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
d7a18ea7
AN
10390 free(sec_name);
10391 return link;
10392}
10393
942025c9 10394struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
84bf5e1f
AN
10395 const char *tp_name)
10396{
10397 char errmsg[STRERR_BUFSIZE];
c016b68e 10398 struct bpf_link *link;
84bf5e1f
AN
10399 int prog_fd, pfd;
10400
10401 prog_fd = bpf_program__fd(prog);
10402 if (prog_fd < 0) {
52109584 10403 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10404 return libbpf_err_ptr(-EINVAL);
84bf5e1f
AN
10405 }
10406
d6958706 10407 link = calloc(1, sizeof(*link));
84bf5e1f 10408 if (!link)
e9fc3ce9 10409 return libbpf_err_ptr(-ENOMEM);
c016b68e 10410 link->detach = &bpf_link__detach_fd;
84bf5e1f
AN
10411
10412 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
10413 if (pfd < 0) {
10414 pfd = -errno;
10415 free(link);
52109584
AN
10416 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
10417 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10418 return libbpf_err_ptr(pfd);
84bf5e1f
AN
10419 }
10420 link->fd = pfd;
c016b68e 10421 return link;
84bf5e1f
AN
10422}
10423
12d9466d 10424static struct bpf_link *attach_raw_tp(const struct bpf_program *prog, long cookie)
d7a18ea7 10425{
ccaf12d6
HT
10426 static const char *const prefixes[] = {
10427 "raw_tp/",
10428 "raw_tracepoint/",
10429 "raw_tp.w/",
10430 "raw_tracepoint.w/",
10431 };
10432 size_t i;
10433 const char *tp_name = NULL;
13d35a0c 10434
ccaf12d6
HT
10435 for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
10436 if (str_has_pfx(prog->sec_name, prefixes[i])) {
10437 tp_name = prog->sec_name + strlen(prefixes[i]);
10438 break;
10439 }
10440 }
10441 if (!tp_name) {
10442 pr_warn("prog '%s': invalid section name '%s'\n",
10443 prog->name, prog->sec_name);
10444 return libbpf_err_ptr(-EINVAL);
10445 }
d7a18ea7
AN
10446
10447 return bpf_program__attach_raw_tracepoint(prog, tp_name);
10448}
10449
1e092a03 10450/* Common logic for all BPF program types that attach to a btf_id */
942025c9 10451static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog)
b8c54ea4
AS
10452{
10453 char errmsg[STRERR_BUFSIZE];
c016b68e 10454 struct bpf_link *link;
b8c54ea4
AS
10455 int prog_fd, pfd;
10456
10457 prog_fd = bpf_program__fd(prog);
10458 if (prog_fd < 0) {
52109584 10459 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10460 return libbpf_err_ptr(-EINVAL);
b8c54ea4
AS
10461 }
10462
d6958706 10463 link = calloc(1, sizeof(*link));
b8c54ea4 10464 if (!link)
e9fc3ce9 10465 return libbpf_err_ptr(-ENOMEM);
c016b68e 10466 link->detach = &bpf_link__detach_fd;
b8c54ea4
AS
10467
10468 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
10469 if (pfd < 0) {
10470 pfd = -errno;
10471 free(link);
52109584
AN
10472 pr_warn("prog '%s': failed to attach: %s\n",
10473 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
e9fc3ce9 10474 return libbpf_err_ptr(pfd);
b8c54ea4
AS
10475 }
10476 link->fd = pfd;
10477 return (struct bpf_link *)link;
10478}
10479
942025c9 10480struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
1e092a03
KS
10481{
10482 return bpf_program__attach_btf_id(prog);
10483}
10484
942025c9 10485struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
1e092a03
KS
10486{
10487 return bpf_program__attach_btf_id(prog);
10488}
10489
12d9466d 10490static struct bpf_link *attach_trace(const struct bpf_program *prog, long cookie)
d7a18ea7
AN
10491{
10492 return bpf_program__attach_trace(prog);
10493}
10494
12d9466d 10495static struct bpf_link *attach_lsm(const struct bpf_program *prog, long cookie)
1e092a03
KS
10496{
10497 return bpf_program__attach_lsm(prog);
10498}
10499
d60d81ac 10500static struct bpf_link *
942025c9 10501bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
d60d81ac 10502 const char *target_name)
cc4f864b 10503{
a5359091
THJ
10504 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
10505 .target_btf_id = btf_id);
cc4f864b
AN
10506 enum bpf_attach_type attach_type;
10507 char errmsg[STRERR_BUFSIZE];
10508 struct bpf_link *link;
10509 int prog_fd, link_fd;
10510
10511 prog_fd = bpf_program__fd(prog);
10512 if (prog_fd < 0) {
52109584 10513 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10514 return libbpf_err_ptr(-EINVAL);
cc4f864b
AN
10515 }
10516
10517 link = calloc(1, sizeof(*link));
10518 if (!link)
e9fc3ce9 10519 return libbpf_err_ptr(-ENOMEM);
cc4f864b
AN
10520 link->detach = &bpf_link__detach_fd;
10521
10522 attach_type = bpf_program__get_expected_attach_type(prog);
a5359091 10523 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
cc4f864b
AN
10524 if (link_fd < 0) {
10525 link_fd = -errno;
10526 free(link);
52109584
AN
10527 pr_warn("prog '%s': failed to attach to %s: %s\n",
10528 prog->name, target_name,
cc4f864b 10529 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 10530 return libbpf_err_ptr(link_fd);
cc4f864b
AN
10531 }
10532 link->fd = link_fd;
10533 return link;
10534}
10535
d60d81ac 10536struct bpf_link *
942025c9 10537bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
d60d81ac 10538{
a5359091 10539 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
d60d81ac
JS
10540}
10541
10542struct bpf_link *
942025c9 10543bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
d60d81ac 10544{
a5359091 10545 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
d60d81ac
JS
10546}
10547
942025c9 10548struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
dc8698ca
AN
10549{
10550 /* target_fd/target_ifindex use the same field in LINK_CREATE */
a5359091
THJ
10551 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
10552}
10553
942025c9 10554struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
a5359091
THJ
10555 int target_fd,
10556 const char *attach_func_name)
10557{
10558 int btf_id;
10559
10560 if (!!target_fd != !!attach_func_name) {
10561 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
10562 prog->name);
e9fc3ce9 10563 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
10564 }
10565
10566 if (prog->type != BPF_PROG_TYPE_EXT) {
10567 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
10568 prog->name);
e9fc3ce9 10569 return libbpf_err_ptr(-EINVAL);
a5359091
THJ
10570 }
10571
10572 if (target_fd) {
10573 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
10574 if (btf_id < 0)
e9fc3ce9 10575 return libbpf_err_ptr(btf_id);
a5359091
THJ
10576
10577 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
10578 } else {
10579 /* no target, so use raw_tracepoint_open for compatibility
10580 * with old kernels
10581 */
10582 return bpf_program__attach_trace(prog);
10583 }
dc8698ca
AN
10584}
10585
c09add2f 10586struct bpf_link *
942025c9 10587bpf_program__attach_iter(const struct bpf_program *prog,
c09add2f
YS
10588 const struct bpf_iter_attach_opts *opts)
10589{
cd31039a 10590 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
c09add2f
YS
10591 char errmsg[STRERR_BUFSIZE];
10592 struct bpf_link *link;
10593 int prog_fd, link_fd;
cd31039a 10594 __u32 target_fd = 0;
c09add2f
YS
10595
10596 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
e9fc3ce9 10597 return libbpf_err_ptr(-EINVAL);
c09add2f 10598
74fc097d
YS
10599 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
10600 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
cd31039a 10601
c09add2f
YS
10602 prog_fd = bpf_program__fd(prog);
10603 if (prog_fd < 0) {
52109584 10604 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
e9fc3ce9 10605 return libbpf_err_ptr(-EINVAL);
c09add2f
YS
10606 }
10607
10608 link = calloc(1, sizeof(*link));
10609 if (!link)
e9fc3ce9 10610 return libbpf_err_ptr(-ENOMEM);
c09add2f
YS
10611 link->detach = &bpf_link__detach_fd;
10612
cd31039a
YS
10613 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
10614 &link_create_opts);
c09add2f
YS
10615 if (link_fd < 0) {
10616 link_fd = -errno;
10617 free(link);
52109584
AN
10618 pr_warn("prog '%s': failed to attach to iterator: %s\n",
10619 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
e9fc3ce9 10620 return libbpf_err_ptr(link_fd);
c09add2f
YS
10621 }
10622 link->fd = link_fd;
10623 return link;
10624}
10625
12d9466d 10626static struct bpf_link *attach_iter(const struct bpf_program *prog, long cookie)
e9fc3ce9
AN
10627{
10628 return bpf_program__attach_iter(prog, NULL);
10629}
10630
942025c9 10631struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
d7a18ea7 10632{
5532dfd4 10633 if (!prog->sec_def || !prog->sec_def->attach_fn)
e9fc3ce9 10634 return libbpf_err_ptr(-ESRCH);
d7a18ea7 10635
12d9466d 10636 return prog->sec_def->attach_fn(prog, prog->sec_def->cookie);
d7a18ea7
AN
10637}
10638
590a0088
MKL
10639static int bpf_link__detach_struct_ops(struct bpf_link *link)
10640{
590a0088
MKL
10641 __u32 zero = 0;
10642
c016b68e 10643 if (bpf_map_delete_elem(link->fd, &zero))
590a0088
MKL
10644 return -errno;
10645
10646 return 0;
10647}
10648
942025c9 10649struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
590a0088
MKL
10650{
10651 struct bpf_struct_ops *st_ops;
c016b68e 10652 struct bpf_link *link;
590a0088
MKL
10653 __u32 i, zero = 0;
10654 int err;
10655
10656 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
e9fc3ce9 10657 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
10658
10659 link = calloc(1, sizeof(*link));
10660 if (!link)
e9fc3ce9 10661 return libbpf_err_ptr(-EINVAL);
590a0088
MKL
10662
10663 st_ops = map->st_ops;
10664 for (i = 0; i < btf_vlen(st_ops->type); i++) {
10665 struct bpf_program *prog = st_ops->progs[i];
10666 void *kern_data;
10667 int prog_fd;
10668
10669 if (!prog)
10670 continue;
10671
10672 prog_fd = bpf_program__fd(prog);
10673 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
10674 *(unsigned long *)kern_data = prog_fd;
10675 }
10676
10677 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
10678 if (err) {
10679 err = -errno;
10680 free(link);
e9fc3ce9 10681 return libbpf_err_ptr(err);
590a0088
MKL
10682 }
10683
c016b68e 10684 link->detach = bpf_link__detach_struct_ops;
590a0088
MKL
10685 link->fd = map->fd;
10686
c016b68e 10687 return link;
590a0088
MKL
10688}
10689
7218c28c
CL
10690static enum bpf_perf_event_ret
10691perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10692 void **copy_mem, size_t *copy_size,
10693 bpf_perf_event_print_t fn, void *private_data)
d0cabbb0 10694{
3dca2115 10695 struct perf_event_mmap_page *header = mmap_mem;
a64af0ef 10696 __u64 data_head = ring_buffer_read_head(header);
d0cabbb0 10697 __u64 data_tail = header->data_tail;
3dca2115
DB
10698 void *base = ((__u8 *)header) + page_size;
10699 int ret = LIBBPF_PERF_EVENT_CONT;
10700 struct perf_event_header *ehdr;
10701 size_t ehdr_size;
10702
10703 while (data_head != data_tail) {
10704 ehdr = base + (data_tail & (mmap_size - 1));
10705 ehdr_size = ehdr->size;
10706
10707 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
10708 void *copy_start = ehdr;
10709 size_t len_first = base + mmap_size - copy_start;
10710 size_t len_secnd = ehdr_size - len_first;
10711
10712 if (*copy_size < ehdr_size) {
10713 free(*copy_mem);
10714 *copy_mem = malloc(ehdr_size);
10715 if (!*copy_mem) {
10716 *copy_size = 0;
d0cabbb0
JK
10717 ret = LIBBPF_PERF_EVENT_ERROR;
10718 break;
10719 }
3dca2115 10720 *copy_size = ehdr_size;
d0cabbb0
JK
10721 }
10722
3dca2115
DB
10723 memcpy(*copy_mem, copy_start, len_first);
10724 memcpy(*copy_mem + len_first, base, len_secnd);
10725 ehdr = *copy_mem;
d0cabbb0
JK
10726 }
10727
3dca2115
DB
10728 ret = fn(ehdr, private_data);
10729 data_tail += ehdr_size;
d0cabbb0
JK
10730 if (ret != LIBBPF_PERF_EVENT_CONT)
10731 break;
d0cabbb0
JK
10732 }
10733
a64af0ef 10734 ring_buffer_write_tail(header, data_tail);
e9fc3ce9 10735 return libbpf_err(ret);
d0cabbb0 10736}
34be1646 10737
7218c28c
CL
10738__attribute__((alias("perf_event_read_simple")))
10739enum bpf_perf_event_ret
10740bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
10741 void **copy_mem, size_t *copy_size,
10742 bpf_perf_event_print_t fn, void *private_data);
10743
fb84b822
AN
10744struct perf_buffer;
10745
10746struct perf_buffer_params {
10747 struct perf_event_attr *attr;
10748 /* if event_cb is specified, it takes precendence */
10749 perf_buffer_event_fn event_cb;
10750 /* sample_cb and lost_cb are higher-level common-case callbacks */
10751 perf_buffer_sample_fn sample_cb;
10752 perf_buffer_lost_fn lost_cb;
10753 void *ctx;
10754 int cpu_cnt;
10755 int *cpus;
10756 int *map_keys;
10757};
10758
10759struct perf_cpu_buf {
10760 struct perf_buffer *pb;
10761 void *base; /* mmap()'ed memory */
10762 void *buf; /* for reconstructing segmented data */
10763 size_t buf_size;
10764 int fd;
10765 int cpu;
10766 int map_key;
10767};
10768
10769struct perf_buffer {
10770 perf_buffer_event_fn event_cb;
10771 perf_buffer_sample_fn sample_cb;
10772 perf_buffer_lost_fn lost_cb;
10773 void *ctx; /* passed into callbacks */
10774
10775 size_t page_size;
10776 size_t mmap_size;
10777 struct perf_cpu_buf **cpu_bufs;
10778 struct epoll_event *events;
783b8f01 10779 int cpu_cnt; /* number of allocated CPU buffers */
fb84b822
AN
10780 int epoll_fd; /* perf event FD */
10781 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
10782};
10783
10784static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
10785 struct perf_cpu_buf *cpu_buf)
10786{
10787 if (!cpu_buf)
10788 return;
10789 if (cpu_buf->base &&
10790 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
be18010e 10791 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
fb84b822
AN
10792 if (cpu_buf->fd >= 0) {
10793 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
10794 close(cpu_buf->fd);
10795 }
10796 free(cpu_buf->buf);
10797 free(cpu_buf);
10798}
10799
10800void perf_buffer__free(struct perf_buffer *pb)
10801{
10802 int i;
10803
50450fc7 10804 if (IS_ERR_OR_NULL(pb))
fb84b822
AN
10805 return;
10806 if (pb->cpu_bufs) {
601b05ca 10807 for (i = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
10808 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10809
601b05ca
EC
10810 if (!cpu_buf)
10811 continue;
10812
fb84b822
AN
10813 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10814 perf_buffer__free_cpu_buf(pb, cpu_buf);
10815 }
10816 free(pb->cpu_bufs);
10817 }
10818 if (pb->epoll_fd >= 0)
10819 close(pb->epoll_fd);
10820 free(pb->events);
10821 free(pb);
10822}
10823
10824static struct perf_cpu_buf *
10825perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10826 int cpu, int map_key)
10827{
10828 struct perf_cpu_buf *cpu_buf;
10829 char msg[STRERR_BUFSIZE];
10830 int err;
10831
10832 cpu_buf = calloc(1, sizeof(*cpu_buf));
10833 if (!cpu_buf)
10834 return ERR_PTR(-ENOMEM);
10835
10836 cpu_buf->pb = pb;
10837 cpu_buf->cpu = cpu;
10838 cpu_buf->map_key = map_key;
10839
10840 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10841 -1, PERF_FLAG_FD_CLOEXEC);
10842 if (cpu_buf->fd < 0) {
10843 err = -errno;
be18010e
KW
10844 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10845 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
10846 goto error;
10847 }
10848
10849 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10850 PROT_READ | PROT_WRITE, MAP_SHARED,
10851 cpu_buf->fd, 0);
10852 if (cpu_buf->base == MAP_FAILED) {
10853 cpu_buf->base = NULL;
10854 err = -errno;
be18010e
KW
10855 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10856 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
10857 goto error;
10858 }
10859
10860 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10861 err = -errno;
be18010e
KW
10862 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10863 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
10864 goto error;
10865 }
10866
10867 return cpu_buf;
10868
10869error:
10870 perf_buffer__free_cpu_buf(pb, cpu_buf);
10871 return (struct perf_cpu_buf *)ERR_PTR(err);
10872}
10873
10874static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10875 struct perf_buffer_params *p);
10876
41788934
AN
10877DEFAULT_VERSION(perf_buffer__new_v0_6_0, perf_buffer__new, LIBBPF_0.6.0)
10878struct perf_buffer *perf_buffer__new_v0_6_0(int map_fd, size_t page_cnt,
10879 perf_buffer_sample_fn sample_cb,
10880 perf_buffer_lost_fn lost_cb,
10881 void *ctx,
10882 const struct perf_buffer_opts *opts)
fb84b822
AN
10883{
10884 struct perf_buffer_params p = {};
41788934
AN
10885 struct perf_event_attr attr = {};
10886
10887 if (!OPTS_VALID(opts, perf_buffer_opts))
10888 return libbpf_err_ptr(-EINVAL);
4be6e05c 10889
65bb2e0f 10890 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
4be6e05c
ACM
10891 attr.type = PERF_TYPE_SOFTWARE;
10892 attr.sample_type = PERF_SAMPLE_RAW;
10893 attr.sample_period = 1;
10894 attr.wakeup_events = 1;
fb84b822
AN
10895
10896 p.attr = &attr;
41788934
AN
10897 p.sample_cb = sample_cb;
10898 p.lost_cb = lost_cb;
10899 p.ctx = ctx;
fb84b822 10900
e9fc3ce9 10901 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
10902}
10903
41788934
AN
10904COMPAT_VERSION(perf_buffer__new_deprecated, perf_buffer__new, LIBBPF_0.0.4)
10905struct perf_buffer *perf_buffer__new_deprecated(int map_fd, size_t page_cnt,
10906 const struct perf_buffer_opts *opts)
10907{
10908 return perf_buffer__new_v0_6_0(map_fd, page_cnt,
10909 opts ? opts->sample_cb : NULL,
10910 opts ? opts->lost_cb : NULL,
10911 opts ? opts->ctx : NULL,
10912 NULL);
10913}
10914
10915DEFAULT_VERSION(perf_buffer__new_raw_v0_6_0, perf_buffer__new_raw, LIBBPF_0.6.0)
10916struct perf_buffer *perf_buffer__new_raw_v0_6_0(int map_fd, size_t page_cnt,
10917 struct perf_event_attr *attr,
10918 perf_buffer_event_fn event_cb, void *ctx,
10919 const struct perf_buffer_raw_opts *opts)
fb84b822
AN
10920{
10921 struct perf_buffer_params p = {};
10922
41788934
AN
10923 if (page_cnt == 0 || !attr)
10924 return libbpf_err_ptr(-EINVAL);
10925
10926 if (!OPTS_VALID(opts, perf_buffer_raw_opts))
10927 return libbpf_err_ptr(-EINVAL);
10928
10929 p.attr = attr;
10930 p.event_cb = event_cb;
10931 p.ctx = ctx;
10932 p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
10933 p.cpus = OPTS_GET(opts, cpus, NULL);
10934 p.map_keys = OPTS_GET(opts, map_keys, NULL);
fb84b822 10935
e9fc3ce9 10936 return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
fb84b822
AN
10937}
10938
41788934
AN
10939COMPAT_VERSION(perf_buffer__new_raw_deprecated, perf_buffer__new_raw, LIBBPF_0.0.4)
10940struct perf_buffer *perf_buffer__new_raw_deprecated(int map_fd, size_t page_cnt,
10941 const struct perf_buffer_raw_opts *opts)
10942{
10943 LIBBPF_OPTS(perf_buffer_raw_opts, inner_opts,
10944 .cpu_cnt = opts->cpu_cnt,
10945 .cpus = opts->cpus,
10946 .map_keys = opts->map_keys,
10947 );
10948
10949 return perf_buffer__new_raw_v0_6_0(map_fd, page_cnt, opts->attr,
10950 opts->event_cb, opts->ctx, &inner_opts);
10951}
10952
fb84b822
AN
10953static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10954 struct perf_buffer_params *p)
10955{
783b8f01 10956 const char *online_cpus_file = "/sys/devices/system/cpu/online";
0e289487 10957 struct bpf_map_info map;
fb84b822
AN
10958 char msg[STRERR_BUFSIZE];
10959 struct perf_buffer *pb;
783b8f01 10960 bool *online = NULL;
fb84b822 10961 __u32 map_info_len;
783b8f01 10962 int err, i, j, n;
fb84b822
AN
10963
10964 if (page_cnt & (page_cnt - 1)) {
be18010e
KW
10965 pr_warn("page count should be power of two, but is %zu\n",
10966 page_cnt);
fb84b822
AN
10967 return ERR_PTR(-EINVAL);
10968 }
10969
0e289487
AN
10970 /* best-effort sanity checks */
10971 memset(&map, 0, sizeof(map));
fb84b822
AN
10972 map_info_len = sizeof(map);
10973 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10974 if (err) {
10975 err = -errno;
0e289487
AN
10976 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10977 * -EBADFD, -EFAULT, or -E2BIG on real error
10978 */
10979 if (err != -EINVAL) {
10980 pr_warn("failed to get map info for map FD %d: %s\n",
10981 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10982 return ERR_PTR(err);
10983 }
10984 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10985 map_fd);
10986 } else {
10987 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10988 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10989 map.name);
10990 return ERR_PTR(-EINVAL);
10991 }
fb84b822
AN
10992 }
10993
10994 pb = calloc(1, sizeof(*pb));
10995 if (!pb)
10996 return ERR_PTR(-ENOMEM);
10997
10998 pb->event_cb = p->event_cb;
10999 pb->sample_cb = p->sample_cb;
11000 pb->lost_cb = p->lost_cb;
11001 pb->ctx = p->ctx;
11002
11003 pb->page_size = getpagesize();
11004 pb->mmap_size = pb->page_size * page_cnt;
11005 pb->map_fd = map_fd;
11006
11007 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11008 if (pb->epoll_fd < 0) {
11009 err = -errno;
be18010e
KW
11010 pr_warn("failed to create epoll instance: %s\n",
11011 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11012 goto error;
11013 }
11014
11015 if (p->cpu_cnt > 0) {
11016 pb->cpu_cnt = p->cpu_cnt;
11017 } else {
11018 pb->cpu_cnt = libbpf_num_possible_cpus();
11019 if (pb->cpu_cnt < 0) {
11020 err = pb->cpu_cnt;
11021 goto error;
11022 }
0e289487 11023 if (map.max_entries && map.max_entries < pb->cpu_cnt)
fb84b822
AN
11024 pb->cpu_cnt = map.max_entries;
11025 }
11026
11027 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11028 if (!pb->events) {
11029 err = -ENOMEM;
be18010e 11030 pr_warn("failed to allocate events: out of memory\n");
fb84b822
AN
11031 goto error;
11032 }
11033 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11034 if (!pb->cpu_bufs) {
11035 err = -ENOMEM;
be18010e 11036 pr_warn("failed to allocate buffers: out of memory\n");
fb84b822
AN
11037 goto error;
11038 }
11039
783b8f01
AN
11040 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11041 if (err) {
11042 pr_warn("failed to get online CPU mask: %d\n", err);
11043 goto error;
11044 }
11045
11046 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
fb84b822
AN
11047 struct perf_cpu_buf *cpu_buf;
11048 int cpu, map_key;
11049
11050 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11051 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11052
783b8f01
AN
11053 /* in case user didn't explicitly requested particular CPUs to
11054 * be attached to, skip offline/not present CPUs
11055 */
11056 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11057 continue;
11058
fb84b822
AN
11059 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11060 if (IS_ERR(cpu_buf)) {
11061 err = PTR_ERR(cpu_buf);
11062 goto error;
11063 }
11064
783b8f01 11065 pb->cpu_bufs[j] = cpu_buf;
fb84b822
AN
11066
11067 err = bpf_map_update_elem(pb->map_fd, &map_key,
11068 &cpu_buf->fd, 0);
11069 if (err) {
11070 err = -errno;
be18010e
KW
11071 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11072 cpu, map_key, cpu_buf->fd,
11073 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11074 goto error;
11075 }
11076
783b8f01
AN
11077 pb->events[j].events = EPOLLIN;
11078 pb->events[j].data.ptr = cpu_buf;
fb84b822 11079 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
783b8f01 11080 &pb->events[j]) < 0) {
fb84b822 11081 err = -errno;
be18010e
KW
11082 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11083 cpu, cpu_buf->fd,
11084 libbpf_strerror_r(err, msg, sizeof(msg)));
fb84b822
AN
11085 goto error;
11086 }
783b8f01 11087 j++;
fb84b822 11088 }
783b8f01
AN
11089 pb->cpu_cnt = j;
11090 free(online);
fb84b822
AN
11091
11092 return pb;
11093
11094error:
783b8f01 11095 free(online);
fb84b822
AN
11096 if (pb)
11097 perf_buffer__free(pb);
11098 return ERR_PTR(err);
11099}
11100
11101struct perf_sample_raw {
11102 struct perf_event_header header;
11103 uint32_t size;
385bbf7b 11104 char data[];
fb84b822
AN
11105};
11106
11107struct perf_sample_lost {
11108 struct perf_event_header header;
11109 uint64_t id;
11110 uint64_t lost;
11111 uint64_t sample_id;
11112};
11113
11114static enum bpf_perf_event_ret
11115perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11116{
11117 struct perf_cpu_buf *cpu_buf = ctx;
11118 struct perf_buffer *pb = cpu_buf->pb;
11119 void *data = e;
11120
11121 /* user wants full control over parsing perf event */
11122 if (pb->event_cb)
11123 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11124
11125 switch (e->type) {
11126 case PERF_RECORD_SAMPLE: {
11127 struct perf_sample_raw *s = data;
11128
11129 if (pb->sample_cb)
11130 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11131 break;
11132 }
11133 case PERF_RECORD_LOST: {
11134 struct perf_sample_lost *s = data;
11135
11136 if (pb->lost_cb)
11137 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11138 break;
11139 }
11140 default:
be18010e 11141 pr_warn("unknown perf sample type %d\n", e->type);
fb84b822
AN
11142 return LIBBPF_PERF_EVENT_ERROR;
11143 }
11144 return LIBBPF_PERF_EVENT_CONT;
11145}
11146
11147static int perf_buffer__process_records(struct perf_buffer *pb,
11148 struct perf_cpu_buf *cpu_buf)
11149{
11150 enum bpf_perf_event_ret ret;
11151
7218c28c
CL
11152 ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11153 pb->page_size, &cpu_buf->buf,
11154 &cpu_buf->buf_size,
11155 perf_buffer__process_record, cpu_buf);
fb84b822
AN
11156 if (ret != LIBBPF_PERF_EVENT_CONT)
11157 return ret;
11158 return 0;
11159}
11160
dca5612f
AN
11161int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11162{
11163 return pb->epoll_fd;
11164}
11165
fb84b822
AN
11166int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11167{
11168 int i, cnt, err;
11169
11170 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
e9fc3ce9 11171 if (cnt < 0)
af0efa05 11172 return -errno;
e9fc3ce9 11173
fb84b822
AN
11174 for (i = 0; i < cnt; i++) {
11175 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11176
11177 err = perf_buffer__process_records(pb, cpu_buf);
11178 if (err) {
be18010e 11179 pr_warn("error while processing records: %d\n", err);
e9fc3ce9 11180 return libbpf_err(err);
fb84b822
AN
11181 }
11182 }
e9fc3ce9 11183 return cnt;
fb84b822
AN
11184}
11185
dca5612f
AN
11186/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11187 * manager.
11188 */
11189size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11190{
11191 return pb->cpu_cnt;
11192}
11193
11194/*
11195 * Return perf_event FD of a ring buffer in *buf_idx* slot of
11196 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11197 * select()/poll()/epoll() Linux syscalls.
11198 */
11199int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11200{
11201 struct perf_cpu_buf *cpu_buf;
11202
11203 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 11204 return libbpf_err(-EINVAL);
dca5612f
AN
11205
11206 cpu_buf = pb->cpu_bufs[buf_idx];
11207 if (!cpu_buf)
e9fc3ce9 11208 return libbpf_err(-ENOENT);
dca5612f
AN
11209
11210 return cpu_buf->fd;
11211}
11212
11213/*
11214 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11215 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11216 * consume, do nothing and return success.
11217 * Returns:
11218 * - 0 on success;
11219 * - <0 on failure.
11220 */
11221int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11222{
11223 struct perf_cpu_buf *cpu_buf;
11224
11225 if (buf_idx >= pb->cpu_cnt)
e9fc3ce9 11226 return libbpf_err(-EINVAL);
dca5612f
AN
11227
11228 cpu_buf = pb->cpu_bufs[buf_idx];
11229 if (!cpu_buf)
e9fc3ce9 11230 return libbpf_err(-ENOENT);
dca5612f
AN
11231
11232 return perf_buffer__process_records(pb, cpu_buf);
11233}
11234
272d51af
EC
11235int perf_buffer__consume(struct perf_buffer *pb)
11236{
11237 int i, err;
11238
11239 for (i = 0; i < pb->cpu_cnt; i++) {
11240 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11241
11242 if (!cpu_buf)
11243 continue;
11244
11245 err = perf_buffer__process_records(pb, cpu_buf);
11246 if (err) {
dca5612f 11247 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
e9fc3ce9 11248 return libbpf_err(err);
272d51af
EC
11249 }
11250 }
11251 return 0;
11252}
11253
34be1646
SL
11254struct bpf_prog_info_array_desc {
11255 int array_offset; /* e.g. offset of jited_prog_insns */
11256 int count_offset; /* e.g. offset of jited_prog_len */
11257 int size_offset; /* > 0: offset of rec size,
11258 * < 0: fix size of -size_offset
11259 */
11260};
11261
11262static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
11263 [BPF_PROG_INFO_JITED_INSNS] = {
11264 offsetof(struct bpf_prog_info, jited_prog_insns),
11265 offsetof(struct bpf_prog_info, jited_prog_len),
11266 -1,
11267 },
11268 [BPF_PROG_INFO_XLATED_INSNS] = {
11269 offsetof(struct bpf_prog_info, xlated_prog_insns),
11270 offsetof(struct bpf_prog_info, xlated_prog_len),
11271 -1,
11272 },
11273 [BPF_PROG_INFO_MAP_IDS] = {
11274 offsetof(struct bpf_prog_info, map_ids),
11275 offsetof(struct bpf_prog_info, nr_map_ids),
11276 -(int)sizeof(__u32),
11277 },
11278 [BPF_PROG_INFO_JITED_KSYMS] = {
11279 offsetof(struct bpf_prog_info, jited_ksyms),
11280 offsetof(struct bpf_prog_info, nr_jited_ksyms),
11281 -(int)sizeof(__u64),
11282 },
11283 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
11284 offsetof(struct bpf_prog_info, jited_func_lens),
11285 offsetof(struct bpf_prog_info, nr_jited_func_lens),
11286 -(int)sizeof(__u32),
11287 },
11288 [BPF_PROG_INFO_FUNC_INFO] = {
11289 offsetof(struct bpf_prog_info, func_info),
11290 offsetof(struct bpf_prog_info, nr_func_info),
11291 offsetof(struct bpf_prog_info, func_info_rec_size),
11292 },
11293 [BPF_PROG_INFO_LINE_INFO] = {
11294 offsetof(struct bpf_prog_info, line_info),
11295 offsetof(struct bpf_prog_info, nr_line_info),
11296 offsetof(struct bpf_prog_info, line_info_rec_size),
11297 },
11298 [BPF_PROG_INFO_JITED_LINE_INFO] = {
11299 offsetof(struct bpf_prog_info, jited_line_info),
11300 offsetof(struct bpf_prog_info, nr_jited_line_info),
11301 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
11302 },
11303 [BPF_PROG_INFO_PROG_TAGS] = {
11304 offsetof(struct bpf_prog_info, prog_tags),
11305 offsetof(struct bpf_prog_info, nr_prog_tags),
11306 -(int)sizeof(__u8) * BPF_TAG_SIZE,
11307 },
11308
11309};
11310
8983b731
AN
11311static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
11312 int offset)
34be1646
SL
11313{
11314 __u32 *array = (__u32 *)info;
11315
11316 if (offset >= 0)
11317 return array[offset / sizeof(__u32)];
11318 return -(int)offset;
11319}
11320
8983b731
AN
11321static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
11322 int offset)
34be1646
SL
11323{
11324 __u64 *array = (__u64 *)info;
11325
11326 if (offset >= 0)
11327 return array[offset / sizeof(__u64)];
11328 return -(int)offset;
11329}
11330
11331static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
11332 __u32 val)
11333{
11334 __u32 *array = (__u32 *)info;
11335
11336 if (offset >= 0)
11337 array[offset / sizeof(__u32)] = val;
11338}
11339
11340static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
11341 __u64 val)
11342{
11343 __u64 *array = (__u64 *)info;
11344
11345 if (offset >= 0)
11346 array[offset / sizeof(__u64)] = val;
11347}
11348
11349struct bpf_prog_info_linear *
11350bpf_program__get_prog_info_linear(int fd, __u64 arrays)
11351{
11352 struct bpf_prog_info_linear *info_linear;
11353 struct bpf_prog_info info = {};
11354 __u32 info_len = sizeof(info);
11355 __u32 data_len = 0;
11356 int i, err;
11357 void *ptr;
11358
11359 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
e9fc3ce9 11360 return libbpf_err_ptr(-EINVAL);
34be1646
SL
11361
11362 /* step 1: get array dimensions */
11363 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
11364 if (err) {
11365 pr_debug("can't get prog info: %s", strerror(errno));
e9fc3ce9 11366 return libbpf_err_ptr(-EFAULT);
34be1646
SL
11367 }
11368
11369 /* step 2: calculate total size of all arrays */
11370 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11371 bool include_array = (arrays & (1UL << i)) > 0;
11372 struct bpf_prog_info_array_desc *desc;
11373 __u32 count, size;
11374
11375 desc = bpf_prog_info_array_desc + i;
11376
11377 /* kernel is too old to support this field */
11378 if (info_len < desc->array_offset + sizeof(__u32) ||
11379 info_len < desc->count_offset + sizeof(__u32) ||
11380 (desc->size_offset > 0 && info_len < desc->size_offset))
11381 include_array = false;
11382
11383 if (!include_array) {
11384 arrays &= ~(1UL << i); /* clear the bit */
11385 continue;
11386 }
11387
11388 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11389 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11390
11391 data_len += count * size;
11392 }
11393
11394 /* step 3: allocate continuous memory */
11395 data_len = roundup(data_len, sizeof(__u64));
11396 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
11397 if (!info_linear)
e9fc3ce9 11398 return libbpf_err_ptr(-ENOMEM);
34be1646
SL
11399
11400 /* step 4: fill data to info_linear->info */
11401 info_linear->arrays = arrays;
11402 memset(&info_linear->info, 0, sizeof(info));
11403 ptr = info_linear->data;
11404
11405 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11406 struct bpf_prog_info_array_desc *desc;
11407 __u32 count, size;
11408
11409 if ((arrays & (1UL << i)) == 0)
11410 continue;
11411
11412 desc = bpf_prog_info_array_desc + i;
11413 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11414 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11415 bpf_prog_info_set_offset_u32(&info_linear->info,
11416 desc->count_offset, count);
11417 bpf_prog_info_set_offset_u32(&info_linear->info,
11418 desc->size_offset, size);
11419 bpf_prog_info_set_offset_u64(&info_linear->info,
11420 desc->array_offset,
11421 ptr_to_u64(ptr));
11422 ptr += count * size;
11423 }
11424
11425 /* step 5: call syscall again to get required arrays */
11426 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
11427 if (err) {
11428 pr_debug("can't get prog info: %s", strerror(errno));
11429 free(info_linear);
e9fc3ce9 11430 return libbpf_err_ptr(-EFAULT);
34be1646
SL
11431 }
11432
11433 /* step 6: verify the data */
11434 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11435 struct bpf_prog_info_array_desc *desc;
11436 __u32 v1, v2;
11437
11438 if ((arrays & (1UL << i)) == 0)
11439 continue;
11440
11441 desc = bpf_prog_info_array_desc + i;
11442 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
11443 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11444 desc->count_offset);
11445 if (v1 != v2)
be18010e 11446 pr_warn("%s: mismatch in element count\n", __func__);
34be1646
SL
11447
11448 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
11449 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
11450 desc->size_offset);
11451 if (v1 != v2)
be18010e 11452 pr_warn("%s: mismatch in rec size\n", __func__);
34be1646
SL
11453 }
11454
11455 /* step 7: update info_len and data_len */
11456 info_linear->info_len = sizeof(struct bpf_prog_info);
11457 info_linear->data_len = data_len;
11458
11459 return info_linear;
11460}
11461
11462void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
11463{
11464 int i;
11465
11466 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11467 struct bpf_prog_info_array_desc *desc;
11468 __u64 addr, offs;
11469
11470 if ((info_linear->arrays & (1UL << i)) == 0)
11471 continue;
11472
11473 desc = bpf_prog_info_array_desc + i;
11474 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
11475 desc->array_offset);
11476 offs = addr - ptr_to_u64(info_linear->data);
11477 bpf_prog_info_set_offset_u64(&info_linear->info,
11478 desc->array_offset, offs);
11479 }
11480}
11481
11482void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
11483{
11484 int i;
11485
11486 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
11487 struct bpf_prog_info_array_desc *desc;
11488 __u64 addr, offs;
11489
11490 if ((info_linear->arrays & (1UL << i)) == 0)
11491 continue;
11492
11493 desc = bpf_prog_info_array_desc + i;
11494 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
11495 desc->array_offset);
11496 addr = offs + ptr_to_u64(info_linear->data);
11497 bpf_prog_info_set_offset_u64(&info_linear->info,
11498 desc->array_offset, addr);
11499 }
11500}
6446b315 11501
ff26ce5c
EC
11502int bpf_program__set_attach_target(struct bpf_program *prog,
11503 int attach_prog_fd,
11504 const char *attach_func_name)
11505{
fe62de31 11506 int btf_obj_fd = 0, btf_id = 0, err;
ff26ce5c 11507
2d5ec1c6 11508 if (!prog || attach_prog_fd < 0)
e9fc3ce9 11509 return libbpf_err(-EINVAL);
ff26ce5c 11510
fe62de31 11511 if (prog->obj->loaded)
e9fc3ce9 11512 return libbpf_err(-EINVAL);
fe62de31 11513
2d5ec1c6
AN
11514 if (attach_prog_fd && !attach_func_name) {
11515 /* remember attach_prog_fd and let bpf_program__load() find
11516 * BTF ID during the program load
11517 */
11518 prog->attach_prog_fd = attach_prog_fd;
11519 return 0;
11520 }
11521
fe62de31 11522 if (attach_prog_fd) {
ff26ce5c
EC
11523 btf_id = libbpf_find_prog_btf_id(attach_func_name,
11524 attach_prog_fd);
fe62de31 11525 if (btf_id < 0)
e9fc3ce9 11526 return libbpf_err(btf_id);
fe62de31 11527 } else {
2d5ec1c6
AN
11528 if (!attach_func_name)
11529 return libbpf_err(-EINVAL);
11530
fe62de31
AN
11531 /* load btf_vmlinux, if not yet */
11532 err = bpf_object__load_vmlinux_btf(prog->obj, true);
11533 if (err)
e9fc3ce9 11534 return libbpf_err(err);
fe62de31
AN
11535 err = find_kernel_btf_id(prog->obj, attach_func_name,
11536 prog->expected_attach_type,
11537 &btf_obj_fd, &btf_id);
11538 if (err)
e9fc3ce9 11539 return libbpf_err(err);
fe62de31 11540 }
ff26ce5c
EC
11541
11542 prog->attach_btf_id = btf_id;
fe62de31 11543 prog->attach_btf_obj_fd = btf_obj_fd;
ff26ce5c
EC
11544 prog->attach_prog_fd = attach_prog_fd;
11545 return 0;
11546}
11547
6803ee25 11548int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
6446b315 11549{
6803ee25
AN
11550 int err = 0, n, len, start, end = -1;
11551 bool *tmp;
6446b315 11552
6803ee25
AN
11553 *mask = NULL;
11554 *mask_sz = 0;
11555
11556 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
11557 while (*s) {
11558 if (*s == ',' || *s == '\n') {
11559 s++;
11560 continue;
11561 }
11562 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
11563 if (n <= 0 || n > 2) {
11564 pr_warn("Failed to get CPU range %s: %d\n", s, n);
11565 err = -EINVAL;
11566 goto cleanup;
11567 } else if (n == 1) {
11568 end = start;
11569 }
11570 if (start < 0 || start > end) {
11571 pr_warn("Invalid CPU range [%d,%d] in %s\n",
11572 start, end, s);
11573 err = -EINVAL;
11574 goto cleanup;
11575 }
11576 tmp = realloc(*mask, end + 1);
11577 if (!tmp) {
11578 err = -ENOMEM;
11579 goto cleanup;
11580 }
11581 *mask = tmp;
11582 memset(tmp + *mask_sz, 0, start - *mask_sz);
11583 memset(tmp + start, 1, end - start + 1);
11584 *mask_sz = end + 1;
11585 s += len;
11586 }
11587 if (!*mask_sz) {
11588 pr_warn("Empty CPU range\n");
11589 return -EINVAL;
11590 }
11591 return 0;
11592cleanup:
11593 free(*mask);
11594 *mask = NULL;
11595 return err;
11596}
11597
11598int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
11599{
11600 int fd, err = 0, len;
11601 char buf[128];
6446b315 11602
92274e24 11603 fd = open(fcpu, O_RDONLY | O_CLOEXEC);
6446b315 11604 if (fd < 0) {
6803ee25
AN
11605 err = -errno;
11606 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
11607 return err;
6446b315
HL
11608 }
11609 len = read(fd, buf, sizeof(buf));
11610 close(fd);
11611 if (len <= 0) {
6803ee25
AN
11612 err = len ? -errno : -EINVAL;
11613 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
11614 return err;
6446b315 11615 }
6803ee25
AN
11616 if (len >= sizeof(buf)) {
11617 pr_warn("CPU mask is too big in file %s\n", fcpu);
11618 return -E2BIG;
6446b315
HL
11619 }
11620 buf[len] = '\0';
11621
6803ee25
AN
11622 return parse_cpu_mask_str(buf, mask, mask_sz);
11623}
11624
11625int libbpf_num_possible_cpus(void)
11626{
11627 static const char *fcpu = "/sys/devices/system/cpu/possible";
11628 static int cpus;
11629 int err, n, i, tmp_cpus;
11630 bool *mask;
11631
11632 tmp_cpus = READ_ONCE(cpus);
11633 if (tmp_cpus > 0)
11634 return tmp_cpus;
11635
11636 err = parse_cpu_mask_file(fcpu, &mask, &n);
11637 if (err)
e9fc3ce9 11638 return libbpf_err(err);
6803ee25
AN
11639
11640 tmp_cpus = 0;
11641 for (i = 0; i < n; i++) {
11642 if (mask[i])
11643 tmp_cpus++;
6446b315 11644 }
6803ee25 11645 free(mask);
56fbc241
TC
11646
11647 WRITE_ONCE(cpus, tmp_cpus);
11648 return tmp_cpus;
6446b315 11649}
d66562fb
AN
11650
11651int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
11652 const struct bpf_object_open_opts *opts)
11653{
11654 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
11655 .object_name = s->name,
11656 );
11657 struct bpf_object *obj;
e9fc3ce9 11658 int i, err;
d66562fb
AN
11659
11660 /* Attempt to preserve opts->object_name, unless overriden by user
11661 * explicitly. Overwriting object name for skeletons is discouraged,
11662 * as it breaks global data maps, because they contain object name
11663 * prefix as their own map name prefix. When skeleton is generated,
11664 * bpftool is making an assumption that this name will stay the same.
11665 */
11666 if (opts) {
11667 memcpy(&skel_opts, opts, sizeof(*opts));
11668 if (!opts->object_name)
11669 skel_opts.object_name = s->name;
11670 }
11671
11672 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
e9fc3ce9
AN
11673 err = libbpf_get_error(obj);
11674 if (err) {
11675 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
11676 s->name, err);
11677 return libbpf_err(err);
d66562fb
AN
11678 }
11679
11680 *s->obj = obj;
11681
11682 for (i = 0; i < s->map_cnt; i++) {
11683 struct bpf_map **map = s->maps[i].map;
11684 const char *name = s->maps[i].name;
11685 void **mmaped = s->maps[i].mmaped;
11686
11687 *map = bpf_object__find_map_by_name(obj, name);
11688 if (!*map) {
11689 pr_warn("failed to find skeleton map '%s'\n", name);
e9fc3ce9 11690 return libbpf_err(-ESRCH);
d66562fb
AN
11691 }
11692
2ad97d47 11693 /* externs shouldn't be pre-setup from user code */
81bfdd08 11694 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
d66562fb
AN
11695 *mmaped = (*map)->mmaped;
11696 }
11697
11698 for (i = 0; i < s->prog_cnt; i++) {
11699 struct bpf_program **prog = s->progs[i].prog;
11700 const char *name = s->progs[i].name;
11701
11702 *prog = bpf_object__find_program_by_name(obj, name);
11703 if (!*prog) {
11704 pr_warn("failed to find skeleton program '%s'\n", name);
e9fc3ce9 11705 return libbpf_err(-ESRCH);
d66562fb
AN
11706 }
11707 }
11708
11709 return 0;
11710}
11711
11712int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
11713{
11714 int i, err;
11715
11716 err = bpf_object__load(*s->obj);
11717 if (err) {
11718 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
e9fc3ce9 11719 return libbpf_err(err);
d66562fb
AN
11720 }
11721
11722 for (i = 0; i < s->map_cnt; i++) {
11723 struct bpf_map *map = *s->maps[i].map;
11724 size_t mmap_sz = bpf_map_mmap_sz(map);
11725 int prot, map_fd = bpf_map__fd(map);
11726 void **mmaped = s->maps[i].mmaped;
d66562fb
AN
11727
11728 if (!mmaped)
11729 continue;
11730
11731 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
11732 *mmaped = NULL;
11733 continue;
11734 }
11735
11736 if (map->def.map_flags & BPF_F_RDONLY_PROG)
11737 prot = PROT_READ;
11738 else
11739 prot = PROT_READ | PROT_WRITE;
11740
11741 /* Remap anonymous mmap()-ed "map initialization image" as
11742 * a BPF map-backed mmap()-ed memory, but preserving the same
11743 * memory address. This will cause kernel to change process'
11744 * page table to point to a different piece of kernel memory,
11745 * but from userspace point of view memory address (and its
11746 * contents, being identical at this point) will stay the
11747 * same. This mapping will be released by bpf_object__close()
11748 * as per normal clean up procedure, so we don't need to worry
11749 * about it from skeleton's clean up perspective.
11750 */
2ad97d47
AN
11751 *mmaped = mmap(map->mmaped, mmap_sz, prot,
11752 MAP_SHARED | MAP_FIXED, map_fd, 0);
11753 if (*mmaped == MAP_FAILED) {
d66562fb
AN
11754 err = -errno;
11755 *mmaped = NULL;
11756 pr_warn("failed to re-mmap() map '%s': %d\n",
11757 bpf_map__name(map), err);
e9fc3ce9 11758 return libbpf_err(err);
d66562fb
AN
11759 }
11760 }
11761
11762 return 0;
11763}
11764
11765int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
11766{
e9fc3ce9 11767 int i, err;
d66562fb
AN
11768
11769 for (i = 0; i < s->prog_cnt; i++) {
11770 struct bpf_program *prog = *s->progs[i].prog;
11771 struct bpf_link **link = s->progs[i].link;
d66562fb 11772
d9297581
AN
11773 if (!prog->load)
11774 continue;
11775
5532dfd4
AN
11776 /* auto-attaching not supported for this program */
11777 if (!prog->sec_def || !prog->sec_def->attach_fn)
d66562fb
AN
11778 continue;
11779
942025c9 11780 *link = bpf_program__attach(prog);
e9fc3ce9
AN
11781 err = libbpf_get_error(*link);
11782 if (err) {
11783 pr_warn("failed to auto-attach program '%s': %d\n",
11784 bpf_program__name(prog), err);
11785 return libbpf_err(err);
d66562fb
AN
11786 }
11787 }
11788
11789 return 0;
11790}
11791
11792void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
11793{
11794 int i;
11795
11796 for (i = 0; i < s->prog_cnt; i++) {
11797 struct bpf_link **link = s->progs[i].link;
11798
50450fc7 11799 bpf_link__destroy(*link);
d66562fb
AN
11800 *link = NULL;
11801 }
11802}
11803
11804void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
11805{
a32ea51a
YS
11806 if (!s)
11807 return;
11808
d66562fb
AN
11809 if (s->progs)
11810 bpf_object__detach_skeleton(s);
11811 if (s->obj)
11812 bpf_object__close(*s->obj);
11813 free(s->maps);
11814 free(s->progs);
11815 free(s);
11816}