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