Revert BPF token-related functionality
[linux-2.6-block.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_UNIX_CONNECT]       = "cgroup_unix_connect",
86         [BPF_CGROUP_INET4_POST_BIND]    = "cgroup_inet4_post_bind",
87         [BPF_CGROUP_INET6_POST_BIND]    = "cgroup_inet6_post_bind",
88         [BPF_CGROUP_INET4_GETPEERNAME]  = "cgroup_inet4_getpeername",
89         [BPF_CGROUP_INET6_GETPEERNAME]  = "cgroup_inet6_getpeername",
90         [BPF_CGROUP_UNIX_GETPEERNAME]   = "cgroup_unix_getpeername",
91         [BPF_CGROUP_INET4_GETSOCKNAME]  = "cgroup_inet4_getsockname",
92         [BPF_CGROUP_INET6_GETSOCKNAME]  = "cgroup_inet6_getsockname",
93         [BPF_CGROUP_UNIX_GETSOCKNAME]   = "cgroup_unix_getsockname",
94         [BPF_CGROUP_UDP4_SENDMSG]       = "cgroup_udp4_sendmsg",
95         [BPF_CGROUP_UDP6_SENDMSG]       = "cgroup_udp6_sendmsg",
96         [BPF_CGROUP_UNIX_SENDMSG]       = "cgroup_unix_sendmsg",
97         [BPF_CGROUP_SYSCTL]             = "cgroup_sysctl",
98         [BPF_CGROUP_UDP4_RECVMSG]       = "cgroup_udp4_recvmsg",
99         [BPF_CGROUP_UDP6_RECVMSG]       = "cgroup_udp6_recvmsg",
100         [BPF_CGROUP_UNIX_RECVMSG]       = "cgroup_unix_recvmsg",
101         [BPF_CGROUP_GETSOCKOPT]         = "cgroup_getsockopt",
102         [BPF_CGROUP_SETSOCKOPT]         = "cgroup_setsockopt",
103         [BPF_SK_SKB_STREAM_PARSER]      = "sk_skb_stream_parser",
104         [BPF_SK_SKB_STREAM_VERDICT]     = "sk_skb_stream_verdict",
105         [BPF_SK_SKB_VERDICT]            = "sk_skb_verdict",
106         [BPF_SK_MSG_VERDICT]            = "sk_msg_verdict",
107         [BPF_LIRC_MODE2]                = "lirc_mode2",
108         [BPF_FLOW_DISSECTOR]            = "flow_dissector",
109         [BPF_TRACE_RAW_TP]              = "trace_raw_tp",
110         [BPF_TRACE_FENTRY]              = "trace_fentry",
111         [BPF_TRACE_FEXIT]               = "trace_fexit",
112         [BPF_MODIFY_RETURN]             = "modify_return",
113         [BPF_LSM_MAC]                   = "lsm_mac",
114         [BPF_LSM_CGROUP]                = "lsm_cgroup",
115         [BPF_SK_LOOKUP]                 = "sk_lookup",
116         [BPF_TRACE_ITER]                = "trace_iter",
117         [BPF_XDP_DEVMAP]                = "xdp_devmap",
118         [BPF_XDP_CPUMAP]                = "xdp_cpumap",
119         [BPF_XDP]                       = "xdp",
120         [BPF_SK_REUSEPORT_SELECT]       = "sk_reuseport_select",
121         [BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]    = "sk_reuseport_select_or_migrate",
122         [BPF_PERF_EVENT]                = "perf_event",
123         [BPF_TRACE_KPROBE_MULTI]        = "trace_kprobe_multi",
124         [BPF_STRUCT_OPS]                = "struct_ops",
125         [BPF_NETFILTER]                 = "netfilter",
126         [BPF_TCX_INGRESS]               = "tcx_ingress",
127         [BPF_TCX_EGRESS]                = "tcx_egress",
128         [BPF_TRACE_UPROBE_MULTI]        = "trace_uprobe_multi",
129         [BPF_NETKIT_PRIMARY]            = "netkit_primary",
130         [BPF_NETKIT_PEER]               = "netkit_peer",
131 };
132
133 static const char * const link_type_name[] = {
134         [BPF_LINK_TYPE_UNSPEC]                  = "unspec",
135         [BPF_LINK_TYPE_RAW_TRACEPOINT]          = "raw_tracepoint",
136         [BPF_LINK_TYPE_TRACING]                 = "tracing",
137         [BPF_LINK_TYPE_CGROUP]                  = "cgroup",
138         [BPF_LINK_TYPE_ITER]                    = "iter",
139         [BPF_LINK_TYPE_NETNS]                   = "netns",
140         [BPF_LINK_TYPE_XDP]                     = "xdp",
141         [BPF_LINK_TYPE_PERF_EVENT]              = "perf_event",
142         [BPF_LINK_TYPE_KPROBE_MULTI]            = "kprobe_multi",
143         [BPF_LINK_TYPE_STRUCT_OPS]              = "struct_ops",
144         [BPF_LINK_TYPE_NETFILTER]               = "netfilter",
145         [BPF_LINK_TYPE_TCX]                     = "tcx",
146         [BPF_LINK_TYPE_UPROBE_MULTI]            = "uprobe_multi",
147         [BPF_LINK_TYPE_NETKIT]                  = "netkit",
148 };
149
150 static const char * const map_type_name[] = {
151         [BPF_MAP_TYPE_UNSPEC]                   = "unspec",
152         [BPF_MAP_TYPE_HASH]                     = "hash",
153         [BPF_MAP_TYPE_ARRAY]                    = "array",
154         [BPF_MAP_TYPE_PROG_ARRAY]               = "prog_array",
155         [BPF_MAP_TYPE_PERF_EVENT_ARRAY]         = "perf_event_array",
156         [BPF_MAP_TYPE_PERCPU_HASH]              = "percpu_hash",
157         [BPF_MAP_TYPE_PERCPU_ARRAY]             = "percpu_array",
158         [BPF_MAP_TYPE_STACK_TRACE]              = "stack_trace",
159         [BPF_MAP_TYPE_CGROUP_ARRAY]             = "cgroup_array",
160         [BPF_MAP_TYPE_LRU_HASH]                 = "lru_hash",
161         [BPF_MAP_TYPE_LRU_PERCPU_HASH]          = "lru_percpu_hash",
162         [BPF_MAP_TYPE_LPM_TRIE]                 = "lpm_trie",
163         [BPF_MAP_TYPE_ARRAY_OF_MAPS]            = "array_of_maps",
164         [BPF_MAP_TYPE_HASH_OF_MAPS]             = "hash_of_maps",
165         [BPF_MAP_TYPE_DEVMAP]                   = "devmap",
166         [BPF_MAP_TYPE_DEVMAP_HASH]              = "devmap_hash",
167         [BPF_MAP_TYPE_SOCKMAP]                  = "sockmap",
168         [BPF_MAP_TYPE_CPUMAP]                   = "cpumap",
169         [BPF_MAP_TYPE_XSKMAP]                   = "xskmap",
170         [BPF_MAP_TYPE_SOCKHASH]                 = "sockhash",
171         [BPF_MAP_TYPE_CGROUP_STORAGE]           = "cgroup_storage",
172         [BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]      = "reuseport_sockarray",
173         [BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]    = "percpu_cgroup_storage",
174         [BPF_MAP_TYPE_QUEUE]                    = "queue",
175         [BPF_MAP_TYPE_STACK]                    = "stack",
176         [BPF_MAP_TYPE_SK_STORAGE]               = "sk_storage",
177         [BPF_MAP_TYPE_STRUCT_OPS]               = "struct_ops",
178         [BPF_MAP_TYPE_RINGBUF]                  = "ringbuf",
179         [BPF_MAP_TYPE_INODE_STORAGE]            = "inode_storage",
180         [BPF_MAP_TYPE_TASK_STORAGE]             = "task_storage",
181         [BPF_MAP_TYPE_BLOOM_FILTER]             = "bloom_filter",
182         [BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
183         [BPF_MAP_TYPE_CGRP_STORAGE]             = "cgrp_storage",
184 };
185
186 static const char * const prog_type_name[] = {
187         [BPF_PROG_TYPE_UNSPEC]                  = "unspec",
188         [BPF_PROG_TYPE_SOCKET_FILTER]           = "socket_filter",
189         [BPF_PROG_TYPE_KPROBE]                  = "kprobe",
190         [BPF_PROG_TYPE_SCHED_CLS]               = "sched_cls",
191         [BPF_PROG_TYPE_SCHED_ACT]               = "sched_act",
192         [BPF_PROG_TYPE_TRACEPOINT]              = "tracepoint",
193         [BPF_PROG_TYPE_XDP]                     = "xdp",
194         [BPF_PROG_TYPE_PERF_EVENT]              = "perf_event",
195         [BPF_PROG_TYPE_CGROUP_SKB]              = "cgroup_skb",
196         [BPF_PROG_TYPE_CGROUP_SOCK]             = "cgroup_sock",
197         [BPF_PROG_TYPE_LWT_IN]                  = "lwt_in",
198         [BPF_PROG_TYPE_LWT_OUT]                 = "lwt_out",
199         [BPF_PROG_TYPE_LWT_XMIT]                = "lwt_xmit",
200         [BPF_PROG_TYPE_SOCK_OPS]                = "sock_ops",
201         [BPF_PROG_TYPE_SK_SKB]                  = "sk_skb",
202         [BPF_PROG_TYPE_CGROUP_DEVICE]           = "cgroup_device",
203         [BPF_PROG_TYPE_SK_MSG]                  = "sk_msg",
204         [BPF_PROG_TYPE_RAW_TRACEPOINT]          = "raw_tracepoint",
205         [BPF_PROG_TYPE_CGROUP_SOCK_ADDR]        = "cgroup_sock_addr",
206         [BPF_PROG_TYPE_LWT_SEG6LOCAL]           = "lwt_seg6local",
207         [BPF_PROG_TYPE_LIRC_MODE2]              = "lirc_mode2",
208         [BPF_PROG_TYPE_SK_REUSEPORT]            = "sk_reuseport",
209         [BPF_PROG_TYPE_FLOW_DISSECTOR]          = "flow_dissector",
210         [BPF_PROG_TYPE_CGROUP_SYSCTL]           = "cgroup_sysctl",
211         [BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE] = "raw_tracepoint_writable",
212         [BPF_PROG_TYPE_CGROUP_SOCKOPT]          = "cgroup_sockopt",
213         [BPF_PROG_TYPE_TRACING]                 = "tracing",
214         [BPF_PROG_TYPE_STRUCT_OPS]              = "struct_ops",
215         [BPF_PROG_TYPE_EXT]                     = "ext",
216         [BPF_PROG_TYPE_LSM]                     = "lsm",
217         [BPF_PROG_TYPE_SK_LOOKUP]               = "sk_lookup",
218         [BPF_PROG_TYPE_SYSCALL]                 = "syscall",
219         [BPF_PROG_TYPE_NETFILTER]               = "netfilter",
220 };
221
222 static int __base_pr(enum libbpf_print_level level, const char *format,
223                      va_list args)
224 {
225         if (level == LIBBPF_DEBUG)
226                 return 0;
227
228         return vfprintf(stderr, format, args);
229 }
230
231 static libbpf_print_fn_t __libbpf_pr = __base_pr;
232
233 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
234 {
235         libbpf_print_fn_t old_print_fn;
236
237         old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
238
239         return old_print_fn;
240 }
241
242 __printf(2, 3)
243 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
244 {
245         va_list args;
246         int old_errno;
247         libbpf_print_fn_t print_fn;
248
249         print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
250         if (!print_fn)
251                 return;
252
253         old_errno = errno;
254
255         va_start(args, format);
256         __libbpf_pr(level, format, args);
257         va_end(args);
258
259         errno = old_errno;
260 }
261
262 static void pr_perm_msg(int err)
263 {
264         struct rlimit limit;
265         char buf[100];
266
267         if (err != -EPERM || geteuid() != 0)
268                 return;
269
270         err = getrlimit(RLIMIT_MEMLOCK, &limit);
271         if (err)
272                 return;
273
274         if (limit.rlim_cur == RLIM_INFINITY)
275                 return;
276
277         if (limit.rlim_cur < 1024)
278                 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
279         else if (limit.rlim_cur < 1024*1024)
280                 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
281         else
282                 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
283
284         pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
285                 buf);
286 }
287
288 #define STRERR_BUFSIZE  128
289
290 /* Copied from tools/perf/util/util.h */
291 #ifndef zfree
292 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
293 #endif
294
295 #ifndef zclose
296 # define zclose(fd) ({                  \
297         int ___err = 0;                 \
298         if ((fd) >= 0)                  \
299                 ___err = close((fd));   \
300         fd = -1;                        \
301         ___err; })
302 #endif
303
304 static inline __u64 ptr_to_u64(const void *ptr)
305 {
306         return (__u64) (unsigned long) ptr;
307 }
308
309 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
310 {
311         /* as of v1.0 libbpf_set_strict_mode() is a no-op */
312         return 0;
313 }
314
315 __u32 libbpf_major_version(void)
316 {
317         return LIBBPF_MAJOR_VERSION;
318 }
319
320 __u32 libbpf_minor_version(void)
321 {
322         return LIBBPF_MINOR_VERSION;
323 }
324
325 const char *libbpf_version_string(void)
326 {
327 #define __S(X) #X
328 #define _S(X) __S(X)
329         return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
330 #undef _S
331 #undef __S
332 }
333
334 enum reloc_type {
335         RELO_LD64,
336         RELO_CALL,
337         RELO_DATA,
338         RELO_EXTERN_LD64,
339         RELO_EXTERN_CALL,
340         RELO_SUBPROG_ADDR,
341         RELO_CORE,
342 };
343
344 struct reloc_desc {
345         enum reloc_type type;
346         int insn_idx;
347         union {
348                 const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
349                 struct {
350                         int map_idx;
351                         int sym_off;
352                         int ext_idx;
353                 };
354         };
355 };
356
357 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
358 enum sec_def_flags {
359         SEC_NONE = 0,
360         /* expected_attach_type is optional, if kernel doesn't support that */
361         SEC_EXP_ATTACH_OPT = 1,
362         /* legacy, only used by libbpf_get_type_names() and
363          * libbpf_attach_type_by_name(), not used by libbpf itself at all.
364          * This used to be associated with cgroup (and few other) BPF programs
365          * that were attachable through BPF_PROG_ATTACH command. Pretty
366          * meaningless nowadays, though.
367          */
368         SEC_ATTACHABLE = 2,
369         SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
370         /* attachment target is specified through BTF ID in either kernel or
371          * other BPF program's BTF object
372          */
373         SEC_ATTACH_BTF = 4,
374         /* BPF program type allows sleeping/blocking in kernel */
375         SEC_SLEEPABLE = 8,
376         /* BPF program support non-linear XDP buffer */
377         SEC_XDP_FRAGS = 16,
378         /* Setup proper attach type for usdt probes. */
379         SEC_USDT = 32,
380 };
381
382 struct bpf_sec_def {
383         char *sec;
384         enum bpf_prog_type prog_type;
385         enum bpf_attach_type expected_attach_type;
386         long cookie;
387         int handler_id;
388
389         libbpf_prog_setup_fn_t prog_setup_fn;
390         libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
391         libbpf_prog_attach_fn_t prog_attach_fn;
392 };
393
394 /*
395  * bpf_prog should be a better name but it has been used in
396  * linux/filter.h.
397  */
398 struct bpf_program {
399         char *name;
400         char *sec_name;
401         size_t sec_idx;
402         const struct bpf_sec_def *sec_def;
403         /* this program's instruction offset (in number of instructions)
404          * within its containing ELF section
405          */
406         size_t sec_insn_off;
407         /* number of original instructions in ELF section belonging to this
408          * program, not taking into account subprogram instructions possible
409          * appended later during relocation
410          */
411         size_t sec_insn_cnt;
412         /* Offset (in number of instructions) of the start of instruction
413          * belonging to this BPF program  within its containing main BPF
414          * program. For the entry-point (main) BPF program, this is always
415          * zero. For a sub-program, this gets reset before each of main BPF
416          * programs are processed and relocated and is used to determined
417          * whether sub-program was already appended to the main program, and
418          * if yes, at which instruction offset.
419          */
420         size_t sub_insn_off;
421
422         /* instructions that belong to BPF program; insns[0] is located at
423          * sec_insn_off instruction within its ELF section in ELF file, so
424          * when mapping ELF file instruction index to the local instruction,
425          * one needs to subtract sec_insn_off; and vice versa.
426          */
427         struct bpf_insn *insns;
428         /* actual number of instruction in this BPF program's image; for
429          * entry-point BPF programs this includes the size of main program
430          * itself plus all the used sub-programs, appended at the end
431          */
432         size_t insns_cnt;
433
434         struct reloc_desc *reloc_desc;
435         int nr_reloc;
436
437         /* BPF verifier log settings */
438         char *log_buf;
439         size_t log_size;
440         __u32 log_level;
441
442         struct bpf_object *obj;
443
444         int fd;
445         bool autoload;
446         bool autoattach;
447         bool sym_global;
448         bool mark_btf_static;
449         enum bpf_prog_type type;
450         enum bpf_attach_type expected_attach_type;
451         int exception_cb_idx;
452
453         int prog_ifindex;
454         __u32 attach_btf_obj_fd;
455         __u32 attach_btf_id;
456         __u32 attach_prog_fd;
457
458         void *func_info;
459         __u32 func_info_rec_size;
460         __u32 func_info_cnt;
461
462         void *line_info;
463         __u32 line_info_rec_size;
464         __u32 line_info_cnt;
465         __u32 prog_flags;
466 };
467
468 struct bpf_struct_ops {
469         const char *tname;
470         const struct btf_type *type;
471         struct bpf_program **progs;
472         __u32 *kern_func_off;
473         /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
474         void *data;
475         /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
476          *      btf_vmlinux's format.
477          * struct bpf_struct_ops_tcp_congestion_ops {
478          *      [... some other kernel fields ...]
479          *      struct tcp_congestion_ops data;
480          * }
481          * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
482          * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
483          * from "data".
484          */
485         void *kern_vdata;
486         __u32 type_id;
487 };
488
489 #define DATA_SEC ".data"
490 #define BSS_SEC ".bss"
491 #define RODATA_SEC ".rodata"
492 #define KCONFIG_SEC ".kconfig"
493 #define KSYMS_SEC ".ksyms"
494 #define STRUCT_OPS_SEC ".struct_ops"
495 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
496
497 enum libbpf_map_type {
498         LIBBPF_MAP_UNSPEC,
499         LIBBPF_MAP_DATA,
500         LIBBPF_MAP_BSS,
501         LIBBPF_MAP_RODATA,
502         LIBBPF_MAP_KCONFIG,
503 };
504
505 struct bpf_map_def {
506         unsigned int type;
507         unsigned int key_size;
508         unsigned int value_size;
509         unsigned int max_entries;
510         unsigned int map_flags;
511 };
512
513 struct bpf_map {
514         struct bpf_object *obj;
515         char *name;
516         /* real_name is defined for special internal maps (.rodata*,
517          * .data*, .bss, .kconfig) and preserves their original ELF section
518          * name. This is important to be able to find corresponding BTF
519          * DATASEC information.
520          */
521         char *real_name;
522         int fd;
523         int sec_idx;
524         size_t sec_offset;
525         int map_ifindex;
526         int inner_map_fd;
527         struct bpf_map_def def;
528         __u32 numa_node;
529         __u32 btf_var_idx;
530         __u32 btf_key_type_id;
531         __u32 btf_value_type_id;
532         __u32 btf_vmlinux_value_type_id;
533         enum libbpf_map_type libbpf_type;
534         void *mmaped;
535         struct bpf_struct_ops *st_ops;
536         struct bpf_map *inner_map;
537         void **init_slots;
538         int init_slots_sz;
539         char *pin_path;
540         bool pinned;
541         bool reused;
542         bool autocreate;
543         __u64 map_extra;
544 };
545
546 enum extern_type {
547         EXT_UNKNOWN,
548         EXT_KCFG,
549         EXT_KSYM,
550 };
551
552 enum kcfg_type {
553         KCFG_UNKNOWN,
554         KCFG_CHAR,
555         KCFG_BOOL,
556         KCFG_INT,
557         KCFG_TRISTATE,
558         KCFG_CHAR_ARR,
559 };
560
561 struct extern_desc {
562         enum extern_type type;
563         int sym_idx;
564         int btf_id;
565         int sec_btf_id;
566         const char *name;
567         char *essent_name;
568         bool is_set;
569         bool is_weak;
570         union {
571                 struct {
572                         enum kcfg_type type;
573                         int sz;
574                         int align;
575                         int data_off;
576                         bool is_signed;
577                 } kcfg;
578                 struct {
579                         unsigned long long addr;
580
581                         /* target btf_id of the corresponding kernel var. */
582                         int kernel_btf_obj_fd;
583                         int kernel_btf_id;
584
585                         /* local btf_id of the ksym extern's type. */
586                         __u32 type_id;
587                         /* BTF fd index to be patched in for insn->off, this is
588                          * 0 for vmlinux BTF, index in obj->fd_array for module
589                          * BTF
590                          */
591                         __s16 btf_fd_idx;
592                 } ksym;
593         };
594 };
595
596 struct module_btf {
597         struct btf *btf;
598         char *name;
599         __u32 id;
600         int fd;
601         int fd_array_idx;
602 };
603
604 enum sec_type {
605         SEC_UNUSED = 0,
606         SEC_RELO,
607         SEC_BSS,
608         SEC_DATA,
609         SEC_RODATA,
610 };
611
612 struct elf_sec_desc {
613         enum sec_type sec_type;
614         Elf64_Shdr *shdr;
615         Elf_Data *data;
616 };
617
618 struct elf_state {
619         int fd;
620         const void *obj_buf;
621         size_t obj_buf_sz;
622         Elf *elf;
623         Elf64_Ehdr *ehdr;
624         Elf_Data *symbols;
625         Elf_Data *st_ops_data;
626         Elf_Data *st_ops_link_data;
627         size_t shstrndx; /* section index for section name strings */
628         size_t strtabidx;
629         struct elf_sec_desc *secs;
630         size_t sec_cnt;
631         int btf_maps_shndx;
632         __u32 btf_maps_sec_btf_id;
633         int text_shndx;
634         int symbols_shndx;
635         int st_ops_shndx;
636         int st_ops_link_shndx;
637 };
638
639 struct usdt_manager;
640
641 struct bpf_object {
642         char name[BPF_OBJ_NAME_LEN];
643         char license[64];
644         __u32 kern_version;
645
646         struct bpf_program *programs;
647         size_t nr_programs;
648         struct bpf_map *maps;
649         size_t nr_maps;
650         size_t maps_cap;
651
652         char *kconfig;
653         struct extern_desc *externs;
654         int nr_extern;
655         int kconfig_map_idx;
656
657         bool loaded;
658         bool has_subcalls;
659         bool has_rodata;
660
661         struct bpf_gen *gen_loader;
662
663         /* Information when doing ELF related work. Only valid if efile.elf is not NULL */
664         struct elf_state efile;
665
666         struct btf *btf;
667         struct btf_ext *btf_ext;
668
669         /* Parse and load BTF vmlinux if any of the programs in the object need
670          * it at load time.
671          */
672         struct btf *btf_vmlinux;
673         /* Path to the custom BTF to be used for BPF CO-RE relocations as an
674          * override for vmlinux BTF.
675          */
676         char *btf_custom_path;
677         /* vmlinux BTF override for CO-RE relocations */
678         struct btf *btf_vmlinux_override;
679         /* Lazily initialized kernel module BTFs */
680         struct module_btf *btf_modules;
681         bool btf_modules_loaded;
682         size_t btf_module_cnt;
683         size_t btf_module_cap;
684
685         /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
686         char *log_buf;
687         size_t log_size;
688         __u32 log_level;
689
690         int *fd_array;
691         size_t fd_array_cap;
692         size_t fd_array_cnt;
693
694         struct usdt_manager *usdt_man;
695
696         char path[];
697 };
698
699 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
700 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
701 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
702 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
703 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
705 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
706 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
707 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
708
709 void bpf_program__unload(struct bpf_program *prog)
710 {
711         if (!prog)
712                 return;
713
714         zclose(prog->fd);
715
716         zfree(&prog->func_info);
717         zfree(&prog->line_info);
718 }
719
720 static void bpf_program__exit(struct bpf_program *prog)
721 {
722         if (!prog)
723                 return;
724
725         bpf_program__unload(prog);
726         zfree(&prog->name);
727         zfree(&prog->sec_name);
728         zfree(&prog->insns);
729         zfree(&prog->reloc_desc);
730
731         prog->nr_reloc = 0;
732         prog->insns_cnt = 0;
733         prog->sec_idx = -1;
734 }
735
736 static bool insn_is_subprog_call(const struct bpf_insn *insn)
737 {
738         return BPF_CLASS(insn->code) == BPF_JMP &&
739                BPF_OP(insn->code) == BPF_CALL &&
740                BPF_SRC(insn->code) == BPF_K &&
741                insn->src_reg == BPF_PSEUDO_CALL &&
742                insn->dst_reg == 0 &&
743                insn->off == 0;
744 }
745
746 static bool is_call_insn(const struct bpf_insn *insn)
747 {
748         return insn->code == (BPF_JMP | BPF_CALL);
749 }
750
751 static bool insn_is_pseudo_func(struct bpf_insn *insn)
752 {
753         return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
754 }
755
756 static int
757 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
758                       const char *name, size_t sec_idx, const char *sec_name,
759                       size_t sec_off, void *insn_data, size_t insn_data_sz)
760 {
761         if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
762                 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
763                         sec_name, name, sec_off, insn_data_sz);
764                 return -EINVAL;
765         }
766
767         memset(prog, 0, sizeof(*prog));
768         prog->obj = obj;
769
770         prog->sec_idx = sec_idx;
771         prog->sec_insn_off = sec_off / BPF_INSN_SZ;
772         prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
773         /* insns_cnt can later be increased by appending used subprograms */
774         prog->insns_cnt = prog->sec_insn_cnt;
775
776         prog->type = BPF_PROG_TYPE_UNSPEC;
777         prog->fd = -1;
778         prog->exception_cb_idx = -1;
779
780         /* libbpf's convention for SEC("?abc...") is that it's just like
781          * SEC("abc...") but the corresponding bpf_program starts out with
782          * autoload set to false.
783          */
784         if (sec_name[0] == '?') {
785                 prog->autoload = false;
786                 /* from now on forget there was ? in section name */
787                 sec_name++;
788         } else {
789                 prog->autoload = true;
790         }
791
792         prog->autoattach = true;
793
794         /* inherit object's log_level */
795         prog->log_level = obj->log_level;
796
797         prog->sec_name = strdup(sec_name);
798         if (!prog->sec_name)
799                 goto errout;
800
801         prog->name = strdup(name);
802         if (!prog->name)
803                 goto errout;
804
805         prog->insns = malloc(insn_data_sz);
806         if (!prog->insns)
807                 goto errout;
808         memcpy(prog->insns, insn_data, insn_data_sz);
809
810         return 0;
811 errout:
812         pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
813         bpf_program__exit(prog);
814         return -ENOMEM;
815 }
816
817 static int
818 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
819                          const char *sec_name, int sec_idx)
820 {
821         Elf_Data *symbols = obj->efile.symbols;
822         struct bpf_program *prog, *progs;
823         void *data = sec_data->d_buf;
824         size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
825         int nr_progs, err, i;
826         const char *name;
827         Elf64_Sym *sym;
828
829         progs = obj->programs;
830         nr_progs = obj->nr_programs;
831         nr_syms = symbols->d_size / sizeof(Elf64_Sym);
832
833         for (i = 0; i < nr_syms; i++) {
834                 sym = elf_sym_by_idx(obj, i);
835
836                 if (sym->st_shndx != sec_idx)
837                         continue;
838                 if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
839                         continue;
840
841                 prog_sz = sym->st_size;
842                 sec_off = sym->st_value;
843
844                 name = elf_sym_str(obj, sym->st_name);
845                 if (!name) {
846                         pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
847                                 sec_name, sec_off);
848                         return -LIBBPF_ERRNO__FORMAT;
849                 }
850
851                 if (sec_off + prog_sz > sec_sz) {
852                         pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
853                                 sec_name, sec_off);
854                         return -LIBBPF_ERRNO__FORMAT;
855                 }
856
857                 if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
858                         pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
859                         return -ENOTSUP;
860                 }
861
862                 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
863                          sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
864
865                 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
866                 if (!progs) {
867                         /*
868                          * In this case the original obj->programs
869                          * is still valid, so don't need special treat for
870                          * bpf_close_object().
871                          */
872                         pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
873                                 sec_name, name);
874                         return -ENOMEM;
875                 }
876                 obj->programs = progs;
877
878                 prog = &progs[nr_progs];
879
880                 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
881                                             sec_off, data + sec_off, prog_sz);
882                 if (err)
883                         return err;
884
885                 if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
886                         prog->sym_global = true;
887
888                 /* if function is a global/weak symbol, but has restricted
889                  * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
890                  * as static to enable more permissive BPF verification mode
891                  * with more outside context available to BPF verifier
892                  */
893                 if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
894                     || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
895                         prog->mark_btf_static = true;
896
897                 nr_progs++;
898                 obj->nr_programs = nr_progs;
899         }
900
901         return 0;
902 }
903
904 static const struct btf_member *
905 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
906 {
907         struct btf_member *m;
908         int i;
909
910         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
911                 if (btf_member_bit_offset(t, i) == bit_offset)
912                         return m;
913         }
914
915         return NULL;
916 }
917
918 static const struct btf_member *
919 find_member_by_name(const struct btf *btf, const struct btf_type *t,
920                     const char *name)
921 {
922         struct btf_member *m;
923         int i;
924
925         for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
926                 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
927                         return m;
928         }
929
930         return NULL;
931 }
932
933 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
934 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
935                                    const char *name, __u32 kind);
936
937 static int
938 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
939                            const struct btf_type **type, __u32 *type_id,
940                            const struct btf_type **vtype, __u32 *vtype_id,
941                            const struct btf_member **data_member)
942 {
943         const struct btf_type *kern_type, *kern_vtype;
944         const struct btf_member *kern_data_member;
945         __s32 kern_vtype_id, kern_type_id;
946         __u32 i;
947
948         kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
949         if (kern_type_id < 0) {
950                 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
951                         tname);
952                 return kern_type_id;
953         }
954         kern_type = btf__type_by_id(btf, kern_type_id);
955
956         /* Find the corresponding "map_value" type that will be used
957          * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
958          * find "struct bpf_struct_ops_tcp_congestion_ops" from the
959          * btf_vmlinux.
960          */
961         kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
962                                                 tname, BTF_KIND_STRUCT);
963         if (kern_vtype_id < 0) {
964                 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
965                         STRUCT_OPS_VALUE_PREFIX, tname);
966                 return kern_vtype_id;
967         }
968         kern_vtype = btf__type_by_id(btf, kern_vtype_id);
969
970         /* Find "struct tcp_congestion_ops" from
971          * struct bpf_struct_ops_tcp_congestion_ops {
972          *      [ ... ]
973          *      struct tcp_congestion_ops data;
974          * }
975          */
976         kern_data_member = btf_members(kern_vtype);
977         for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
978                 if (kern_data_member->type == kern_type_id)
979                         break;
980         }
981         if (i == btf_vlen(kern_vtype)) {
982                 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
983                         tname, STRUCT_OPS_VALUE_PREFIX, tname);
984                 return -EINVAL;
985         }
986
987         *type = kern_type;
988         *type_id = kern_type_id;
989         *vtype = kern_vtype;
990         *vtype_id = kern_vtype_id;
991         *data_member = kern_data_member;
992
993         return 0;
994 }
995
996 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
997 {
998         return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
999 }
1000
1001 /* Init the map's fields that depend on kern_btf */
1002 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1003                                          const struct btf *btf,
1004                                          const struct btf *kern_btf)
1005 {
1006         const struct btf_member *member, *kern_member, *kern_data_member;
1007         const struct btf_type *type, *kern_type, *kern_vtype;
1008         __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1009         struct bpf_struct_ops *st_ops;
1010         void *data, *kern_data;
1011         const char *tname;
1012         int err;
1013
1014         st_ops = map->st_ops;
1015         type = st_ops->type;
1016         tname = st_ops->tname;
1017         err = find_struct_ops_kern_types(kern_btf, tname,
1018                                          &kern_type, &kern_type_id,
1019                                          &kern_vtype, &kern_vtype_id,
1020                                          &kern_data_member);
1021         if (err)
1022                 return err;
1023
1024         pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1025                  map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1026
1027         map->def.value_size = kern_vtype->size;
1028         map->btf_vmlinux_value_type_id = kern_vtype_id;
1029
1030         st_ops->kern_vdata = calloc(1, kern_vtype->size);
1031         if (!st_ops->kern_vdata)
1032                 return -ENOMEM;
1033
1034         data = st_ops->data;
1035         kern_data_off = kern_data_member->offset / 8;
1036         kern_data = st_ops->kern_vdata + kern_data_off;
1037
1038         member = btf_members(type);
1039         for (i = 0; i < btf_vlen(type); i++, member++) {
1040                 const struct btf_type *mtype, *kern_mtype;
1041                 __u32 mtype_id, kern_mtype_id;
1042                 void *mdata, *kern_mdata;
1043                 __s64 msize, kern_msize;
1044                 __u32 moff, kern_moff;
1045                 __u32 kern_member_idx;
1046                 const char *mname;
1047
1048                 mname = btf__name_by_offset(btf, member->name_off);
1049                 kern_member = find_member_by_name(kern_btf, kern_type, mname);
1050                 if (!kern_member) {
1051                         pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1052                                 map->name, mname);
1053                         return -ENOTSUP;
1054                 }
1055
1056                 kern_member_idx = kern_member - btf_members(kern_type);
1057                 if (btf_member_bitfield_size(type, i) ||
1058                     btf_member_bitfield_size(kern_type, kern_member_idx)) {
1059                         pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1060                                 map->name, mname);
1061                         return -ENOTSUP;
1062                 }
1063
1064                 moff = member->offset / 8;
1065                 kern_moff = kern_member->offset / 8;
1066
1067                 mdata = data + moff;
1068                 kern_mdata = kern_data + kern_moff;
1069
1070                 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1071                 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1072                                                     &kern_mtype_id);
1073                 if (BTF_INFO_KIND(mtype->info) !=
1074                     BTF_INFO_KIND(kern_mtype->info)) {
1075                         pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1076                                 map->name, mname, BTF_INFO_KIND(mtype->info),
1077                                 BTF_INFO_KIND(kern_mtype->info));
1078                         return -ENOTSUP;
1079                 }
1080
1081                 if (btf_is_ptr(mtype)) {
1082                         struct bpf_program *prog;
1083
1084                         prog = st_ops->progs[i];
1085                         if (!prog)
1086                                 continue;
1087
1088                         kern_mtype = skip_mods_and_typedefs(kern_btf,
1089                                                             kern_mtype->type,
1090                                                             &kern_mtype_id);
1091
1092                         /* mtype->type must be a func_proto which was
1093                          * guaranteed in bpf_object__collect_st_ops_relos(),
1094                          * so only check kern_mtype for func_proto here.
1095                          */
1096                         if (!btf_is_func_proto(kern_mtype)) {
1097                                 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1098                                         map->name, mname);
1099                                 return -ENOTSUP;
1100                         }
1101
1102                         prog->attach_btf_id = kern_type_id;
1103                         prog->expected_attach_type = kern_member_idx;
1104
1105                         st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1106
1107                         pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1108                                  map->name, mname, prog->name, moff,
1109                                  kern_moff);
1110
1111                         continue;
1112                 }
1113
1114                 msize = btf__resolve_size(btf, mtype_id);
1115                 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1116                 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1117                         pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1118                                 map->name, mname, (ssize_t)msize,
1119                                 (ssize_t)kern_msize);
1120                         return -ENOTSUP;
1121                 }
1122
1123                 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1124                          map->name, mname, (unsigned int)msize,
1125                          moff, kern_moff);
1126                 memcpy(kern_mdata, mdata, msize);
1127         }
1128
1129         return 0;
1130 }
1131
1132 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1133 {
1134         struct bpf_map *map;
1135         size_t i;
1136         int err;
1137
1138         for (i = 0; i < obj->nr_maps; i++) {
1139                 map = &obj->maps[i];
1140
1141                 if (!bpf_map__is_struct_ops(map))
1142                         continue;
1143
1144                 err = bpf_map__init_kern_struct_ops(map, obj->btf,
1145                                                     obj->btf_vmlinux);
1146                 if (err)
1147                         return err;
1148         }
1149
1150         return 0;
1151 }
1152
1153 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1154                                 int shndx, Elf_Data *data, __u32 map_flags)
1155 {
1156         const struct btf_type *type, *datasec;
1157         const struct btf_var_secinfo *vsi;
1158         struct bpf_struct_ops *st_ops;
1159         const char *tname, *var_name;
1160         __s32 type_id, datasec_id;
1161         const struct btf *btf;
1162         struct bpf_map *map;
1163         __u32 i;
1164
1165         if (shndx == -1)
1166                 return 0;
1167
1168         btf = obj->btf;
1169         datasec_id = btf__find_by_name_kind(btf, sec_name,
1170                                             BTF_KIND_DATASEC);
1171         if (datasec_id < 0) {
1172                 pr_warn("struct_ops init: DATASEC %s not found\n",
1173                         sec_name);
1174                 return -EINVAL;
1175         }
1176
1177         datasec = btf__type_by_id(btf, datasec_id);
1178         vsi = btf_var_secinfos(datasec);
1179         for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1180                 type = btf__type_by_id(obj->btf, vsi->type);
1181                 var_name = btf__name_by_offset(obj->btf, type->name_off);
1182
1183                 type_id = btf__resolve_type(obj->btf, vsi->type);
1184                 if (type_id < 0) {
1185                         pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1186                                 vsi->type, sec_name);
1187                         return -EINVAL;
1188                 }
1189
1190                 type = btf__type_by_id(obj->btf, type_id);
1191                 tname = btf__name_by_offset(obj->btf, type->name_off);
1192                 if (!tname[0]) {
1193                         pr_warn("struct_ops init: anonymous type is not supported\n");
1194                         return -ENOTSUP;
1195                 }
1196                 if (!btf_is_struct(type)) {
1197                         pr_warn("struct_ops init: %s is not a struct\n", tname);
1198                         return -EINVAL;
1199                 }
1200
1201                 map = bpf_object__add_map(obj);
1202                 if (IS_ERR(map))
1203                         return PTR_ERR(map);
1204
1205                 map->sec_idx = shndx;
1206                 map->sec_offset = vsi->offset;
1207                 map->name = strdup(var_name);
1208                 if (!map->name)
1209                         return -ENOMEM;
1210
1211                 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1212                 map->def.key_size = sizeof(int);
1213                 map->def.value_size = type->size;
1214                 map->def.max_entries = 1;
1215                 map->def.map_flags = map_flags;
1216
1217                 map->st_ops = calloc(1, sizeof(*map->st_ops));
1218                 if (!map->st_ops)
1219                         return -ENOMEM;
1220                 st_ops = map->st_ops;
1221                 st_ops->data = malloc(type->size);
1222                 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1223                 st_ops->kern_func_off = malloc(btf_vlen(type) *
1224                                                sizeof(*st_ops->kern_func_off));
1225                 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1226                         return -ENOMEM;
1227
1228                 if (vsi->offset + type->size > data->d_size) {
1229                         pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1230                                 var_name, sec_name);
1231                         return -EINVAL;
1232                 }
1233
1234                 memcpy(st_ops->data,
1235                        data->d_buf + vsi->offset,
1236                        type->size);
1237                 st_ops->tname = tname;
1238                 st_ops->type = type;
1239                 st_ops->type_id = type_id;
1240
1241                 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1242                          tname, type_id, var_name, vsi->offset);
1243         }
1244
1245         return 0;
1246 }
1247
1248 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1249 {
1250         int err;
1251
1252         err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1253                                    obj->efile.st_ops_data, 0);
1254         err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1255                                           obj->efile.st_ops_link_shndx,
1256                                           obj->efile.st_ops_link_data,
1257                                           BPF_F_LINK);
1258         return err;
1259 }
1260
1261 static struct bpf_object *bpf_object__new(const char *path,
1262                                           const void *obj_buf,
1263                                           size_t obj_buf_sz,
1264                                           const char *obj_name)
1265 {
1266         struct bpf_object *obj;
1267         char *end;
1268
1269         obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1270         if (!obj) {
1271                 pr_warn("alloc memory failed for %s\n", path);
1272                 return ERR_PTR(-ENOMEM);
1273         }
1274
1275         strcpy(obj->path, path);
1276         if (obj_name) {
1277                 libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1278         } else {
1279                 /* Using basename() GNU version which doesn't modify arg. */
1280                 libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1281                 end = strchr(obj->name, '.');
1282                 if (end)
1283                         *end = 0;
1284         }
1285
1286         obj->efile.fd = -1;
1287         /*
1288          * Caller of this function should also call
1289          * bpf_object__elf_finish() after data collection to return
1290          * obj_buf to user. If not, we should duplicate the buffer to
1291          * avoid user freeing them before elf finish.
1292          */
1293         obj->efile.obj_buf = obj_buf;
1294         obj->efile.obj_buf_sz = obj_buf_sz;
1295         obj->efile.btf_maps_shndx = -1;
1296         obj->efile.st_ops_shndx = -1;
1297         obj->efile.st_ops_link_shndx = -1;
1298         obj->kconfig_map_idx = -1;
1299
1300         obj->kern_version = get_kernel_version();
1301         obj->loaded = false;
1302
1303         return obj;
1304 }
1305
1306 static void bpf_object__elf_finish(struct bpf_object *obj)
1307 {
1308         if (!obj->efile.elf)
1309                 return;
1310
1311         elf_end(obj->efile.elf);
1312         obj->efile.elf = NULL;
1313         obj->efile.symbols = NULL;
1314         obj->efile.st_ops_data = NULL;
1315         obj->efile.st_ops_link_data = NULL;
1316
1317         zfree(&obj->efile.secs);
1318         obj->efile.sec_cnt = 0;
1319         zclose(obj->efile.fd);
1320         obj->efile.obj_buf = NULL;
1321         obj->efile.obj_buf_sz = 0;
1322 }
1323
1324 static int bpf_object__elf_init(struct bpf_object *obj)
1325 {
1326         Elf64_Ehdr *ehdr;
1327         int err = 0;
1328         Elf *elf;
1329
1330         if (obj->efile.elf) {
1331                 pr_warn("elf: init internal error\n");
1332                 return -LIBBPF_ERRNO__LIBELF;
1333         }
1334
1335         if (obj->efile.obj_buf_sz > 0) {
1336                 /* obj_buf should have been validated by bpf_object__open_mem(). */
1337                 elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1338         } else {
1339                 obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1340                 if (obj->efile.fd < 0) {
1341                         char errmsg[STRERR_BUFSIZE], *cp;
1342
1343                         err = -errno;
1344                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1345                         pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1346                         return err;
1347                 }
1348
1349                 elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1350         }
1351
1352         if (!elf) {
1353                 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1354                 err = -LIBBPF_ERRNO__LIBELF;
1355                 goto errout;
1356         }
1357
1358         obj->efile.elf = elf;
1359
1360         if (elf_kind(elf) != ELF_K_ELF) {
1361                 err = -LIBBPF_ERRNO__FORMAT;
1362                 pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1363                 goto errout;
1364         }
1365
1366         if (gelf_getclass(elf) != ELFCLASS64) {
1367                 err = -LIBBPF_ERRNO__FORMAT;
1368                 pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1369                 goto errout;
1370         }
1371
1372         obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1373         if (!obj->efile.ehdr) {
1374                 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1375                 err = -LIBBPF_ERRNO__FORMAT;
1376                 goto errout;
1377         }
1378
1379         if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1380                 pr_warn("elf: failed to get section names section index for %s: %s\n",
1381                         obj->path, elf_errmsg(-1));
1382                 err = -LIBBPF_ERRNO__FORMAT;
1383                 goto errout;
1384         }
1385
1386         /* ELF is corrupted/truncated, avoid calling elf_strptr. */
1387         if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1388                 pr_warn("elf: failed to get section names strings from %s: %s\n",
1389                         obj->path, elf_errmsg(-1));
1390                 err = -LIBBPF_ERRNO__FORMAT;
1391                 goto errout;
1392         }
1393
1394         /* Old LLVM set e_machine to EM_NONE */
1395         if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1396                 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1397                 err = -LIBBPF_ERRNO__FORMAT;
1398                 goto errout;
1399         }
1400
1401         return 0;
1402 errout:
1403         bpf_object__elf_finish(obj);
1404         return err;
1405 }
1406
1407 static int bpf_object__check_endianness(struct bpf_object *obj)
1408 {
1409 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1410         if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1411                 return 0;
1412 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1413         if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1414                 return 0;
1415 #else
1416 # error "Unrecognized __BYTE_ORDER__"
1417 #endif
1418         pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1419         return -LIBBPF_ERRNO__ENDIAN;
1420 }
1421
1422 static int
1423 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1424 {
1425         if (!data) {
1426                 pr_warn("invalid license section in %s\n", obj->path);
1427                 return -LIBBPF_ERRNO__FORMAT;
1428         }
1429         /* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1430          * go over allowed ELF data section buffer
1431          */
1432         libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1433         pr_debug("license of %s is %s\n", obj->path, obj->license);
1434         return 0;
1435 }
1436
1437 static int
1438 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1439 {
1440         __u32 kver;
1441
1442         if (!data || size != sizeof(kver)) {
1443                 pr_warn("invalid kver section in %s\n", obj->path);
1444                 return -LIBBPF_ERRNO__FORMAT;
1445         }
1446         memcpy(&kver, data, sizeof(kver));
1447         obj->kern_version = kver;
1448         pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1449         return 0;
1450 }
1451
1452 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1453 {
1454         if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1455             type == BPF_MAP_TYPE_HASH_OF_MAPS)
1456                 return true;
1457         return false;
1458 }
1459
1460 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1461 {
1462         Elf_Data *data;
1463         Elf_Scn *scn;
1464
1465         if (!name)
1466                 return -EINVAL;
1467
1468         scn = elf_sec_by_name(obj, name);
1469         data = elf_sec_data(obj, scn);
1470         if (data) {
1471                 *size = data->d_size;
1472                 return 0; /* found it */
1473         }
1474
1475         return -ENOENT;
1476 }
1477
1478 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1479 {
1480         Elf_Data *symbols = obj->efile.symbols;
1481         const char *sname;
1482         size_t si;
1483
1484         for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1485                 Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1486
1487                 if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1488                         continue;
1489
1490                 if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1491                     ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1492                         continue;
1493
1494                 sname = elf_sym_str(obj, sym->st_name);
1495                 if (!sname) {
1496                         pr_warn("failed to get sym name string for var %s\n", name);
1497                         return ERR_PTR(-EIO);
1498                 }
1499                 if (strcmp(name, sname) == 0)
1500                         return sym;
1501         }
1502
1503         return ERR_PTR(-ENOENT);
1504 }
1505
1506 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1507 {
1508         struct bpf_map *map;
1509         int err;
1510
1511         err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1512                                 sizeof(*obj->maps), obj->nr_maps + 1);
1513         if (err)
1514                 return ERR_PTR(err);
1515
1516         map = &obj->maps[obj->nr_maps++];
1517         map->obj = obj;
1518         map->fd = -1;
1519         map->inner_map_fd = -1;
1520         map->autocreate = true;
1521
1522         return map;
1523 }
1524
1525 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1526 {
1527         const long page_sz = sysconf(_SC_PAGE_SIZE);
1528         size_t map_sz;
1529
1530         map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1531         map_sz = roundup(map_sz, page_sz);
1532         return map_sz;
1533 }
1534
1535 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1536 {
1537         void *mmaped;
1538
1539         if (!map->mmaped)
1540                 return -EINVAL;
1541
1542         if (old_sz == new_sz)
1543                 return 0;
1544
1545         mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1546         if (mmaped == MAP_FAILED)
1547                 return -errno;
1548
1549         memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1550         munmap(map->mmaped, old_sz);
1551         map->mmaped = mmaped;
1552         return 0;
1553 }
1554
1555 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1556 {
1557         char map_name[BPF_OBJ_NAME_LEN], *p;
1558         int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1559
1560         /* This is one of the more confusing parts of libbpf for various
1561          * reasons, some of which are historical. The original idea for naming
1562          * internal names was to include as much of BPF object name prefix as
1563          * possible, so that it can be distinguished from similar internal
1564          * maps of a different BPF object.
1565          * As an example, let's say we have bpf_object named 'my_object_name'
1566          * and internal map corresponding to '.rodata' ELF section. The final
1567          * map name advertised to user and to the kernel will be
1568          * 'my_objec.rodata', taking first 8 characters of object name and
1569          * entire 7 characters of '.rodata'.
1570          * Somewhat confusingly, if internal map ELF section name is shorter
1571          * than 7 characters, e.g., '.bss', we still reserve 7 characters
1572          * for the suffix, even though we only have 4 actual characters, and
1573          * resulting map will be called 'my_objec.bss', not even using all 15
1574          * characters allowed by the kernel. Oh well, at least the truncated
1575          * object name is somewhat consistent in this case. But if the map
1576          * name is '.kconfig', we'll still have entirety of '.kconfig' added
1577          * (8 chars) and thus will be left with only first 7 characters of the
1578          * object name ('my_obje'). Happy guessing, user, that the final map
1579          * name will be "my_obje.kconfig".
1580          * Now, with libbpf starting to support arbitrarily named .rodata.*
1581          * and .data.* data sections, it's possible that ELF section name is
1582          * longer than allowed 15 chars, so we now need to be careful to take
1583          * only up to 15 first characters of ELF name, taking no BPF object
1584          * name characters at all. So '.rodata.abracadabra' will result in
1585          * '.rodata.abracad' kernel and user-visible name.
1586          * We need to keep this convoluted logic intact for .data, .bss and
1587          * .rodata maps, but for new custom .data.custom and .rodata.custom
1588          * maps we use their ELF names as is, not prepending bpf_object name
1589          * in front. We still need to truncate them to 15 characters for the
1590          * kernel. Full name can be recovered for such maps by using DATASEC
1591          * BTF type associated with such map's value type, though.
1592          */
1593         if (sfx_len >= BPF_OBJ_NAME_LEN)
1594                 sfx_len = BPF_OBJ_NAME_LEN - 1;
1595
1596         /* if there are two or more dots in map name, it's a custom dot map */
1597         if (strchr(real_name + 1, '.') != NULL)
1598                 pfx_len = 0;
1599         else
1600                 pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1601
1602         snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1603                  sfx_len, real_name);
1604
1605         /* sanitise map name to characters allowed by kernel */
1606         for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1607                 if (!isalnum(*p) && *p != '_' && *p != '.')
1608                         *p = '_';
1609
1610         return strdup(map_name);
1611 }
1612
1613 static int
1614 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1615
1616 /* Internal BPF map is mmap()'able only if at least one of corresponding
1617  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1618  * variable and it's not marked as __hidden (which turns it into, effectively,
1619  * a STATIC variable).
1620  */
1621 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1622 {
1623         const struct btf_type *t, *vt;
1624         struct btf_var_secinfo *vsi;
1625         int i, n;
1626
1627         if (!map->btf_value_type_id)
1628                 return false;
1629
1630         t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1631         if (!btf_is_datasec(t))
1632                 return false;
1633
1634         vsi = btf_var_secinfos(t);
1635         for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1636                 vt = btf__type_by_id(obj->btf, vsi->type);
1637                 if (!btf_is_var(vt))
1638                         continue;
1639
1640                 if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1641                         return true;
1642         }
1643
1644         return false;
1645 }
1646
1647 static int
1648 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1649                               const char *real_name, int sec_idx, void *data, size_t data_sz)
1650 {
1651         struct bpf_map_def *def;
1652         struct bpf_map *map;
1653         size_t mmap_sz;
1654         int err;
1655
1656         map = bpf_object__add_map(obj);
1657         if (IS_ERR(map))
1658                 return PTR_ERR(map);
1659
1660         map->libbpf_type = type;
1661         map->sec_idx = sec_idx;
1662         map->sec_offset = 0;
1663         map->real_name = strdup(real_name);
1664         map->name = internal_map_name(obj, real_name);
1665         if (!map->real_name || !map->name) {
1666                 zfree(&map->real_name);
1667                 zfree(&map->name);
1668                 return -ENOMEM;
1669         }
1670
1671         def = &map->def;
1672         def->type = BPF_MAP_TYPE_ARRAY;
1673         def->key_size = sizeof(int);
1674         def->value_size = data_sz;
1675         def->max_entries = 1;
1676         def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1677                          ? BPF_F_RDONLY_PROG : 0;
1678
1679         /* failures are fine because of maps like .rodata.str1.1 */
1680         (void) map_fill_btf_type_info(obj, map);
1681
1682         if (map_is_mmapable(obj, map))
1683                 def->map_flags |= BPF_F_MMAPABLE;
1684
1685         pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1686                  map->name, map->sec_idx, map->sec_offset, def->map_flags);
1687
1688         mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1689         map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1690                            MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1691         if (map->mmaped == MAP_FAILED) {
1692                 err = -errno;
1693                 map->mmaped = NULL;
1694                 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1695                         map->name, err);
1696                 zfree(&map->real_name);
1697                 zfree(&map->name);
1698                 return err;
1699         }
1700
1701         if (data)
1702                 memcpy(map->mmaped, data, data_sz);
1703
1704         pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1705         return 0;
1706 }
1707
1708 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1709 {
1710         struct elf_sec_desc *sec_desc;
1711         const char *sec_name;
1712         int err = 0, sec_idx;
1713
1714         /*
1715          * Populate obj->maps with libbpf internal maps.
1716          */
1717         for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1718                 sec_desc = &obj->efile.secs[sec_idx];
1719
1720                 /* Skip recognized sections with size 0. */
1721                 if (!sec_desc->data || sec_desc->data->d_size == 0)
1722                         continue;
1723
1724                 switch (sec_desc->sec_type) {
1725                 case SEC_DATA:
1726                         sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727                         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1728                                                             sec_name, sec_idx,
1729                                                             sec_desc->data->d_buf,
1730                                                             sec_desc->data->d_size);
1731                         break;
1732                 case SEC_RODATA:
1733                         obj->has_rodata = true;
1734                         sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1735                         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1736                                                             sec_name, sec_idx,
1737                                                             sec_desc->data->d_buf,
1738                                                             sec_desc->data->d_size);
1739                         break;
1740                 case SEC_BSS:
1741                         sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1742                         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1743                                                             sec_name, sec_idx,
1744                                                             NULL,
1745                                                             sec_desc->data->d_size);
1746                         break;
1747                 default:
1748                         /* skip */
1749                         break;
1750                 }
1751                 if (err)
1752                         return err;
1753         }
1754         return 0;
1755 }
1756
1757
1758 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1759                                                const void *name)
1760 {
1761         int i;
1762
1763         for (i = 0; i < obj->nr_extern; i++) {
1764                 if (strcmp(obj->externs[i].name, name) == 0)
1765                         return &obj->externs[i];
1766         }
1767         return NULL;
1768 }
1769
1770 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1771                               char value)
1772 {
1773         switch (ext->kcfg.type) {
1774         case KCFG_BOOL:
1775                 if (value == 'm') {
1776                         pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1777                                 ext->name, value);
1778                         return -EINVAL;
1779                 }
1780                 *(bool *)ext_val = value == 'y' ? true : false;
1781                 break;
1782         case KCFG_TRISTATE:
1783                 if (value == 'y')
1784                         *(enum libbpf_tristate *)ext_val = TRI_YES;
1785                 else if (value == 'm')
1786                         *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1787                 else /* value == 'n' */
1788                         *(enum libbpf_tristate *)ext_val = TRI_NO;
1789                 break;
1790         case KCFG_CHAR:
1791                 *(char *)ext_val = value;
1792                 break;
1793         case KCFG_UNKNOWN:
1794         case KCFG_INT:
1795         case KCFG_CHAR_ARR:
1796         default:
1797                 pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1798                         ext->name, value);
1799                 return -EINVAL;
1800         }
1801         ext->is_set = true;
1802         return 0;
1803 }
1804
1805 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1806                               const char *value)
1807 {
1808         size_t len;
1809
1810         if (ext->kcfg.type != KCFG_CHAR_ARR) {
1811                 pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1812                         ext->name, value);
1813                 return -EINVAL;
1814         }
1815
1816         len = strlen(value);
1817         if (value[len - 1] != '"') {
1818                 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1819                         ext->name, value);
1820                 return -EINVAL;
1821         }
1822
1823         /* strip quotes */
1824         len -= 2;
1825         if (len >= ext->kcfg.sz) {
1826                 pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1827                         ext->name, value, len, ext->kcfg.sz - 1);
1828                 len = ext->kcfg.sz - 1;
1829         }
1830         memcpy(ext_val, value + 1, len);
1831         ext_val[len] = '\0';
1832         ext->is_set = true;
1833         return 0;
1834 }
1835
1836 static int parse_u64(const char *value, __u64 *res)
1837 {
1838         char *value_end;
1839         int err;
1840
1841         errno = 0;
1842         *res = strtoull(value, &value_end, 0);
1843         if (errno) {
1844                 err = -errno;
1845                 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1846                 return err;
1847         }
1848         if (*value_end) {
1849                 pr_warn("failed to parse '%s' as integer completely\n", value);
1850                 return -EINVAL;
1851         }
1852         return 0;
1853 }
1854
1855 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1856 {
1857         int bit_sz = ext->kcfg.sz * 8;
1858
1859         if (ext->kcfg.sz == 8)
1860                 return true;
1861
1862         /* Validate that value stored in u64 fits in integer of `ext->sz`
1863          * bytes size without any loss of information. If the target integer
1864          * is signed, we rely on the following limits of integer type of
1865          * Y bits and subsequent transformation:
1866          *
1867          *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1868          *            0 <= X + 2^(Y-1) <= 2^Y - 1
1869          *            0 <= X + 2^(Y-1) <  2^Y
1870          *
1871          *  For unsigned target integer, check that all the (64 - Y) bits are
1872          *  zero.
1873          */
1874         if (ext->kcfg.is_signed)
1875                 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1876         else
1877                 return (v >> bit_sz) == 0;
1878 }
1879
1880 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1881                               __u64 value)
1882 {
1883         if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1884             ext->kcfg.type != KCFG_BOOL) {
1885                 pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1886                         ext->name, (unsigned long long)value);
1887                 return -EINVAL;
1888         }
1889         if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1890                 pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1891                         ext->name, (unsigned long long)value);
1892                 return -EINVAL;
1893
1894         }
1895         if (!is_kcfg_value_in_range(ext, value)) {
1896                 pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1897                         ext->name, (unsigned long long)value, ext->kcfg.sz);
1898                 return -ERANGE;
1899         }
1900         switch (ext->kcfg.sz) {
1901         case 1:
1902                 *(__u8 *)ext_val = value;
1903                 break;
1904         case 2:
1905                 *(__u16 *)ext_val = value;
1906                 break;
1907         case 4:
1908                 *(__u32 *)ext_val = value;
1909                 break;
1910         case 8:
1911                 *(__u64 *)ext_val = value;
1912                 break;
1913         default:
1914                 return -EINVAL;
1915         }
1916         ext->is_set = true;
1917         return 0;
1918 }
1919
1920 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1921                                             char *buf, void *data)
1922 {
1923         struct extern_desc *ext;
1924         char *sep, *value;
1925         int len, err = 0;
1926         void *ext_val;
1927         __u64 num;
1928
1929         if (!str_has_pfx(buf, "CONFIG_"))
1930                 return 0;
1931
1932         sep = strchr(buf, '=');
1933         if (!sep) {
1934                 pr_warn("failed to parse '%s': no separator\n", buf);
1935                 return -EINVAL;
1936         }
1937
1938         /* Trim ending '\n' */
1939         len = strlen(buf);
1940         if (buf[len - 1] == '\n')
1941                 buf[len - 1] = '\0';
1942         /* Split on '=' and ensure that a value is present. */
1943         *sep = '\0';
1944         if (!sep[1]) {
1945                 *sep = '=';
1946                 pr_warn("failed to parse '%s': no value\n", buf);
1947                 return -EINVAL;
1948         }
1949
1950         ext = find_extern_by_name(obj, buf);
1951         if (!ext || ext->is_set)
1952                 return 0;
1953
1954         ext_val = data + ext->kcfg.data_off;
1955         value = sep + 1;
1956
1957         switch (*value) {
1958         case 'y': case 'n': case 'm':
1959                 err = set_kcfg_value_tri(ext, ext_val, *value);
1960                 break;
1961         case '"':
1962                 err = set_kcfg_value_str(ext, ext_val, value);
1963                 break;
1964         default:
1965                 /* assume integer */
1966                 err = parse_u64(value, &num);
1967                 if (err) {
1968                         pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1969                         return err;
1970                 }
1971                 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1972                         pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1973                         return -EINVAL;
1974                 }
1975                 err = set_kcfg_value_num(ext, ext_val, num);
1976                 break;
1977         }
1978         if (err)
1979                 return err;
1980         pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1981         return 0;
1982 }
1983
1984 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1985 {
1986         char buf[PATH_MAX];
1987         struct utsname uts;
1988         int len, err = 0;
1989         gzFile file;
1990
1991         uname(&uts);
1992         len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1993         if (len < 0)
1994                 return -EINVAL;
1995         else if (len >= PATH_MAX)
1996                 return -ENAMETOOLONG;
1997
1998         /* gzopen also accepts uncompressed files. */
1999         file = gzopen(buf, "re");
2000         if (!file)
2001                 file = gzopen("/proc/config.gz", "re");
2002
2003         if (!file) {
2004                 pr_warn("failed to open system Kconfig\n");
2005                 return -ENOENT;
2006         }
2007
2008         while (gzgets(file, buf, sizeof(buf))) {
2009                 err = bpf_object__process_kconfig_line(obj, buf, data);
2010                 if (err) {
2011                         pr_warn("error parsing system Kconfig line '%s': %d\n",
2012                                 buf, err);
2013                         goto out;
2014                 }
2015         }
2016
2017 out:
2018         gzclose(file);
2019         return err;
2020 }
2021
2022 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2023                                         const char *config, void *data)
2024 {
2025         char buf[PATH_MAX];
2026         int err = 0;
2027         FILE *file;
2028
2029         file = fmemopen((void *)config, strlen(config), "r");
2030         if (!file) {
2031                 err = -errno;
2032                 pr_warn("failed to open in-memory Kconfig: %d\n", err);
2033                 return err;
2034         }
2035
2036         while (fgets(buf, sizeof(buf), file)) {
2037                 err = bpf_object__process_kconfig_line(obj, buf, data);
2038                 if (err) {
2039                         pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2040                                 buf, err);
2041                         break;
2042                 }
2043         }
2044
2045         fclose(file);
2046         return err;
2047 }
2048
2049 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2050 {
2051         struct extern_desc *last_ext = NULL, *ext;
2052         size_t map_sz;
2053         int i, err;
2054
2055         for (i = 0; i < obj->nr_extern; i++) {
2056                 ext = &obj->externs[i];
2057                 if (ext->type == EXT_KCFG)
2058                         last_ext = ext;
2059         }
2060
2061         if (!last_ext)
2062                 return 0;
2063
2064         map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2065         err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2066                                             ".kconfig", obj->efile.symbols_shndx,
2067                                             NULL, map_sz);
2068         if (err)
2069                 return err;
2070
2071         obj->kconfig_map_idx = obj->nr_maps - 1;
2072
2073         return 0;
2074 }
2075
2076 const struct btf_type *
2077 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2078 {
2079         const struct btf_type *t = btf__type_by_id(btf, id);
2080
2081         if (res_id)
2082                 *res_id = id;
2083
2084         while (btf_is_mod(t) || btf_is_typedef(t)) {
2085                 if (res_id)
2086                         *res_id = t->type;
2087                 t = btf__type_by_id(btf, t->type);
2088         }
2089
2090         return t;
2091 }
2092
2093 static const struct btf_type *
2094 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2095 {
2096         const struct btf_type *t;
2097
2098         t = skip_mods_and_typedefs(btf, id, NULL);
2099         if (!btf_is_ptr(t))
2100                 return NULL;
2101
2102         t = skip_mods_and_typedefs(btf, t->type, res_id);
2103
2104         return btf_is_func_proto(t) ? t : NULL;
2105 }
2106
2107 static const char *__btf_kind_str(__u16 kind)
2108 {
2109         switch (kind) {
2110         case BTF_KIND_UNKN: return "void";
2111         case BTF_KIND_INT: return "int";
2112         case BTF_KIND_PTR: return "ptr";
2113         case BTF_KIND_ARRAY: return "array";
2114         case BTF_KIND_STRUCT: return "struct";
2115         case BTF_KIND_UNION: return "union";
2116         case BTF_KIND_ENUM: return "enum";
2117         case BTF_KIND_FWD: return "fwd";
2118         case BTF_KIND_TYPEDEF: return "typedef";
2119         case BTF_KIND_VOLATILE: return "volatile";
2120         case BTF_KIND_CONST: return "const";
2121         case BTF_KIND_RESTRICT: return "restrict";
2122         case BTF_KIND_FUNC: return "func";
2123         case BTF_KIND_FUNC_PROTO: return "func_proto";
2124         case BTF_KIND_VAR: return "var";
2125         case BTF_KIND_DATASEC: return "datasec";
2126         case BTF_KIND_FLOAT: return "float";
2127         case BTF_KIND_DECL_TAG: return "decl_tag";
2128         case BTF_KIND_TYPE_TAG: return "type_tag";
2129         case BTF_KIND_ENUM64: return "enum64";
2130         default: return "unknown";
2131         }
2132 }
2133
2134 const char *btf_kind_str(const struct btf_type *t)
2135 {
2136         return __btf_kind_str(btf_kind(t));
2137 }
2138
2139 /*
2140  * Fetch integer attribute of BTF map definition. Such attributes are
2141  * represented using a pointer to an array, in which dimensionality of array
2142  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2143  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2144  * type definition, while using only sizeof(void *) space in ELF data section.
2145  */
2146 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2147                               const struct btf_member *m, __u32 *res)
2148 {
2149         const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2150         const char *name = btf__name_by_offset(btf, m->name_off);
2151         const struct btf_array *arr_info;
2152         const struct btf_type *arr_t;
2153
2154         if (!btf_is_ptr(t)) {
2155                 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2156                         map_name, name, btf_kind_str(t));
2157                 return false;
2158         }
2159
2160         arr_t = btf__type_by_id(btf, t->type);
2161         if (!arr_t) {
2162                 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2163                         map_name, name, t->type);
2164                 return false;
2165         }
2166         if (!btf_is_array(arr_t)) {
2167                 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2168                         map_name, name, btf_kind_str(arr_t));
2169                 return false;
2170         }
2171         arr_info = btf_array(arr_t);
2172         *res = arr_info->nelems;
2173         return true;
2174 }
2175
2176 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2177 {
2178         int len;
2179
2180         len = snprintf(buf, buf_sz, "%s/%s", path, name);
2181         if (len < 0)
2182                 return -EINVAL;
2183         if (len >= buf_sz)
2184                 return -ENAMETOOLONG;
2185
2186         return 0;
2187 }
2188
2189 static int build_map_pin_path(struct bpf_map *map, const char *path)
2190 {
2191         char buf[PATH_MAX];
2192         int err;
2193
2194         if (!path)
2195                 path = "/sys/fs/bpf";
2196
2197         err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2198         if (err)
2199                 return err;
2200
2201         return bpf_map__set_pin_path(map, buf);
2202 }
2203
2204 /* should match definition in bpf_helpers.h */
2205 enum libbpf_pin_type {
2206         LIBBPF_PIN_NONE,
2207         /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2208         LIBBPF_PIN_BY_NAME,
2209 };
2210
2211 int parse_btf_map_def(const char *map_name, struct btf *btf,
2212                       const struct btf_type *def_t, bool strict,
2213                       struct btf_map_def *map_def, struct btf_map_def *inner_def)
2214 {
2215         const struct btf_type *t;
2216         const struct btf_member *m;
2217         bool is_inner = inner_def == NULL;
2218         int vlen, i;
2219
2220         vlen = btf_vlen(def_t);
2221         m = btf_members(def_t);
2222         for (i = 0; i < vlen; i++, m++) {
2223                 const char *name = btf__name_by_offset(btf, m->name_off);
2224
2225                 if (!name) {
2226                         pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2227                         return -EINVAL;
2228                 }
2229                 if (strcmp(name, "type") == 0) {
2230                         if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2231                                 return -EINVAL;
2232                         map_def->parts |= MAP_DEF_MAP_TYPE;
2233                 } else if (strcmp(name, "max_entries") == 0) {
2234                         if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2235                                 return -EINVAL;
2236                         map_def->parts |= MAP_DEF_MAX_ENTRIES;
2237                 } else if (strcmp(name, "map_flags") == 0) {
2238                         if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2239                                 return -EINVAL;
2240                         map_def->parts |= MAP_DEF_MAP_FLAGS;
2241                 } else if (strcmp(name, "numa_node") == 0) {
2242                         if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2243                                 return -EINVAL;
2244                         map_def->parts |= MAP_DEF_NUMA_NODE;
2245                 } else if (strcmp(name, "key_size") == 0) {
2246                         __u32 sz;
2247
2248                         if (!get_map_field_int(map_name, btf, m, &sz))
2249                                 return -EINVAL;
2250                         if (map_def->key_size && map_def->key_size != sz) {
2251                                 pr_warn("map '%s': conflicting key size %u != %u.\n",
2252                                         map_name, map_def->key_size, sz);
2253                                 return -EINVAL;
2254                         }
2255                         map_def->key_size = sz;
2256                         map_def->parts |= MAP_DEF_KEY_SIZE;
2257                 } else if (strcmp(name, "key") == 0) {
2258                         __s64 sz;
2259
2260                         t = btf__type_by_id(btf, m->type);
2261                         if (!t) {
2262                                 pr_warn("map '%s': key type [%d] not found.\n",
2263                                         map_name, m->type);
2264                                 return -EINVAL;
2265                         }
2266                         if (!btf_is_ptr(t)) {
2267                                 pr_warn("map '%s': key spec is not PTR: %s.\n",
2268                                         map_name, btf_kind_str(t));
2269                                 return -EINVAL;
2270                         }
2271                         sz = btf__resolve_size(btf, t->type);
2272                         if (sz < 0) {
2273                                 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2274                                         map_name, t->type, (ssize_t)sz);
2275                                 return sz;
2276                         }
2277                         if (map_def->key_size && map_def->key_size != sz) {
2278                                 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2279                                         map_name, map_def->key_size, (ssize_t)sz);
2280                                 return -EINVAL;
2281                         }
2282                         map_def->key_size = sz;
2283                         map_def->key_type_id = t->type;
2284                         map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2285                 } else if (strcmp(name, "value_size") == 0) {
2286                         __u32 sz;
2287
2288                         if (!get_map_field_int(map_name, btf, m, &sz))
2289                                 return -EINVAL;
2290                         if (map_def->value_size && map_def->value_size != sz) {
2291                                 pr_warn("map '%s': conflicting value size %u != %u.\n",
2292                                         map_name, map_def->value_size, sz);
2293                                 return -EINVAL;
2294                         }
2295                         map_def->value_size = sz;
2296                         map_def->parts |= MAP_DEF_VALUE_SIZE;
2297                 } else if (strcmp(name, "value") == 0) {
2298                         __s64 sz;
2299
2300                         t = btf__type_by_id(btf, m->type);
2301                         if (!t) {
2302                                 pr_warn("map '%s': value type [%d] not found.\n",
2303                                         map_name, m->type);
2304                                 return -EINVAL;
2305                         }
2306                         if (!btf_is_ptr(t)) {
2307                                 pr_warn("map '%s': value spec is not PTR: %s.\n",
2308                                         map_name, btf_kind_str(t));
2309                                 return -EINVAL;
2310                         }
2311                         sz = btf__resolve_size(btf, t->type);
2312                         if (sz < 0) {
2313                                 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2314                                         map_name, t->type, (ssize_t)sz);
2315                                 return sz;
2316                         }
2317                         if (map_def->value_size && map_def->value_size != sz) {
2318                                 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2319                                         map_name, map_def->value_size, (ssize_t)sz);
2320                                 return -EINVAL;
2321                         }
2322                         map_def->value_size = sz;
2323                         map_def->value_type_id = t->type;
2324                         map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2325                 }
2326                 else if (strcmp(name, "values") == 0) {
2327                         bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2328                         bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2329                         const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2330                         char inner_map_name[128];
2331                         int err;
2332
2333                         if (is_inner) {
2334                                 pr_warn("map '%s': multi-level inner maps not supported.\n",
2335                                         map_name);
2336                                 return -ENOTSUP;
2337                         }
2338                         if (i != vlen - 1) {
2339                                 pr_warn("map '%s': '%s' member should be last.\n",
2340                                         map_name, name);
2341                                 return -EINVAL;
2342                         }
2343                         if (!is_map_in_map && !is_prog_array) {
2344                                 pr_warn("map '%s': should be map-in-map or prog-array.\n",
2345                                         map_name);
2346                                 return -ENOTSUP;
2347                         }
2348                         if (map_def->value_size && map_def->value_size != 4) {
2349                                 pr_warn("map '%s': conflicting value size %u != 4.\n",
2350                                         map_name, map_def->value_size);
2351                                 return -EINVAL;
2352                         }
2353                         map_def->value_size = 4;
2354                         t = btf__type_by_id(btf, m->type);
2355                         if (!t) {
2356                                 pr_warn("map '%s': %s type [%d] not found.\n",
2357                                         map_name, desc, m->type);
2358                                 return -EINVAL;
2359                         }
2360                         if (!btf_is_array(t) || btf_array(t)->nelems) {
2361                                 pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2362                                         map_name, desc);
2363                                 return -EINVAL;
2364                         }
2365                         t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2366                         if (!btf_is_ptr(t)) {
2367                                 pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2368                                         map_name, desc, btf_kind_str(t));
2369                                 return -EINVAL;
2370                         }
2371                         t = skip_mods_and_typedefs(btf, t->type, NULL);
2372                         if (is_prog_array) {
2373                                 if (!btf_is_func_proto(t)) {
2374                                         pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2375                                                 map_name, btf_kind_str(t));
2376                                         return -EINVAL;
2377                                 }
2378                                 continue;
2379                         }
2380                         if (!btf_is_struct(t)) {
2381                                 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2382                                         map_name, btf_kind_str(t));
2383                                 return -EINVAL;
2384                         }
2385
2386                         snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2387                         err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2388                         if (err)
2389                                 return err;
2390
2391                         map_def->parts |= MAP_DEF_INNER_MAP;
2392                 } else if (strcmp(name, "pinning") == 0) {
2393                         __u32 val;
2394
2395                         if (is_inner) {
2396                                 pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2397                                 return -EINVAL;
2398                         }
2399                         if (!get_map_field_int(map_name, btf, m, &val))
2400                                 return -EINVAL;
2401                         if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2402                                 pr_warn("map '%s': invalid pinning value %u.\n",
2403                                         map_name, val);
2404                                 return -EINVAL;
2405                         }
2406                         map_def->pinning = val;
2407                         map_def->parts |= MAP_DEF_PINNING;
2408                 } else if (strcmp(name, "map_extra") == 0) {
2409                         __u32 map_extra;
2410
2411                         if (!get_map_field_int(map_name, btf, m, &map_extra))
2412                                 return -EINVAL;
2413                         map_def->map_extra = map_extra;
2414                         map_def->parts |= MAP_DEF_MAP_EXTRA;
2415                 } else {
2416                         if (strict) {
2417                                 pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2418                                 return -ENOTSUP;
2419                         }
2420                         pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2421                 }
2422         }
2423
2424         if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2425                 pr_warn("map '%s': map type isn't specified.\n", map_name);
2426                 return -EINVAL;
2427         }
2428
2429         return 0;
2430 }
2431
2432 static size_t adjust_ringbuf_sz(size_t sz)
2433 {
2434         __u32 page_sz = sysconf(_SC_PAGE_SIZE);
2435         __u32 mul;
2436
2437         /* if user forgot to set any size, make sure they see error */
2438         if (sz == 0)
2439                 return 0;
2440         /* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2441          * a power-of-2 multiple of kernel's page size. If user diligently
2442          * satisified these conditions, pass the size through.
2443          */
2444         if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2445                 return sz;
2446
2447         /* Otherwise find closest (page_sz * power_of_2) product bigger than
2448          * user-set size to satisfy both user size request and kernel
2449          * requirements and substitute correct max_entries for map creation.
2450          */
2451         for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2452                 if (mul * page_sz > sz)
2453                         return mul * page_sz;
2454         }
2455
2456         /* if it's impossible to satisfy the conditions (i.e., user size is
2457          * very close to UINT_MAX but is not a power-of-2 multiple of
2458          * page_size) then just return original size and let kernel reject it
2459          */
2460         return sz;
2461 }
2462
2463 static bool map_is_ringbuf(const struct bpf_map *map)
2464 {
2465         return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2466                map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2467 }
2468
2469 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2470 {
2471         map->def.type = def->map_type;
2472         map->def.key_size = def->key_size;
2473         map->def.value_size = def->value_size;
2474         map->def.max_entries = def->max_entries;
2475         map->def.map_flags = def->map_flags;
2476         map->map_extra = def->map_extra;
2477
2478         map->numa_node = def->numa_node;
2479         map->btf_key_type_id = def->key_type_id;
2480         map->btf_value_type_id = def->value_type_id;
2481
2482         /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2483         if (map_is_ringbuf(map))
2484                 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2485
2486         if (def->parts & MAP_DEF_MAP_TYPE)
2487                 pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2488
2489         if (def->parts & MAP_DEF_KEY_TYPE)
2490                 pr_debug("map '%s': found key [%u], sz = %u.\n",
2491                          map->name, def->key_type_id, def->key_size);
2492         else if (def->parts & MAP_DEF_KEY_SIZE)
2493                 pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2494
2495         if (def->parts & MAP_DEF_VALUE_TYPE)
2496                 pr_debug("map '%s': found value [%u], sz = %u.\n",
2497                          map->name, def->value_type_id, def->value_size);
2498         else if (def->parts & MAP_DEF_VALUE_SIZE)
2499                 pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2500
2501         if (def->parts & MAP_DEF_MAX_ENTRIES)
2502                 pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2503         if (def->parts & MAP_DEF_MAP_FLAGS)
2504                 pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2505         if (def->parts & MAP_DEF_MAP_EXTRA)
2506                 pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2507                          (unsigned long long)def->map_extra);
2508         if (def->parts & MAP_DEF_PINNING)
2509                 pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2510         if (def->parts & MAP_DEF_NUMA_NODE)
2511                 pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2512
2513         if (def->parts & MAP_DEF_INNER_MAP)
2514                 pr_debug("map '%s': found inner map definition.\n", map->name);
2515 }
2516
2517 static const char *btf_var_linkage_str(__u32 linkage)
2518 {
2519         switch (linkage) {
2520         case BTF_VAR_STATIC: return "static";
2521         case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2522         case BTF_VAR_GLOBAL_EXTERN: return "extern";
2523         default: return "unknown";
2524         }
2525 }
2526
2527 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2528                                          const struct btf_type *sec,
2529                                          int var_idx, int sec_idx,
2530                                          const Elf_Data *data, bool strict,
2531                                          const char *pin_root_path)
2532 {
2533         struct btf_map_def map_def = {}, inner_def = {};
2534         const struct btf_type *var, *def;
2535         const struct btf_var_secinfo *vi;
2536         const struct btf_var *var_extra;
2537         const char *map_name;
2538         struct bpf_map *map;
2539         int err;
2540
2541         vi = btf_var_secinfos(sec) + var_idx;
2542         var = btf__type_by_id(obj->btf, vi->type);
2543         var_extra = btf_var(var);
2544         map_name = btf__name_by_offset(obj->btf, var->name_off);
2545
2546         if (map_name == NULL || map_name[0] == '\0') {
2547                 pr_warn("map #%d: empty name.\n", var_idx);
2548                 return -EINVAL;
2549         }
2550         if ((__u64)vi->offset + vi->size > data->d_size) {
2551                 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2552                 return -EINVAL;
2553         }
2554         if (!btf_is_var(var)) {
2555                 pr_warn("map '%s': unexpected var kind %s.\n",
2556                         map_name, btf_kind_str(var));
2557                 return -EINVAL;
2558         }
2559         if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2560                 pr_warn("map '%s': unsupported map linkage %s.\n",
2561                         map_name, btf_var_linkage_str(var_extra->linkage));
2562                 return -EOPNOTSUPP;
2563         }
2564
2565         def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2566         if (!btf_is_struct(def)) {
2567                 pr_warn("map '%s': unexpected def kind %s.\n",
2568                         map_name, btf_kind_str(var));
2569                 return -EINVAL;
2570         }
2571         if (def->size > vi->size) {
2572                 pr_warn("map '%s': invalid def size.\n", map_name);
2573                 return -EINVAL;
2574         }
2575
2576         map = bpf_object__add_map(obj);
2577         if (IS_ERR(map))
2578                 return PTR_ERR(map);
2579         map->name = strdup(map_name);
2580         if (!map->name) {
2581                 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2582                 return -ENOMEM;
2583         }
2584         map->libbpf_type = LIBBPF_MAP_UNSPEC;
2585         map->def.type = BPF_MAP_TYPE_UNSPEC;
2586         map->sec_idx = sec_idx;
2587         map->sec_offset = vi->offset;
2588         map->btf_var_idx = var_idx;
2589         pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2590                  map_name, map->sec_idx, map->sec_offset);
2591
2592         err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2593         if (err)
2594                 return err;
2595
2596         fill_map_from_def(map, &map_def);
2597
2598         if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2599                 err = build_map_pin_path(map, pin_root_path);
2600                 if (err) {
2601                         pr_warn("map '%s': couldn't build pin path.\n", map->name);
2602                         return err;
2603                 }
2604         }
2605
2606         if (map_def.parts & MAP_DEF_INNER_MAP) {
2607                 map->inner_map = calloc(1, sizeof(*map->inner_map));
2608                 if (!map->inner_map)
2609                         return -ENOMEM;
2610                 map->inner_map->fd = -1;
2611                 map->inner_map->sec_idx = sec_idx;
2612                 map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2613                 if (!map->inner_map->name)
2614                         return -ENOMEM;
2615                 sprintf(map->inner_map->name, "%s.inner", map_name);
2616
2617                 fill_map_from_def(map->inner_map, &inner_def);
2618         }
2619
2620         err = map_fill_btf_type_info(obj, map);
2621         if (err)
2622                 return err;
2623
2624         return 0;
2625 }
2626
2627 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2628                                           const char *pin_root_path)
2629 {
2630         const struct btf_type *sec = NULL;
2631         int nr_types, i, vlen, err;
2632         const struct btf_type *t;
2633         const char *name;
2634         Elf_Data *data;
2635         Elf_Scn *scn;
2636
2637         if (obj->efile.btf_maps_shndx < 0)
2638                 return 0;
2639
2640         scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2641         data = elf_sec_data(obj, scn);
2642         if (!scn || !data) {
2643                 pr_warn("elf: failed to get %s map definitions for %s\n",
2644                         MAPS_ELF_SEC, obj->path);
2645                 return -EINVAL;
2646         }
2647
2648         nr_types = btf__type_cnt(obj->btf);
2649         for (i = 1; i < nr_types; i++) {
2650                 t = btf__type_by_id(obj->btf, i);
2651                 if (!btf_is_datasec(t))
2652                         continue;
2653                 name = btf__name_by_offset(obj->btf, t->name_off);
2654                 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2655                         sec = t;
2656                         obj->efile.btf_maps_sec_btf_id = i;
2657                         break;
2658                 }
2659         }
2660
2661         if (!sec) {
2662                 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2663                 return -ENOENT;
2664         }
2665
2666         vlen = btf_vlen(sec);
2667         for (i = 0; i < vlen; i++) {
2668                 err = bpf_object__init_user_btf_map(obj, sec, i,
2669                                                     obj->efile.btf_maps_shndx,
2670                                                     data, strict,
2671                                                     pin_root_path);
2672                 if (err)
2673                         return err;
2674         }
2675
2676         return 0;
2677 }
2678
2679 static int bpf_object__init_maps(struct bpf_object *obj,
2680                                  const struct bpf_object_open_opts *opts)
2681 {
2682         const char *pin_root_path;
2683         bool strict;
2684         int err = 0;
2685
2686         strict = !OPTS_GET(opts, relaxed_maps, false);
2687         pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2688
2689         err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2690         err = err ?: bpf_object__init_global_data_maps(obj);
2691         err = err ?: bpf_object__init_kconfig_map(obj);
2692         err = err ?: bpf_object_init_struct_ops(obj);
2693
2694         return err;
2695 }
2696
2697 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2698 {
2699         Elf64_Shdr *sh;
2700
2701         sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2702         if (!sh)
2703                 return false;
2704
2705         return sh->sh_flags & SHF_EXECINSTR;
2706 }
2707
2708 static bool btf_needs_sanitization(struct bpf_object *obj)
2709 {
2710         bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2711         bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2712         bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2713         bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2714         bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2715         bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2716         bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2717
2718         return !has_func || !has_datasec || !has_func_global || !has_float ||
2719                !has_decl_tag || !has_type_tag || !has_enum64;
2720 }
2721
2722 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2723 {
2724         bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2725         bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2726         bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2727         bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2728         bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2729         bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2730         bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2731         int enum64_placeholder_id = 0;
2732         struct btf_type *t;
2733         int i, j, vlen;
2734
2735         for (i = 1; i < btf__type_cnt(btf); i++) {
2736                 t = (struct btf_type *)btf__type_by_id(btf, i);
2737
2738                 if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2739                         /* replace VAR/DECL_TAG with INT */
2740                         t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2741                         /*
2742                          * using size = 1 is the safest choice, 4 will be too
2743                          * big and cause kernel BTF validation failure if
2744                          * original variable took less than 4 bytes
2745                          */
2746                         t->size = 1;
2747                         *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2748                 } else if (!has_datasec && btf_is_datasec(t)) {
2749                         /* replace DATASEC with STRUCT */
2750                         const struct btf_var_secinfo *v = btf_var_secinfos(t);
2751                         struct btf_member *m = btf_members(t);
2752                         struct btf_type *vt;
2753                         char *name;
2754
2755                         name = (char *)btf__name_by_offset(btf, t->name_off);
2756                         while (*name) {
2757                                 if (*name == '.')
2758                                         *name = '_';
2759                                 name++;
2760                         }
2761
2762                         vlen = btf_vlen(t);
2763                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2764                         for (j = 0; j < vlen; j++, v++, m++) {
2765                                 /* order of field assignments is important */
2766                                 m->offset = v->offset * 8;
2767                                 m->type = v->type;
2768                                 /* preserve variable name as member name */
2769                                 vt = (void *)btf__type_by_id(btf, v->type);
2770                                 m->name_off = vt->name_off;
2771                         }
2772                 } else if (!has_func && btf_is_func_proto(t)) {
2773                         /* replace FUNC_PROTO with ENUM */
2774                         vlen = btf_vlen(t);
2775                         t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2776                         t->size = sizeof(__u32); /* kernel enforced */
2777                 } else if (!has_func && btf_is_func(t)) {
2778                         /* replace FUNC with TYPEDEF */
2779                         t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2780                 } else if (!has_func_global && btf_is_func(t)) {
2781                         /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2782                         t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2783                 } else if (!has_float && btf_is_float(t)) {
2784                         /* replace FLOAT with an equally-sized empty STRUCT;
2785                          * since C compilers do not accept e.g. "float" as a
2786                          * valid struct name, make it anonymous
2787                          */
2788                         t->name_off = 0;
2789                         t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2790                 } else if (!has_type_tag && btf_is_type_tag(t)) {
2791                         /* replace TYPE_TAG with a CONST */
2792                         t->name_off = 0;
2793                         t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2794                 } else if (!has_enum64 && btf_is_enum(t)) {
2795                         /* clear the kflag */
2796                         t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2797                 } else if (!has_enum64 && btf_is_enum64(t)) {
2798                         /* replace ENUM64 with a union */
2799                         struct btf_member *m;
2800
2801                         if (enum64_placeholder_id == 0) {
2802                                 enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2803                                 if (enum64_placeholder_id < 0)
2804                                         return enum64_placeholder_id;
2805
2806                                 t = (struct btf_type *)btf__type_by_id(btf, i);
2807                         }
2808
2809                         m = btf_members(t);
2810                         vlen = btf_vlen(t);
2811                         t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2812                         for (j = 0; j < vlen; j++, m++) {
2813                                 m->type = enum64_placeholder_id;
2814                                 m->offset = 0;
2815                         }
2816                 }
2817         }
2818
2819         return 0;
2820 }
2821
2822 static bool libbpf_needs_btf(const struct bpf_object *obj)
2823 {
2824         return obj->efile.btf_maps_shndx >= 0 ||
2825                obj->efile.st_ops_shndx >= 0 ||
2826                obj->efile.st_ops_link_shndx >= 0 ||
2827                obj->nr_extern > 0;
2828 }
2829
2830 static bool kernel_needs_btf(const struct bpf_object *obj)
2831 {
2832         return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2833 }
2834
2835 static int bpf_object__init_btf(struct bpf_object *obj,
2836                                 Elf_Data *btf_data,
2837                                 Elf_Data *btf_ext_data)
2838 {
2839         int err = -ENOENT;
2840
2841         if (btf_data) {
2842                 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2843                 err = libbpf_get_error(obj->btf);
2844                 if (err) {
2845                         obj->btf = NULL;
2846                         pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2847                         goto out;
2848                 }
2849                 /* enforce 8-byte pointers for BPF-targeted BTFs */
2850                 btf__set_pointer_size(obj->btf, 8);
2851         }
2852         if (btf_ext_data) {
2853                 struct btf_ext_info *ext_segs[3];
2854                 int seg_num, sec_num;
2855
2856                 if (!obj->btf) {
2857                         pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2858                                  BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2859                         goto out;
2860                 }
2861                 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2862                 err = libbpf_get_error(obj->btf_ext);
2863                 if (err) {
2864                         pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2865                                 BTF_EXT_ELF_SEC, err);
2866                         obj->btf_ext = NULL;
2867                         goto out;
2868                 }
2869
2870                 /* setup .BTF.ext to ELF section mapping */
2871                 ext_segs[0] = &obj->btf_ext->func_info;
2872                 ext_segs[1] = &obj->btf_ext->line_info;
2873                 ext_segs[2] = &obj->btf_ext->core_relo_info;
2874                 for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2875                         struct btf_ext_info *seg = ext_segs[seg_num];
2876                         const struct btf_ext_info_sec *sec;
2877                         const char *sec_name;
2878                         Elf_Scn *scn;
2879
2880                         if (seg->sec_cnt == 0)
2881                                 continue;
2882
2883                         seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2884                         if (!seg->sec_idxs) {
2885                                 err = -ENOMEM;
2886                                 goto out;
2887                         }
2888
2889                         sec_num = 0;
2890                         for_each_btf_ext_sec(seg, sec) {
2891                                 /* preventively increment index to avoid doing
2892                                  * this before every continue below
2893                                  */
2894                                 sec_num++;
2895
2896                                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2897                                 if (str_is_empty(sec_name))
2898                                         continue;
2899                                 scn = elf_sec_by_name(obj, sec_name);
2900                                 if (!scn)
2901                                         continue;
2902
2903                                 seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2904                         }
2905                 }
2906         }
2907 out:
2908         if (err && libbpf_needs_btf(obj)) {
2909                 pr_warn("BTF is required, but is missing or corrupted.\n");
2910                 return err;
2911         }
2912         return 0;
2913 }
2914
2915 static int compare_vsi_off(const void *_a, const void *_b)
2916 {
2917         const struct btf_var_secinfo *a = _a;
2918         const struct btf_var_secinfo *b = _b;
2919
2920         return a->offset - b->offset;
2921 }
2922
2923 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2924                              struct btf_type *t)
2925 {
2926         __u32 size = 0, i, vars = btf_vlen(t);
2927         const char *sec_name = btf__name_by_offset(btf, t->name_off);
2928         struct btf_var_secinfo *vsi;
2929         bool fixup_offsets = false;
2930         int err;
2931
2932         if (!sec_name) {
2933                 pr_debug("No name found in string section for DATASEC kind.\n");
2934                 return -ENOENT;
2935         }
2936
2937         /* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2938          * variable offsets set at the previous step. Further, not every
2939          * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2940          * all fixups altogether for such sections and go straight to sorting
2941          * VARs within their DATASEC.
2942          */
2943         if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2944                 goto sort_vars;
2945
2946         /* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2947          * fix this up. But BPF static linker already fixes this up and fills
2948          * all the sizes and offsets during static linking. So this step has
2949          * to be optional. But the STV_HIDDEN handling is non-optional for any
2950          * non-extern DATASEC, so the variable fixup loop below handles both
2951          * functions at the same time, paying the cost of BTF VAR <-> ELF
2952          * symbol matching just once.
2953          */
2954         if (t->size == 0) {
2955                 err = find_elf_sec_sz(obj, sec_name, &size);
2956                 if (err || !size) {
2957                         pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2958                                  sec_name, size, err);
2959                         return -ENOENT;
2960                 }
2961
2962                 t->size = size;
2963                 fixup_offsets = true;
2964         }
2965
2966         for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2967                 const struct btf_type *t_var;
2968                 struct btf_var *var;
2969                 const char *var_name;
2970                 Elf64_Sym *sym;
2971
2972                 t_var = btf__type_by_id(btf, vsi->type);
2973                 if (!t_var || !btf_is_var(t_var)) {
2974                         pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2975                         return -EINVAL;
2976                 }
2977
2978                 var = btf_var(t_var);
2979                 if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2980                         continue;
2981
2982                 var_name = btf__name_by_offset(btf, t_var->name_off);
2983                 if (!var_name) {
2984                         pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2985                                  sec_name, i);
2986                         return -ENOENT;
2987                 }
2988
2989                 sym = find_elf_var_sym(obj, var_name);
2990                 if (IS_ERR(sym)) {
2991                         pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2992                                  sec_name, var_name);
2993                         return -ENOENT;
2994                 }
2995
2996                 if (fixup_offsets)
2997                         vsi->offset = sym->st_value;
2998
2999                 /* if variable is a global/weak symbol, but has restricted
3000                  * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3001                  * as static. This follows similar logic for functions (BPF
3002                  * subprogs) and influences libbpf's further decisions about
3003                  * whether to make global data BPF array maps as
3004                  * BPF_F_MMAPABLE.
3005                  */
3006                 if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3007                     || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3008                         var->linkage = BTF_VAR_STATIC;
3009         }
3010
3011 sort_vars:
3012         qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3013         return 0;
3014 }
3015
3016 static int bpf_object_fixup_btf(struct bpf_object *obj)
3017 {
3018         int i, n, err = 0;
3019
3020         if (!obj->btf)
3021                 return 0;
3022
3023         n = btf__type_cnt(obj->btf);
3024         for (i = 1; i < n; i++) {
3025                 struct btf_type *t = btf_type_by_id(obj->btf, i);
3026
3027                 /* Loader needs to fix up some of the things compiler
3028                  * couldn't get its hands on while emitting BTF. This
3029                  * is section size and global variable offset. We use
3030                  * the info from the ELF itself for this purpose.
3031                  */
3032                 if (btf_is_datasec(t)) {
3033                         err = btf_fixup_datasec(obj, obj->btf, t);
3034                         if (err)
3035                                 return err;
3036                 }
3037         }
3038
3039         return 0;
3040 }
3041
3042 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3043 {
3044         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3045             prog->type == BPF_PROG_TYPE_LSM)
3046                 return true;
3047
3048         /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3049          * also need vmlinux BTF
3050          */
3051         if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3052                 return true;
3053
3054         return false;
3055 }
3056
3057 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3058 {
3059         return bpf_map__is_struct_ops(map);
3060 }
3061
3062 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3063 {
3064         struct bpf_program *prog;
3065         struct bpf_map *map;
3066         int i;
3067
3068         /* CO-RE relocations need kernel BTF, only when btf_custom_path
3069          * is not specified
3070          */
3071         if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3072                 return true;
3073
3074         /* Support for typed ksyms needs kernel BTF */
3075         for (i = 0; i < obj->nr_extern; i++) {
3076                 const struct extern_desc *ext;
3077
3078                 ext = &obj->externs[i];
3079                 if (ext->type == EXT_KSYM && ext->ksym.type_id)
3080                         return true;
3081         }
3082
3083         bpf_object__for_each_program(prog, obj) {
3084                 if (!prog->autoload)
3085                         continue;
3086                 if (prog_needs_vmlinux_btf(prog))
3087                         return true;
3088         }
3089
3090         bpf_object__for_each_map(map, obj) {
3091                 if (map_needs_vmlinux_btf(map))
3092                         return true;
3093         }
3094
3095         return false;
3096 }
3097
3098 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3099 {
3100         int err;
3101
3102         /* btf_vmlinux could be loaded earlier */
3103         if (obj->btf_vmlinux || obj->gen_loader)
3104                 return 0;
3105
3106         if (!force && !obj_needs_vmlinux_btf(obj))
3107                 return 0;
3108
3109         obj->btf_vmlinux = btf__load_vmlinux_btf();
3110         err = libbpf_get_error(obj->btf_vmlinux);
3111         if (err) {
3112                 pr_warn("Error loading vmlinux BTF: %d\n", err);
3113                 obj->btf_vmlinux = NULL;
3114                 return err;
3115         }
3116         return 0;
3117 }
3118
3119 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3120 {
3121         struct btf *kern_btf = obj->btf;
3122         bool btf_mandatory, sanitize;
3123         int i, err = 0;
3124
3125         if (!obj->btf)
3126                 return 0;
3127
3128         if (!kernel_supports(obj, FEAT_BTF)) {
3129                 if (kernel_needs_btf(obj)) {
3130                         err = -EOPNOTSUPP;
3131                         goto report;
3132                 }
3133                 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3134                 return 0;
3135         }
3136
3137         /* Even though some subprogs are global/weak, user might prefer more
3138          * permissive BPF verification process that BPF verifier performs for
3139          * static functions, taking into account more context from the caller
3140          * functions. In such case, they need to mark such subprogs with
3141          * __attribute__((visibility("hidden"))) and libbpf will adjust
3142          * corresponding FUNC BTF type to be marked as static and trigger more
3143          * involved BPF verification process.
3144          */
3145         for (i = 0; i < obj->nr_programs; i++) {
3146                 struct bpf_program *prog = &obj->programs[i];
3147                 struct btf_type *t;
3148                 const char *name;
3149                 int j, n;
3150
3151                 if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3152                         continue;
3153
3154                 n = btf__type_cnt(obj->btf);
3155                 for (j = 1; j < n; j++) {
3156                         t = btf_type_by_id(obj->btf, j);
3157                         if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3158                                 continue;
3159
3160                         name = btf__str_by_offset(obj->btf, t->name_off);
3161                         if (strcmp(name, prog->name) != 0)
3162                                 continue;
3163
3164                         t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3165                         break;
3166                 }
3167         }
3168
3169         if (!kernel_supports(obj, FEAT_BTF_DECL_TAG))
3170                 goto skip_exception_cb;
3171         for (i = 0; i < obj->nr_programs; i++) {
3172                 struct bpf_program *prog = &obj->programs[i];
3173                 int j, k, n;
3174
3175                 if (prog_is_subprog(obj, prog))
3176                         continue;
3177                 n = btf__type_cnt(obj->btf);
3178                 for (j = 1; j < n; j++) {
3179                         const char *str = "exception_callback:", *name;
3180                         size_t len = strlen(str);
3181                         struct btf_type *t;
3182
3183                         t = btf_type_by_id(obj->btf, j);
3184                         if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
3185                                 continue;
3186
3187                         name = btf__str_by_offset(obj->btf, t->name_off);
3188                         if (strncmp(name, str, len))
3189                                 continue;
3190
3191                         t = btf_type_by_id(obj->btf, t->type);
3192                         if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3193                                 pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
3194                                         prog->name);
3195                                 return -EINVAL;
3196                         }
3197                         if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)))
3198                                 continue;
3199                         /* Multiple callbacks are specified for the same prog,
3200                          * the verifier will eventually return an error for this
3201                          * case, hence simply skip appending a subprog.
3202                          */
3203                         if (prog->exception_cb_idx >= 0) {
3204                                 prog->exception_cb_idx = -1;
3205                                 break;
3206                         }
3207
3208                         name += len;
3209                         if (str_is_empty(name)) {
3210                                 pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
3211                                         prog->name);
3212                                 return -EINVAL;
3213                         }
3214
3215                         for (k = 0; k < obj->nr_programs; k++) {
3216                                 struct bpf_program *subprog = &obj->programs[k];
3217
3218                                 if (!prog_is_subprog(obj, subprog))
3219                                         continue;
3220                                 if (strcmp(name, subprog->name))
3221                                         continue;
3222                                 /* Enforce non-hidden, as from verifier point of
3223                                  * view it expects global functions, whereas the
3224                                  * mark_btf_static fixes up linkage as static.
3225                                  */
3226                                 if (!subprog->sym_global || subprog->mark_btf_static) {
3227                                         pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
3228                                                 prog->name, subprog->name);
3229                                         return -EINVAL;
3230                                 }
3231                                 /* Let's see if we already saw a static exception callback with the same name */
3232                                 if (prog->exception_cb_idx >= 0) {
3233                                         pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
3234                                                 prog->name, subprog->name);
3235                                         return -EINVAL;
3236                                 }
3237                                 prog->exception_cb_idx = k;
3238                                 break;
3239                         }
3240
3241                         if (prog->exception_cb_idx >= 0)
3242                                 continue;
3243                         pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
3244                         return -ENOENT;
3245                 }
3246         }
3247 skip_exception_cb:
3248
3249         sanitize = btf_needs_sanitization(obj);
3250         if (sanitize) {
3251                 const void *raw_data;
3252                 __u32 sz;
3253
3254                 /* clone BTF to sanitize a copy and leave the original intact */
3255                 raw_data = btf__raw_data(obj->btf, &sz);
3256                 kern_btf = btf__new(raw_data, sz);
3257                 err = libbpf_get_error(kern_btf);
3258                 if (err)
3259                         return err;
3260
3261                 /* enforce 8-byte pointers for BPF-targeted BTFs */
3262                 btf__set_pointer_size(obj->btf, 8);
3263                 err = bpf_object__sanitize_btf(obj, kern_btf);
3264                 if (err)
3265                         return err;
3266         }
3267
3268         if (obj->gen_loader) {
3269                 __u32 raw_size = 0;
3270                 const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3271
3272                 if (!raw_data)
3273                         return -ENOMEM;
3274                 bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3275                 /* Pretend to have valid FD to pass various fd >= 0 checks.
3276                  * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3277                  */
3278                 btf__set_fd(kern_btf, 0);
3279         } else {
3280                 /* currently BPF_BTF_LOAD only supports log_level 1 */
3281                 err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3282                                            obj->log_level ? 1 : 0);
3283         }
3284         if (sanitize) {
3285                 if (!err) {
3286                         /* move fd to libbpf's BTF */
3287                         btf__set_fd(obj->btf, btf__fd(kern_btf));
3288                         btf__set_fd(kern_btf, -1);
3289                 }
3290                 btf__free(kern_btf);
3291         }
3292 report:
3293         if (err) {
3294                 btf_mandatory = kernel_needs_btf(obj);
3295                 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3296                         btf_mandatory ? "BTF is mandatory, can't proceed."
3297                                       : "BTF is optional, ignoring.");
3298                 if (!btf_mandatory)
3299                         err = 0;
3300         }
3301         return err;
3302 }
3303
3304 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3305 {
3306         const char *name;
3307
3308         name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3309         if (!name) {
3310                 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3311                         off, obj->path, elf_errmsg(-1));
3312                 return NULL;
3313         }
3314
3315         return name;
3316 }
3317
3318 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3319 {
3320         const char *name;
3321
3322         name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3323         if (!name) {
3324                 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3325                         off, obj->path, elf_errmsg(-1));
3326                 return NULL;
3327         }
3328
3329         return name;
3330 }
3331
3332 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3333 {
3334         Elf_Scn *scn;
3335
3336         scn = elf_getscn(obj->efile.elf, idx);
3337         if (!scn) {
3338                 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3339                         idx, obj->path, elf_errmsg(-1));
3340                 return NULL;
3341         }
3342         return scn;
3343 }
3344
3345 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3346 {
3347         Elf_Scn *scn = NULL;
3348         Elf *elf = obj->efile.elf;
3349         const char *sec_name;
3350
3351         while ((scn = elf_nextscn(elf, scn)) != NULL) {
3352                 sec_name = elf_sec_name(obj, scn);
3353                 if (!sec_name)
3354                         return NULL;
3355
3356                 if (strcmp(sec_name, name) != 0)
3357                         continue;
3358
3359                 return scn;
3360         }
3361         return NULL;
3362 }
3363
3364 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3365 {
3366         Elf64_Shdr *shdr;
3367
3368         if (!scn)
3369                 return NULL;
3370
3371         shdr = elf64_getshdr(scn);
3372         if (!shdr) {
3373                 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3374                         elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3375                 return NULL;
3376         }
3377
3378         return shdr;
3379 }
3380
3381 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3382 {
3383         const char *name;
3384         Elf64_Shdr *sh;
3385
3386         if (!scn)
3387                 return NULL;
3388
3389         sh = elf_sec_hdr(obj, scn);
3390         if (!sh)
3391                 return NULL;
3392
3393         name = elf_sec_str(obj, sh->sh_name);
3394         if (!name) {
3395                 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3396                         elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3397                 return NULL;
3398         }
3399
3400         return name;
3401 }
3402
3403 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3404 {
3405         Elf_Data *data;
3406
3407         if (!scn)
3408                 return NULL;
3409
3410         data = elf_getdata(scn, 0);
3411         if (!data) {
3412                 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3413                         elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3414                         obj->path, elf_errmsg(-1));
3415                 return NULL;
3416         }
3417
3418         return data;
3419 }
3420
3421 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3422 {
3423         if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3424                 return NULL;
3425
3426         return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3427 }
3428
3429 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3430 {
3431         if (idx >= data->d_size / sizeof(Elf64_Rel))
3432                 return NULL;
3433
3434         return (Elf64_Rel *)data->d_buf + idx;
3435 }
3436
3437 static bool is_sec_name_dwarf(const char *name)
3438 {
3439         /* approximation, but the actual list is too long */
3440         return str_has_pfx(name, ".debug_");
3441 }
3442
3443 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3444 {
3445         /* no special handling of .strtab */
3446         if (hdr->sh_type == SHT_STRTAB)
3447                 return true;
3448
3449         /* ignore .llvm_addrsig section as well */
3450         if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3451                 return true;
3452
3453         /* no subprograms will lead to an empty .text section, ignore it */
3454         if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3455             strcmp(name, ".text") == 0)
3456                 return true;
3457
3458         /* DWARF sections */
3459         if (is_sec_name_dwarf(name))
3460                 return true;
3461
3462         if (str_has_pfx(name, ".rel")) {
3463                 name += sizeof(".rel") - 1;
3464                 /* DWARF section relocations */
3465                 if (is_sec_name_dwarf(name))
3466                         return true;
3467
3468                 /* .BTF and .BTF.ext don't need relocations */
3469                 if (strcmp(name, BTF_ELF_SEC) == 0 ||
3470                     strcmp(name, BTF_EXT_ELF_SEC) == 0)
3471                         return true;
3472         }
3473
3474         return false;
3475 }
3476
3477 static int cmp_progs(const void *_a, const void *_b)
3478 {
3479         const struct bpf_program *a = _a;
3480         const struct bpf_program *b = _b;
3481
3482         if (a->sec_idx != b->sec_idx)
3483                 return a->sec_idx < b->sec_idx ? -1 : 1;
3484
3485         /* sec_insn_off can't be the same within the section */
3486         return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3487 }
3488
3489 static int bpf_object__elf_collect(struct bpf_object *obj)
3490 {
3491         struct elf_sec_desc *sec_desc;
3492         Elf *elf = obj->efile.elf;
3493         Elf_Data *btf_ext_data = NULL;
3494         Elf_Data *btf_data = NULL;
3495         int idx = 0, err = 0;
3496         const char *name;
3497         Elf_Data *data;
3498         Elf_Scn *scn;
3499         Elf64_Shdr *sh;
3500
3501         /* ELF section indices are 0-based, but sec #0 is special "invalid"
3502          * section. Since section count retrieved by elf_getshdrnum() does
3503          * include sec #0, it is already the necessary size of an array to keep
3504          * all the sections.
3505          */
3506         if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3507                 pr_warn("elf: failed to get the number of sections for %s: %s\n",
3508                         obj->path, elf_errmsg(-1));
3509                 return -LIBBPF_ERRNO__FORMAT;
3510         }
3511         obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3512         if (!obj->efile.secs)
3513                 return -ENOMEM;
3514
3515         /* a bunch of ELF parsing functionality depends on processing symbols,
3516          * so do the first pass and find the symbol table
3517          */
3518         scn = NULL;
3519         while ((scn = elf_nextscn(elf, scn)) != NULL) {
3520                 sh = elf_sec_hdr(obj, scn);
3521                 if (!sh)
3522                         return -LIBBPF_ERRNO__FORMAT;
3523
3524                 if (sh->sh_type == SHT_SYMTAB) {
3525                         if (obj->efile.symbols) {
3526                                 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3527                                 return -LIBBPF_ERRNO__FORMAT;
3528                         }
3529
3530                         data = elf_sec_data(obj, scn);
3531                         if (!data)
3532                                 return -LIBBPF_ERRNO__FORMAT;
3533
3534                         idx = elf_ndxscn(scn);
3535
3536                         obj->efile.symbols = data;
3537                         obj->efile.symbols_shndx = idx;
3538                         obj->efile.strtabidx = sh->sh_link;
3539                 }
3540         }
3541
3542         if (!obj->efile.symbols) {
3543                 pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3544                         obj->path);
3545                 return -ENOENT;
3546         }
3547
3548         scn = NULL;
3549         while ((scn = elf_nextscn(elf, scn)) != NULL) {
3550                 idx = elf_ndxscn(scn);
3551                 sec_desc = &obj->efile.secs[idx];
3552
3553                 sh = elf_sec_hdr(obj, scn);
3554                 if (!sh)
3555                         return -LIBBPF_ERRNO__FORMAT;
3556
3557                 name = elf_sec_str(obj, sh->sh_name);
3558                 if (!name)
3559                         return -LIBBPF_ERRNO__FORMAT;
3560
3561                 if (ignore_elf_section(sh, name))
3562                         continue;
3563
3564                 data = elf_sec_data(obj, scn);
3565                 if (!data)
3566                         return -LIBBPF_ERRNO__FORMAT;
3567
3568                 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3569                          idx, name, (unsigned long)data->d_size,
3570                          (int)sh->sh_link, (unsigned long)sh->sh_flags,
3571                          (int)sh->sh_type);
3572
3573                 if (strcmp(name, "license") == 0) {
3574                         err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3575                         if (err)
3576                                 return err;
3577                 } else if (strcmp(name, "version") == 0) {
3578                         err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3579                         if (err)
3580                                 return err;
3581                 } else if (strcmp(name, "maps") == 0) {
3582                         pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3583                         return -ENOTSUP;
3584                 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3585                         obj->efile.btf_maps_shndx = idx;
3586                 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
3587                         if (sh->sh_type != SHT_PROGBITS)
3588                                 return -LIBBPF_ERRNO__FORMAT;
3589                         btf_data = data;
3590                 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3591                         if (sh->sh_type != SHT_PROGBITS)
3592                                 return -LIBBPF_ERRNO__FORMAT;
3593                         btf_ext_data = data;
3594                 } else if (sh->sh_type == SHT_SYMTAB) {
3595                         /* already processed during the first pass above */
3596                 } else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3597                         if (sh->sh_flags & SHF_EXECINSTR) {
3598                                 if (strcmp(name, ".text") == 0)
3599                                         obj->efile.text_shndx = idx;
3600                                 err = bpf_object__add_programs(obj, data, name, idx);
3601                                 if (err)
3602                                         return err;
3603                         } else if (strcmp(name, DATA_SEC) == 0 ||
3604                                    str_has_pfx(name, DATA_SEC ".")) {
3605                                 sec_desc->sec_type = SEC_DATA;
3606                                 sec_desc->shdr = sh;
3607                                 sec_desc->data = data;
3608                         } else if (strcmp(name, RODATA_SEC) == 0 ||
3609                                    str_has_pfx(name, RODATA_SEC ".")) {
3610                                 sec_desc->sec_type = SEC_RODATA;
3611                                 sec_desc->shdr = sh;
3612                                 sec_desc->data = data;
3613                         } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3614                                 obj->efile.st_ops_data = data;
3615                                 obj->efile.st_ops_shndx = idx;
3616                         } else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3617                                 obj->efile.st_ops_link_data = data;
3618                                 obj->efile.st_ops_link_shndx = idx;
3619                         } else {
3620                                 pr_info("elf: skipping unrecognized data section(%d) %s\n",
3621                                         idx, name);
3622                         }
3623                 } else if (sh->sh_type == SHT_REL) {
3624                         int targ_sec_idx = sh->sh_info; /* points to other section */
3625
3626                         if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3627                             targ_sec_idx >= obj->efile.sec_cnt)
3628                                 return -LIBBPF_ERRNO__FORMAT;
3629
3630                         /* Only do relo for section with exec instructions */
3631                         if (!section_have_execinstr(obj, targ_sec_idx) &&
3632                             strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3633                             strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3634                             strcmp(name, ".rel" MAPS_ELF_SEC)) {
3635                                 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3636                                         idx, name, targ_sec_idx,
3637                                         elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3638                                 continue;
3639                         }
3640
3641                         sec_desc->sec_type = SEC_RELO;
3642                         sec_desc->shdr = sh;
3643                         sec_desc->data = data;
3644                 } else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3645                                                          str_has_pfx(name, BSS_SEC "."))) {
3646                         sec_desc->sec_type = SEC_BSS;
3647                         sec_desc->shdr = sh;
3648                         sec_desc->data = data;
3649                 } else {
3650                         pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3651                                 (size_t)sh->sh_size);
3652                 }
3653         }
3654
3655         if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3656                 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3657                 return -LIBBPF_ERRNO__FORMAT;
3658         }
3659
3660         /* sort BPF programs by section name and in-section instruction offset
3661          * for faster search
3662          */
3663         if (obj->nr_programs)
3664                 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3665
3666         return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3667 }
3668
3669 static bool sym_is_extern(const Elf64_Sym *sym)
3670 {
3671         int bind = ELF64_ST_BIND(sym->st_info);
3672         /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3673         return sym->st_shndx == SHN_UNDEF &&
3674                (bind == STB_GLOBAL || bind == STB_WEAK) &&
3675                ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3676 }
3677
3678 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3679 {
3680         int bind = ELF64_ST_BIND(sym->st_info);
3681         int type = ELF64_ST_TYPE(sym->st_info);
3682
3683         /* in .text section */
3684         if (sym->st_shndx != text_shndx)
3685                 return false;
3686
3687         /* local function */
3688         if (bind == STB_LOCAL && type == STT_SECTION)
3689                 return true;
3690
3691         /* global function */
3692         return bind == STB_GLOBAL && type == STT_FUNC;
3693 }
3694
3695 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3696 {
3697         const struct btf_type *t;
3698         const char *tname;
3699         int i, n;
3700
3701         if (!btf)
3702                 return -ESRCH;
3703
3704         n = btf__type_cnt(btf);
3705         for (i = 1; i < n; i++) {
3706                 t = btf__type_by_id(btf, i);
3707
3708                 if (!btf_is_var(t) && !btf_is_func(t))
3709                         continue;
3710
3711                 tname = btf__name_by_offset(btf, t->name_off);
3712                 if (strcmp(tname, ext_name))
3713                         continue;
3714
3715                 if (btf_is_var(t) &&
3716                     btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3717                         return -EINVAL;
3718
3719                 if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3720                         return -EINVAL;
3721
3722                 return i;
3723         }
3724
3725         return -ENOENT;
3726 }
3727
3728 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3729         const struct btf_var_secinfo *vs;
3730         const struct btf_type *t;
3731         int i, j, n;
3732
3733         if (!btf)
3734                 return -ESRCH;
3735
3736         n = btf__type_cnt(btf);
3737         for (i = 1; i < n; i++) {
3738                 t = btf__type_by_id(btf, i);
3739
3740                 if (!btf_is_datasec(t))
3741                         continue;
3742
3743                 vs = btf_var_secinfos(t);
3744                 for (j = 0; j < btf_vlen(t); j++, vs++) {
3745                         if (vs->type == ext_btf_id)
3746                                 return i;
3747                 }
3748         }
3749
3750         return -ENOENT;
3751 }
3752
3753 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3754                                      bool *is_signed)
3755 {
3756         const struct btf_type *t;
3757         const char *name;
3758
3759         t = skip_mods_and_typedefs(btf, id, NULL);
3760         name = btf__name_by_offset(btf, t->name_off);
3761
3762         if (is_signed)
3763                 *is_signed = false;
3764         switch (btf_kind(t)) {
3765         case BTF_KIND_INT: {
3766                 int enc = btf_int_encoding(t);
3767
3768                 if (enc & BTF_INT_BOOL)
3769                         return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3770                 if (is_signed)
3771                         *is_signed = enc & BTF_INT_SIGNED;
3772                 if (t->size == 1)
3773                         return KCFG_CHAR;
3774                 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3775                         return KCFG_UNKNOWN;
3776                 return KCFG_INT;
3777         }
3778         case BTF_KIND_ENUM:
3779                 if (t->size != 4)
3780                         return KCFG_UNKNOWN;
3781                 if (strcmp(name, "libbpf_tristate"))
3782                         return KCFG_UNKNOWN;
3783                 return KCFG_TRISTATE;
3784         case BTF_KIND_ENUM64:
3785                 if (strcmp(name, "libbpf_tristate"))
3786                         return KCFG_UNKNOWN;
3787                 return KCFG_TRISTATE;
3788         case BTF_KIND_ARRAY:
3789                 if (btf_array(t)->nelems == 0)
3790                         return KCFG_UNKNOWN;
3791                 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3792                         return KCFG_UNKNOWN;
3793                 return KCFG_CHAR_ARR;
3794         default:
3795                 return KCFG_UNKNOWN;
3796         }
3797 }
3798
3799 static int cmp_externs(const void *_a, const void *_b)
3800 {
3801         const struct extern_desc *a = _a;
3802         const struct extern_desc *b = _b;
3803
3804         if (a->type != b->type)
3805                 return a->type < b->type ? -1 : 1;
3806
3807         if (a->type == EXT_KCFG) {
3808                 /* descending order by alignment requirements */
3809                 if (a->kcfg.align != b->kcfg.align)
3810                         return a->kcfg.align > b->kcfg.align ? -1 : 1;
3811                 /* ascending order by size, within same alignment class */
3812                 if (a->kcfg.sz != b->kcfg.sz)
3813                         return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3814         }
3815
3816         /* resolve ties by name */
3817         return strcmp(a->name, b->name);
3818 }
3819
3820 static int find_int_btf_id(const struct btf *btf)
3821 {
3822         const struct btf_type *t;
3823         int i, n;
3824
3825         n = btf__type_cnt(btf);
3826         for (i = 1; i < n; i++) {
3827                 t = btf__type_by_id(btf, i);
3828
3829                 if (btf_is_int(t) && btf_int_bits(t) == 32)
3830                         return i;
3831         }
3832
3833         return 0;
3834 }
3835
3836 static int add_dummy_ksym_var(struct btf *btf)
3837 {
3838         int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3839         const struct btf_var_secinfo *vs;
3840         const struct btf_type *sec;
3841
3842         if (!btf)
3843                 return 0;
3844
3845         sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3846                                             BTF_KIND_DATASEC);
3847         if (sec_btf_id < 0)
3848                 return 0;
3849
3850         sec = btf__type_by_id(btf, sec_btf_id);
3851         vs = btf_var_secinfos(sec);
3852         for (i = 0; i < btf_vlen(sec); i++, vs++) {
3853                 const struct btf_type *vt;
3854
3855                 vt = btf__type_by_id(btf, vs->type);
3856                 if (btf_is_func(vt))
3857                         break;
3858         }
3859
3860         /* No func in ksyms sec.  No need to add dummy var. */
3861         if (i == btf_vlen(sec))
3862                 return 0;
3863
3864         int_btf_id = find_int_btf_id(btf);
3865         dummy_var_btf_id = btf__add_var(btf,
3866                                         "dummy_ksym",
3867                                         BTF_VAR_GLOBAL_ALLOCATED,
3868                                         int_btf_id);
3869         if (dummy_var_btf_id < 0)
3870                 pr_warn("cannot create a dummy_ksym var\n");
3871
3872         return dummy_var_btf_id;
3873 }
3874
3875 static int bpf_object__collect_externs(struct bpf_object *obj)
3876 {
3877         struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3878         const struct btf_type *t;
3879         struct extern_desc *ext;
3880         int i, n, off, dummy_var_btf_id;
3881         const char *ext_name, *sec_name;
3882         size_t ext_essent_len;
3883         Elf_Scn *scn;
3884         Elf64_Shdr *sh;
3885
3886         if (!obj->efile.symbols)
3887                 return 0;
3888
3889         scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3890         sh = elf_sec_hdr(obj, scn);
3891         if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3892                 return -LIBBPF_ERRNO__FORMAT;
3893
3894         dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3895         if (dummy_var_btf_id < 0)
3896                 return dummy_var_btf_id;
3897
3898         n = sh->sh_size / sh->sh_entsize;
3899         pr_debug("looking for externs among %d symbols...\n", n);
3900
3901         for (i = 0; i < n; i++) {
3902                 Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3903
3904                 if (!sym)
3905                         return -LIBBPF_ERRNO__FORMAT;
3906                 if (!sym_is_extern(sym))
3907                         continue;
3908                 ext_name = elf_sym_str(obj, sym->st_name);
3909                 if (!ext_name || !ext_name[0])
3910                         continue;
3911
3912                 ext = obj->externs;
3913                 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3914                 if (!ext)
3915                         return -ENOMEM;
3916                 obj->externs = ext;
3917                 ext = &ext[obj->nr_extern];
3918                 memset(ext, 0, sizeof(*ext));
3919                 obj->nr_extern++;
3920
3921                 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3922                 if (ext->btf_id <= 0) {
3923                         pr_warn("failed to find BTF for extern '%s': %d\n",
3924                                 ext_name, ext->btf_id);
3925                         return ext->btf_id;
3926                 }
3927                 t = btf__type_by_id(obj->btf, ext->btf_id);
3928                 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3929                 ext->sym_idx = i;
3930                 ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3931
3932                 ext_essent_len = bpf_core_essential_name_len(ext->name);
3933                 ext->essent_name = NULL;
3934                 if (ext_essent_len != strlen(ext->name)) {
3935                         ext->essent_name = strndup(ext->name, ext_essent_len);
3936                         if (!ext->essent_name)
3937                                 return -ENOMEM;
3938                 }
3939
3940                 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3941                 if (ext->sec_btf_id <= 0) {
3942                         pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3943                                 ext_name, ext->btf_id, ext->sec_btf_id);
3944                         return ext->sec_btf_id;
3945                 }
3946                 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3947                 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3948
3949                 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3950                         if (btf_is_func(t)) {
3951                                 pr_warn("extern function %s is unsupported under %s section\n",
3952                                         ext->name, KCONFIG_SEC);
3953                                 return -ENOTSUP;
3954                         }
3955                         kcfg_sec = sec;
3956                         ext->type = EXT_KCFG;
3957                         ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3958                         if (ext->kcfg.sz <= 0) {
3959                                 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3960                                         ext_name, ext->kcfg.sz);
3961                                 return ext->kcfg.sz;
3962                         }
3963                         ext->kcfg.align = btf__align_of(obj->btf, t->type);
3964                         if (ext->kcfg.align <= 0) {
3965                                 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3966                                         ext_name, ext->kcfg.align);
3967                                 return -EINVAL;
3968                         }
3969                         ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3970                                                         &ext->kcfg.is_signed);
3971                         if (ext->kcfg.type == KCFG_UNKNOWN) {
3972                                 pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3973                                 return -ENOTSUP;
3974                         }
3975                 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3976                         ksym_sec = sec;
3977                         ext->type = EXT_KSYM;
3978                         skip_mods_and_typedefs(obj->btf, t->type,
3979                                                &ext->ksym.type_id);
3980                 } else {
3981                         pr_warn("unrecognized extern section '%s'\n", sec_name);
3982                         return -ENOTSUP;
3983                 }
3984         }
3985         pr_debug("collected %d externs total\n", obj->nr_extern);
3986
3987         if (!obj->nr_extern)
3988                 return 0;
3989
3990         /* sort externs by type, for kcfg ones also by (align, size, name) */
3991         qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3992
3993         /* for .ksyms section, we need to turn all externs into allocated
3994          * variables in BTF to pass kernel verification; we do this by
3995          * pretending that each extern is a 8-byte variable
3996          */
3997         if (ksym_sec) {
3998                 /* find existing 4-byte integer type in BTF to use for fake
3999                  * extern variables in DATASEC
4000                  */
4001                 int int_btf_id = find_int_btf_id(obj->btf);
4002                 /* For extern function, a dummy_var added earlier
4003                  * will be used to replace the vs->type and
4004                  * its name string will be used to refill
4005                  * the missing param's name.
4006                  */
4007                 const struct btf_type *dummy_var;
4008
4009                 dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4010                 for (i = 0; i < obj->nr_extern; i++) {
4011                         ext = &obj->externs[i];
4012                         if (ext->type != EXT_KSYM)
4013                                 continue;
4014                         pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4015                                  i, ext->sym_idx, ext->name);
4016                 }
4017
4018                 sec = ksym_sec;
4019                 n = btf_vlen(sec);
4020                 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4021                         struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4022                         struct btf_type *vt;
4023
4024                         vt = (void *)btf__type_by_id(obj->btf, vs->type);
4025                         ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4026                         ext = find_extern_by_name(obj, ext_name);
4027                         if (!ext) {
4028                                 pr_warn("failed to find extern definition for BTF %s '%s'\n",
4029                                         btf_kind_str(vt), ext_name);
4030                                 return -ESRCH;
4031                         }
4032                         if (btf_is_func(vt)) {
4033                                 const struct btf_type *func_proto;
4034                                 struct btf_param *param;
4035                                 int j;
4036
4037                                 func_proto = btf__type_by_id(obj->btf,
4038                                                              vt->type);
4039                                 param = btf_params(func_proto);
4040                                 /* Reuse the dummy_var string if the
4041                                  * func proto does not have param name.
4042                                  */
4043                                 for (j = 0; j < btf_vlen(func_proto); j++)
4044                                         if (param[j].type && !param[j].name_off)
4045                                                 param[j].name_off =
4046                                                         dummy_var->name_off;
4047                                 vs->type = dummy_var_btf_id;
4048                                 vt->info &= ~0xffff;
4049                                 vt->info |= BTF_FUNC_GLOBAL;
4050                         } else {
4051                                 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4052                                 vt->type = int_btf_id;
4053                         }
4054                         vs->offset = off;
4055                         vs->size = sizeof(int);
4056                 }
4057                 sec->size = off;
4058         }
4059
4060         if (kcfg_sec) {
4061                 sec = kcfg_sec;
4062                 /* for kcfg externs calculate their offsets within a .kconfig map */
4063                 off = 0;
4064                 for (i = 0; i < obj->nr_extern; i++) {
4065                         ext = &obj->externs[i];
4066                         if (ext->type != EXT_KCFG)
4067                                 continue;
4068
4069                         ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4070                         off = ext->kcfg.data_off + ext->kcfg.sz;
4071                         pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4072                                  i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4073                 }
4074                 sec->size = off;
4075                 n = btf_vlen(sec);
4076                 for (i = 0; i < n; i++) {
4077                         struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4078
4079                         t = btf__type_by_id(obj->btf, vs->type);
4080                         ext_name = btf__name_by_offset(obj->btf, t->name_off);
4081                         ext = find_extern_by_name(obj, ext_name);
4082                         if (!ext) {
4083                                 pr_warn("failed to find extern definition for BTF var '%s'\n",
4084                                         ext_name);
4085                                 return -ESRCH;
4086                         }
4087                         btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4088                         vs->offset = ext->kcfg.data_off;
4089                 }
4090         }
4091         return 0;
4092 }
4093
4094 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4095 {
4096         return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4097 }
4098
4099 struct bpf_program *
4100 bpf_object__find_program_by_name(const struct bpf_object *obj,
4101                                  const char *name)
4102 {
4103         struct bpf_program *prog;
4104
4105         bpf_object__for_each_program(prog, obj) {
4106                 if (prog_is_subprog(obj, prog))
4107                         continue;
4108                 if (!strcmp(prog->name, name))
4109                         return prog;
4110         }
4111         return errno = ENOENT, NULL;
4112 }
4113
4114 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4115                                       int shndx)
4116 {
4117         switch (obj->efile.secs[shndx].sec_type) {
4118         case SEC_BSS:
4119         case SEC_DATA:
4120         case SEC_RODATA:
4121                 return true;
4122         default:
4123                 return false;
4124         }
4125 }
4126
4127 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4128                                       int shndx)
4129 {
4130         return shndx == obj->efile.btf_maps_shndx;
4131 }
4132
4133 static enum libbpf_map_type
4134 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4135 {
4136         if (shndx == obj->efile.symbols_shndx)
4137                 return LIBBPF_MAP_KCONFIG;
4138
4139         switch (obj->efile.secs[shndx].sec_type) {
4140         case SEC_BSS:
4141                 return LIBBPF_MAP_BSS;
4142         case SEC_DATA:
4143                 return LIBBPF_MAP_DATA;
4144         case SEC_RODATA:
4145                 return LIBBPF_MAP_RODATA;
4146         default:
4147                 return LIBBPF_MAP_UNSPEC;
4148         }
4149 }
4150
4151 static int bpf_program__record_reloc(struct bpf_program *prog,
4152                                      struct reloc_desc *reloc_desc,
4153                                      __u32 insn_idx, const char *sym_name,
4154                                      const Elf64_Sym *sym, const Elf64_Rel *rel)
4155 {
4156         struct bpf_insn *insn = &prog->insns[insn_idx];
4157         size_t map_idx, nr_maps = prog->obj->nr_maps;
4158         struct bpf_object *obj = prog->obj;
4159         __u32 shdr_idx = sym->st_shndx;
4160         enum libbpf_map_type type;
4161         const char *sym_sec_name;
4162         struct bpf_map *map;
4163
4164         if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4165                 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4166                         prog->name, sym_name, insn_idx, insn->code);
4167                 return -LIBBPF_ERRNO__RELOC;
4168         }
4169
4170         if (sym_is_extern(sym)) {
4171                 int sym_idx = ELF64_R_SYM(rel->r_info);
4172                 int i, n = obj->nr_extern;
4173                 struct extern_desc *ext;
4174
4175                 for (i = 0; i < n; i++) {
4176                         ext = &obj->externs[i];
4177                         if (ext->sym_idx == sym_idx)
4178                                 break;
4179                 }
4180                 if (i >= n) {
4181                         pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4182                                 prog->name, sym_name, sym_idx);
4183                         return -LIBBPF_ERRNO__RELOC;
4184                 }
4185                 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4186                          prog->name, i, ext->name, ext->sym_idx, insn_idx);
4187                 if (insn->code == (BPF_JMP | BPF_CALL))
4188                         reloc_desc->type = RELO_EXTERN_CALL;
4189                 else
4190                         reloc_desc->type = RELO_EXTERN_LD64;
4191                 reloc_desc->insn_idx = insn_idx;
4192                 reloc_desc->ext_idx = i;
4193                 return 0;
4194         }
4195
4196         /* sub-program call relocation */
4197         if (is_call_insn(insn)) {
4198                 if (insn->src_reg != BPF_PSEUDO_CALL) {
4199                         pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4200                         return -LIBBPF_ERRNO__RELOC;
4201                 }
4202                 /* text_shndx can be 0, if no default "main" program exists */
4203                 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4204                         sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4205                         pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4206                                 prog->name, sym_name, sym_sec_name);
4207                         return -LIBBPF_ERRNO__RELOC;
4208                 }
4209                 if (sym->st_value % BPF_INSN_SZ) {
4210                         pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4211                                 prog->name, sym_name, (size_t)sym->st_value);
4212                         return -LIBBPF_ERRNO__RELOC;
4213                 }
4214                 reloc_desc->type = RELO_CALL;
4215                 reloc_desc->insn_idx = insn_idx;
4216                 reloc_desc->sym_off = sym->st_value;
4217                 return 0;
4218         }
4219
4220         if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4221                 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4222                         prog->name, sym_name, shdr_idx);
4223                 return -LIBBPF_ERRNO__RELOC;
4224         }
4225
4226         /* loading subprog addresses */
4227         if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4228                 /* global_func: sym->st_value = offset in the section, insn->imm = 0.
4229                  * local_func: sym->st_value = 0, insn->imm = offset in the section.
4230                  */
4231                 if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4232                         pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4233                                 prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4234                         return -LIBBPF_ERRNO__RELOC;
4235                 }
4236
4237                 reloc_desc->type = RELO_SUBPROG_ADDR;
4238                 reloc_desc->insn_idx = insn_idx;
4239                 reloc_desc->sym_off = sym->st_value;
4240                 return 0;
4241         }
4242
4243         type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4244         sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4245
4246         /* generic map reference relocation */
4247         if (type == LIBBPF_MAP_UNSPEC) {
4248                 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4249                         pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4250                                 prog->name, sym_name, sym_sec_name);
4251                         return -LIBBPF_ERRNO__RELOC;
4252                 }
4253                 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4254                         map = &obj->maps[map_idx];
4255                         if (map->libbpf_type != type ||
4256                             map->sec_idx != sym->st_shndx ||
4257                             map->sec_offset != sym->st_value)
4258                                 continue;
4259                         pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4260                                  prog->name, map_idx, map->name, map->sec_idx,
4261                                  map->sec_offset, insn_idx);
4262                         break;
4263                 }
4264                 if (map_idx >= nr_maps) {
4265                         pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4266                                 prog->name, sym_sec_name, (size_t)sym->st_value);
4267                         return -LIBBPF_ERRNO__RELOC;
4268                 }
4269                 reloc_desc->type = RELO_LD64;
4270                 reloc_desc->insn_idx = insn_idx;
4271                 reloc_desc->map_idx = map_idx;
4272                 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4273                 return 0;
4274         }
4275
4276         /* global data map relocation */
4277         if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4278                 pr_warn("prog '%s': bad data relo against section '%s'\n",
4279                         prog->name, sym_sec_name);
4280                 return -LIBBPF_ERRNO__RELOC;
4281         }
4282         for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4283                 map = &obj->maps[map_idx];
4284                 if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4285                         continue;
4286                 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4287                          prog->name, map_idx, map->name, map->sec_idx,
4288                          map->sec_offset, insn_idx);
4289                 break;
4290         }
4291         if (map_idx >= nr_maps) {
4292                 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4293                         prog->name, sym_sec_name);
4294                 return -LIBBPF_ERRNO__RELOC;
4295         }
4296
4297         reloc_desc->type = RELO_DATA;
4298         reloc_desc->insn_idx = insn_idx;
4299         reloc_desc->map_idx = map_idx;
4300         reloc_desc->sym_off = sym->st_value;
4301         return 0;
4302 }
4303
4304 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4305 {
4306         return insn_idx >= prog->sec_insn_off &&
4307                insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4308 }
4309
4310 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4311                                                  size_t sec_idx, size_t insn_idx)
4312 {
4313         int l = 0, r = obj->nr_programs - 1, m;
4314         struct bpf_program *prog;
4315
4316         if (!obj->nr_programs)
4317                 return NULL;
4318
4319         while (l < r) {
4320                 m = l + (r - l + 1) / 2;
4321                 prog = &obj->programs[m];
4322
4323                 if (prog->sec_idx < sec_idx ||
4324                     (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4325                         l = m;
4326                 else
4327                         r = m - 1;
4328         }
4329         /* matching program could be at index l, but it still might be the
4330          * wrong one, so we need to double check conditions for the last time
4331          */
4332         prog = &obj->programs[l];
4333         if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4334                 return prog;
4335         return NULL;
4336 }
4337
4338 static int
4339 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4340 {
4341         const char *relo_sec_name, *sec_name;
4342         size_t sec_idx = shdr->sh_info, sym_idx;
4343         struct bpf_program *prog;
4344         struct reloc_desc *relos;
4345         int err, i, nrels;
4346         const char *sym_name;
4347         __u32 insn_idx;
4348         Elf_Scn *scn;
4349         Elf_Data *scn_data;
4350         Elf64_Sym *sym;
4351         Elf64_Rel *rel;
4352
4353         if (sec_idx >= obj->efile.sec_cnt)
4354                 return -EINVAL;
4355
4356         scn = elf_sec_by_idx(obj, sec_idx);
4357         scn_data = elf_sec_data(obj, scn);
4358
4359         relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4360         sec_name = elf_sec_name(obj, scn);
4361         if (!relo_sec_name || !sec_name)
4362                 return -EINVAL;
4363
4364         pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4365                  relo_sec_name, sec_idx, sec_name);
4366         nrels = shdr->sh_size / shdr->sh_entsize;
4367
4368         for (i = 0; i < nrels; i++) {
4369                 rel = elf_rel_by_idx(data, i);
4370                 if (!rel) {
4371                         pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4372                         return -LIBBPF_ERRNO__FORMAT;
4373                 }
4374
4375                 sym_idx = ELF64_R_SYM(rel->r_info);
4376                 sym = elf_sym_by_idx(obj, sym_idx);
4377                 if (!sym) {
4378                         pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4379                                 relo_sec_name, sym_idx, i);
4380                         return -LIBBPF_ERRNO__FORMAT;
4381                 }
4382
4383                 if (sym->st_shndx >= obj->efile.sec_cnt) {
4384                         pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4385                                 relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4386                         return -LIBBPF_ERRNO__FORMAT;
4387                 }
4388
4389                 if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4390                         pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4391                                 relo_sec_name, (size_t)rel->r_offset, i);
4392                         return -LIBBPF_ERRNO__FORMAT;
4393                 }
4394
4395                 insn_idx = rel->r_offset / BPF_INSN_SZ;
4396                 /* relocations against static functions are recorded as
4397                  * relocations against the section that contains a function;
4398                  * in such case, symbol will be STT_SECTION and sym.st_name
4399                  * will point to empty string (0), so fetch section name
4400                  * instead
4401                  */
4402                 if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4403                         sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4404                 else
4405                         sym_name = elf_sym_str(obj, sym->st_name);
4406                 sym_name = sym_name ?: "<?";
4407
4408                 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4409                          relo_sec_name, i, insn_idx, sym_name);
4410
4411                 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4412                 if (!prog) {
4413                         pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4414                                 relo_sec_name, i, sec_name, insn_idx);
4415                         continue;
4416                 }
4417
4418                 relos = libbpf_reallocarray(prog->reloc_desc,
4419                                             prog->nr_reloc + 1, sizeof(*relos));
4420                 if (!relos)
4421                         return -ENOMEM;
4422                 prog->reloc_desc = relos;
4423
4424                 /* adjust insn_idx to local BPF program frame of reference */
4425                 insn_idx -= prog->sec_insn_off;
4426                 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4427                                                 insn_idx, sym_name, sym, rel);
4428                 if (err)
4429                         return err;
4430
4431                 prog->nr_reloc++;
4432         }
4433         return 0;
4434 }
4435
4436 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4437 {
4438         int id;
4439
4440         if (!obj->btf)
4441                 return -ENOENT;
4442
4443         /* if it's BTF-defined map, we don't need to search for type IDs.
4444          * For struct_ops map, it does not need btf_key_type_id and
4445          * btf_value_type_id.
4446          */
4447         if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4448                 return 0;
4449
4450         /*
4451          * LLVM annotates global data differently in BTF, that is,
4452          * only as '.data', '.bss' or '.rodata'.
4453          */
4454         if (!bpf_map__is_internal(map))
4455                 return -ENOENT;
4456
4457         id = btf__find_by_name(obj->btf, map->real_name);
4458         if (id < 0)
4459                 return id;
4460
4461         map->btf_key_type_id = 0;
4462         map->btf_value_type_id = id;
4463         return 0;
4464 }
4465
4466 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4467 {
4468         char file[PATH_MAX], buff[4096];
4469         FILE *fp;
4470         __u32 val;
4471         int err;
4472
4473         snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4474         memset(info, 0, sizeof(*info));
4475
4476         fp = fopen(file, "re");
4477         if (!fp) {
4478                 err = -errno;
4479                 pr_warn("failed to open %s: %d. No procfs support?\n", file,
4480                         err);
4481                 return err;
4482         }
4483
4484         while (fgets(buff, sizeof(buff), fp)) {
4485                 if (sscanf(buff, "map_type:\t%u", &val) == 1)
4486                         info->type = val;
4487                 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4488                         info->key_size = val;
4489                 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4490                         info->value_size = val;
4491                 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4492                         info->max_entries = val;
4493                 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4494                         info->map_flags = val;
4495         }
4496
4497         fclose(fp);
4498
4499         return 0;
4500 }
4501
4502 bool bpf_map__autocreate(const struct bpf_map *map)
4503 {
4504         return map->autocreate;
4505 }
4506
4507 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4508 {
4509         if (map->obj->loaded)
4510                 return libbpf_err(-EBUSY);
4511
4512         map->autocreate = autocreate;
4513         return 0;
4514 }
4515
4516 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4517 {
4518         struct bpf_map_info info;
4519         __u32 len = sizeof(info), name_len;
4520         int new_fd, err;
4521         char *new_name;
4522
4523         memset(&info, 0, len);
4524         err = bpf_map_get_info_by_fd(fd, &info, &len);
4525         if (err && errno == EINVAL)
4526                 err = bpf_get_map_info_from_fdinfo(fd, &info);
4527         if (err)
4528                 return libbpf_err(err);
4529
4530         name_len = strlen(info.name);
4531         if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4532                 new_name = strdup(map->name);
4533         else
4534                 new_name = strdup(info.name);
4535
4536         if (!new_name)
4537                 return libbpf_err(-errno);
4538
4539         /*
4540          * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4541          * This is similar to what we do in ensure_good_fd(), but without
4542          * closing original FD.
4543          */
4544         new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4545         if (new_fd < 0) {
4546                 err = -errno;
4547                 goto err_free_new_name;
4548         }
4549
4550         err = zclose(map->fd);
4551         if (err) {
4552                 err = -errno;
4553                 goto err_close_new_fd;
4554         }
4555         free(map->name);
4556
4557         map->fd = new_fd;
4558         map->name = new_name;
4559         map->def.type = info.type;
4560         map->def.key_size = info.key_size;
4561         map->def.value_size = info.value_size;
4562         map->def.max_entries = info.max_entries;
4563         map->def.map_flags = info.map_flags;
4564         map->btf_key_type_id = info.btf_key_type_id;
4565         map->btf_value_type_id = info.btf_value_type_id;
4566         map->reused = true;
4567         map->map_extra = info.map_extra;
4568
4569         return 0;
4570
4571 err_close_new_fd:
4572         close(new_fd);
4573 err_free_new_name:
4574         free(new_name);
4575         return libbpf_err(err);
4576 }
4577
4578 __u32 bpf_map__max_entries(const struct bpf_map *map)
4579 {
4580         return map->def.max_entries;
4581 }
4582
4583 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4584 {
4585         if (!bpf_map_type__is_map_in_map(map->def.type))
4586                 return errno = EINVAL, NULL;
4587
4588         return map->inner_map;
4589 }
4590
4591 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4592 {
4593         if (map->obj->loaded)
4594                 return libbpf_err(-EBUSY);
4595
4596         map->def.max_entries = max_entries;
4597
4598         /* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4599         if (map_is_ringbuf(map))
4600                 map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4601
4602         return 0;
4603 }
4604
4605 static int
4606 bpf_object__probe_loading(struct bpf_object *obj)
4607 {
4608         char *cp, errmsg[STRERR_BUFSIZE];
4609         struct bpf_insn insns[] = {
4610                 BPF_MOV64_IMM(BPF_REG_0, 0),
4611                 BPF_EXIT_INSN(),
4612         };
4613         int ret, insn_cnt = ARRAY_SIZE(insns);
4614
4615         if (obj->gen_loader)
4616                 return 0;
4617
4618         ret = bump_rlimit_memlock();
4619         if (ret)
4620                 pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4621
4622         /* make sure basic loading works */
4623         ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4624         if (ret < 0)
4625                 ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4626         if (ret < 0) {
4627                 ret = errno;
4628                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4629                 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4630                         "program. Make sure your kernel supports BPF "
4631                         "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4632                         "set to big enough value.\n", __func__, cp, ret);
4633                 return -ret;
4634         }
4635         close(ret);
4636
4637         return 0;
4638 }
4639
4640 static int probe_fd(int fd)
4641 {
4642         if (fd >= 0)
4643                 close(fd);
4644         return fd >= 0;
4645 }
4646
4647 static int probe_kern_prog_name(void)
4648 {
4649         const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4650         struct bpf_insn insns[] = {
4651                 BPF_MOV64_IMM(BPF_REG_0, 0),
4652                 BPF_EXIT_INSN(),
4653         };
4654         union bpf_attr attr;
4655         int ret;
4656
4657         memset(&attr, 0, attr_sz);
4658         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4659         attr.license = ptr_to_u64("GPL");
4660         attr.insns = ptr_to_u64(insns);
4661         attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4662         libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4663
4664         /* make sure loading with name works */
4665         ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4666         return probe_fd(ret);
4667 }
4668
4669 static int probe_kern_global_data(void)
4670 {
4671         char *cp, errmsg[STRERR_BUFSIZE];
4672         struct bpf_insn insns[] = {
4673                 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4674                 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4675                 BPF_MOV64_IMM(BPF_REG_0, 0),
4676                 BPF_EXIT_INSN(),
4677         };
4678         int ret, map, insn_cnt = ARRAY_SIZE(insns);
4679
4680         map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4681         if (map < 0) {
4682                 ret = -errno;
4683                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4684                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4685                         __func__, cp, -ret);
4686                 return ret;
4687         }
4688
4689         insns[0].imm = map;
4690
4691         ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4692         close(map);
4693         return probe_fd(ret);
4694 }
4695
4696 static int probe_kern_btf(void)
4697 {
4698         static const char strs[] = "\0int";
4699         __u32 types[] = {
4700                 /* int */
4701                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4702         };
4703
4704         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4705                                              strs, sizeof(strs)));
4706 }
4707
4708 static int probe_kern_btf_func(void)
4709 {
4710         static const char strs[] = "\0int\0x\0a";
4711         /* void x(int a) {} */
4712         __u32 types[] = {
4713                 /* int */
4714                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4715                 /* FUNC_PROTO */                                /* [2] */
4716                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4717                 BTF_PARAM_ENC(7, 1),
4718                 /* FUNC x */                                    /* [3] */
4719                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4720         };
4721
4722         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4723                                              strs, sizeof(strs)));
4724 }
4725
4726 static int probe_kern_btf_func_global(void)
4727 {
4728         static const char strs[] = "\0int\0x\0a";
4729         /* static void x(int a) {} */
4730         __u32 types[] = {
4731                 /* int */
4732                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4733                 /* FUNC_PROTO */                                /* [2] */
4734                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4735                 BTF_PARAM_ENC(7, 1),
4736                 /* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4737                 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4738         };
4739
4740         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4741                                              strs, sizeof(strs)));
4742 }
4743
4744 static int probe_kern_btf_datasec(void)
4745 {
4746         static const char strs[] = "\0x\0.data";
4747         /* static int a; */
4748         __u32 types[] = {
4749                 /* int */
4750                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4751                 /* VAR x */                                     /* [2] */
4752                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4753                 BTF_VAR_STATIC,
4754                 /* DATASEC val */                               /* [3] */
4755                 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4756                 BTF_VAR_SECINFO_ENC(2, 0, 4),
4757         };
4758
4759         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4760                                              strs, sizeof(strs)));
4761 }
4762
4763 static int probe_kern_btf_float(void)
4764 {
4765         static const char strs[] = "\0float";
4766         __u32 types[] = {
4767                 /* float */
4768                 BTF_TYPE_FLOAT_ENC(1, 4),
4769         };
4770
4771         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4772                                              strs, sizeof(strs)));
4773 }
4774
4775 static int probe_kern_btf_decl_tag(void)
4776 {
4777         static const char strs[] = "\0tag";
4778         __u32 types[] = {
4779                 /* int */
4780                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4781                 /* VAR x */                                     /* [2] */
4782                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4783                 BTF_VAR_STATIC,
4784                 /* attr */
4785                 BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4786         };
4787
4788         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4789                                              strs, sizeof(strs)));
4790 }
4791
4792 static int probe_kern_btf_type_tag(void)
4793 {
4794         static const char strs[] = "\0tag";
4795         __u32 types[] = {
4796                 /* int */
4797                 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),          /* [1] */
4798                 /* attr */
4799                 BTF_TYPE_TYPE_TAG_ENC(1, 1),                            /* [2] */
4800                 /* ptr */
4801                 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),   /* [3] */
4802         };
4803
4804         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4805                                              strs, sizeof(strs)));
4806 }
4807
4808 static int probe_kern_array_mmap(void)
4809 {
4810         LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4811         int fd;
4812
4813         fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4814         return probe_fd(fd);
4815 }
4816
4817 static int probe_kern_exp_attach_type(void)
4818 {
4819         LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4820         struct bpf_insn insns[] = {
4821                 BPF_MOV64_IMM(BPF_REG_0, 0),
4822                 BPF_EXIT_INSN(),
4823         };
4824         int fd, insn_cnt = ARRAY_SIZE(insns);
4825
4826         /* use any valid combination of program type and (optional)
4827          * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4828          * to see if kernel supports expected_attach_type field for
4829          * BPF_PROG_LOAD command
4830          */
4831         fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4832         return probe_fd(fd);
4833 }
4834
4835 static int probe_kern_probe_read_kernel(void)
4836 {
4837         struct bpf_insn insns[] = {
4838                 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),   /* r1 = r10 (fp) */
4839                 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),  /* r1 += -8 */
4840                 BPF_MOV64_IMM(BPF_REG_2, 8),            /* r2 = 8 */
4841                 BPF_MOV64_IMM(BPF_REG_3, 0),            /* r3 = 0 */
4842                 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4843                 BPF_EXIT_INSN(),
4844         };
4845         int fd, insn_cnt = ARRAY_SIZE(insns);
4846
4847         fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4848         return probe_fd(fd);
4849 }
4850
4851 static int probe_prog_bind_map(void)
4852 {
4853         char *cp, errmsg[STRERR_BUFSIZE];
4854         struct bpf_insn insns[] = {
4855                 BPF_MOV64_IMM(BPF_REG_0, 0),
4856                 BPF_EXIT_INSN(),
4857         };
4858         int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4859
4860         map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4861         if (map < 0) {
4862                 ret = -errno;
4863                 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4864                 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4865                         __func__, cp, -ret);
4866                 return ret;
4867         }
4868
4869         prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4870         if (prog < 0) {
4871                 close(map);
4872                 return 0;
4873         }
4874
4875         ret = bpf_prog_bind_map(prog, map, NULL);
4876
4877         close(map);
4878         close(prog);
4879
4880         return ret >= 0;
4881 }
4882
4883 static int probe_module_btf(void)
4884 {
4885         static const char strs[] = "\0int";
4886         __u32 types[] = {
4887                 /* int */
4888                 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4889         };
4890         struct bpf_btf_info info;
4891         __u32 len = sizeof(info);
4892         char name[16];
4893         int fd, err;
4894
4895         fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4896         if (fd < 0)
4897                 return 0; /* BTF not supported at all */
4898
4899         memset(&info, 0, sizeof(info));
4900         info.name = ptr_to_u64(name);
4901         info.name_len = sizeof(name);
4902
4903         /* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4904          * kernel's module BTF support coincides with support for
4905          * name/name_len fields in struct bpf_btf_info.
4906          */
4907         err = bpf_btf_get_info_by_fd(fd, &info, &len);
4908         close(fd);
4909         return !err;
4910 }
4911
4912 static int probe_perf_link(void)
4913 {
4914         struct bpf_insn insns[] = {
4915                 BPF_MOV64_IMM(BPF_REG_0, 0),
4916                 BPF_EXIT_INSN(),
4917         };
4918         int prog_fd, link_fd, err;
4919
4920         prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4921                                 insns, ARRAY_SIZE(insns), NULL);
4922         if (prog_fd < 0)
4923                 return -errno;
4924
4925         /* use invalid perf_event FD to get EBADF, if link is supported;
4926          * otherwise EINVAL should be returned
4927          */
4928         link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4929         err = -errno; /* close() can clobber errno */
4930
4931         if (link_fd >= 0)
4932                 close(link_fd);
4933         close(prog_fd);
4934
4935         return link_fd < 0 && err == -EBADF;
4936 }
4937
4938 static int probe_uprobe_multi_link(void)
4939 {
4940         LIBBPF_OPTS(bpf_prog_load_opts, load_opts,
4941                 .expected_attach_type = BPF_TRACE_UPROBE_MULTI,
4942         );
4943         LIBBPF_OPTS(bpf_link_create_opts, link_opts);
4944         struct bpf_insn insns[] = {
4945                 BPF_MOV64_IMM(BPF_REG_0, 0),
4946                 BPF_EXIT_INSN(),
4947         };
4948         int prog_fd, link_fd, err;
4949         unsigned long offset = 0;
4950
4951         prog_fd = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL",
4952                                 insns, ARRAY_SIZE(insns), &load_opts);
4953         if (prog_fd < 0)
4954                 return -errno;
4955
4956         /* Creating uprobe in '/' binary should fail with -EBADF. */
4957         link_opts.uprobe_multi.path = "/";
4958         link_opts.uprobe_multi.offsets = &offset;
4959         link_opts.uprobe_multi.cnt = 1;
4960
4961         link_fd = bpf_link_create(prog_fd, -1, BPF_TRACE_UPROBE_MULTI, &link_opts);
4962         err = -errno; /* close() can clobber errno */
4963
4964         if (link_fd >= 0)
4965                 close(link_fd);
4966         close(prog_fd);
4967
4968         return link_fd < 0 && err == -EBADF;
4969 }
4970
4971 static int probe_kern_bpf_cookie(void)
4972 {
4973         struct bpf_insn insns[] = {
4974                 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4975                 BPF_EXIT_INSN(),
4976         };
4977         int ret, insn_cnt = ARRAY_SIZE(insns);
4978
4979         ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4980         return probe_fd(ret);
4981 }
4982
4983 static int probe_kern_btf_enum64(void)
4984 {
4985         static const char strs[] = "\0enum64";
4986         __u32 types[] = {
4987                 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4988         };
4989
4990         return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4991                                              strs, sizeof(strs)));
4992 }
4993
4994 static int probe_kern_syscall_wrapper(void);
4995
4996 enum kern_feature_result {
4997         FEAT_UNKNOWN = 0,
4998         FEAT_SUPPORTED = 1,
4999         FEAT_MISSING = 2,
5000 };
5001
5002 typedef int (*feature_probe_fn)(void);
5003
5004 static struct kern_feature_desc {
5005         const char *desc;
5006         feature_probe_fn probe;
5007         enum kern_feature_result res;
5008 } feature_probes[__FEAT_CNT] = {
5009         [FEAT_PROG_NAME] = {
5010                 "BPF program name", probe_kern_prog_name,
5011         },
5012         [FEAT_GLOBAL_DATA] = {
5013                 "global variables", probe_kern_global_data,
5014         },
5015         [FEAT_BTF] = {
5016                 "minimal BTF", probe_kern_btf,
5017         },
5018         [FEAT_BTF_FUNC] = {
5019                 "BTF functions", probe_kern_btf_func,
5020         },
5021         [FEAT_BTF_GLOBAL_FUNC] = {
5022                 "BTF global function", probe_kern_btf_func_global,
5023         },
5024         [FEAT_BTF_DATASEC] = {
5025                 "BTF data section and variable", probe_kern_btf_datasec,
5026         },
5027         [FEAT_ARRAY_MMAP] = {
5028                 "ARRAY map mmap()", probe_kern_array_mmap,
5029         },
5030         [FEAT_EXP_ATTACH_TYPE] = {
5031                 "BPF_PROG_LOAD expected_attach_type attribute",
5032                 probe_kern_exp_attach_type,
5033         },
5034         [FEAT_PROBE_READ_KERN] = {
5035                 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
5036         },
5037         [FEAT_PROG_BIND_MAP] = {
5038                 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
5039         },
5040         [FEAT_MODULE_BTF] = {
5041                 "module BTF support", probe_module_btf,
5042         },
5043         [FEAT_BTF_FLOAT] = {
5044                 "BTF_KIND_FLOAT support", probe_kern_btf_float,
5045         },
5046         [FEAT_PERF_LINK] = {
5047                 "BPF perf link support", probe_perf_link,
5048         },
5049         [FEAT_BTF_DECL_TAG] = {
5050                 "BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
5051         },
5052         [FEAT_BTF_TYPE_TAG] = {
5053                 "BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
5054         },
5055         [FEAT_MEMCG_ACCOUNT] = {
5056                 "memcg-based memory accounting", probe_memcg_account,
5057         },
5058         [FEAT_BPF_COOKIE] = {
5059                 "BPF cookie support", probe_kern_bpf_cookie,
5060         },
5061         [FEAT_BTF_ENUM64] = {
5062                 "BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
5063         },
5064         [FEAT_SYSCALL_WRAPPER] = {
5065                 "Kernel using syscall wrapper", probe_kern_syscall_wrapper,
5066         },
5067         [FEAT_UPROBE_MULTI_LINK] = {
5068                 "BPF multi-uprobe link support", probe_uprobe_multi_link,
5069         },
5070 };
5071
5072 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5073 {
5074         struct kern_feature_desc *feat = &feature_probes[feat_id];
5075         int ret;
5076
5077         if (obj && obj->gen_loader)
5078                 /* To generate loader program assume the latest kernel
5079                  * to avoid doing extra prog_load, map_create syscalls.
5080                  */
5081                 return true;
5082
5083         if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
5084                 ret = feat->probe();
5085                 if (ret > 0) {
5086                         WRITE_ONCE(feat->res, FEAT_SUPPORTED);
5087                 } else if (ret == 0) {
5088                         WRITE_ONCE(feat->res, FEAT_MISSING);
5089                 } else {
5090                         pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
5091                         WRITE_ONCE(feat->res, FEAT_MISSING);
5092                 }
5093         }
5094
5095         return READ_ONCE(feat->res) == FEAT_SUPPORTED;
5096 }
5097
5098 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5099 {
5100         struct bpf_map_info map_info;
5101         char msg[STRERR_BUFSIZE];
5102         __u32 map_info_len = sizeof(map_info);
5103         int err;
5104
5105         memset(&map_info, 0, map_info_len);
5106         err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5107         if (err && errno == EINVAL)
5108                 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5109         if (err) {
5110                 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5111                         libbpf_strerror_r(errno, msg, sizeof(msg)));
5112                 return false;
5113         }
5114
5115         return (map_info.type == map->def.type &&
5116                 map_info.key_size == map->def.key_size &&
5117                 map_info.value_size == map->def.value_size &&
5118                 map_info.max_entries == map->def.max_entries &&
5119                 map_info.map_flags == map->def.map_flags &&
5120                 map_info.map_extra == map->map_extra);
5121 }
5122
5123 static int
5124 bpf_object__reuse_map(struct bpf_map *map)
5125 {
5126         char *cp, errmsg[STRERR_BUFSIZE];
5127         int err, pin_fd;
5128
5129         pin_fd = bpf_obj_get(map->pin_path);
5130         if (pin_fd < 0) {
5131                 err = -errno;
5132                 if (err == -ENOENT) {
5133                         pr_debug("found no pinned map to reuse at '%s'\n",
5134                                  map->pin_path);
5135                         return 0;
5136                 }
5137
5138                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5139                 pr_warn("couldn't retrieve pinned map '%s': %s\n",
5140                         map->pin_path, cp);
5141                 return err;
5142         }
5143
5144         if (!map_is_reuse_compat(map, pin_fd)) {
5145                 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5146                         map->pin_path);
5147                 close(pin_fd);
5148                 return -EINVAL;
5149         }
5150
5151         err = bpf_map__reuse_fd(map, pin_fd);
5152         close(pin_fd);
5153         if (err)
5154                 return err;
5155
5156         map->pinned = true;
5157         pr_debug("reused pinned map at '%s'\n", map->pin_path);
5158
5159         return 0;
5160 }
5161
5162 static int
5163 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5164 {
5165         enum libbpf_map_type map_type = map->libbpf_type;
5166         char *cp, errmsg[STRERR_BUFSIZE];
5167         int err, zero = 0;
5168
5169         if (obj->gen_loader) {
5170                 bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5171                                          map->mmaped, map->def.value_size);
5172                 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5173                         bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5174                 return 0;
5175         }
5176         err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5177         if (err) {
5178                 err = -errno;
5179                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5180                 pr_warn("Error setting initial map(%s) contents: %s\n",
5181                         map->name, cp);
5182                 return err;
5183         }
5184
5185         /* Freeze .rodata and .kconfig map as read-only from syscall side. */
5186         if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5187                 err = bpf_map_freeze(map->fd);
5188                 if (err) {
5189                         err = -errno;
5190                         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5191                         pr_warn("Error freezing map(%s) as read-only: %s\n",
5192                                 map->name, cp);
5193                         return err;
5194                 }
5195         }
5196         return 0;
5197 }
5198
5199 static void bpf_map__destroy(struct bpf_map *map);
5200
5201 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5202 {
5203         LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5204         struct bpf_map_def *def = &map->def;
5205         const char *map_name = NULL;
5206         int err = 0;
5207
5208         if (kernel_supports(obj, FEAT_PROG_NAME))
5209                 map_name = map->name;
5210         create_attr.map_ifindex = map->map_ifindex;
5211         create_attr.map_flags = def->map_flags;
5212         create_attr.numa_node = map->numa_node;
5213         create_attr.map_extra = map->map_extra;
5214
5215         if (bpf_map__is_struct_ops(map))
5216                 create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5217
5218         if (obj->btf && btf__fd(obj->btf) >= 0) {
5219                 create_attr.btf_fd = btf__fd(obj->btf);
5220                 create_attr.btf_key_type_id = map->btf_key_type_id;
5221                 create_attr.btf_value_type_id = map->btf_value_type_id;
5222         }
5223
5224         if (bpf_map_type__is_map_in_map(def->type)) {
5225                 if (map->inner_map) {
5226                         err = bpf_object__create_map(obj, map->inner_map, true);
5227                         if (err) {
5228                                 pr_warn("map '%s': failed to create inner map: %d\n",
5229                                         map->name, err);
5230                                 return err;
5231                         }
5232                         map->inner_map_fd = bpf_map__fd(map->inner_map);
5233                 }
5234                 if (map->inner_map_fd >= 0)
5235                         create_attr.inner_map_fd = map->inner_map_fd;
5236         }
5237
5238         switch (def->type) {
5239         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5240         case BPF_MAP_TYPE_CGROUP_ARRAY:
5241         case BPF_MAP_TYPE_STACK_TRACE:
5242         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5243         case BPF_MAP_TYPE_HASH_OF_MAPS:
5244         case BPF_MAP_TYPE_DEVMAP:
5245         case BPF_MAP_TYPE_DEVMAP_HASH:
5246         case BPF_MAP_TYPE_CPUMAP:
5247         case BPF_MAP_TYPE_XSKMAP:
5248         case BPF_MAP_TYPE_SOCKMAP:
5249         case BPF_MAP_TYPE_SOCKHASH:
5250         case BPF_MAP_TYPE_QUEUE:
5251         case BPF_MAP_TYPE_STACK:
5252                 create_attr.btf_fd = 0;
5253                 create_attr.btf_key_type_id = 0;
5254                 create_attr.btf_value_type_id = 0;
5255                 map->btf_key_type_id = 0;
5256                 map->btf_value_type_id = 0;
5257         default:
5258                 break;
5259         }
5260
5261         if (obj->gen_loader) {
5262                 bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5263                                     def->key_size, def->value_size, def->max_entries,
5264                                     &create_attr, is_inner ? -1 : map - obj->maps);
5265                 /* Pretend to have valid FD to pass various fd >= 0 checks.
5266                  * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5267                  */
5268                 map->fd = 0;
5269         } else {
5270                 map->fd = bpf_map_create(def->type, map_name,
5271                                          def->key_size, def->value_size,
5272                                          def->max_entries, &create_attr);
5273         }
5274         if (map->fd < 0 && (create_attr.btf_key_type_id ||
5275                             create_attr.btf_value_type_id)) {
5276                 char *cp, errmsg[STRERR_BUFSIZE];
5277
5278                 err = -errno;
5279                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5280                 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5281                         map->name, cp, err);
5282                 create_attr.btf_fd = 0;
5283                 create_attr.btf_key_type_id = 0;
5284                 create_attr.btf_value_type_id = 0;
5285                 map->btf_key_type_id = 0;
5286                 map->btf_value_type_id = 0;
5287                 map->fd = bpf_map_create(def->type, map_name,
5288                                          def->key_size, def->value_size,
5289                                          def->max_entries, &create_attr);
5290         }
5291
5292         err = map->fd < 0 ? -errno : 0;
5293
5294         if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5295                 if (obj->gen_loader)
5296                         map->inner_map->fd = -1;
5297                 bpf_map__destroy(map->inner_map);
5298                 zfree(&map->inner_map);
5299         }
5300
5301         return err;
5302 }
5303
5304 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5305 {
5306         const struct bpf_map *targ_map;
5307         unsigned int i;
5308         int fd, err = 0;
5309
5310         for (i = 0; i < map->init_slots_sz; i++) {
5311                 if (!map->init_slots[i])
5312                         continue;
5313
5314                 targ_map = map->init_slots[i];
5315                 fd = bpf_map__fd(targ_map);
5316
5317                 if (obj->gen_loader) {
5318                         bpf_gen__populate_outer_map(obj->gen_loader,
5319                                                     map - obj->maps, i,
5320                                                     targ_map - obj->maps);
5321                 } else {
5322                         err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5323                 }
5324                 if (err) {
5325                         err = -errno;
5326                         pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5327                                 map->name, i, targ_map->name, fd, err);
5328                         return err;
5329                 }
5330                 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5331                          map->name, i, targ_map->name, fd);
5332         }
5333
5334         zfree(&map->init_slots);
5335         map->init_slots_sz = 0;
5336
5337         return 0;
5338 }
5339
5340 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5341 {
5342         const struct bpf_program *targ_prog;
5343         unsigned int i;
5344         int fd, err;
5345
5346         if (obj->gen_loader)
5347                 return -ENOTSUP;
5348
5349         for (i = 0; i < map->init_slots_sz; i++) {
5350                 if (!map->init_slots[i])
5351                         continue;
5352
5353                 targ_prog = map->init_slots[i];
5354                 fd = bpf_program__fd(targ_prog);
5355
5356                 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5357                 if (err) {
5358                         err = -errno;
5359                         pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5360                                 map->name, i, targ_prog->name, fd, err);
5361                         return err;
5362                 }
5363                 pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5364                          map->name, i, targ_prog->name, fd);
5365         }
5366
5367         zfree(&map->init_slots);
5368         map->init_slots_sz = 0;
5369
5370         return 0;
5371 }
5372
5373 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5374 {
5375         struct bpf_map *map;
5376         int i, err;
5377
5378         for (i = 0; i < obj->nr_maps; i++) {
5379                 map = &obj->maps[i];
5380
5381                 if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5382                         continue;
5383
5384                 err = init_prog_array_slots(obj, map);
5385                 if (err < 0) {
5386                         zclose(map->fd);
5387                         return err;
5388                 }
5389         }
5390         return 0;
5391 }
5392
5393 static int map_set_def_max_entries(struct bpf_map *map)
5394 {
5395         if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5396                 int nr_cpus;
5397
5398                 nr_cpus = libbpf_num_possible_cpus();
5399                 if (nr_cpus < 0) {
5400                         pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5401                                 map->name, nr_cpus);
5402                         return nr_cpus;
5403                 }
5404                 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5405                 map->def.max_entries = nr_cpus;
5406         }
5407
5408         return 0;
5409 }
5410
5411 static int
5412 bpf_object__create_maps(struct bpf_object *obj)
5413 {
5414         struct bpf_map *map;
5415         char *cp, errmsg[STRERR_BUFSIZE];
5416         unsigned int i, j;
5417         int err;
5418         bool retried;
5419
5420         for (i = 0; i < obj->nr_maps; i++) {
5421                 map = &obj->maps[i];
5422
5423                 /* To support old kernels, we skip creating global data maps
5424                  * (.rodata, .data, .kconfig, etc); later on, during program
5425                  * loading, if we detect that at least one of the to-be-loaded
5426                  * programs is referencing any global data map, we'll error
5427                  * out with program name and relocation index logged.
5428                  * This approach allows to accommodate Clang emitting
5429                  * unnecessary .rodata.str1.1 sections for string literals,
5430                  * but also it allows to have CO-RE applications that use
5431                  * global variables in some of BPF programs, but not others.
5432                  * If those global variable-using programs are not loaded at
5433                  * runtime due to bpf_program__set_autoload(prog, false),
5434                  * bpf_object loading will succeed just fine even on old
5435                  * kernels.
5436                  */
5437                 if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5438                         map->autocreate = false;
5439
5440                 if (!map->autocreate) {
5441                         pr_debug("map '%s': skipped auto-creating...\n", map->name);
5442                         continue;
5443                 }
5444
5445                 err = map_set_def_max_entries(map);
5446                 if (err)
5447                         goto err_out;
5448
5449                 retried = false;
5450 retry:
5451                 if (map->pin_path) {
5452                         err = bpf_object__reuse_map(map);
5453                         if (err) {
5454                                 pr_warn("map '%s': error reusing pinned map\n",
5455                                         map->name);
5456                                 goto err_out;
5457                         }
5458                         if (retried && map->fd < 0) {
5459                                 pr_warn("map '%s': cannot find pinned map\n",
5460                                         map->name);
5461                                 err = -ENOENT;
5462                                 goto err_out;
5463                         }
5464                 }
5465
5466                 if (map->fd >= 0) {
5467                         pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5468                                  map->name, map->fd);
5469                 } else {
5470                         err = bpf_object__create_map(obj, map, false);
5471                         if (err)
5472                                 goto err_out;
5473
5474                         pr_debug("map '%s': created successfully, fd=%d\n",
5475                                  map->name, map->fd);
5476
5477                         if (bpf_map__is_internal(map)) {
5478                                 err = bpf_object__populate_internal_map(obj, map);
5479                                 if (err < 0) {
5480                                         zclose(map->fd);
5481                                         goto err_out;
5482                                 }
5483                         }
5484
5485                         if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5486                                 err = init_map_in_map_slots(obj, map);
5487                                 if (err < 0) {
5488                                         zclose(map->fd);
5489                                         goto err_out;
5490                                 }
5491                         }
5492                 }
5493
5494                 if (map->pin_path && !map->pinned) {
5495                         err = bpf_map__pin(map, NULL);
5496                         if (err) {
5497                                 zclose(map->fd);
5498                                 if (!retried && err == -EEXIST) {
5499                                         retried = true;
5500                                         goto retry;
5501                                 }
5502                                 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5503                                         map->name, map->pin_path, err);
5504                                 goto err_out;
5505                         }
5506                 }
5507         }
5508
5509         return 0;
5510
5511 err_out:
5512         cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5513         pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5514         pr_perm_msg(err);
5515         for (j = 0; j < i; j++)
5516                 zclose(obj->maps[j].fd);
5517         return err;
5518 }
5519
5520 static bool bpf_core_is_flavor_sep(const char *s)
5521 {
5522         /* check X___Y name pattern, where X and Y are not underscores */
5523         return s[0] != '_' &&                                 /* X */
5524                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5525                s[4] != '_';                                   /* Y */
5526 }
5527
5528 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5529  * before last triple underscore. Struct name part after last triple
5530  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5531  */
5532 size_t bpf_core_essential_name_len(const char *name)
5533 {
5534         size_t n = strlen(name);
5535         int i;
5536
5537         for (i = n - 5; i >= 0; i--) {
5538                 if (bpf_core_is_flavor_sep(name + i))
5539                         return i + 1;
5540         }
5541         return n;
5542 }
5543
5544 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5545 {
5546         if (!cands)
5547                 return;
5548
5549         free(cands->cands);
5550         free(cands);
5551 }
5552
5553 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5554                        size_t local_essent_len,
5555                        const struct btf *targ_btf,
5556                        const char *targ_btf_name,
5557                        int targ_start_id,
5558                        struct bpf_core_cand_list *cands)
5559 {
5560         struct bpf_core_cand *new_cands, *cand;
5561         const struct btf_type *t, *local_t;
5562         const char *targ_name, *local_name;
5563         size_t targ_essent_len;
5564         int n, i;
5565
5566         local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5567         local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5568
5569         n = btf__type_cnt(targ_btf);
5570         for (i = targ_start_id; i < n; i++) {
5571                 t = btf__type_by_id(targ_btf, i);
5572                 if (!btf_kind_core_compat(t, local_t))
5573                         continue;
5574
5575                 targ_name = btf__name_by_offset(targ_btf, t->name_off);
5576                 if (str_is_empty(targ_name))
5577                         continue;
5578
5579                 targ_essent_len = bpf_core_essential_name_len(targ_name);
5580                 if (targ_essent_len != local_essent_len)
5581                         continue;
5582
5583                 if (strncmp(local_name, targ_name, local_essent_len) != 0)
5584                         continue;
5585
5586                 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5587                          local_cand->id, btf_kind_str(local_t),
5588                          local_name, i, btf_kind_str(t), targ_name,
5589                          targ_btf_name);
5590                 new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5591                                               sizeof(*cands->cands));
5592                 if (!new_cands)
5593                         return -ENOMEM;
5594
5595                 cand = &new_cands[cands->len];
5596                 cand->btf = targ_btf;
5597                 cand->id = i;
5598
5599                 cands->cands = new_cands;
5600                 cands->len++;
5601         }
5602         return 0;
5603 }
5604
5605 static int load_module_btfs(struct bpf_object *obj)
5606 {
5607         struct bpf_btf_info info;
5608         struct module_btf *mod_btf;
5609         struct btf *btf;
5610         char name[64];
5611         __u32 id = 0, len;
5612         int err, fd;
5613
5614         if (obj->btf_modules_loaded)
5615                 return 0;
5616
5617         if (obj->gen_loader)
5618                 return 0;
5619
5620         /* don't do this again, even if we find no module BTFs */
5621         obj->btf_modules_loaded = true;
5622
5623         /* kernel too old to support module BTFs */
5624         if (!kernel_supports(obj, FEAT_MODULE_BTF))
5625                 return 0;
5626
5627         while (true) {
5628                 err = bpf_btf_get_next_id(id, &id);
5629                 if (err && errno == ENOENT)
5630                         return 0;
5631                 if (err && errno == EPERM) {
5632                         pr_debug("skipping module BTFs loading, missing privileges\n");
5633                         return 0;
5634                 }
5635                 if (err) {
5636                         err = -errno;
5637                         pr_warn("failed to iterate BTF objects: %d\n", err);
5638                         return err;
5639                 }
5640
5641                 fd = bpf_btf_get_fd_by_id(id);
5642                 if (fd < 0) {
5643                         if (errno == ENOENT)
5644                                 continue; /* expected race: BTF was unloaded */
5645                         err = -errno;
5646                         pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5647                         return err;
5648                 }
5649
5650                 len = sizeof(info);
5651                 memset(&info, 0, sizeof(info));
5652                 info.name = ptr_to_u64(name);
5653                 info.name_len = sizeof(name);
5654
5655                 err = bpf_btf_get_info_by_fd(fd, &info, &len);
5656                 if (err) {
5657                         err = -errno;
5658                         pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5659                         goto err_out;
5660                 }
5661
5662                 /* ignore non-module BTFs */
5663                 if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5664                         close(fd);
5665                         continue;
5666                 }
5667
5668                 btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5669                 err = libbpf_get_error(btf);
5670                 if (err) {
5671                         pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5672                                 name, id, err);
5673                         goto err_out;
5674                 }
5675
5676                 err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5677                                         sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5678                 if (err)
5679                         goto err_out;
5680
5681                 mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5682
5683                 mod_btf->btf = btf;
5684                 mod_btf->id = id;
5685                 mod_btf->fd = fd;
5686                 mod_btf->name = strdup(name);
5687                 if (!mod_btf->name) {
5688                         err = -ENOMEM;
5689                         goto err_out;
5690                 }
5691                 continue;
5692
5693 err_out:
5694                 close(fd);
5695                 return err;
5696         }
5697
5698         return 0;
5699 }
5700
5701 static struct bpf_core_cand_list *
5702 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5703 {
5704         struct bpf_core_cand local_cand = {};
5705         struct bpf_core_cand_list *cands;
5706         const struct btf *main_btf;
5707         const struct btf_type *local_t;
5708         const char *local_name;
5709         size_t local_essent_len;
5710         int err, i;
5711
5712         local_cand.btf = local_btf;
5713         local_cand.id = local_type_id;
5714         local_t = btf__type_by_id(local_btf, local_type_id);
5715         if (!local_t)
5716                 return ERR_PTR(-EINVAL);
5717
5718         local_name = btf__name_by_offset(local_btf, local_t->name_off);
5719         if (str_is_empty(local_name))
5720                 return ERR_PTR(-EINVAL);
5721         local_essent_len = bpf_core_essential_name_len(local_name);
5722
5723         cands = calloc(1, sizeof(*cands));
5724         if (!cands)
5725                 return ERR_PTR(-ENOMEM);
5726
5727         /* Attempt to find target candidates in vmlinux BTF first */
5728         main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5729         err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5730         if (err)
5731                 goto err_out;
5732
5733         /* if vmlinux BTF has any candidate, don't got for module BTFs */
5734         if (cands->len)
5735                 return cands;
5736
5737         /* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5738         if (obj->btf_vmlinux_override)
5739                 return cands;
5740
5741         /* now look through module BTFs, trying to still find candidates */
5742         err = load_module_btfs(obj);
5743         if (err)
5744                 goto err_out;
5745
5746         for (i = 0; i < obj->btf_module_cnt; i++) {
5747                 err = bpf_core_add_cands(&local_cand, local_essent_len,
5748                                          obj->btf_modules[i].btf,
5749                                          obj->btf_modules[i].name,
5750                                          btf__type_cnt(obj->btf_vmlinux),
5751                                          cands);
5752                 if (err)
5753                         goto err_out;
5754         }
5755
5756         return cands;
5757 err_out:
5758         bpf_core_free_cands(cands);
5759         return ERR_PTR(err);
5760 }
5761
5762 /* Check local and target types for compatibility. This check is used for
5763  * type-based CO-RE relocations and follow slightly different rules than
5764  * field-based relocations. This function assumes that root types were already
5765  * checked for name match. Beyond that initial root-level name check, names
5766  * are completely ignored. Compatibility rules are as follows:
5767  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5768  *     kind should match for local and target types (i.e., STRUCT is not
5769  *     compatible with UNION);
5770  *   - for ENUMs, the size is ignored;
5771  *   - for INT, size and signedness are ignored;
5772  *   - for ARRAY, dimensionality is ignored, element types are checked for
5773  *     compatibility recursively;
5774  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5775  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5776  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5777  *     number of input args and compatible return and argument types.
5778  * These rules are not set in stone and probably will be adjusted as we get
5779  * more experience with using BPF CO-RE relocations.
5780  */
5781 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5782                               const struct btf *targ_btf, __u32 targ_id)
5783 {
5784         return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5785 }
5786
5787 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5788                          const struct btf *targ_btf, __u32 targ_id)
5789 {
5790         return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5791 }
5792
5793 static size_t bpf_core_hash_fn(const long key, void *ctx)
5794 {
5795         return key;
5796 }
5797
5798 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5799 {
5800         return k1 == k2;
5801 }
5802
5803 static int record_relo_core(struct bpf_program *prog,
5804                             const struct bpf_core_relo *core_relo, int insn_idx)
5805 {
5806         struct reloc_desc *relos, *relo;
5807
5808         relos = libbpf_reallocarray(prog->reloc_desc,
5809                                     prog->nr_reloc + 1, sizeof(*relos));
5810         if (!relos)
5811                 return -ENOMEM;
5812         relo = &relos[prog->nr_reloc];
5813         relo->type = RELO_CORE;
5814         relo->insn_idx = insn_idx;
5815         relo->core_relo = core_relo;
5816         prog->reloc_desc = relos;
5817         prog->nr_reloc++;
5818         return 0;
5819 }
5820
5821 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5822 {
5823         struct reloc_desc *relo;
5824         int i;
5825
5826         for (i = 0; i < prog->nr_reloc; i++) {
5827                 relo = &prog->reloc_desc[i];
5828                 if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5829                         continue;
5830
5831                 return relo->core_relo;
5832         }
5833
5834         return NULL;
5835 }
5836
5837 static int bpf_core_resolve_relo(struct bpf_program *prog,
5838                                  const struct bpf_core_relo *relo,
5839                                  int relo_idx,
5840                                  const struct btf *local_btf,
5841                                  struct hashmap *cand_cache,
5842                                  struct bpf_core_relo_res *targ_res)
5843 {
5844         struct bpf_core_spec specs_scratch[3] = {};
5845         struct bpf_core_cand_list *cands = NULL;
5846         const char *prog_name = prog->name;
5847         const struct btf_type *local_type;
5848         const char *local_name;
5849         __u32 local_id = relo->type_id;
5850         int err;
5851
5852         local_type = btf__type_by_id(local_btf, local_id);
5853         if (!local_type)
5854                 return -EINVAL;
5855
5856         local_name = btf__name_by_offset(local_btf, local_type->name_off);
5857         if (!local_name)
5858                 return -EINVAL;
5859
5860         if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5861             !hashmap__find(cand_cache, local_id, &cands)) {
5862                 cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5863                 if (IS_ERR(cands)) {
5864                         pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5865                                 prog_name, relo_idx, local_id, btf_kind_str(local_type),
5866                                 local_name, PTR_ERR(cands));
5867                         return PTR_ERR(cands);
5868                 }
5869                 err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5870                 if (err) {
5871                         bpf_core_free_cands(cands);
5872                         return err;
5873                 }
5874         }
5875
5876         return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5877                                        targ_res);
5878 }
5879
5880 static int
5881 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5882 {
5883         const struct btf_ext_info_sec *sec;
5884         struct bpf_core_relo_res targ_res;
5885         const struct bpf_core_relo *rec;
5886         const struct btf_ext_info *seg;
5887         struct hashmap_entry *entry;
5888         struct hashmap *cand_cache = NULL;
5889         struct bpf_program *prog;
5890         struct bpf_insn *insn;
5891         const char *sec_name;
5892         int i, err = 0, insn_idx, sec_idx, sec_num;
5893
5894         if (obj->btf_ext->core_relo_info.len == 0)
5895                 return 0;
5896
5897         if (targ_btf_path) {
5898                 obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5899                 err = libbpf_get_error(obj->btf_vmlinux_override);
5900                 if (err) {
5901                         pr_warn("failed to parse target BTF: %d\n", err);
5902                         return err;
5903                 }
5904         }
5905
5906         cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5907         if (IS_ERR(cand_cache)) {
5908                 err = PTR_ERR(cand_cache);
5909                 goto out;
5910         }
5911
5912         seg = &obj->btf_ext->core_relo_info;
5913         sec_num = 0;
5914         for_each_btf_ext_sec(seg, sec) {
5915                 sec_idx = seg->sec_idxs[sec_num];
5916                 sec_num++;
5917
5918                 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5919                 if (str_is_empty(sec_name)) {
5920                         err = -EINVAL;
5921                         goto out;
5922                 }
5923
5924                 pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5925
5926                 for_each_btf_ext_rec(seg, sec, i, rec) {
5927                         if (rec->insn_off % BPF_INSN_SZ)
5928                                 return -EINVAL;
5929                         insn_idx = rec->insn_off / BPF_INSN_SZ;
5930                         prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5931                         if (!prog) {
5932                                 /* When __weak subprog is "overridden" by another instance
5933                                  * of the subprog from a different object file, linker still
5934                                  * appends all the .BTF.ext info that used to belong to that
5935                                  * eliminated subprogram.
5936                                  * This is similar to what x86-64 linker does for relocations.
5937                                  * So just ignore such relocations just like we ignore
5938                                  * subprog instructions when discovering subprograms.
5939                                  */
5940                                 pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5941                                          sec_name, i, insn_idx);
5942                                 continue;
5943                         }
5944                         /* no need to apply CO-RE relocation if the program is
5945                          * not going to be loaded
5946                          */
5947                         if (!prog->autoload)
5948                                 continue;
5949
5950                         /* adjust insn_idx from section frame of reference to the local
5951                          * program's frame of reference; (sub-)program code is not yet
5952                          * relocated, so it's enough to just subtract in-section offset
5953                          */
5954                         insn_idx = insn_idx - prog->sec_insn_off;
5955                         if (insn_idx >= prog->insns_cnt)
5956                                 return -EINVAL;
5957                         insn = &prog->insns[insn_idx];
5958
5959                         err = record_relo_core(prog, rec, insn_idx);
5960                         if (err) {
5961                                 pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5962                                         prog->name, i, err);
5963                                 goto out;
5964                         }
5965
5966                         if (prog->obj->gen_loader)
5967                                 continue;
5968
5969                         err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5970                         if (err) {
5971                                 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5972                                         prog->name, i, err);
5973                                 goto out;
5974                         }
5975
5976                         err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5977                         if (err) {
5978                                 pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5979                                         prog->name, i, insn_idx, err);
5980                                 goto out;
5981                         }
5982                 }
5983         }
5984
5985 out:
5986         /* obj->btf_vmlinux and module BTFs are freed after object load */
5987         btf__free(obj->btf_vmlinux_override);
5988         obj->btf_vmlinux_override = NULL;
5989
5990         if (!IS_ERR_OR_NULL(cand_cache)) {
5991                 hashmap__for_each_entry(cand_cache, entry, i) {
5992                         bpf_core_free_cands(entry->pvalue);
5993                 }
5994                 hashmap__free(cand_cache);
5995         }
5996         return err;
5997 }
5998
5999 /* base map load ldimm64 special constant, used also for log fixup logic */
6000 #define POISON_LDIMM64_MAP_BASE 2001000000
6001 #define POISON_LDIMM64_MAP_PFX "200100"
6002
6003 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6004                                int insn_idx, struct bpf_insn *insn,
6005                                int map_idx, const struct bpf_map *map)
6006 {
6007         int i;
6008
6009         pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6010                  prog->name, relo_idx, insn_idx, map_idx, map->name);
6011
6012         /* we turn single ldimm64 into two identical invalid calls */
6013         for (i = 0; i < 2; i++) {
6014                 insn->code = BPF_JMP | BPF_CALL;
6015                 insn->dst_reg = 0;
6016                 insn->src_reg = 0;
6017                 insn->off = 0;
6018                 /* if this instruction is reachable (not a dead code),
6019                  * verifier will complain with something like:
6020                  * invalid func unknown#2001000123
6021                  * where lower 123 is map index into obj->maps[] array
6022                  */
6023                 insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6024
6025                 insn++;
6026         }
6027 }
6028
6029 /* unresolved kfunc call special constant, used also for log fixup logic */
6030 #define POISON_CALL_KFUNC_BASE 2002000000
6031 #define POISON_CALL_KFUNC_PFX "2002"
6032
6033 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6034                               int insn_idx, struct bpf_insn *insn,
6035                               int ext_idx, const struct extern_desc *ext)
6036 {
6037         pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6038                  prog->name, relo_idx, insn_idx, ext->name);
6039
6040         /* we turn kfunc call into invalid helper call with identifiable constant */
6041         insn->code = BPF_JMP | BPF_CALL;
6042         insn->dst_reg = 0;
6043         insn->src_reg = 0;
6044         insn->off = 0;
6045         /* if this instruction is reachable (not a dead code),
6046          * verifier will complain with something like:
6047          * invalid func unknown#2001000123
6048          * where lower 123 is extern index into obj->externs[] array
6049          */
6050         insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6051 }
6052
6053 /* Relocate data references within program code:
6054  *  - map references;
6055  *  - global variable references;
6056  *  - extern references.
6057  */
6058 static int
6059 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6060 {
6061         int i;
6062
6063         for (i = 0; i < prog->nr_reloc; i++) {
6064                 struct reloc_desc *relo = &prog->reloc_desc[i];
6065                 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6066                 const struct bpf_map *map;
6067                 struct extern_desc *ext;
6068
6069                 switch (relo->type) {
6070                 case RELO_LD64:
6071                         map = &obj->maps[relo->map_idx];
6072                         if (obj->gen_loader) {
6073                                 insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6074                                 insn[0].imm = relo->map_idx;
6075                         } else if (map->autocreate) {
6076                                 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6077                                 insn[0].imm = map->fd;
6078                         } else {
6079                                 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6080                                                    relo->map_idx, map);
6081                         }
6082                         break;
6083                 case RELO_DATA:
6084                         map = &obj->maps[relo->map_idx];
6085                         insn[1].imm = insn[0].imm + relo->sym_off;
6086                         if (obj->gen_loader) {
6087                                 insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6088                                 insn[0].imm = relo->map_idx;
6089                         } else if (map->autocreate) {
6090                                 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6091                                 insn[0].imm = map->fd;
6092                         } else {
6093                                 poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6094                                                    relo->map_idx, map);
6095                         }
6096                         break;
6097                 case RELO_EXTERN_LD64:
6098                         ext = &obj->externs[relo->ext_idx];
6099                         if (ext->type == EXT_KCFG) {
6100                                 if (obj->gen_loader) {
6101                                         insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6102                                         insn[0].imm = obj->kconfig_map_idx;
6103                                 } else {
6104                                         insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6105                                         insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6106                                 }
6107                                 insn[1].imm = ext->kcfg.data_off;
6108                         } else /* EXT_KSYM */ {
6109                                 if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6110                                         insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6111                                         insn[0].imm = ext->ksym.kernel_btf_id;
6112                                         insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6113                                 } else { /* typeless ksyms or unresolved typed ksyms */
6114                                         insn[0].imm = (__u32)ext->ksym.addr;
6115                                         insn[1].imm = ext->ksym.addr >> 32;
6116                                 }
6117                         }
6118                         break;
6119                 case RELO_EXTERN_CALL:
6120                         ext = &obj->externs[relo->ext_idx];
6121                         insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6122                         if (ext->is_set) {
6123                                 insn[0].imm = ext->ksym.kernel_btf_id;
6124                                 insn[0].off = ext->ksym.btf_fd_idx;
6125                         } else { /* unresolved weak kfunc call */
6126                                 poison_kfunc_call(prog, i, relo->insn_idx, insn,
6127                                                   relo->ext_idx, ext);
6128                         }
6129                         break;
6130                 case RELO_SUBPROG_ADDR:
6131                         if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6132                                 pr_warn("prog '%s': relo #%d: bad insn\n",
6133                                         prog->name, i);
6134                                 return -EINVAL;
6135                         }
6136                         /* handled already */
6137                         break;
6138                 case RELO_CALL:
6139                         /* handled already */
6140                         break;
6141                 case RELO_CORE:
6142                         /* will be handled by bpf_program_record_relos() */
6143                         break;
6144                 default:
6145                         pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6146                                 prog->name, i, relo->type);
6147                         return -EINVAL;
6148                 }
6149         }
6150
6151         return 0;
6152 }
6153
6154 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6155                                     const struct bpf_program *prog,
6156                                     const struct btf_ext_info *ext_info,
6157                                     void **prog_info, __u32 *prog_rec_cnt,
6158                                     __u32 *prog_rec_sz)
6159 {
6160         void *copy_start = NULL, *copy_end = NULL;
6161         void *rec, *rec_end, *new_prog_info;
6162         const struct btf_ext_info_sec *sec;
6163         size_t old_sz, new_sz;
6164         int i, sec_num, sec_idx, off_adj;
6165
6166         sec_num = 0;
6167         for_each_btf_ext_sec(ext_info, sec) {
6168                 sec_idx = ext_info->sec_idxs[sec_num];
6169                 sec_num++;
6170                 if (prog->sec_idx != sec_idx)
6171                         continue;
6172
6173                 for_each_btf_ext_rec(ext_info, sec, i, rec) {
6174                         __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6175
6176                         if (insn_off < prog->sec_insn_off)
6177                                 continue;
6178                         if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6179                                 break;
6180
6181                         if (!copy_start)
6182                                 copy_start = rec;
6183                         copy_end = rec + ext_info->rec_size;
6184                 }
6185
6186                 if (!copy_start)
6187                         return -ENOENT;
6188
6189                 /* append func/line info of a given (sub-)program to the main
6190                  * program func/line info
6191                  */
6192                 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6193                 new_sz = old_sz + (copy_end - copy_start);
6194                 new_prog_info = realloc(*prog_info, new_sz);
6195                 if (!new_prog_info)
6196                         return -ENOMEM;
6197                 *prog_info = new_prog_info;
6198                 *prog_rec_cnt = new_sz / ext_info->rec_size;
6199                 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6200
6201                 /* Kernel instruction offsets are in units of 8-byte
6202                  * instructions, while .BTF.ext instruction offsets generated
6203                  * by Clang are in units of bytes. So convert Clang offsets
6204                  * into kernel offsets and adjust offset according to program
6205                  * relocated position.
6206                  */
6207                 off_adj = prog->sub_insn_off - prog->sec_insn_off;
6208                 rec = new_prog_info + old_sz;
6209                 rec_end = new_prog_info + new_sz;
6210                 for (; rec < rec_end; rec += ext_info->rec_size) {
6211                         __u32 *insn_off = rec;
6212
6213                         *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6214                 }
6215                 *prog_rec_sz = ext_info->rec_size;
6216                 return 0;
6217         }
6218
6219         return -ENOENT;
6220 }
6221
6222 static int
6223 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6224                               struct bpf_program *main_prog,
6225                               const struct bpf_program *prog)
6226 {
6227         int err;
6228
6229         /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6230          * supprot func/line info
6231          */
6232         if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6233                 return 0;
6234
6235         /* only attempt func info relocation if main program's func_info
6236          * relocation was successful
6237          */
6238         if (main_prog != prog && !main_prog->func_info)
6239                 goto line_info;
6240
6241         err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6242                                        &main_prog->func_info,
6243                                        &main_prog->func_info_cnt,
6244                                        &main_prog->func_info_rec_size);
6245         if (err) {
6246                 if (err != -ENOENT) {
6247                         pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6248                                 prog->name, err);
6249                         return err;
6250                 }
6251                 if (main_prog->func_info) {
6252                         /*
6253                          * Some info has already been found but has problem
6254                          * in the last btf_ext reloc. Must have to error out.
6255                          */
6256                         pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6257                         return err;
6258                 }
6259                 /* Have problem loading the very first info. Ignore the rest. */
6260                 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6261                         prog->name);
6262         }
6263
6264 line_info:
6265         /* don't relocate line info if main program's relocation failed */
6266         if (main_prog != prog && !main_prog->line_info)
6267                 return 0;
6268
6269         err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6270                                        &main_prog->line_info,
6271                                        &main_prog->line_info_cnt,
6272                                        &main_prog->line_info_rec_size);
6273         if (err) {
6274                 if (err != -ENOENT) {
6275                         pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6276                                 prog->name, err);
6277                         return err;
6278                 }
6279                 if (main_prog->line_info) {
6280                         /*
6281                          * Some info has already been found but has problem
6282                          * in the last btf_ext reloc. Must have to error out.
6283                          */
6284                         pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6285                         return err;
6286                 }
6287                 /* Have problem loading the very first info. Ignore the rest. */
6288                 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6289                         prog->name);
6290         }
6291         return 0;
6292 }
6293
6294 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6295 {
6296         size_t insn_idx = *(const size_t *)key;
6297         const struct reloc_desc *relo = elem;
6298
6299         if (insn_idx == relo->insn_idx)
6300                 return 0;
6301         return insn_idx < relo->insn_idx ? -1 : 1;
6302 }
6303
6304 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6305 {
6306         if (!prog->nr_reloc)
6307                 return NULL;
6308         return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6309                        sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6310 }
6311
6312 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6313 {
6314         int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6315         struct reloc_desc *relos;
6316         int i;
6317
6318         if (main_prog == subprog)
6319                 return 0;
6320         relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6321         /* if new count is zero, reallocarray can return a valid NULL result;
6322          * in this case the previous pointer will be freed, so we *have to*
6323          * reassign old pointer to the new value (even if it's NULL)
6324          */
6325         if (!relos && new_cnt)
6326                 return -ENOMEM;
6327         if (subprog->nr_reloc)
6328                 memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6329                        sizeof(*relos) * subprog->nr_reloc);
6330
6331         for (i = main_prog->nr_reloc; i < new_cnt; i++)
6332                 relos[i].insn_idx += subprog->sub_insn_off;
6333         /* After insn_idx adjustment the 'relos' array is still sorted
6334          * by insn_idx and doesn't break bsearch.
6335          */
6336         main_prog->reloc_desc = relos;
6337         main_prog->nr_reloc = new_cnt;
6338         return 0;
6339 }
6340
6341 static int
6342 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6343                                 struct bpf_program *subprog)
6344 {
6345        struct bpf_insn *insns;
6346        size_t new_cnt;
6347        int err;
6348
6349        subprog->sub_insn_off = main_prog->insns_cnt;
6350
6351        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6352        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6353        if (!insns) {
6354                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6355                return -ENOMEM;
6356        }
6357        main_prog->insns = insns;
6358        main_prog->insns_cnt = new_cnt;
6359
6360        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6361               subprog->insns_cnt * sizeof(*insns));
6362
6363        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6364                 main_prog->name, subprog->insns_cnt, subprog->name);
6365
6366        /* The subprog insns are now appended. Append its relos too. */
6367        err = append_subprog_relos(main_prog, subprog);
6368        if (err)
6369                return err;
6370        return 0;
6371 }
6372
6373 static int
6374 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6375                        struct bpf_program *prog)
6376 {
6377         size_t sub_insn_idx, insn_idx;
6378         struct bpf_program *subprog;
6379         struct reloc_desc *relo;
6380         struct bpf_insn *insn;
6381         int err;
6382
6383         err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6384         if (err)
6385                 return err;
6386
6387         for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6388                 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6389                 if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6390                         continue;
6391
6392                 relo = find_prog_insn_relo(prog, insn_idx);
6393                 if (relo && relo->type == RELO_EXTERN_CALL)
6394                         /* kfunc relocations will be handled later
6395                          * in bpf_object__relocate_data()
6396                          */
6397                         continue;
6398                 if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6399                         pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6400                                 prog->name, insn_idx, relo->type);
6401                         return -LIBBPF_ERRNO__RELOC;
6402                 }
6403                 if (relo) {
6404                         /* sub-program instruction index is a combination of
6405                          * an offset of a symbol pointed to by relocation and
6406                          * call instruction's imm field; for global functions,
6407                          * call always has imm = -1, but for static functions
6408                          * relocation is against STT_SECTION and insn->imm
6409                          * points to a start of a static function
6410                          *
6411                          * for subprog addr relocation, the relo->sym_off + insn->imm is
6412                          * the byte offset in the corresponding section.
6413                          */
6414                         if (relo->type == RELO_CALL)
6415                                 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6416                         else
6417                                 sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6418                 } else if (insn_is_pseudo_func(insn)) {
6419                         /*
6420                          * RELO_SUBPROG_ADDR relo is always emitted even if both
6421                          * functions are in the same section, so it shouldn't reach here.
6422                          */
6423                         pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6424                                 prog->name, insn_idx);
6425                         return -LIBBPF_ERRNO__RELOC;
6426                 } else {
6427                         /* if subprogram call is to a static function within
6428                          * the same ELF section, there won't be any relocation
6429                          * emitted, but it also means there is no additional
6430                          * offset necessary, insns->imm is relative to
6431                          * instruction's original position within the section
6432                          */
6433                         sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6434                 }
6435
6436                 /* we enforce that sub-programs should be in .text section */
6437                 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6438                 if (!subprog) {
6439                         pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6440                                 prog->name);
6441                         return -LIBBPF_ERRNO__RELOC;
6442                 }
6443
6444                 /* if it's the first call instruction calling into this
6445                  * subprogram (meaning this subprog hasn't been processed
6446                  * yet) within the context of current main program:
6447                  *   - append it at the end of main program's instructions blog;
6448                  *   - process is recursively, while current program is put on hold;
6449                  *   - if that subprogram calls some other not yet processes
6450                  *   subprogram, same thing will happen recursively until
6451                  *   there are no more unprocesses subprograms left to append
6452                  *   and relocate.
6453                  */
6454                 if (subprog->sub_insn_off == 0) {
6455                         err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6456                         if (err)
6457                                 return err;
6458                         err = bpf_object__reloc_code(obj, main_prog, subprog);
6459                         if (err)
6460                                 return err;
6461                 }
6462
6463                 /* main_prog->insns memory could have been re-allocated, so
6464                  * calculate pointer again
6465                  */
6466                 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6467                 /* calculate correct instruction position within current main
6468                  * prog; each main prog can have a different set of
6469                  * subprograms appended (potentially in different order as
6470                  * well), so position of any subprog can be different for
6471                  * different main programs
6472                  */
6473                 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6474
6475                 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6476                          prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6477         }
6478
6479         return 0;
6480 }
6481
6482 /*
6483  * Relocate sub-program calls.
6484  *
6485  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6486  * main prog) is processed separately. For each subprog (non-entry functions,
6487  * that can be called from either entry progs or other subprogs) gets their
6488  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6489  * hasn't been yet appended and relocated within current main prog. Once its
6490  * relocated, sub_insn_off will point at the position within current main prog
6491  * where given subprog was appended. This will further be used to relocate all
6492  * the call instructions jumping into this subprog.
6493  *
6494  * We start with main program and process all call instructions. If the call
6495  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6496  * is zero), subprog instructions are appended at the end of main program's
6497  * instruction array. Then main program is "put on hold" while we recursively
6498  * process newly appended subprogram. If that subprogram calls into another
6499  * subprogram that hasn't been appended, new subprogram is appended again to
6500  * the *main* prog's instructions (subprog's instructions are always left
6501  * untouched, as they need to be in unmodified state for subsequent main progs
6502  * and subprog instructions are always sent only as part of a main prog) and
6503  * the process continues recursively. Once all the subprogs called from a main
6504  * prog or any of its subprogs are appended (and relocated), all their
6505  * positions within finalized instructions array are known, so it's easy to
6506  * rewrite call instructions with correct relative offsets, corresponding to
6507  * desired target subprog.
6508  *
6509  * Its important to realize that some subprogs might not be called from some
6510  * main prog and any of its called/used subprogs. Those will keep their
6511  * subprog->sub_insn_off as zero at all times and won't be appended to current
6512  * main prog and won't be relocated within the context of current main prog.
6513  * They might still be used from other main progs later.
6514  *
6515  * Visually this process can be shown as below. Suppose we have two main
6516  * programs mainA and mainB and BPF object contains three subprogs: subA,
6517  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6518  * subC both call subB:
6519  *
6520  *        +--------+ +-------+
6521  *        |        v v       |
6522  *     +--+---+ +--+-+-+ +---+--+
6523  *     | subA | | subB | | subC |
6524  *     +--+---+ +------+ +---+--+
6525  *        ^                  ^
6526  *        |                  |
6527  *    +---+-------+   +------+----+
6528  *    |   mainA   |   |   mainB   |
6529  *    +-----------+   +-----------+
6530  *
6531  * We'll start relocating mainA, will find subA, append it and start
6532  * processing sub A recursively:
6533  *
6534  *    +-----------+------+
6535  *    |   mainA   | subA |
6536  *    +-----------+------+
6537  *
6538  * At this point we notice that subB is used from subA, so we append it and
6539  * relocate (there are no further subcalls from subB):
6540  *
6541  *    +-----------+------+------+
6542  *    |   mainA   | subA | subB |
6543  *    +-----------+------+------+
6544  *
6545  * At this point, we relocate subA calls, then go one level up and finish with
6546  * relocatin mainA calls. mainA is done.
6547  *
6548  * For mainB process is similar but results in different order. We start with
6549  * mainB and skip subA and subB, as mainB never calls them (at least
6550  * directly), but we see subC is needed, so we append and start processing it:
6551  *
6552  *    +-----------+------+
6553  *    |   mainB   | subC |
6554  *    +-----------+------+
6555  * Now we see subC needs subB, so we go back to it, append and relocate it:
6556  *
6557  *    +-----------+------+------+
6558  *    |   mainB   | subC | subB |
6559  *    +-----------+------+------+
6560  *
6561  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6562  */
6563 static int
6564 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6565 {
6566         struct bpf_program *subprog;
6567         int i, err;
6568
6569         /* mark all subprogs as not relocated (yet) within the context of
6570          * current main program
6571          */
6572         for (i = 0; i < obj->nr_programs; i++) {
6573                 subprog = &obj->programs[i];
6574                 if (!prog_is_subprog(obj, subprog))
6575                         continue;
6576
6577                 subprog->sub_insn_off = 0;
6578         }
6579
6580         err = bpf_object__reloc_code(obj, prog, prog);
6581         if (err)
6582                 return err;
6583
6584         return 0;
6585 }
6586
6587 static void
6588 bpf_object__free_relocs(struct bpf_object *obj)
6589 {
6590         struct bpf_program *prog;
6591         int i;
6592
6593         /* free up relocation descriptors */
6594         for (i = 0; i < obj->nr_programs; i++) {
6595                 prog = &obj->programs[i];
6596                 zfree(&prog->reloc_desc);
6597                 prog->nr_reloc = 0;
6598         }
6599 }
6600
6601 static int cmp_relocs(const void *_a, const void *_b)
6602 {
6603         const struct reloc_desc *a = _a;
6604         const struct reloc_desc *b = _b;
6605
6606         if (a->insn_idx != b->insn_idx)
6607                 return a->insn_idx < b->insn_idx ? -1 : 1;
6608
6609         /* no two relocations should have the same insn_idx, but ... */
6610         if (a->type != b->type)
6611                 return a->type < b->type ? -1 : 1;
6612
6613         return 0;
6614 }
6615
6616 static void bpf_object__sort_relos(struct bpf_object *obj)
6617 {
6618         int i;
6619
6620         for (i = 0; i < obj->nr_programs; i++) {
6621                 struct bpf_program *p = &obj->programs[i];
6622
6623                 if (!p->nr_reloc)
6624                         continue;
6625
6626                 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6627         }
6628 }
6629
6630 static int
6631 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6632 {
6633         struct bpf_program *prog;
6634         size_t i, j;
6635         int err;
6636
6637         if (obj->btf_ext) {
6638                 err = bpf_object__relocate_core(obj, targ_btf_path);
6639                 if (err) {
6640                         pr_warn("failed to perform CO-RE relocations: %d\n",
6641                                 err);
6642                         return err;
6643                 }
6644                 bpf_object__sort_relos(obj);
6645         }
6646
6647         /* Before relocating calls pre-process relocations and mark
6648          * few ld_imm64 instructions that points to subprogs.
6649          * Otherwise bpf_object__reloc_code() later would have to consider
6650          * all ld_imm64 insns as relocation candidates. That would
6651          * reduce relocation speed, since amount of find_prog_insn_relo()
6652          * would increase and most of them will fail to find a relo.
6653          */
6654         for (i = 0; i < obj->nr_programs; i++) {
6655                 prog = &obj->programs[i];
6656                 for (j = 0; j < prog->nr_reloc; j++) {
6657                         struct reloc_desc *relo = &prog->reloc_desc[j];
6658                         struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6659
6660                         /* mark the insn, so it's recognized by insn_is_pseudo_func() */
6661                         if (relo->type == RELO_SUBPROG_ADDR)
6662                                 insn[0].src_reg = BPF_PSEUDO_FUNC;
6663                 }
6664         }
6665
6666         /* relocate subprogram calls and append used subprograms to main
6667          * programs; each copy of subprogram code needs to be relocated
6668          * differently for each main program, because its code location might
6669          * have changed.
6670          * Append subprog relos to main programs to allow data relos to be
6671          * processed after text is completely relocated.
6672          */
6673         for (i = 0; i < obj->nr_programs; i++) {
6674                 prog = &obj->programs[i];
6675                 /* sub-program's sub-calls are relocated within the context of
6676                  * its main program only
6677                  */
6678                 if (prog_is_subprog(obj, prog))
6679                         continue;
6680                 if (!prog->autoload)
6681                         continue;
6682
6683                 err = bpf_object__relocate_calls(obj, prog);
6684                 if (err) {
6685                         pr_warn("prog '%s': failed to relocate calls: %d\n",
6686                                 prog->name, err);
6687                         return err;
6688                 }
6689
6690                 /* Now, also append exception callback if it has not been done already. */
6691                 if (prog->exception_cb_idx >= 0) {
6692                         struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
6693
6694                         /* Calling exception callback directly is disallowed, which the
6695                          * verifier will reject later. In case it was processed already,
6696                          * we can skip this step, otherwise for all other valid cases we
6697                          * have to append exception callback now.
6698                          */
6699                         if (subprog->sub_insn_off == 0) {
6700                                 err = bpf_object__append_subprog_code(obj, prog, subprog);
6701                                 if (err)
6702                                         return err;
6703                                 err = bpf_object__reloc_code(obj, prog, subprog);
6704                                 if (err)
6705                                         return err;
6706                         }
6707                 }
6708         }
6709         /* Process data relos for main programs */
6710         for (i = 0; i < obj->nr_programs; i++) {
6711                 prog = &obj->programs[i];
6712                 if (prog_is_subprog(obj, prog))
6713                         continue;
6714                 if (!prog->autoload)
6715                         continue;
6716                 err = bpf_object__relocate_data(obj, prog);
6717                 if (err) {
6718                         pr_warn("prog '%s': failed to relocate data references: %d\n",
6719                                 prog->name, err);
6720                         return err;
6721                 }
6722         }
6723
6724         return 0;
6725 }
6726
6727 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6728                                             Elf64_Shdr *shdr, Elf_Data *data);
6729
6730 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6731                                          Elf64_Shdr *shdr, Elf_Data *data)
6732 {
6733         const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6734         int i, j, nrels, new_sz;
6735         const struct btf_var_secinfo *vi = NULL;
6736         const struct btf_type *sec, *var, *def;
6737         struct bpf_map *map = NULL, *targ_map = NULL;
6738         struct bpf_program *targ_prog = NULL;
6739         bool is_prog_array, is_map_in_map;
6740         const struct btf_member *member;
6741         const char *name, *mname, *type;
6742         unsigned int moff;
6743         Elf64_Sym *sym;
6744         Elf64_Rel *rel;
6745         void *tmp;
6746
6747         if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6748                 return -EINVAL;
6749         sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6750         if (!sec)
6751                 return -EINVAL;
6752
6753         nrels = shdr->sh_size / shdr->sh_entsize;
6754         for (i = 0; i < nrels; i++) {
6755                 rel = elf_rel_by_idx(data, i);
6756                 if (!rel) {
6757                         pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6758                         return -LIBBPF_ERRNO__FORMAT;
6759                 }
6760
6761                 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6762                 if (!sym) {
6763                         pr_warn(".maps relo #%d: symbol %zx not found\n",
6764                                 i, (size_t)ELF64_R_SYM(rel->r_info));
6765                         return -LIBBPF_ERRNO__FORMAT;
6766                 }
6767                 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6768
6769                 pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6770                          i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6771                          (size_t)rel->r_offset, sym->st_name, name);
6772
6773                 for (j = 0; j < obj->nr_maps; j++) {
6774                         map = &obj->maps[j];
6775                         if (map->sec_idx != obj->efile.btf_maps_shndx)
6776                                 continue;
6777
6778                         vi = btf_var_secinfos(sec) + map->btf_var_idx;
6779                         if (vi->offset <= rel->r_offset &&
6780                             rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6781                                 break;
6782                 }
6783                 if (j == obj->nr_maps) {
6784                         pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6785                                 i, name, (size_t)rel->r_offset);
6786                         return -EINVAL;
6787                 }
6788
6789                 is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6790                 is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6791                 type = is_map_in_map ? "map" : "prog";
6792                 if (is_map_in_map) {
6793                         if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6794                                 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6795                                         i, name);
6796                                 return -LIBBPF_ERRNO__RELOC;
6797                         }
6798                         if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6799                             map->def.key_size != sizeof(int)) {
6800                                 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6801                                         i, map->name, sizeof(int));
6802                                 return -EINVAL;
6803                         }
6804                         targ_map = bpf_object__find_map_by_name(obj, name);
6805                         if (!targ_map) {
6806                                 pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6807                                         i, name);
6808                                 return -ESRCH;
6809                         }
6810                 } else if (is_prog_array) {
6811                         targ_prog = bpf_object__find_program_by_name(obj, name);
6812                         if (!targ_prog) {
6813                                 pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6814                                         i, name);
6815                                 return -ESRCH;
6816                         }
6817                         if (targ_prog->sec_idx != sym->st_shndx ||
6818                             targ_prog->sec_insn_off * 8 != sym->st_value ||
6819                             prog_is_subprog(obj, targ_prog)) {
6820                                 pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6821                                         i, name);
6822                                 return -LIBBPF_ERRNO__RELOC;
6823                         }
6824                 } else {
6825                         return -EINVAL;
6826                 }
6827
6828                 var = btf__type_by_id(obj->btf, vi->type);
6829                 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6830                 if (btf_vlen(def) == 0)
6831                         return -EINVAL;
6832                 member = btf_members(def) + btf_vlen(def) - 1;
6833                 mname = btf__name_by_offset(obj->btf, member->name_off);
6834                 if (strcmp(mname, "values"))
6835                         return -EINVAL;
6836
6837                 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6838                 if (rel->r_offset - vi->offset < moff)
6839                         return -EINVAL;
6840
6841                 moff = rel->r_offset - vi->offset - moff;
6842                 /* here we use BPF pointer size, which is always 64 bit, as we
6843                  * are parsing ELF that was built for BPF target
6844                  */
6845                 if (moff % bpf_ptr_sz)
6846                         return -EINVAL;
6847                 moff /= bpf_ptr_sz;
6848                 if (moff >= map->init_slots_sz) {
6849                         new_sz = moff + 1;
6850                         tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6851                         if (!tmp)
6852                                 return -ENOMEM;
6853                         map->init_slots = tmp;
6854                         memset(map->init_slots + map->init_slots_sz, 0,
6855                                (new_sz - map->init_slots_sz) * host_ptr_sz);
6856                         map->init_slots_sz = new_sz;
6857                 }
6858                 map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6859
6860                 pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6861                          i, map->name, moff, type, name);
6862         }
6863
6864         return 0;
6865 }
6866
6867 static int bpf_object__collect_relos(struct bpf_object *obj)
6868 {
6869         int i, err;
6870
6871         for (i = 0; i < obj->efile.sec_cnt; i++) {
6872                 struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6873                 Elf64_Shdr *shdr;
6874                 Elf_Data *data;
6875                 int idx;
6876
6877                 if (sec_desc->sec_type != SEC_RELO)
6878                         continue;
6879
6880                 shdr = sec_desc->shdr;
6881                 data = sec_desc->data;
6882                 idx = shdr->sh_info;
6883
6884                 if (shdr->sh_type != SHT_REL) {
6885                         pr_warn("internal error at %d\n", __LINE__);
6886                         return -LIBBPF_ERRNO__INTERNAL;
6887                 }
6888
6889                 if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6890                         err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6891                 else if (idx == obj->efile.btf_maps_shndx)
6892                         err = bpf_object__collect_map_relos(obj, shdr, data);
6893                 else
6894                         err = bpf_object__collect_prog_relos(obj, shdr, data);
6895                 if (err)
6896                         return err;
6897         }
6898
6899         bpf_object__sort_relos(obj);
6900         return 0;
6901 }
6902
6903 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6904 {
6905         if (BPF_CLASS(insn->code) == BPF_JMP &&
6906             BPF_OP(insn->code) == BPF_CALL &&
6907             BPF_SRC(insn->code) == BPF_K &&
6908             insn->src_reg == 0 &&
6909             insn->dst_reg == 0) {
6910                     *func_id = insn->imm;
6911                     return true;
6912         }
6913         return false;
6914 }
6915
6916 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6917 {
6918         struct bpf_insn *insn = prog->insns;
6919         enum bpf_func_id func_id;
6920         int i;
6921
6922         if (obj->gen_loader)
6923                 return 0;
6924
6925         for (i = 0; i < prog->insns_cnt; i++, insn++) {
6926                 if (!insn_is_helper_call(insn, &func_id))
6927                         continue;
6928
6929                 /* on kernels that don't yet support
6930                  * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6931                  * to bpf_probe_read() which works well for old kernels
6932                  */
6933                 switch (func_id) {
6934                 case BPF_FUNC_probe_read_kernel:
6935                 case BPF_FUNC_probe_read_user:
6936                         if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6937                                 insn->imm = BPF_FUNC_probe_read;
6938                         break;
6939                 case BPF_FUNC_probe_read_kernel_str:
6940                 case BPF_FUNC_probe_read_user_str:
6941                         if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6942                                 insn->imm = BPF_FUNC_probe_read_str;
6943                         break;
6944                 default:
6945                         break;
6946                 }
6947         }
6948         return 0;
6949 }
6950
6951 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6952                                      int *btf_obj_fd, int *btf_type_id);
6953
6954 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6955 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6956                                     struct bpf_prog_load_opts *opts, long cookie)
6957 {
6958         enum sec_def_flags def = cookie;
6959
6960         /* old kernels might not support specifying expected_attach_type */
6961         if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6962                 opts->expected_attach_type = 0;
6963
6964         if (def & SEC_SLEEPABLE)
6965                 opts->prog_flags |= BPF_F_SLEEPABLE;
6966
6967         if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6968                 opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6969
6970         /* special check for usdt to use uprobe_multi link */
6971         if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
6972                 prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
6973
6974         if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6975                 int btf_obj_fd = 0, btf_type_id = 0, err;
6976                 const char *attach_name;
6977
6978                 attach_name = strchr(prog->sec_name, '/');
6979                 if (!attach_name) {
6980                         /* if BPF program is annotated with just SEC("fentry")
6981                          * (or similar) without declaratively specifying
6982                          * target, then it is expected that target will be
6983                          * specified with bpf_program__set_attach_target() at
6984                          * runtime before BPF object load step. If not, then
6985                          * there is nothing to load into the kernel as BPF
6986                          * verifier won't be able to validate BPF program
6987                          * correctness anyways.
6988                          */
6989                         pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6990                                 prog->name);
6991                         return -EINVAL;
6992                 }
6993                 attach_name++; /* skip over / */
6994
6995                 err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6996                 if (err)
6997                         return err;
6998
6999                 /* cache resolved BTF FD and BTF type ID in the prog */
7000                 prog->attach_btf_obj_fd = btf_obj_fd;
7001                 prog->attach_btf_id = btf_type_id;
7002
7003                 /* but by now libbpf common logic is not utilizing
7004                  * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7005                  * this callback is called after opts were populated by
7006                  * libbpf, so this callback has to update opts explicitly here
7007                  */
7008                 opts->attach_btf_obj_fd = btf_obj_fd;
7009                 opts->attach_btf_id = btf_type_id;
7010         }
7011         return 0;
7012 }
7013
7014 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7015
7016 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7017                                 struct bpf_insn *insns, int insns_cnt,
7018                                 const char *license, __u32 kern_version, int *prog_fd)
7019 {
7020         LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7021         const char *prog_name = NULL;
7022         char *cp, errmsg[STRERR_BUFSIZE];
7023         size_t log_buf_size = 0;
7024         char *log_buf = NULL, *tmp;
7025         int btf_fd, ret, err;
7026         bool own_log_buf = true;
7027         __u32 log_level = prog->log_level;
7028
7029         if (prog->type == BPF_PROG_TYPE_UNSPEC) {
7030                 /*
7031                  * The program type must be set.  Most likely we couldn't find a proper
7032                  * section definition at load time, and thus we didn't infer the type.
7033                  */
7034                 pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7035                         prog->name, prog->sec_name);
7036                 return -EINVAL;
7037         }
7038
7039         if (!insns || !insns_cnt)
7040                 return -EINVAL;
7041
7042         if (kernel_supports(obj, FEAT_PROG_NAME))
7043                 prog_name = prog->name;
7044         load_attr.attach_prog_fd = prog->attach_prog_fd;
7045         load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7046         load_attr.attach_btf_id = prog->attach_btf_id;
7047         load_attr.kern_version = kern_version;
7048         load_attr.prog_ifindex = prog->prog_ifindex;
7049
7050         /* specify func_info/line_info only if kernel supports them */
7051         btf_fd = bpf_object__btf_fd(obj);
7052         if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7053                 load_attr.prog_btf_fd = btf_fd;
7054                 load_attr.func_info = prog->func_info;
7055                 load_attr.func_info_rec_size = prog->func_info_rec_size;
7056                 load_attr.func_info_cnt = prog->func_info_cnt;
7057                 load_attr.line_info = prog->line_info;
7058                 load_attr.line_info_rec_size = prog->line_info_rec_size;
7059                 load_attr.line_info_cnt = prog->line_info_cnt;
7060         }
7061         load_attr.log_level = log_level;
7062         load_attr.prog_flags = prog->prog_flags;
7063         load_attr.fd_array = obj->fd_array;
7064
7065         /* adjust load_attr if sec_def provides custom preload callback */
7066         if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7067                 err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7068                 if (err < 0) {
7069                         pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7070                                 prog->name, err);
7071                         return err;
7072                 }
7073                 insns = prog->insns;
7074                 insns_cnt = prog->insns_cnt;
7075         }
7076
7077         /* allow prog_prepare_load_fn to change expected_attach_type */
7078         load_attr.expected_attach_type = prog->expected_attach_type;
7079
7080         if (obj->gen_loader) {
7081                 bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7082                                    license, insns, insns_cnt, &load_attr,
7083                                    prog - obj->programs);
7084                 *prog_fd = -1;
7085                 return 0;
7086         }
7087
7088 retry_load:
7089         /* if log_level is zero, we don't request logs initially even if
7090          * custom log_buf is specified; if the program load fails, then we'll
7091          * bump log_level to 1 and use either custom log_buf or we'll allocate
7092          * our own and retry the load to get details on what failed
7093          */
7094         if (log_level) {
7095                 if (prog->log_buf) {
7096                         log_buf = prog->log_buf;
7097                         log_buf_size = prog->log_size;
7098                         own_log_buf = false;
7099                 } else if (obj->log_buf) {
7100                         log_buf = obj->log_buf;
7101                         log_buf_size = obj->log_size;
7102                         own_log_buf = false;
7103                 } else {
7104                         log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7105                         tmp = realloc(log_buf, log_buf_size);
7106                         if (!tmp) {
7107                                 ret = -ENOMEM;
7108                                 goto out;
7109                         }
7110                         log_buf = tmp;
7111                         log_buf[0] = '\0';
7112                         own_log_buf = true;
7113                 }
7114         }
7115
7116         load_attr.log_buf = log_buf;
7117         load_attr.log_size = log_buf_size;
7118         load_attr.log_level = log_level;
7119
7120         ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7121         if (ret >= 0) {
7122                 if (log_level && own_log_buf) {
7123                         pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7124                                  prog->name, log_buf);
7125                 }
7126
7127                 if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7128                         struct bpf_map *map;
7129                         int i;
7130
7131                         for (i = 0; i < obj->nr_maps; i++) {
7132                                 map = &prog->obj->maps[i];
7133                                 if (map->libbpf_type != LIBBPF_MAP_RODATA)
7134                                         continue;
7135
7136                                 if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
7137                                         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7138                                         pr_warn("prog '%s': failed to bind map '%s': %s\n",
7139                                                 prog->name, map->real_name, cp);
7140                                         /* Don't fail hard if can't bind rodata. */
7141                                 }
7142                         }
7143                 }
7144
7145                 *prog_fd = ret;
7146                 ret = 0;
7147                 goto out;
7148         }
7149
7150         if (log_level == 0) {
7151                 log_level = 1;
7152                 goto retry_load;
7153         }
7154         /* On ENOSPC, increase log buffer size and retry, unless custom
7155          * log_buf is specified.
7156          * Be careful to not overflow u32, though. Kernel's log buf size limit
7157          * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7158          * multiply by 2 unless we are sure we'll fit within 32 bits.
7159          * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7160          */
7161         if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7162                 goto retry_load;
7163
7164         ret = -errno;
7165
7166         /* post-process verifier log to improve error descriptions */
7167         fixup_verifier_log(prog, log_buf, log_buf_size);
7168
7169         cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7170         pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7171         pr_perm_msg(ret);
7172
7173         if (own_log_buf && log_buf && log_buf[0] != '\0') {
7174                 pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7175                         prog->name, log_buf);
7176         }
7177
7178 out:
7179         if (own_log_buf)
7180                 free(log_buf);
7181         return ret;
7182 }
7183
7184 static char *find_prev_line(char *buf, char *cur)
7185 {
7186         char *p;
7187
7188         if (cur == buf) /* end of a log buf */
7189                 return NULL;
7190
7191         p = cur - 1;
7192         while (p - 1 >= buf && *(p - 1) != '\n')
7193                 p--;
7194
7195         return p;
7196 }
7197
7198 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7199                       char *orig, size_t orig_sz, const char *patch)
7200 {
7201         /* size of the remaining log content to the right from the to-be-replaced part */
7202         size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7203         size_t patch_sz = strlen(patch);
7204
7205         if (patch_sz != orig_sz) {
7206                 /* If patch line(s) are longer than original piece of verifier log,
7207                  * shift log contents by (patch_sz - orig_sz) bytes to the right
7208                  * starting from after to-be-replaced part of the log.
7209                  *
7210                  * If patch line(s) are shorter than original piece of verifier log,
7211                  * shift log contents by (orig_sz - patch_sz) bytes to the left
7212                  * starting from after to-be-replaced part of the log
7213                  *
7214                  * We need to be careful about not overflowing available
7215                  * buf_sz capacity. If that's the case, we'll truncate the end
7216                  * of the original log, as necessary.
7217                  */
7218                 if (patch_sz > orig_sz) {
7219                         if (orig + patch_sz >= buf + buf_sz) {
7220                                 /* patch is big enough to cover remaining space completely */
7221                                 patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7222                                 rem_sz = 0;
7223                         } else if (patch_sz - orig_sz > buf_sz - log_sz) {
7224                                 /* patch causes part of remaining log to be truncated */
7225                                 rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7226                         }
7227                 }
7228                 /* shift remaining log to the right by calculated amount */
7229                 memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7230         }
7231
7232         memcpy(orig, patch, patch_sz);
7233 }
7234
7235 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7236                                        char *buf, size_t buf_sz, size_t log_sz,
7237                                        char *line1, char *line2, char *line3)
7238 {
7239         /* Expected log for failed and not properly guarded CO-RE relocation:
7240          * line1 -> 123: (85) call unknown#195896080
7241          * line2 -> invalid func unknown#195896080
7242          * line3 -> <anything else or end of buffer>
7243          *
7244          * "123" is the index of the instruction that was poisoned. We extract
7245          * instruction index to find corresponding CO-RE relocation and
7246          * replace this part of the log with more relevant information about
7247          * failed CO-RE relocation.
7248          */
7249         const struct bpf_core_relo *relo;
7250         struct bpf_core_spec spec;
7251         char patch[512], spec_buf[256];
7252         int insn_idx, err, spec_len;
7253
7254         if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7255                 return;
7256
7257         relo = find_relo_core(prog, insn_idx);
7258         if (!relo)
7259                 return;
7260
7261         err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7262         if (err)
7263                 return;
7264
7265         spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7266         snprintf(patch, sizeof(patch),
7267                  "%d: <invalid CO-RE relocation>\n"
7268                  "failed to resolve CO-RE relocation %s%s\n",
7269                  insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7270
7271         patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7272 }
7273
7274 static void fixup_log_missing_map_load(struct bpf_program *prog,
7275                                        char *buf, size_t buf_sz, size_t log_sz,
7276                                        char *line1, char *line2, char *line3)
7277 {
7278         /* Expected log for failed and not properly guarded map reference:
7279          * line1 -> 123: (85) call unknown#2001000345
7280          * line2 -> invalid func unknown#2001000345
7281          * line3 -> <anything else or end of buffer>
7282          *
7283          * "123" is the index of the instruction that was poisoned.
7284          * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7285          */
7286         struct bpf_object *obj = prog->obj;
7287         const struct bpf_map *map;
7288         int insn_idx, map_idx;
7289         char patch[128];
7290
7291         if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7292                 return;
7293
7294         map_idx -= POISON_LDIMM64_MAP_BASE;
7295         if (map_idx < 0 || map_idx >= obj->nr_maps)
7296                 return;
7297         map = &obj->maps[map_idx];
7298
7299         snprintf(patch, sizeof(patch),
7300                  "%d: <invalid BPF map reference>\n"
7301                  "BPF map '%s' is referenced but wasn't created\n",
7302                  insn_idx, map->name);
7303
7304         patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7305 }
7306
7307 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7308                                          char *buf, size_t buf_sz, size_t log_sz,
7309                                          char *line1, char *line2, char *line3)
7310 {
7311         /* Expected log for failed and not properly guarded kfunc call:
7312          * line1 -> 123: (85) call unknown#2002000345
7313          * line2 -> invalid func unknown#2002000345
7314          * line3 -> <anything else or end of buffer>
7315          *
7316          * "123" is the index of the instruction that was poisoned.
7317          * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7318          */
7319         struct bpf_object *obj = prog->obj;
7320         const struct extern_desc *ext;
7321         int insn_idx, ext_idx;
7322         char patch[128];
7323
7324         if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7325                 return;
7326
7327         ext_idx -= POISON_CALL_KFUNC_BASE;
7328         if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7329                 return;
7330         ext = &obj->externs[ext_idx];
7331
7332         snprintf(patch, sizeof(patch),
7333                  "%d: <invalid kfunc call>\n"
7334                  "kfunc '%s' is referenced but wasn't resolved\n",
7335                  insn_idx, ext->name);
7336
7337         patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7338 }
7339
7340 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7341 {
7342         /* look for familiar error patterns in last N lines of the log */
7343         const size_t max_last_line_cnt = 10;
7344         char *prev_line, *cur_line, *next_line;
7345         size_t log_sz;
7346         int i;
7347
7348         if (!buf)
7349                 return;
7350
7351         log_sz = strlen(buf) + 1;
7352         next_line = buf + log_sz - 1;
7353
7354         for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7355                 cur_line = find_prev_line(buf, next_line);
7356                 if (!cur_line)
7357                         return;
7358
7359                 if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7360                         prev_line = find_prev_line(buf, cur_line);
7361                         if (!prev_line)
7362                                 continue;
7363
7364                         /* failed CO-RE relocation case */
7365                         fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7366                                                    prev_line, cur_line, next_line);
7367                         return;
7368                 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7369                         prev_line = find_prev_line(buf, cur_line);
7370                         if (!prev_line)
7371                                 continue;
7372
7373                         /* reference to uncreated BPF map */
7374                         fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7375                                                    prev_line, cur_line, next_line);
7376                         return;
7377                 } else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7378                         prev_line = find_prev_line(buf, cur_line);
7379                         if (!prev_line)
7380                                 continue;
7381
7382                         /* reference to unresolved kfunc */
7383                         fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7384                                                      prev_line, cur_line, next_line);
7385                         return;
7386                 }
7387         }
7388 }
7389
7390 static int bpf_program_record_relos(struct bpf_program *prog)
7391 {
7392         struct bpf_object *obj = prog->obj;
7393         int i;
7394
7395         for (i = 0; i < prog->nr_reloc; i++) {
7396                 struct reloc_desc *relo = &prog->reloc_desc[i];
7397                 struct extern_desc *ext = &obj->externs[relo->ext_idx];
7398                 int kind;
7399
7400                 switch (relo->type) {
7401                 case RELO_EXTERN_LD64:
7402                         if (ext->type != EXT_KSYM)
7403                                 continue;
7404                         kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7405                                 BTF_KIND_VAR : BTF_KIND_FUNC;
7406                         bpf_gen__record_extern(obj->gen_loader, ext->name,
7407                                                ext->is_weak, !ext->ksym.type_id,
7408                                                true, kind, relo->insn_idx);
7409                         break;
7410                 case RELO_EXTERN_CALL:
7411                         bpf_gen__record_extern(obj->gen_loader, ext->name,
7412                                                ext->is_weak, false, false, BTF_KIND_FUNC,
7413                                                relo->insn_idx);
7414                         break;
7415                 case RELO_CORE: {
7416                         struct bpf_core_relo cr = {
7417                                 .insn_off = relo->insn_idx * 8,
7418                                 .type_id = relo->core_relo->type_id,
7419                                 .access_str_off = relo->core_relo->access_str_off,
7420                                 .kind = relo->core_relo->kind,
7421                         };
7422
7423                         bpf_gen__record_relo_core(obj->gen_loader, &cr);
7424                         break;
7425                 }
7426                 default:
7427                         continue;
7428                 }
7429         }
7430         return 0;
7431 }
7432
7433 static int
7434 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7435 {
7436         struct bpf_program *prog;
7437         size_t i;
7438         int err;
7439
7440         for (i = 0; i < obj->nr_programs; i++) {
7441                 prog = &obj->programs[i];
7442                 err = bpf_object__sanitize_prog(obj, prog);
7443                 if (err)
7444                         return err;
7445         }
7446
7447         for (i = 0; i < obj->nr_programs; i++) {
7448                 prog = &obj->programs[i];
7449                 if (prog_is_subprog(obj, prog))
7450                         continue;
7451                 if (!prog->autoload) {
7452                         pr_debug("prog '%s': skipped loading\n", prog->name);
7453                         continue;
7454                 }
7455                 prog->log_level |= log_level;
7456
7457                 if (obj->gen_loader)
7458                         bpf_program_record_relos(prog);
7459
7460                 err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7461                                            obj->license, obj->kern_version, &prog->fd);
7462                 if (err) {
7463                         pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7464                         return err;
7465                 }
7466         }
7467
7468         bpf_object__free_relocs(obj);
7469         return 0;
7470 }
7471
7472 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7473
7474 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7475 {
7476         struct bpf_program *prog;
7477         int err;
7478
7479         bpf_object__for_each_program(prog, obj) {
7480                 prog->sec_def = find_sec_def(prog->sec_name);
7481                 if (!prog->sec_def) {
7482                         /* couldn't guess, but user might manually specify */
7483                         pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7484                                 prog->name, prog->sec_name);
7485                         continue;
7486                 }
7487
7488                 prog->type = prog->sec_def->prog_type;
7489                 prog->expected_attach_type = prog->sec_def->expected_attach_type;
7490
7491                 /* sec_def can have custom callback which should be called
7492                  * after bpf_program is initialized to adjust its properties
7493                  */
7494                 if (prog->sec_def->prog_setup_fn) {
7495                         err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7496                         if (err < 0) {
7497                                 pr_warn("prog '%s': failed to initialize: %d\n",
7498                                         prog->name, err);
7499                                 return err;
7500                         }
7501                 }
7502         }
7503
7504         return 0;
7505 }
7506
7507 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7508                                           const struct bpf_object_open_opts *opts)
7509 {
7510         const char *obj_name, *kconfig, *btf_tmp_path;
7511         struct bpf_object *obj;
7512         char tmp_name[64];
7513         int err;
7514         char *log_buf;
7515         size_t log_size;
7516         __u32 log_level;
7517
7518         if (elf_version(EV_CURRENT) == EV_NONE) {
7519                 pr_warn("failed to init libelf for %s\n",
7520                         path ? : "(mem buf)");
7521                 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7522         }
7523
7524         if (!OPTS_VALID(opts, bpf_object_open_opts))
7525                 return ERR_PTR(-EINVAL);
7526
7527         obj_name = OPTS_GET(opts, object_name, NULL);
7528         if (obj_buf) {
7529                 if (!obj_name) {
7530                         snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7531                                  (unsigned long)obj_buf,
7532                                  (unsigned long)obj_buf_sz);
7533                         obj_name = tmp_name;
7534                 }
7535                 path = obj_name;
7536                 pr_debug("loading object '%s' from buffer\n", obj_name);
7537         }
7538
7539         log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7540         log_size = OPTS_GET(opts, kernel_log_size, 0);
7541         log_level = OPTS_GET(opts, kernel_log_level, 0);
7542         if (log_size > UINT_MAX)
7543                 return ERR_PTR(-EINVAL);
7544         if (log_size && !log_buf)
7545                 return ERR_PTR(-EINVAL);
7546
7547         obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7548         if (IS_ERR(obj))
7549                 return obj;
7550
7551         obj->log_buf = log_buf;
7552         obj->log_size = log_size;
7553         obj->log_level = log_level;
7554
7555         btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7556         if (btf_tmp_path) {
7557                 if (strlen(btf_tmp_path) >= PATH_MAX) {
7558                         err = -ENAMETOOLONG;
7559                         goto out;
7560                 }
7561                 obj->btf_custom_path = strdup(btf_tmp_path);
7562                 if (!obj->btf_custom_path) {
7563                         err = -ENOMEM;
7564                         goto out;
7565                 }
7566         }
7567
7568         kconfig = OPTS_GET(opts, kconfig, NULL);
7569         if (kconfig) {
7570                 obj->kconfig = strdup(kconfig);
7571                 if (!obj->kconfig) {
7572                         err = -ENOMEM;
7573                         goto out;
7574                 }
7575         }
7576
7577         err = bpf_object__elf_init(obj);
7578         err = err ? : bpf_object__check_endianness(obj);
7579         err = err ? : bpf_object__elf_collect(obj);
7580         err = err ? : bpf_object__collect_externs(obj);
7581         err = err ? : bpf_object_fixup_btf(obj);
7582         err = err ? : bpf_object__init_maps(obj, opts);
7583         err = err ? : bpf_object_init_progs(obj, opts);
7584         err = err ? : bpf_object__collect_relos(obj);
7585         if (err)
7586                 goto out;
7587
7588         bpf_object__elf_finish(obj);
7589
7590         return obj;
7591 out:
7592         bpf_object__close(obj);
7593         return ERR_PTR(err);
7594 }
7595
7596 struct bpf_object *
7597 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7598 {
7599         if (!path)
7600                 return libbpf_err_ptr(-EINVAL);
7601
7602         pr_debug("loading %s\n", path);
7603
7604         return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7605 }
7606
7607 struct bpf_object *bpf_object__open(const char *path)
7608 {
7609         return bpf_object__open_file(path, NULL);
7610 }
7611
7612 struct bpf_object *
7613 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7614                      const struct bpf_object_open_opts *opts)
7615 {
7616         if (!obj_buf || obj_buf_sz == 0)
7617                 return libbpf_err_ptr(-EINVAL);
7618
7619         return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7620 }
7621
7622 static int bpf_object_unload(struct bpf_object *obj)
7623 {
7624         size_t i;
7625
7626         if (!obj)
7627                 return libbpf_err(-EINVAL);
7628
7629         for (i = 0; i < obj->nr_maps; i++) {
7630                 zclose(obj->maps[i].fd);
7631                 if (obj->maps[i].st_ops)
7632                         zfree(&obj->maps[i].st_ops->kern_vdata);
7633         }
7634
7635         for (i = 0; i < obj->nr_programs; i++)
7636                 bpf_program__unload(&obj->programs[i]);
7637
7638         return 0;
7639 }
7640
7641 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7642 {
7643         struct bpf_map *m;
7644
7645         bpf_object__for_each_map(m, obj) {
7646                 if (!bpf_map__is_internal(m))
7647                         continue;
7648                 if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7649                         m->def.map_flags &= ~BPF_F_MMAPABLE;
7650         }
7651
7652         return 0;
7653 }
7654
7655 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7656 {
7657         char sym_type, sym_name[500];
7658         unsigned long long sym_addr;
7659         int ret, err = 0;
7660         FILE *f;
7661
7662         f = fopen("/proc/kallsyms", "re");
7663         if (!f) {
7664                 err = -errno;
7665                 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7666                 return err;
7667         }
7668
7669         while (true) {
7670                 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7671                              &sym_addr, &sym_type, sym_name);
7672                 if (ret == EOF && feof(f))
7673                         break;
7674                 if (ret != 3) {
7675                         pr_warn("failed to read kallsyms entry: %d\n", ret);
7676                         err = -EINVAL;
7677                         break;
7678                 }
7679
7680                 err = cb(sym_addr, sym_type, sym_name, ctx);
7681                 if (err)
7682                         break;
7683         }
7684
7685         fclose(f);
7686         return err;
7687 }
7688
7689 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7690                        const char *sym_name, void *ctx)
7691 {
7692         struct bpf_object *obj = ctx;
7693         const struct btf_type *t;
7694         struct extern_desc *ext;
7695
7696         ext = find_extern_by_name(obj, sym_name);
7697         if (!ext || ext->type != EXT_KSYM)
7698                 return 0;
7699
7700         t = btf__type_by_id(obj->btf, ext->btf_id);
7701         if (!btf_is_var(t))
7702                 return 0;
7703
7704         if (ext->is_set && ext->ksym.addr != sym_addr) {
7705                 pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7706                         sym_name, ext->ksym.addr, sym_addr);
7707                 return -EINVAL;
7708         }
7709         if (!ext->is_set) {
7710                 ext->is_set = true;
7711                 ext->ksym.addr = sym_addr;
7712                 pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7713         }
7714         return 0;
7715 }
7716
7717 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7718 {
7719         return libbpf_kallsyms_parse(kallsyms_cb, obj);
7720 }
7721
7722 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7723                             __u16 kind, struct btf **res_btf,
7724                             struct module_btf **res_mod_btf)
7725 {
7726         struct module_btf *mod_btf;
7727         struct btf *btf;
7728         int i, id, err;
7729
7730         btf = obj->btf_vmlinux;
7731         mod_btf = NULL;
7732         id = btf__find_by_name_kind(btf, ksym_name, kind);
7733
7734         if (id == -ENOENT) {
7735                 err = load_module_btfs(obj);
7736                 if (err)
7737                         return err;
7738
7739                 for (i = 0; i < obj->btf_module_cnt; i++) {
7740                         /* we assume module_btf's BTF FD is always >0 */
7741                         mod_btf = &obj->btf_modules[i];
7742                         btf = mod_btf->btf;
7743                         id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7744                         if (id != -ENOENT)
7745                                 break;
7746                 }
7747         }
7748         if (id <= 0)
7749                 return -ESRCH;
7750
7751         *res_btf = btf;
7752         *res_mod_btf = mod_btf;
7753         return id;
7754 }
7755
7756 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7757                                                struct extern_desc *ext)
7758 {
7759         const struct btf_type *targ_var, *targ_type;
7760         __u32 targ_type_id, local_type_id;
7761         struct module_btf *mod_btf = NULL;
7762         const char *targ_var_name;
7763         struct btf *btf = NULL;
7764         int id, err;
7765
7766         id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7767         if (id < 0) {
7768                 if (id == -ESRCH && ext->is_weak)
7769                         return 0;
7770                 pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7771                         ext->name);
7772                 return id;
7773         }
7774
7775         /* find local type_id */
7776         local_type_id = ext->ksym.type_id;
7777
7778         /* find target type_id */
7779         targ_var = btf__type_by_id(btf, id);
7780         targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7781         targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7782
7783         err = bpf_core_types_are_compat(obj->btf, local_type_id,
7784                                         btf, targ_type_id);
7785         if (err <= 0) {
7786                 const struct btf_type *local_type;
7787                 const char *targ_name, *local_name;
7788
7789                 local_type = btf__type_by_id(obj->btf, local_type_id);
7790                 local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7791                 targ_name = btf__name_by_offset(btf, targ_type->name_off);
7792
7793                 pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7794                         ext->name, local_type_id,
7795                         btf_kind_str(local_type), local_name, targ_type_id,
7796                         btf_kind_str(targ_type), targ_name);
7797                 return -EINVAL;
7798         }
7799
7800         ext->is_set = true;
7801         ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7802         ext->ksym.kernel_btf_id = id;
7803         pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7804                  ext->name, id, btf_kind_str(targ_var), targ_var_name);
7805
7806         return 0;
7807 }
7808
7809 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7810                                                 struct extern_desc *ext)
7811 {
7812         int local_func_proto_id, kfunc_proto_id, kfunc_id;
7813         struct module_btf *mod_btf = NULL;
7814         const struct btf_type *kern_func;
7815         struct btf *kern_btf = NULL;
7816         int ret;
7817
7818         local_func_proto_id = ext->ksym.type_id;
7819
7820         kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7821                                     &mod_btf);
7822         if (kfunc_id < 0) {
7823                 if (kfunc_id == -ESRCH && ext->is_weak)
7824                         return 0;
7825                 pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7826                         ext->name);
7827                 return kfunc_id;
7828         }
7829
7830         kern_func = btf__type_by_id(kern_btf, kfunc_id);
7831         kfunc_proto_id = kern_func->type;
7832
7833         ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7834                                         kern_btf, kfunc_proto_id);
7835         if (ret <= 0) {
7836                 if (ext->is_weak)
7837                         return 0;
7838
7839                 pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7840                         ext->name, local_func_proto_id,
7841                         mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7842                 return -EINVAL;
7843         }
7844
7845         /* set index for module BTF fd in fd_array, if unset */
7846         if (mod_btf && !mod_btf->fd_array_idx) {
7847                 /* insn->off is s16 */
7848                 if (obj->fd_array_cnt == INT16_MAX) {
7849                         pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7850                                 ext->name, mod_btf->fd_array_idx);
7851                         return -E2BIG;
7852                 }
7853                 /* Cannot use index 0 for module BTF fd */
7854                 if (!obj->fd_array_cnt)
7855                         obj->fd_array_cnt = 1;
7856
7857                 ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7858                                         obj->fd_array_cnt + 1);
7859                 if (ret)
7860                         return ret;
7861                 mod_btf->fd_array_idx = obj->fd_array_cnt;
7862                 /* we assume module BTF FD is always >0 */
7863                 obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7864         }
7865
7866         ext->is_set = true;
7867         ext->ksym.kernel_btf_id = kfunc_id;
7868         ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7869         /* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7870          * populates FD into ld_imm64 insn when it's used to point to kfunc.
7871          * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7872          * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7873          */
7874         ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7875         pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7876                  ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7877
7878         return 0;
7879 }
7880
7881 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7882 {
7883         const struct btf_type *t;
7884         struct extern_desc *ext;
7885         int i, err;
7886
7887         for (i = 0; i < obj->nr_extern; i++) {
7888                 ext = &obj->externs[i];
7889                 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7890                         continue;
7891
7892                 if (obj->gen_loader) {
7893                         ext->is_set = true;
7894                         ext->ksym.kernel_btf_obj_fd = 0;
7895                         ext->ksym.kernel_btf_id = 0;
7896                         continue;
7897                 }
7898                 t = btf__type_by_id(obj->btf, ext->btf_id);
7899                 if (btf_is_var(t))
7900                         err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7901                 else
7902                         err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7903                 if (err)
7904                         return err;
7905         }
7906         return 0;
7907 }
7908
7909 static int bpf_object__resolve_externs(struct bpf_object *obj,
7910                                        const char *extra_kconfig)
7911 {
7912         bool need_config = false, need_kallsyms = false;
7913         bool need_vmlinux_btf = false;
7914         struct extern_desc *ext;
7915         void *kcfg_data = NULL;
7916         int err, i;
7917
7918         if (obj->nr_extern == 0)
7919                 return 0;
7920
7921         if (obj->kconfig_map_idx >= 0)
7922                 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7923
7924         for (i = 0; i < obj->nr_extern; i++) {
7925                 ext = &obj->externs[i];
7926
7927                 if (ext->type == EXT_KSYM) {
7928                         if (ext->ksym.type_id)
7929                                 need_vmlinux_btf = true;
7930                         else
7931                                 need_kallsyms = true;
7932                         continue;
7933                 } else if (ext->type == EXT_KCFG) {
7934                         void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7935                         __u64 value = 0;
7936
7937                         /* Kconfig externs need actual /proc/config.gz */
7938                         if (str_has_pfx(ext->name, "CONFIG_")) {
7939                                 need_config = true;
7940                                 continue;
7941                         }
7942
7943                         /* Virtual kcfg externs are customly handled by libbpf */
7944                         if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7945                                 value = get_kernel_version();
7946                                 if (!value) {
7947                                         pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7948                                         return -EINVAL;
7949                                 }
7950                         } else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7951                                 value = kernel_supports(obj, FEAT_BPF_COOKIE);
7952                         } else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7953                                 value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7954                         } else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7955                                 /* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7956                                  * __kconfig externs, where LINUX_ ones are virtual and filled out
7957                                  * customly by libbpf (their values don't come from Kconfig).
7958                                  * If LINUX_xxx variable is not recognized by libbpf, but is marked
7959                                  * __weak, it defaults to zero value, just like for CONFIG_xxx
7960                                  * externs.
7961                                  */
7962                                 pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7963                                 return -EINVAL;
7964                         }
7965
7966                         err = set_kcfg_value_num(ext, ext_ptr, value);
7967                         if (err)
7968                                 return err;
7969                         pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7970                                  ext->name, (long long)value);
7971                 } else {
7972                         pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7973                         return -EINVAL;
7974                 }
7975         }
7976         if (need_config && extra_kconfig) {
7977                 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7978                 if (err)
7979                         return -EINVAL;
7980                 need_config = false;
7981                 for (i = 0; i < obj->nr_extern; i++) {
7982                         ext = &obj->externs[i];
7983                         if (ext->type == EXT_KCFG && !ext->is_set) {
7984                                 need_config = true;
7985                                 break;
7986                         }
7987                 }
7988         }
7989         if (need_config) {
7990                 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7991                 if (err)
7992                         return -EINVAL;
7993         }
7994         if (need_kallsyms) {
7995                 err = bpf_object__read_kallsyms_file(obj);
7996                 if (err)
7997                         return -EINVAL;
7998         }
7999         if (need_vmlinux_btf) {
8000                 err = bpf_object__resolve_ksyms_btf_id(obj);
8001                 if (err)
8002                         return -EINVAL;
8003         }
8004         for (i = 0; i < obj->nr_extern; i++) {
8005                 ext = &obj->externs[i];
8006
8007                 if (!ext->is_set && !ext->is_weak) {
8008                         pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8009                         return -ESRCH;
8010                 } else if (!ext->is_set) {
8011                         pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8012                                  ext->name);
8013                 }
8014         }
8015
8016         return 0;
8017 }
8018
8019 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8020 {
8021         struct bpf_struct_ops *st_ops;
8022         __u32 i;
8023
8024         st_ops = map->st_ops;
8025         for (i = 0; i < btf_vlen(st_ops->type); i++) {
8026                 struct bpf_program *prog = st_ops->progs[i];
8027                 void *kern_data;
8028                 int prog_fd;
8029
8030                 if (!prog)
8031                         continue;
8032
8033                 prog_fd = bpf_program__fd(prog);
8034                 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8035                 *(unsigned long *)kern_data = prog_fd;
8036         }
8037 }
8038
8039 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8040 {
8041         int i;
8042
8043         for (i = 0; i < obj->nr_maps; i++)
8044                 if (bpf_map__is_struct_ops(&obj->maps[i]))
8045                         bpf_map_prepare_vdata(&obj->maps[i]);
8046
8047         return 0;
8048 }
8049
8050 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8051 {
8052         int err, i;
8053
8054         if (!obj)
8055                 return libbpf_err(-EINVAL);
8056
8057         if (obj->loaded) {
8058                 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8059                 return libbpf_err(-EINVAL);
8060         }
8061
8062         if (obj->gen_loader)
8063                 bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8064
8065         err = bpf_object__probe_loading(obj);
8066         err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8067         err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8068         err = err ? : bpf_object__sanitize_and_load_btf(obj);
8069         err = err ? : bpf_object__sanitize_maps(obj);
8070         err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8071         err = err ? : bpf_object__create_maps(obj);
8072         err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8073         err = err ? : bpf_object__load_progs(obj, extra_log_level);
8074         err = err ? : bpf_object_init_prog_arrays(obj);
8075         err = err ? : bpf_object_prepare_struct_ops(obj);
8076
8077         if (obj->gen_loader) {
8078                 /* reset FDs */
8079                 if (obj->btf)
8080                         btf__set_fd(obj->btf, -1);
8081                 for (i = 0; i < obj->nr_maps; i++)
8082                         obj->maps[i].fd = -1;
8083                 if (!err)
8084                         err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8085         }
8086
8087         /* clean up fd_array */
8088         zfree(&obj->fd_array);
8089
8090         /* clean up module BTFs */
8091         for (i = 0; i < obj->btf_module_cnt; i++) {
8092                 close(obj->btf_modules[i].fd);
8093                 btf__free(obj->btf_modules[i].btf);
8094                 free(obj->btf_modules[i].name);
8095         }
8096         free(obj->btf_modules);
8097
8098         /* clean up vmlinux BTF */
8099         btf__free(obj->btf_vmlinux);
8100         obj->btf_vmlinux = NULL;
8101
8102         obj->loaded = true; /* doesn't matter if successfully or not */
8103
8104         if (err)
8105                 goto out;
8106
8107         return 0;
8108 out:
8109         /* unpin any maps that were auto-pinned during load */
8110         for (i = 0; i < obj->nr_maps; i++)
8111                 if (obj->maps[i].pinned && !obj->maps[i].reused)
8112                         bpf_map__unpin(&obj->maps[i], NULL);
8113
8114         bpf_object_unload(obj);
8115         pr_warn("failed to load object '%s'\n", obj->path);
8116         return libbpf_err(err);
8117 }
8118
8119 int bpf_object__load(struct bpf_object *obj)
8120 {
8121         return bpf_object_load(obj, 0, NULL);
8122 }
8123
8124 static int make_parent_dir(const char *path)
8125 {
8126         char *cp, errmsg[STRERR_BUFSIZE];
8127         char *dname, *dir;
8128         int err = 0;
8129
8130         dname = strdup(path);
8131         if (dname == NULL)
8132                 return -ENOMEM;
8133
8134         dir = dirname(dname);
8135         if (mkdir(dir, 0700) && errno != EEXIST)
8136                 err = -errno;
8137
8138         free(dname);
8139         if (err) {
8140                 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8141                 pr_warn("failed to mkdir %s: %s\n", path, cp);
8142         }
8143         return err;
8144 }
8145
8146 static int check_path(const char *path)
8147 {
8148         char *cp, errmsg[STRERR_BUFSIZE];
8149         struct statfs st_fs;
8150         char *dname, *dir;
8151         int err = 0;
8152
8153         if (path == NULL)
8154                 return -EINVAL;
8155
8156         dname = strdup(path);
8157         if (dname == NULL)
8158                 return -ENOMEM;
8159
8160         dir = dirname(dname);
8161         if (statfs(dir, &st_fs)) {
8162                 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8163                 pr_warn("failed to statfs %s: %s\n", dir, cp);
8164                 err = -errno;
8165         }
8166         free(dname);
8167
8168         if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8169                 pr_warn("specified path %s is not on BPF FS\n", path);
8170                 err = -EINVAL;
8171         }
8172
8173         return err;
8174 }
8175
8176 int bpf_program__pin(struct bpf_program *prog, const char *path)
8177 {
8178         char *cp, errmsg[STRERR_BUFSIZE];
8179         int err;
8180
8181         if (prog->fd < 0) {
8182                 pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8183                 return libbpf_err(-EINVAL);
8184         }
8185
8186         err = make_parent_dir(path);
8187         if (err)
8188                 return libbpf_err(err);
8189
8190         err = check_path(path);
8191         if (err)
8192                 return libbpf_err(err);
8193
8194         if (bpf_obj_pin(prog->fd, path)) {
8195                 err = -errno;
8196                 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8197                 pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8198                 return libbpf_err(err);
8199         }
8200
8201         pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8202         return 0;
8203 }
8204
8205 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8206 {
8207         int err;
8208
8209         if (prog->fd < 0) {
8210                 pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8211                 return libbpf_err(-EINVAL);
8212         }
8213
8214         err = check_path(path);
8215         if (err)
8216                 return libbpf_err(err);
8217
8218         err = unlink(path);
8219         if (err)
8220                 return libbpf_err(-errno);
8221
8222         pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8223         return 0;
8224 }
8225
8226 int bpf_map__pin(struct bpf_map *map, const char *path)
8227 {
8228         char *cp, errmsg[STRERR_BUFSIZE];
8229         int err;
8230
8231         if (map == NULL) {
8232                 pr_warn("invalid map pointer\n");
8233                 return libbpf_err(-EINVAL);
8234         }
8235
8236         if (map->pin_path) {
8237                 if (path && strcmp(path, map->pin_path)) {
8238                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8239                                 bpf_map__name(map), map->pin_path, path);
8240                         return libbpf_err(-EINVAL);
8241                 } else if (map->pinned) {
8242                         pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8243                                  bpf_map__name(map), map->pin_path);
8244                         return 0;
8245                 }
8246         } else {
8247                 if (!path) {
8248                         pr_warn("missing a path to pin map '%s' at\n",
8249                                 bpf_map__name(map));
8250                         return libbpf_err(-EINVAL);
8251                 } else if (map->pinned) {
8252                         pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8253                         return libbpf_err(-EEXIST);
8254                 }
8255
8256                 map->pin_path = strdup(path);
8257                 if (!map->pin_path) {
8258                         err = -errno;
8259                         goto out_err;
8260                 }
8261         }
8262
8263         err = make_parent_dir(map->pin_path);
8264         if (err)
8265                 return libbpf_err(err);
8266
8267         err = check_path(map->pin_path);
8268         if (err)
8269                 return libbpf_err(err);
8270
8271         if (bpf_obj_pin(map->fd, map->pin_path)) {
8272                 err = -errno;
8273                 goto out_err;
8274         }
8275
8276         map->pinned = true;
8277         pr_debug("pinned map '%s'\n", map->pin_path);
8278
8279         return 0;
8280
8281 out_err:
8282         cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8283         pr_warn("failed to pin map: %s\n", cp);
8284         return libbpf_err(err);
8285 }
8286
8287 int bpf_map__unpin(struct bpf_map *map, const char *path)
8288 {
8289         int err;
8290
8291         if (map == NULL) {
8292                 pr_warn("invalid map pointer\n");
8293                 return libbpf_err(-EINVAL);
8294         }
8295
8296         if (map->pin_path) {
8297                 if (path && strcmp(path, map->pin_path)) {
8298                         pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8299                                 bpf_map__name(map), map->pin_path, path);
8300                         return libbpf_err(-EINVAL);
8301                 }
8302                 path = map->pin_path;
8303         } else if (!path) {
8304                 pr_warn("no path to unpin map '%s' from\n",
8305                         bpf_map__name(map));
8306                 return libbpf_err(-EINVAL);
8307         }
8308
8309         err = check_path(path);
8310         if (err)
8311                 return libbpf_err(err);
8312
8313         err = unlink(path);
8314         if (err != 0)
8315                 return libbpf_err(-errno);
8316
8317         map->pinned = false;
8318         pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8319
8320         return 0;
8321 }
8322
8323 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8324 {
8325         char *new = NULL;
8326
8327         if (path) {
8328                 new = strdup(path);
8329                 if (!new)
8330                         return libbpf_err(-errno);
8331         }
8332
8333         free(map->pin_path);
8334         map->pin_path = new;
8335         return 0;
8336 }
8337
8338 __alias(bpf_map__pin_path)
8339 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8340
8341 const char *bpf_map__pin_path(const struct bpf_map *map)
8342 {
8343         return map->pin_path;
8344 }
8345
8346 bool bpf_map__is_pinned(const struct bpf_map *map)
8347 {
8348         return map->pinned;
8349 }
8350
8351 static void sanitize_pin_path(char *s)
8352 {
8353         /* bpffs disallows periods in path names */
8354         while (*s) {
8355                 if (*s == '.')
8356                         *s = '_';
8357                 s++;
8358         }
8359 }
8360
8361 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8362 {
8363         struct bpf_map *map;
8364         int err;
8365
8366         if (!obj)
8367                 return libbpf_err(-ENOENT);
8368
8369         if (!obj->loaded) {
8370                 pr_warn("object not yet loaded; load it first\n");
8371                 return libbpf_err(-ENOENT);
8372         }
8373
8374         bpf_object__for_each_map(map, obj) {
8375                 char *pin_path = NULL;
8376                 char buf[PATH_MAX];
8377
8378                 if (!map->autocreate)
8379                         continue;
8380
8381                 if (path) {
8382                         err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8383                         if (err)
8384                                 goto err_unpin_maps;
8385                         sanitize_pin_path(buf);
8386                         pin_path = buf;
8387                 } else if (!map->pin_path) {
8388                         continue;
8389                 }
8390
8391                 err = bpf_map__pin(map, pin_path);
8392                 if (err)
8393                         goto err_unpin_maps;
8394         }
8395
8396         return 0;
8397
8398 err_unpin_maps:
8399         while ((map = bpf_object__prev_map(obj, map))) {
8400                 if (!map->pin_path)
8401                         continue;
8402
8403                 bpf_map__unpin(map, NULL);
8404         }
8405
8406         return libbpf_err(err);
8407 }
8408
8409 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8410 {
8411         struct bpf_map *map;
8412         int err;
8413
8414         if (!obj)
8415                 return libbpf_err(-ENOENT);
8416
8417         bpf_object__for_each_map(map, obj) {
8418                 char *pin_path = NULL;
8419                 char buf[PATH_MAX];
8420
8421                 if (path) {
8422                         err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8423                         if (err)
8424                                 return libbpf_err(err);
8425                         sanitize_pin_path(buf);
8426                         pin_path = buf;
8427                 } else if (!map->pin_path) {
8428                         continue;
8429                 }
8430
8431                 err = bpf_map__unpin(map, pin_path);
8432                 if (err)
8433                         return libbpf_err(err);
8434         }
8435
8436         return 0;
8437 }
8438
8439 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8440 {
8441         struct bpf_program *prog;
8442         char buf[PATH_MAX];
8443         int err;
8444
8445         if (!obj)
8446                 return libbpf_err(-ENOENT);
8447
8448         if (!obj->loaded) {
8449                 pr_warn("object not yet loaded; load it first\n");
8450                 return libbpf_err(-ENOENT);
8451         }
8452
8453         bpf_object__for_each_program(prog, obj) {
8454                 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8455                 if (err)
8456                         goto err_unpin_programs;
8457
8458                 err = bpf_program__pin(prog, buf);
8459                 if (err)
8460                         goto err_unpin_programs;
8461         }
8462
8463         return 0;
8464
8465 err_unpin_programs:
8466         while ((prog = bpf_object__prev_program(obj, prog))) {
8467                 if (pathname_concat(buf, sizeof(buf), path, prog->name))
8468                         continue;
8469
8470                 bpf_program__unpin(prog, buf);
8471         }
8472
8473         return libbpf_err(err);
8474 }
8475
8476 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8477 {
8478         struct bpf_program *prog;
8479         int err;
8480
8481         if (!obj)
8482                 return libbpf_err(-ENOENT);
8483
8484         bpf_object__for_each_program(prog, obj) {
8485                 char buf[PATH_MAX];
8486
8487                 err = pathname_concat(buf, sizeof(buf), path, prog->name);
8488                 if (err)
8489                         return libbpf_err(err);
8490
8491                 err = bpf_program__unpin(prog, buf);
8492                 if (err)
8493                         return libbpf_err(err);
8494         }
8495
8496         return 0;
8497 }
8498
8499 int bpf_object__pin(struct bpf_object *obj, const char *path)
8500 {
8501         int err;
8502
8503         err = bpf_object__pin_maps(obj, path);
8504         if (err)
8505                 return libbpf_err(err);
8506
8507         err = bpf_object__pin_programs(obj, path);
8508         if (err) {
8509                 bpf_object__unpin_maps(obj, path);
8510                 return libbpf_err(err);
8511         }
8512
8513         return 0;
8514 }
8515
8516 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8517 {
8518         int err;
8519
8520         err = bpf_object__unpin_programs(obj, path);
8521         if (err)
8522                 return libbpf_err(err);
8523
8524         err = bpf_object__unpin_maps(obj, path);
8525         if (err)
8526                 return libbpf_err(err);
8527
8528         return 0;
8529 }
8530
8531 static void bpf_map__destroy(struct bpf_map *map)
8532 {
8533         if (map->inner_map) {
8534                 bpf_map__destroy(map->inner_map);
8535                 zfree(&map->inner_map);
8536         }
8537
8538         zfree(&map->init_slots);
8539         map->init_slots_sz = 0;
8540
8541         if (map->mmaped) {
8542                 size_t mmap_sz;
8543
8544                 mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8545                 munmap(map->mmaped, mmap_sz);
8546                 map->mmaped = NULL;
8547         }
8548
8549         if (map->st_ops) {
8550                 zfree(&map->st_ops->data);
8551                 zfree(&map->st_ops->progs);
8552                 zfree(&map->st_ops->kern_func_off);
8553                 zfree(&map->st_ops);
8554         }
8555
8556         zfree(&map->name);
8557         zfree(&map->real_name);
8558         zfree(&map->pin_path);
8559
8560         if (map->fd >= 0)
8561                 zclose(map->fd);
8562 }
8563
8564 void bpf_object__close(struct bpf_object *obj)
8565 {
8566         size_t i;
8567
8568         if (IS_ERR_OR_NULL(obj))
8569                 return;
8570
8571         usdt_manager_free(obj->usdt_man);
8572         obj->usdt_man = NULL;
8573
8574         bpf_gen__free(obj->gen_loader);
8575         bpf_object__elf_finish(obj);
8576         bpf_object_unload(obj);
8577         btf__free(obj->btf);
8578         btf__free(obj->btf_vmlinux);
8579         btf_ext__free(obj->btf_ext);
8580
8581         for (i = 0; i < obj->nr_maps; i++)
8582                 bpf_map__destroy(&obj->maps[i]);
8583
8584         zfree(&obj->btf_custom_path);
8585         zfree(&obj->kconfig);
8586
8587         for (i = 0; i < obj->nr_extern; i++)
8588                 zfree(&obj->externs[i].essent_name);
8589
8590         zfree(&obj->externs);
8591         obj->nr_extern = 0;
8592
8593         zfree(&obj->maps);
8594         obj->nr_maps = 0;
8595
8596         if (obj->programs && obj->nr_programs) {
8597                 for (i = 0; i < obj->nr_programs; i++)
8598                         bpf_program__exit(&obj->programs[i]);
8599         }
8600         zfree(&obj->programs);
8601
8602         free(obj);
8603 }
8604
8605 const char *bpf_object__name(const struct bpf_object *obj)
8606 {
8607         return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8608 }
8609
8610 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8611 {
8612         return obj ? obj->kern_version : 0;
8613 }
8614
8615 struct btf *bpf_object__btf(const struct bpf_object *obj)
8616 {
8617         return obj ? obj->btf : NULL;
8618 }
8619
8620 int bpf_object__btf_fd(const struct bpf_object *obj)
8621 {
8622         return obj->btf ? btf__fd(obj->btf) : -1;
8623 }
8624
8625 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8626 {
8627         if (obj->loaded)
8628                 return libbpf_err(-EINVAL);
8629
8630         obj->kern_version = kern_version;
8631
8632         return 0;
8633 }
8634
8635 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8636 {
8637         struct bpf_gen *gen;
8638
8639         if (!opts)
8640                 return -EFAULT;
8641         if (!OPTS_VALID(opts, gen_loader_opts))
8642                 return -EINVAL;
8643         gen = calloc(sizeof(*gen), 1);
8644         if (!gen)
8645                 return -ENOMEM;
8646         gen->opts = opts;
8647         obj->gen_loader = gen;
8648         return 0;
8649 }
8650
8651 static struct bpf_program *
8652 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8653                     bool forward)
8654 {
8655         size_t nr_programs = obj->nr_programs;
8656         ssize_t idx;
8657
8658         if (!nr_programs)
8659                 return NULL;
8660
8661         if (!p)
8662                 /* Iter from the beginning */
8663                 return forward ? &obj->programs[0] :
8664                         &obj->programs[nr_programs - 1];
8665
8666         if (p->obj != obj) {
8667                 pr_warn("error: program handler doesn't match object\n");
8668                 return errno = EINVAL, NULL;
8669         }
8670
8671         idx = (p - obj->programs) + (forward ? 1 : -1);
8672         if (idx >= obj->nr_programs || idx < 0)
8673                 return NULL;
8674         return &obj->programs[idx];
8675 }
8676
8677 struct bpf_program *
8678 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8679 {
8680         struct bpf_program *prog = prev;
8681
8682         do {
8683                 prog = __bpf_program__iter(prog, obj, true);
8684         } while (prog && prog_is_subprog(obj, prog));
8685
8686         return prog;
8687 }
8688
8689 struct bpf_program *
8690 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8691 {
8692         struct bpf_program *prog = next;
8693
8694         do {
8695                 prog = __bpf_program__iter(prog, obj, false);
8696         } while (prog && prog_is_subprog(obj, prog));
8697
8698         return prog;
8699 }
8700
8701 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8702 {
8703         prog->prog_ifindex = ifindex;
8704 }
8705
8706 const char *bpf_program__name(const struct bpf_program *prog)
8707 {
8708         return prog->name;
8709 }
8710
8711 const char *bpf_program__section_name(const struct bpf_program *prog)
8712 {
8713         return prog->sec_name;
8714 }
8715
8716 bool bpf_program__autoload(const struct bpf_program *prog)
8717 {
8718         return prog->autoload;
8719 }
8720
8721 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8722 {
8723         if (prog->obj->loaded)
8724                 return libbpf_err(-EINVAL);
8725
8726         prog->autoload = autoload;
8727         return 0;
8728 }
8729
8730 bool bpf_program__autoattach(const struct bpf_program *prog)
8731 {
8732         return prog->autoattach;
8733 }
8734
8735 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8736 {
8737         prog->autoattach = autoattach;
8738 }
8739
8740 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8741 {
8742         return prog->insns;
8743 }
8744
8745 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8746 {
8747         return prog->insns_cnt;
8748 }
8749
8750 int bpf_program__set_insns(struct bpf_program *prog,
8751                            struct bpf_insn *new_insns, size_t new_insn_cnt)
8752 {
8753         struct bpf_insn *insns;
8754
8755         if (prog->obj->loaded)
8756                 return -EBUSY;
8757
8758         insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8759         /* NULL is a valid return from reallocarray if the new count is zero */
8760         if (!insns && new_insn_cnt) {
8761                 pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8762                 return -ENOMEM;
8763         }
8764         memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8765
8766         prog->insns = insns;
8767         prog->insns_cnt = new_insn_cnt;
8768         return 0;
8769 }
8770
8771 int bpf_program__fd(const struct bpf_program *prog)
8772 {
8773         if (!prog)
8774                 return libbpf_err(-EINVAL);
8775
8776         if (prog->fd < 0)
8777                 return libbpf_err(-ENOENT);
8778
8779         return prog->fd;
8780 }
8781
8782 __alias(bpf_program__type)
8783 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8784
8785 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8786 {
8787         return prog->type;
8788 }
8789
8790 static size_t custom_sec_def_cnt;
8791 static struct bpf_sec_def *custom_sec_defs;
8792 static struct bpf_sec_def custom_fallback_def;
8793 static bool has_custom_fallback_def;
8794 static int last_custom_sec_def_handler_id;
8795
8796 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8797 {
8798         if (prog->obj->loaded)
8799                 return libbpf_err(-EBUSY);
8800
8801         /* if type is not changed, do nothing */
8802         if (prog->type == type)
8803                 return 0;
8804
8805         prog->type = type;
8806
8807         /* If a program type was changed, we need to reset associated SEC()
8808          * handler, as it will be invalid now. The only exception is a generic
8809          * fallback handler, which by definition is program type-agnostic and
8810          * is a catch-all custom handler, optionally set by the application,
8811          * so should be able to handle any type of BPF program.
8812          */
8813         if (prog->sec_def != &custom_fallback_def)
8814                 prog->sec_def = NULL;
8815         return 0;
8816 }
8817
8818 __alias(bpf_program__expected_attach_type)
8819 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8820
8821 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8822 {
8823         return prog->expected_attach_type;
8824 }
8825
8826 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8827                                            enum bpf_attach_type type)
8828 {
8829         if (prog->obj->loaded)
8830                 return libbpf_err(-EBUSY);
8831
8832         prog->expected_attach_type = type;
8833         return 0;
8834 }
8835
8836 __u32 bpf_program__flags(const struct bpf_program *prog)
8837 {
8838         return prog->prog_flags;
8839 }
8840
8841 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8842 {
8843         if (prog->obj->loaded)
8844                 return libbpf_err(-EBUSY);
8845
8846         prog->prog_flags = flags;
8847         return 0;
8848 }
8849
8850 __u32 bpf_program__log_level(const struct bpf_program *prog)
8851 {
8852         return prog->log_level;
8853 }
8854
8855 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8856 {
8857         if (prog->obj->loaded)
8858                 return libbpf_err(-EBUSY);
8859
8860         prog->log_level = log_level;
8861         return 0;
8862 }
8863
8864 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8865 {
8866         *log_size = prog->log_size;
8867         return prog->log_buf;
8868 }
8869
8870 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8871 {
8872         if (log_size && !log_buf)
8873                 return -EINVAL;
8874         if (prog->log_size > UINT_MAX)
8875                 return -EINVAL;
8876         if (prog->obj->loaded)
8877                 return -EBUSY;
8878
8879         prog->log_buf = log_buf;
8880         prog->log_size = log_size;
8881         return 0;
8882 }
8883
8884 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {                        \
8885         .sec = (char *)sec_pfx,                                             \
8886         .prog_type = BPF_PROG_TYPE_##ptype,                                 \
8887         .expected_attach_type = atype,                                      \
8888         .cookie = (long)(flags),                                            \
8889         .prog_prepare_load_fn = libbpf_prepare_prog_load,                   \
8890         __VA_ARGS__                                                         \
8891 }
8892
8893 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8894 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8895 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8896 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8897 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8898 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8899 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8900 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8901 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8902 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8903 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8904
8905 static const struct bpf_sec_def section_defs[] = {
8906         SEC_DEF("socket",               SOCKET_FILTER, 0, SEC_NONE),
8907         SEC_DEF("sk_reuseport/migrate", SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8908         SEC_DEF("sk_reuseport",         SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8909         SEC_DEF("kprobe+",              KPROBE, 0, SEC_NONE, attach_kprobe),
8910         SEC_DEF("uprobe+",              KPROBE, 0, SEC_NONE, attach_uprobe),
8911         SEC_DEF("uprobe.s+",            KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8912         SEC_DEF("kretprobe+",           KPROBE, 0, SEC_NONE, attach_kprobe),
8913         SEC_DEF("uretprobe+",           KPROBE, 0, SEC_NONE, attach_uprobe),
8914         SEC_DEF("uretprobe.s+",         KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8915         SEC_DEF("kprobe.multi+",        KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8916         SEC_DEF("kretprobe.multi+",     KPROBE, BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8917         SEC_DEF("uprobe.multi+",        KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8918         SEC_DEF("uretprobe.multi+",     KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
8919         SEC_DEF("uprobe.multi.s+",      KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8920         SEC_DEF("uretprobe.multi.s+",   KPROBE, BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
8921         SEC_DEF("ksyscall+",            KPROBE, 0, SEC_NONE, attach_ksyscall),
8922         SEC_DEF("kretsyscall+",         KPROBE, 0, SEC_NONE, attach_ksyscall),
8923         SEC_DEF("usdt+",                KPROBE, 0, SEC_USDT, attach_usdt),
8924         SEC_DEF("usdt.s+",              KPROBE, 0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
8925         SEC_DEF("tc/ingress",           SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8926         SEC_DEF("tc/egress",            SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8927         SEC_DEF("tcx/ingress",          SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8928         SEC_DEF("tcx/egress",           SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8929         SEC_DEF("tc",                   SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8930         SEC_DEF("classifier",           SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8931         SEC_DEF("action",               SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8932         SEC_DEF("netkit/primary",       SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
8933         SEC_DEF("netkit/peer",          SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
8934         SEC_DEF("tracepoint+",          TRACEPOINT, 0, SEC_NONE, attach_tp),
8935         SEC_DEF("tp+",                  TRACEPOINT, 0, SEC_NONE, attach_tp),
8936         SEC_DEF("raw_tracepoint+",      RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8937         SEC_DEF("raw_tp+",              RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8938         SEC_DEF("raw_tracepoint.w+",    RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8939         SEC_DEF("raw_tp.w+",            RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8940         SEC_DEF("tp_btf+",              TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8941         SEC_DEF("fentry+",              TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8942         SEC_DEF("fmod_ret+",            TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8943         SEC_DEF("fexit+",               TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8944         SEC_DEF("fentry.s+",            TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8945         SEC_DEF("fmod_ret.s+",          TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8946         SEC_DEF("fexit.s+",             TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8947         SEC_DEF("freplace+",            EXT, 0, SEC_ATTACH_BTF, attach_trace),
8948         SEC_DEF("lsm+",                 LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8949         SEC_DEF("lsm.s+",               LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8950         SEC_DEF("lsm_cgroup+",          LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8951         SEC_DEF("iter+",                TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8952         SEC_DEF("iter.s+",              TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8953         SEC_DEF("syscall",              SYSCALL, 0, SEC_SLEEPABLE),
8954         SEC_DEF("xdp.frags/devmap",     XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8955         SEC_DEF("xdp/devmap",           XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8956         SEC_DEF("xdp.frags/cpumap",     XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8957         SEC_DEF("xdp/cpumap",           XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8958         SEC_DEF("xdp.frags",            XDP, BPF_XDP, SEC_XDP_FRAGS),
8959         SEC_DEF("xdp",                  XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8960         SEC_DEF("perf_event",           PERF_EVENT, 0, SEC_NONE),
8961         SEC_DEF("lwt_in",               LWT_IN, 0, SEC_NONE),
8962         SEC_DEF("lwt_out",              LWT_OUT, 0, SEC_NONE),
8963         SEC_DEF("lwt_xmit",             LWT_XMIT, 0, SEC_NONE),
8964         SEC_DEF("lwt_seg6local",        LWT_SEG6LOCAL, 0, SEC_NONE),
8965         SEC_DEF("sockops",              SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8966         SEC_DEF("sk_skb/stream_parser", SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8967         SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8968         SEC_DEF("sk_skb",               SK_SKB, 0, SEC_NONE),
8969         SEC_DEF("sk_msg",               SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8970         SEC_DEF("lirc_mode2",           LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8971         SEC_DEF("flow_dissector",       FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8972         SEC_DEF("cgroup_skb/ingress",   CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8973         SEC_DEF("cgroup_skb/egress",    CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8974         SEC_DEF("cgroup/skb",           CGROUP_SKB, 0, SEC_NONE),
8975         SEC_DEF("cgroup/sock_create",   CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8976         SEC_DEF("cgroup/sock_release",  CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8977         SEC_DEF("cgroup/sock",          CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8978         SEC_DEF("cgroup/post_bind4",    CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8979         SEC_DEF("cgroup/post_bind6",    CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8980         SEC_DEF("cgroup/bind4",         CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8981         SEC_DEF("cgroup/bind6",         CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8982         SEC_DEF("cgroup/connect4",      CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8983         SEC_DEF("cgroup/connect6",      CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8984         SEC_DEF("cgroup/connect_unix",  CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
8985         SEC_DEF("cgroup/sendmsg4",      CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8986         SEC_DEF("cgroup/sendmsg6",      CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8987         SEC_DEF("cgroup/sendmsg_unix",  CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
8988         SEC_DEF("cgroup/recvmsg4",      CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8989         SEC_DEF("cgroup/recvmsg6",      CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8990         SEC_DEF("cgroup/recvmsg_unix",  CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
8991         SEC_DEF("cgroup/getpeername4",  CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8992         SEC_DEF("cgroup/getpeername6",  CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8993         SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
8994         SEC_DEF("cgroup/getsockname4",  CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8995         SEC_DEF("cgroup/getsockname6",  CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8996         SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
8997         SEC_DEF("cgroup/sysctl",        CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8998         SEC_DEF("cgroup/getsockopt",    CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8999         SEC_DEF("cgroup/setsockopt",    CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9000         SEC_DEF("cgroup/dev",           CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9001         SEC_DEF("struct_ops+",          STRUCT_OPS, 0, SEC_NONE),
9002         SEC_DEF("struct_ops.s+",        STRUCT_OPS, 0, SEC_SLEEPABLE),
9003         SEC_DEF("sk_lookup",            SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9004         SEC_DEF("netfilter",            NETFILTER, BPF_NETFILTER, SEC_NONE),
9005 };
9006
9007 int libbpf_register_prog_handler(const char *sec,
9008                                  enum bpf_prog_type prog_type,
9009                                  enum bpf_attach_type exp_attach_type,
9010                                  const struct libbpf_prog_handler_opts *opts)
9011 {
9012         struct bpf_sec_def *sec_def;
9013
9014         if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9015                 return libbpf_err(-EINVAL);
9016
9017         if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9018                 return libbpf_err(-E2BIG);
9019
9020         if (sec) {
9021                 sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9022                                               sizeof(*sec_def));
9023                 if (!sec_def)
9024                         return libbpf_err(-ENOMEM);
9025
9026                 custom_sec_defs = sec_def;
9027                 sec_def = &custom_sec_defs[custom_sec_def_cnt];
9028         } else {
9029                 if (has_custom_fallback_def)
9030                         return libbpf_err(-EBUSY);
9031
9032                 sec_def = &custom_fallback_def;
9033         }
9034
9035         sec_def->sec = sec ? strdup(sec) : NULL;
9036         if (sec && !sec_def->sec)
9037                 return libbpf_err(-ENOMEM);
9038
9039         sec_def->prog_type = prog_type;
9040         sec_def->expected_attach_type = exp_attach_type;
9041         sec_def->cookie = OPTS_GET(opts, cookie, 0);
9042
9043         sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9044         sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9045         sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9046
9047         sec_def->handler_id = ++last_custom_sec_def_handler_id;
9048
9049         if (sec)
9050                 custom_sec_def_cnt++;
9051         else
9052                 has_custom_fallback_def = true;
9053
9054         return sec_def->handler_id;
9055 }
9056
9057 int libbpf_unregister_prog_handler(int handler_id)
9058 {
9059         struct bpf_sec_def *sec_defs;
9060         int i;
9061
9062         if (handler_id <= 0)
9063                 return libbpf_err(-EINVAL);
9064
9065         if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9066                 memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9067                 has_custom_fallback_def = false;
9068                 return 0;
9069         }
9070
9071         for (i = 0; i < custom_sec_def_cnt; i++) {
9072                 if (custom_sec_defs[i].handler_id == handler_id)
9073                         break;
9074         }
9075
9076         if (i == custom_sec_def_cnt)
9077                 return libbpf_err(-ENOENT);
9078
9079         free(custom_sec_defs[i].sec);
9080         for (i = i + 1; i < custom_sec_def_cnt; i++)
9081                 custom_sec_defs[i - 1] = custom_sec_defs[i];
9082         custom_sec_def_cnt--;
9083
9084         /* try to shrink the array, but it's ok if we couldn't */
9085         sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9086         /* if new count is zero, reallocarray can return a valid NULL result;
9087          * in this case the previous pointer will be freed, so we *have to*
9088          * reassign old pointer to the new value (even if it's NULL)
9089          */
9090         if (sec_defs || custom_sec_def_cnt == 0)
9091                 custom_sec_defs = sec_defs;
9092
9093         return 0;
9094 }
9095
9096 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9097 {
9098         size_t len = strlen(sec_def->sec);
9099
9100         /* "type/" always has to have proper SEC("type/extras") form */
9101         if (sec_def->sec[len - 1] == '/') {
9102                 if (str_has_pfx(sec_name, sec_def->sec))
9103                         return true;
9104                 return false;
9105         }
9106
9107         /* "type+" means it can be either exact SEC("type") or
9108          * well-formed SEC("type/extras") with proper '/' separator
9109          */
9110         if (sec_def->sec[len - 1] == '+') {
9111                 len--;
9112                 /* not even a prefix */
9113                 if (strncmp(sec_name, sec_def->sec, len) != 0)
9114                         return false;
9115                 /* exact match or has '/' separator */
9116                 if (sec_name[len] == '\0' || sec_name[len] == '/')
9117                         return true;
9118                 return false;
9119         }
9120
9121         return strcmp(sec_name, sec_def->sec) == 0;
9122 }
9123
9124 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9125 {
9126         const struct bpf_sec_def *sec_def;
9127         int i, n;
9128
9129         n = custom_sec_def_cnt;
9130         for (i = 0; i < n; i++) {
9131                 sec_def = &custom_sec_defs[i];
9132                 if (sec_def_matches(sec_def, sec_name))
9133                         return sec_def;
9134         }
9135
9136         n = ARRAY_SIZE(section_defs);
9137         for (i = 0; i < n; i++) {
9138                 sec_def = &section_defs[i];
9139                 if (sec_def_matches(sec_def, sec_name))
9140                         return sec_def;
9141         }
9142
9143         if (has_custom_fallback_def)
9144                 return &custom_fallback_def;
9145
9146         return NULL;
9147 }
9148
9149 #define MAX_TYPE_NAME_SIZE 32
9150
9151 static char *libbpf_get_type_names(bool attach_type)
9152 {
9153         int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9154         char *buf;
9155
9156         buf = malloc(len);
9157         if (!buf)
9158                 return NULL;
9159
9160         buf[0] = '\0';
9161         /* Forge string buf with all available names */
9162         for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9163                 const struct bpf_sec_def *sec_def = &section_defs[i];
9164
9165                 if (attach_type) {
9166                         if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9167                                 continue;
9168
9169                         if (!(sec_def->cookie & SEC_ATTACHABLE))
9170                                 continue;
9171                 }
9172
9173                 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9174                         free(buf);
9175                         return NULL;
9176                 }
9177                 strcat(buf, " ");
9178                 strcat(buf, section_defs[i].sec);
9179         }
9180
9181         return buf;
9182 }
9183
9184 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9185                              enum bpf_attach_type *expected_attach_type)
9186 {
9187         const struct bpf_sec_def *sec_def;
9188         char *type_names;
9189
9190         if (!name)
9191                 return libbpf_err(-EINVAL);
9192
9193         sec_def = find_sec_def(name);
9194         if (sec_def) {
9195                 *prog_type = sec_def->prog_type;
9196                 *expected_attach_type = sec_def->expected_attach_type;
9197                 return 0;
9198         }
9199
9200         pr_debug("failed to guess program type from ELF section '%s'\n", name);
9201         type_names = libbpf_get_type_names(false);
9202         if (type_names != NULL) {
9203                 pr_debug("supported section(type) names are:%s\n", type_names);
9204                 free(type_names);
9205         }
9206
9207         return libbpf_err(-ESRCH);
9208 }
9209
9210 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9211 {
9212         if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9213                 return NULL;
9214
9215         return attach_type_name[t];
9216 }
9217
9218 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9219 {
9220         if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9221                 return NULL;
9222
9223         return link_type_name[t];
9224 }
9225
9226 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9227 {
9228         if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9229                 return NULL;
9230
9231         return map_type_name[t];
9232 }
9233
9234 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9235 {
9236         if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9237                 return NULL;
9238
9239         return prog_type_name[t];
9240 }
9241
9242 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9243                                                      int sec_idx,
9244                                                      size_t offset)
9245 {
9246         struct bpf_map *map;
9247         size_t i;
9248
9249         for (i = 0; i < obj->nr_maps; i++) {
9250                 map = &obj->maps[i];
9251                 if (!bpf_map__is_struct_ops(map))
9252                         continue;
9253                 if (map->sec_idx == sec_idx &&
9254                     map->sec_offset <= offset &&
9255                     offset - map->sec_offset < map->def.value_size)
9256                         return map;
9257         }
9258
9259         return NULL;
9260 }
9261
9262 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9263 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9264                                             Elf64_Shdr *shdr, Elf_Data *data)
9265 {
9266         const struct btf_member *member;
9267         struct bpf_struct_ops *st_ops;
9268         struct bpf_program *prog;
9269         unsigned int shdr_idx;
9270         const struct btf *btf;
9271         struct bpf_map *map;
9272         unsigned int moff, insn_idx;
9273         const char *name;
9274         __u32 member_idx;
9275         Elf64_Sym *sym;
9276         Elf64_Rel *rel;
9277         int i, nrels;
9278
9279         btf = obj->btf;
9280         nrels = shdr->sh_size / shdr->sh_entsize;
9281         for (i = 0; i < nrels; i++) {
9282                 rel = elf_rel_by_idx(data, i);
9283                 if (!rel) {
9284                         pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9285                         return -LIBBPF_ERRNO__FORMAT;
9286                 }
9287
9288                 sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9289                 if (!sym) {
9290                         pr_warn("struct_ops reloc: symbol %zx not found\n",
9291                                 (size_t)ELF64_R_SYM(rel->r_info));
9292                         return -LIBBPF_ERRNO__FORMAT;
9293                 }
9294
9295                 name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9296                 map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9297                 if (!map) {
9298                         pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9299                                 (size_t)rel->r_offset);
9300                         return -EINVAL;
9301                 }
9302
9303                 moff = rel->r_offset - map->sec_offset;
9304                 shdr_idx = sym->st_shndx;
9305                 st_ops = map->st_ops;
9306                 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",
9307                          map->name,
9308                          (long long)(rel->r_info >> 32),
9309                          (long long)sym->st_value,
9310                          shdr_idx, (size_t)rel->r_offset,
9311                          map->sec_offset, sym->st_name, name);
9312
9313                 if (shdr_idx >= SHN_LORESERVE) {
9314                         pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9315                                 map->name, (size_t)rel->r_offset, shdr_idx);
9316                         return -LIBBPF_ERRNO__RELOC;
9317                 }
9318                 if (sym->st_value % BPF_INSN_SZ) {
9319                         pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9320                                 map->name, (unsigned long long)sym->st_value);
9321                         return -LIBBPF_ERRNO__FORMAT;
9322                 }
9323                 insn_idx = sym->st_value / BPF_INSN_SZ;
9324
9325                 member = find_member_by_offset(st_ops->type, moff * 8);
9326                 if (!member) {
9327                         pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9328                                 map->name, moff);
9329                         return -EINVAL;
9330                 }
9331                 member_idx = member - btf_members(st_ops->type);
9332                 name = btf__name_by_offset(btf, member->name_off);
9333
9334                 if (!resolve_func_ptr(btf, member->type, NULL)) {
9335                         pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9336                                 map->name, name);
9337                         return -EINVAL;
9338                 }
9339
9340                 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9341                 if (!prog) {
9342                         pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9343                                 map->name, shdr_idx, name);
9344                         return -EINVAL;
9345                 }
9346
9347                 /* prevent the use of BPF prog with invalid type */
9348                 if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9349                         pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9350                                 map->name, prog->name);
9351                         return -EINVAL;
9352                 }
9353
9354                 /* if we haven't yet processed this BPF program, record proper
9355                  * attach_btf_id and member_idx
9356                  */
9357                 if (!prog->attach_btf_id) {
9358                         prog->attach_btf_id = st_ops->type_id;
9359                         prog->expected_attach_type = member_idx;
9360                 }
9361
9362                 /* struct_ops BPF prog can be re-used between multiple
9363                  * .struct_ops & .struct_ops.link as long as it's the
9364                  * same struct_ops struct definition and the same
9365                  * function pointer field
9366                  */
9367                 if (prog->attach_btf_id != st_ops->type_id ||
9368                     prog->expected_attach_type != member_idx) {
9369                         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",
9370                                 map->name, prog->name, prog->sec_name, prog->type,
9371                                 prog->attach_btf_id, prog->expected_attach_type, name);
9372                         return -EINVAL;
9373                 }
9374
9375                 st_ops->progs[member_idx] = prog;
9376         }
9377
9378         return 0;
9379 }
9380
9381 #define BTF_TRACE_PREFIX "btf_trace_"
9382 #define BTF_LSM_PREFIX "bpf_lsm_"
9383 #define BTF_ITER_PREFIX "bpf_iter_"
9384 #define BTF_MAX_NAME_SIZE 128
9385
9386 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9387                                 const char **prefix, int *kind)
9388 {
9389         switch (attach_type) {
9390         case BPF_TRACE_RAW_TP:
9391                 *prefix = BTF_TRACE_PREFIX;
9392                 *kind = BTF_KIND_TYPEDEF;
9393                 break;
9394         case BPF_LSM_MAC:
9395         case BPF_LSM_CGROUP:
9396                 *prefix = BTF_LSM_PREFIX;
9397                 *kind = BTF_KIND_FUNC;
9398                 break;
9399         case BPF_TRACE_ITER:
9400                 *prefix = BTF_ITER_PREFIX;
9401                 *kind = BTF_KIND_FUNC;
9402                 break;
9403         default:
9404                 *prefix = "";
9405                 *kind = BTF_KIND_FUNC;
9406         }
9407 }
9408
9409 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9410                                    const char *name, __u32 kind)
9411 {
9412         char btf_type_name[BTF_MAX_NAME_SIZE];
9413         int ret;
9414
9415         ret = snprintf(btf_type_name, sizeof(btf_type_name),
9416                        "%s%s", prefix, name);
9417         /* snprintf returns the number of characters written excluding the
9418          * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9419          * indicates truncation.
9420          */
9421         if (ret < 0 || ret >= sizeof(btf_type_name))
9422                 return -ENAMETOOLONG;
9423         return btf__find_by_name_kind(btf, btf_type_name, kind);
9424 }
9425
9426 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9427                                      enum bpf_attach_type attach_type)
9428 {
9429         const char *prefix;
9430         int kind;
9431
9432         btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9433         return find_btf_by_prefix_kind(btf, prefix, name, kind);
9434 }
9435
9436 int libbpf_find_vmlinux_btf_id(const char *name,
9437                                enum bpf_attach_type attach_type)
9438 {
9439         struct btf *btf;
9440         int err;
9441
9442         btf = btf__load_vmlinux_btf();
9443         err = libbpf_get_error(btf);
9444         if (err) {
9445                 pr_warn("vmlinux BTF is not found\n");
9446                 return libbpf_err(err);
9447         }
9448
9449         err = find_attach_btf_id(btf, name, attach_type);
9450         if (err <= 0)
9451                 pr_warn("%s is not found in vmlinux BTF\n", name);
9452
9453         btf__free(btf);
9454         return libbpf_err(err);
9455 }
9456
9457 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9458 {
9459         struct bpf_prog_info info;
9460         __u32 info_len = sizeof(info);
9461         struct btf *btf;
9462         int err;
9463
9464         memset(&info, 0, info_len);
9465         err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9466         if (err) {
9467                 pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9468                         attach_prog_fd, err);
9469                 return err;
9470         }
9471
9472         err = -EINVAL;
9473         if (!info.btf_id) {
9474                 pr_warn("The target program doesn't have BTF\n");
9475                 goto out;
9476         }
9477         btf = btf__load_from_kernel_by_id(info.btf_id);
9478         err = libbpf_get_error(btf);
9479         if (err) {
9480                 pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9481                 goto out;
9482         }
9483         err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9484         btf__free(btf);
9485         if (err <= 0) {
9486                 pr_warn("%s is not found in prog's BTF\n", name);
9487                 goto out;
9488         }
9489 out:
9490         return err;
9491 }
9492
9493 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9494                               enum bpf_attach_type attach_type,
9495                               int *btf_obj_fd, int *btf_type_id)
9496 {
9497         int ret, i;
9498
9499         ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9500         if (ret > 0) {
9501                 *btf_obj_fd = 0; /* vmlinux BTF */
9502                 *btf_type_id = ret;
9503                 return 0;
9504         }
9505         if (ret != -ENOENT)
9506                 return ret;
9507
9508         ret = load_module_btfs(obj);
9509         if (ret)
9510                 return ret;
9511
9512         for (i = 0; i < obj->btf_module_cnt; i++) {
9513                 const struct module_btf *mod = &obj->btf_modules[i];
9514
9515                 ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9516                 if (ret > 0) {
9517                         *btf_obj_fd = mod->fd;
9518                         *btf_type_id = ret;
9519                         return 0;
9520                 }
9521                 if (ret == -ENOENT)
9522                         continue;
9523
9524                 return ret;
9525         }
9526
9527         return -ESRCH;
9528 }
9529
9530 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9531                                      int *btf_obj_fd, int *btf_type_id)
9532 {
9533         enum bpf_attach_type attach_type = prog->expected_attach_type;
9534         __u32 attach_prog_fd = prog->attach_prog_fd;
9535         int err = 0;
9536
9537         /* BPF program's BTF ID */
9538         if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9539                 if (!attach_prog_fd) {
9540                         pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9541                         return -EINVAL;
9542                 }
9543                 err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9544                 if (err < 0) {
9545                         pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9546                                  prog->name, attach_prog_fd, attach_name, err);
9547                         return err;
9548                 }
9549                 *btf_obj_fd = 0;
9550                 *btf_type_id = err;
9551                 return 0;
9552         }
9553
9554         /* kernel/module BTF ID */
9555         if (prog->obj->gen_loader) {
9556                 bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9557                 *btf_obj_fd = 0;
9558                 *btf_type_id = 1;
9559         } else {
9560                 err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9561         }
9562         if (err) {
9563                 pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9564                         prog->name, attach_name, err);
9565                 return err;
9566         }
9567         return 0;
9568 }
9569
9570 int libbpf_attach_type_by_name(const char *name,
9571                                enum bpf_attach_type *attach_type)
9572 {
9573         char *type_names;
9574         const struct bpf_sec_def *sec_def;
9575
9576         if (!name)
9577                 return libbpf_err(-EINVAL);
9578
9579         sec_def = find_sec_def(name);
9580         if (!sec_def) {
9581                 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9582                 type_names = libbpf_get_type_names(true);
9583                 if (type_names != NULL) {
9584                         pr_debug("attachable section(type) names are:%s\n", type_names);
9585                         free(type_names);
9586                 }
9587
9588                 return libbpf_err(-EINVAL);
9589         }
9590
9591         if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9592                 return libbpf_err(-EINVAL);
9593         if (!(sec_def->cookie & SEC_ATTACHABLE))
9594                 return libbpf_err(-EINVAL);
9595
9596         *attach_type = sec_def->expected_attach_type;
9597         return 0;
9598 }
9599
9600 int bpf_map__fd(const struct bpf_map *map)
9601 {
9602         return map ? map->fd : libbpf_err(-EINVAL);
9603 }
9604
9605 static bool map_uses_real_name(const struct bpf_map *map)
9606 {
9607         /* Since libbpf started to support custom .data.* and .rodata.* maps,
9608          * their user-visible name differs from kernel-visible name. Users see
9609          * such map's corresponding ELF section name as a map name.
9610          * This check distinguishes .data/.rodata from .data.* and .rodata.*
9611          * maps to know which name has to be returned to the user.
9612          */
9613         if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9614                 return true;
9615         if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9616                 return true;
9617         return false;
9618 }
9619
9620 const char *bpf_map__name(const struct bpf_map *map)
9621 {
9622         if (!map)
9623                 return NULL;
9624
9625         if (map_uses_real_name(map))
9626                 return map->real_name;
9627
9628         return map->name;
9629 }
9630
9631 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9632 {
9633         return map->def.type;
9634 }
9635
9636 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9637 {
9638         if (map->fd >= 0)
9639                 return libbpf_err(-EBUSY);
9640         map->def.type = type;
9641         return 0;
9642 }
9643
9644 __u32 bpf_map__map_flags(const struct bpf_map *map)
9645 {
9646         return map->def.map_flags;
9647 }
9648
9649 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9650 {
9651         if (map->fd >= 0)
9652                 return libbpf_err(-EBUSY);
9653         map->def.map_flags = flags;
9654         return 0;
9655 }
9656
9657 __u64 bpf_map__map_extra(const struct bpf_map *map)
9658 {
9659         return map->map_extra;
9660 }
9661
9662 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9663 {
9664         if (map->fd >= 0)
9665                 return libbpf_err(-EBUSY);
9666         map->map_extra = map_extra;
9667         return 0;
9668 }
9669
9670 __u32 bpf_map__numa_node(const struct bpf_map *map)
9671 {
9672         return map->numa_node;
9673 }
9674
9675 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9676 {
9677         if (map->fd >= 0)
9678                 return libbpf_err(-EBUSY);
9679         map->numa_node = numa_node;
9680         return 0;
9681 }
9682
9683 __u32 bpf_map__key_size(const struct bpf_map *map)
9684 {
9685         return map->def.key_size;
9686 }
9687
9688 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9689 {
9690         if (map->fd >= 0)
9691                 return libbpf_err(-EBUSY);
9692         map->def.key_size = size;
9693         return 0;
9694 }
9695
9696 __u32 bpf_map__value_size(const struct bpf_map *map)
9697 {
9698         return map->def.value_size;
9699 }
9700
9701 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9702 {
9703         struct btf *btf;
9704         struct btf_type *datasec_type, *var_type;
9705         struct btf_var_secinfo *var;
9706         const struct btf_type *array_type;
9707         const struct btf_array *array;
9708         int vlen, element_sz, new_array_id;
9709         __u32 nr_elements;
9710
9711         /* check btf existence */
9712         btf = bpf_object__btf(map->obj);
9713         if (!btf)
9714                 return -ENOENT;
9715
9716         /* verify map is datasec */
9717         datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9718         if (!btf_is_datasec(datasec_type)) {
9719                 pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9720                         bpf_map__name(map));
9721                 return -EINVAL;
9722         }
9723
9724         /* verify datasec has at least one var */
9725         vlen = btf_vlen(datasec_type);
9726         if (vlen == 0) {
9727                 pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9728                         bpf_map__name(map));
9729                 return -EINVAL;
9730         }
9731
9732         /* verify last var in the datasec is an array */
9733         var = &btf_var_secinfos(datasec_type)[vlen - 1];
9734         var_type = btf_type_by_id(btf, var->type);
9735         array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9736         if (!btf_is_array(array_type)) {
9737                 pr_warn("map '%s': cannot be resized, last var must be an array\n",
9738                         bpf_map__name(map));
9739                 return -EINVAL;
9740         }
9741
9742         /* verify request size aligns with array */
9743         array = btf_array(array_type);
9744         element_sz = btf__resolve_size(btf, array->type);
9745         if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9746                 pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9747                         bpf_map__name(map), element_sz, size);
9748                 return -EINVAL;
9749         }
9750
9751         /* create a new array based on the existing array, but with new length */
9752         nr_elements = (size - var->offset) / element_sz;
9753         new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9754         if (new_array_id < 0)
9755                 return new_array_id;
9756
9757         /* adding a new btf type invalidates existing pointers to btf objects,
9758          * so refresh pointers before proceeding
9759          */
9760         datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9761         var = &btf_var_secinfos(datasec_type)[vlen - 1];
9762         var_type = btf_type_by_id(btf, var->type);
9763
9764         /* finally update btf info */
9765         datasec_type->size = size;
9766         var->size = size - var->offset;
9767         var_type->type = new_array_id;
9768
9769         return 0;
9770 }
9771
9772 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9773 {
9774         if (map->fd >= 0)
9775                 return libbpf_err(-EBUSY);
9776
9777         if (map->mmaped) {
9778                 int err;
9779                 size_t mmap_old_sz, mmap_new_sz;
9780
9781                 mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9782                 mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9783                 err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9784                 if (err) {
9785                         pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9786                                 bpf_map__name(map), err);
9787                         return err;
9788                 }
9789                 err = map_btf_datasec_resize(map, size);
9790                 if (err && err != -ENOENT) {
9791                         pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9792                                 bpf_map__name(map), err);
9793                         map->btf_value_type_id = 0;
9794                         map->btf_key_type_id = 0;
9795                 }
9796         }
9797
9798         map->def.value_size = size;
9799         return 0;
9800 }
9801
9802 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9803 {
9804         return map ? map->btf_key_type_id : 0;
9805 }
9806
9807 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9808 {
9809         return map ? map->btf_value_type_id : 0;
9810 }
9811
9812 int bpf_map__set_initial_value(struct bpf_map *map,
9813                                const void *data, size_t size)
9814 {
9815         if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9816             size != map->def.value_size || map->fd >= 0)
9817                 return libbpf_err(-EINVAL);
9818
9819         memcpy(map->mmaped, data, size);
9820         return 0;
9821 }
9822
9823 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9824 {
9825         if (!map->mmaped)
9826                 return NULL;
9827         *psize = map->def.value_size;
9828         return map->mmaped;
9829 }
9830
9831 bool bpf_map__is_internal(const struct bpf_map *map)
9832 {
9833         return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9834 }
9835
9836 __u32 bpf_map__ifindex(const struct bpf_map *map)
9837 {
9838         return map->map_ifindex;
9839 }
9840
9841 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9842 {
9843         if (map->fd >= 0)
9844                 return libbpf_err(-EBUSY);
9845         map->map_ifindex = ifindex;
9846         return 0;
9847 }
9848
9849 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9850 {
9851         if (!bpf_map_type__is_map_in_map(map->def.type)) {
9852                 pr_warn("error: unsupported map type\n");
9853                 return libbpf_err(-EINVAL);
9854         }
9855         if (map->inner_map_fd != -1) {
9856                 pr_warn("error: inner_map_fd already specified\n");
9857                 return libbpf_err(-EINVAL);
9858         }
9859         if (map->inner_map) {
9860                 bpf_map__destroy(map->inner_map);
9861                 zfree(&map->inner_map);
9862         }
9863         map->inner_map_fd = fd;
9864         return 0;
9865 }
9866
9867 static struct bpf_map *
9868 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9869 {
9870         ssize_t idx;
9871         struct bpf_map *s, *e;
9872
9873         if (!obj || !obj->maps)
9874                 return errno = EINVAL, NULL;
9875
9876         s = obj->maps;
9877         e = obj->maps + obj->nr_maps;
9878
9879         if ((m < s) || (m >= e)) {
9880                 pr_warn("error in %s: map handler doesn't belong to object\n",
9881                          __func__);
9882                 return errno = EINVAL, NULL;
9883         }
9884
9885         idx = (m - obj->maps) + i;
9886         if (idx >= obj->nr_maps || idx < 0)
9887                 return NULL;
9888         return &obj->maps[idx];
9889 }
9890
9891 struct bpf_map *
9892 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9893 {
9894         if (prev == NULL)
9895                 return obj->maps;
9896
9897         return __bpf_map__iter(prev, obj, 1);
9898 }
9899
9900 struct bpf_map *
9901 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9902 {
9903         if (next == NULL) {
9904                 if (!obj->nr_maps)
9905                         return NULL;
9906                 return obj->maps + obj->nr_maps - 1;
9907         }
9908
9909         return __bpf_map__iter(next, obj, -1);
9910 }
9911
9912 struct bpf_map *
9913 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9914 {
9915         struct bpf_map *pos;
9916
9917         bpf_object__for_each_map(pos, obj) {
9918                 /* if it's a special internal map name (which always starts
9919                  * with dot) then check if that special name matches the
9920                  * real map name (ELF section name)
9921                  */
9922                 if (name[0] == '.') {
9923                         if (pos->real_name && strcmp(pos->real_name, name) == 0)
9924                                 return pos;
9925                         continue;
9926                 }
9927                 /* otherwise map name has to be an exact match */
9928                 if (map_uses_real_name(pos)) {
9929                         if (strcmp(pos->real_name, name) == 0)
9930                                 return pos;
9931                         continue;
9932                 }
9933                 if (strcmp(pos->name, name) == 0)
9934                         return pos;
9935         }
9936         return errno = ENOENT, NULL;
9937 }
9938
9939 int
9940 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9941 {
9942         return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9943 }
9944
9945 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9946                            size_t value_sz, bool check_value_sz)
9947 {
9948         if (map->fd <= 0)
9949                 return -ENOENT;
9950
9951         if (map->def.key_size != key_sz) {
9952                 pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9953                         map->name, key_sz, map->def.key_size);
9954                 return -EINVAL;
9955         }
9956
9957         if (!check_value_sz)
9958                 return 0;
9959
9960         switch (map->def.type) {
9961         case BPF_MAP_TYPE_PERCPU_ARRAY:
9962         case BPF_MAP_TYPE_PERCPU_HASH:
9963         case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9964         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9965                 int num_cpu = libbpf_num_possible_cpus();
9966                 size_t elem_sz = roundup(map->def.value_size, 8);
9967
9968                 if (value_sz != num_cpu * elem_sz) {
9969                         pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9970                                 map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9971                         return -EINVAL;
9972                 }
9973                 break;
9974         }
9975         default:
9976                 if (map->def.value_size != value_sz) {
9977                         pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9978                                 map->name, value_sz, map->def.value_size);
9979                         return -EINVAL;
9980                 }
9981                 break;
9982         }
9983         return 0;
9984 }
9985
9986 int bpf_map__lookup_elem(const struct bpf_map *map,
9987                          const void *key, size_t key_sz,
9988                          void *value, size_t value_sz, __u64 flags)
9989 {
9990         int err;
9991
9992         err = validate_map_op(map, key_sz, value_sz, true);
9993         if (err)
9994                 return libbpf_err(err);
9995
9996         return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9997 }
9998
9999 int bpf_map__update_elem(const struct bpf_map *map,
10000                          const void *key, size_t key_sz,
10001                          const void *value, size_t value_sz, __u64 flags)
10002 {
10003         int err;
10004
10005         err = validate_map_op(map, key_sz, value_sz, true);
10006         if (err)
10007                 return libbpf_err(err);
10008
10009         return bpf_map_update_elem(map->fd, key, value, flags);
10010 }
10011
10012 int bpf_map__delete_elem(const struct bpf_map *map,
10013                          const void *key, size_t key_sz, __u64 flags)
10014 {
10015         int err;
10016
10017         err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10018         if (err)
10019                 return libbpf_err(err);
10020
10021         return bpf_map_delete_elem_flags(map->fd, key, flags);
10022 }
10023
10024 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10025                                     const void *key, size_t key_sz,
10026                                     void *value, size_t value_sz, __u64 flags)
10027 {
10028         int err;
10029
10030         err = validate_map_op(map, key_sz, value_sz, true);
10031         if (err)
10032                 return libbpf_err(err);
10033
10034         return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10035 }
10036
10037 int bpf_map__get_next_key(const struct bpf_map *map,
10038                           const void *cur_key, void *next_key, size_t key_sz)
10039 {
10040         int err;
10041
10042         err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10043         if (err)
10044                 return libbpf_err(err);
10045
10046         return bpf_map_get_next_key(map->fd, cur_key, next_key);
10047 }
10048
10049 long libbpf_get_error(const void *ptr)
10050 {
10051         if (!IS_ERR_OR_NULL(ptr))
10052                 return 0;
10053
10054         if (IS_ERR(ptr))
10055                 errno = -PTR_ERR(ptr);
10056
10057         /* If ptr == NULL, then errno should be already set by the failing
10058          * API, because libbpf never returns NULL on success and it now always
10059          * sets errno on error. So no extra errno handling for ptr == NULL
10060          * case.
10061          */
10062         return -errno;
10063 }
10064
10065 /* Replace link's underlying BPF program with the new one */
10066 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10067 {
10068         int ret;
10069
10070         ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
10071         return libbpf_err_errno(ret);
10072 }
10073
10074 /* Release "ownership" of underlying BPF resource (typically, BPF program
10075  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10076  * link, when destructed through bpf_link__destroy() call won't attempt to
10077  * detach/unregisted that BPF resource. This is useful in situations where,
10078  * say, attached BPF program has to outlive userspace program that attached it
10079  * in the system. Depending on type of BPF program, though, there might be
10080  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10081  * exit of userspace program doesn't trigger automatic detachment and clean up
10082  * inside the kernel.
10083  */
10084 void bpf_link__disconnect(struct bpf_link *link)
10085 {
10086         link->disconnected = true;
10087 }
10088
10089 int bpf_link__destroy(struct bpf_link *link)
10090 {
10091         int err = 0;
10092
10093         if (IS_ERR_OR_NULL(link))
10094                 return 0;
10095
10096         if (!link->disconnected && link->detach)
10097                 err = link->detach(link);
10098         if (link->pin_path)
10099                 free(link->pin_path);
10100         if (link->dealloc)
10101                 link->dealloc(link);
10102         else
10103                 free(link);
10104
10105         return libbpf_err(err);
10106 }
10107
10108 int bpf_link__fd(const struct bpf_link *link)
10109 {
10110         return link->fd;
10111 }
10112
10113 const char *bpf_link__pin_path(const struct bpf_link *link)
10114 {
10115         return link->pin_path;
10116 }
10117
10118 static int bpf_link__detach_fd(struct bpf_link *link)
10119 {
10120         return libbpf_err_errno(close(link->fd));
10121 }
10122
10123 struct bpf_link *bpf_link__open(const char *path)
10124 {
10125         struct bpf_link *link;
10126         int fd;
10127
10128         fd = bpf_obj_get(path);
10129         if (fd < 0) {
10130                 fd = -errno;
10131                 pr_warn("failed to open link at %s: %d\n", path, fd);
10132                 return libbpf_err_ptr(fd);
10133         }
10134
10135         link = calloc(1, sizeof(*link));
10136         if (!link) {
10137                 close(fd);
10138                 return libbpf_err_ptr(-ENOMEM);
10139         }
10140         link->detach = &bpf_link__detach_fd;
10141         link->fd = fd;
10142
10143         link->pin_path = strdup(path);
10144         if (!link->pin_path) {
10145                 bpf_link__destroy(link);
10146                 return libbpf_err_ptr(-ENOMEM);
10147         }
10148
10149         return link;
10150 }
10151
10152 int bpf_link__detach(struct bpf_link *link)
10153 {
10154         return bpf_link_detach(link->fd) ? -errno : 0;
10155 }
10156
10157 int bpf_link__pin(struct bpf_link *link, const char *path)
10158 {
10159         int err;
10160
10161         if (link->pin_path)
10162                 return libbpf_err(-EBUSY);
10163         err = make_parent_dir(path);
10164         if (err)
10165                 return libbpf_err(err);
10166         err = check_path(path);
10167         if (err)
10168                 return libbpf_err(err);
10169
10170         link->pin_path = strdup(path);
10171         if (!link->pin_path)
10172                 return libbpf_err(-ENOMEM);
10173
10174         if (bpf_obj_pin(link->fd, link->pin_path)) {
10175                 err = -errno;
10176                 zfree(&link->pin_path);
10177                 return libbpf_err(err);
10178         }
10179
10180         pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10181         return 0;
10182 }
10183
10184 int bpf_link__unpin(struct bpf_link *link)
10185 {
10186         int err;
10187
10188         if (!link->pin_path)
10189                 return libbpf_err(-EINVAL);
10190
10191         err = unlink(link->pin_path);
10192         if (err != 0)
10193                 return -errno;
10194
10195         pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10196         zfree(&link->pin_path);
10197         return 0;
10198 }
10199
10200 struct bpf_link_perf {
10201         struct bpf_link link;
10202         int perf_event_fd;
10203         /* legacy kprobe support: keep track of probe identifier and type */
10204         char *legacy_probe_name;
10205         bool legacy_is_kprobe;
10206         bool legacy_is_retprobe;
10207 };
10208
10209 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10210 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10211
10212 static int bpf_link_perf_detach(struct bpf_link *link)
10213 {
10214         struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10215         int err = 0;
10216
10217         if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10218                 err = -errno;
10219
10220         if (perf_link->perf_event_fd != link->fd)
10221                 close(perf_link->perf_event_fd);
10222         close(link->fd);
10223
10224         /* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10225         if (perf_link->legacy_probe_name) {
10226                 if (perf_link->legacy_is_kprobe) {
10227                         err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10228                                                          perf_link->legacy_is_retprobe);
10229                 } else {
10230                         err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10231                                                          perf_link->legacy_is_retprobe);
10232                 }
10233         }
10234
10235         return err;
10236 }
10237
10238 static void bpf_link_perf_dealloc(struct bpf_link *link)
10239 {
10240         struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10241
10242         free(perf_link->legacy_probe_name);
10243         free(perf_link);
10244 }
10245
10246 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10247                                                      const struct bpf_perf_event_opts *opts)
10248 {
10249         char errmsg[STRERR_BUFSIZE];
10250         struct bpf_link_perf *link;
10251         int prog_fd, link_fd = -1, err;
10252         bool force_ioctl_attach;
10253
10254         if (!OPTS_VALID(opts, bpf_perf_event_opts))
10255                 return libbpf_err_ptr(-EINVAL);
10256
10257         if (pfd < 0) {
10258                 pr_warn("prog '%s': invalid perf event FD %d\n",
10259                         prog->name, pfd);
10260                 return libbpf_err_ptr(-EINVAL);
10261         }
10262         prog_fd = bpf_program__fd(prog);
10263         if (prog_fd < 0) {
10264                 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10265                         prog->name);
10266                 return libbpf_err_ptr(-EINVAL);
10267         }
10268
10269         link = calloc(1, sizeof(*link));
10270         if (!link)
10271                 return libbpf_err_ptr(-ENOMEM);
10272         link->link.detach = &bpf_link_perf_detach;
10273         link->link.dealloc = &bpf_link_perf_dealloc;
10274         link->perf_event_fd = pfd;
10275
10276         force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10277         if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10278                 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10279                         .perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10280
10281                 link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10282                 if (link_fd < 0) {
10283                         err = -errno;
10284                         pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10285                                 prog->name, pfd,
10286                                 err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10287                         goto err_out;
10288                 }
10289                 link->link.fd = link_fd;
10290         } else {
10291                 if (OPTS_GET(opts, bpf_cookie, 0)) {
10292                         pr_warn("prog '%s': user context value is not supported\n", prog->name);
10293                         err = -EOPNOTSUPP;
10294                         goto err_out;
10295                 }
10296
10297                 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10298                         err = -errno;
10299                         pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10300                                 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10301                         if (err == -EPROTO)
10302                                 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10303                                         prog->name, pfd);
10304                         goto err_out;
10305                 }
10306                 link->link.fd = pfd;
10307         }
10308         if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10309                 err = -errno;
10310                 pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10311                         prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10312                 goto err_out;
10313         }
10314
10315         return &link->link;
10316 err_out:
10317         if (link_fd >= 0)
10318                 close(link_fd);
10319         free(link);
10320         return libbpf_err_ptr(err);
10321 }
10322
10323 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10324 {
10325         return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10326 }
10327
10328 /*
10329  * this function is expected to parse integer in the range of [0, 2^31-1] from
10330  * given file using scanf format string fmt. If actual parsed value is
10331  * negative, the result might be indistinguishable from error
10332  */
10333 static int parse_uint_from_file(const char *file, const char *fmt)
10334 {
10335         char buf[STRERR_BUFSIZE];
10336         int err, ret;
10337         FILE *f;
10338
10339         f = fopen(file, "re");
10340         if (!f) {
10341                 err = -errno;
10342                 pr_debug("failed to open '%s': %s\n", file,
10343                          libbpf_strerror_r(err, buf, sizeof(buf)));
10344                 return err;
10345         }
10346         err = fscanf(f, fmt, &ret);
10347         if (err != 1) {
10348                 err = err == EOF ? -EIO : -errno;
10349                 pr_debug("failed to parse '%s': %s\n", file,
10350                         libbpf_strerror_r(err, buf, sizeof(buf)));
10351                 fclose(f);
10352                 return err;
10353         }
10354         fclose(f);
10355         return ret;
10356 }
10357
10358 static int determine_kprobe_perf_type(void)
10359 {
10360         const char *file = "/sys/bus/event_source/devices/kprobe/type";
10361
10362         return parse_uint_from_file(file, "%d\n");
10363 }
10364
10365 static int determine_uprobe_perf_type(void)
10366 {
10367         const char *file = "/sys/bus/event_source/devices/uprobe/type";
10368
10369         return parse_uint_from_file(file, "%d\n");
10370 }
10371
10372 static int determine_kprobe_retprobe_bit(void)
10373 {
10374         const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10375
10376         return parse_uint_from_file(file, "config:%d\n");
10377 }
10378
10379 static int determine_uprobe_retprobe_bit(void)
10380 {
10381         const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10382
10383         return parse_uint_from_file(file, "config:%d\n");
10384 }
10385
10386 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10387 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10388
10389 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10390                                  uint64_t offset, int pid, size_t ref_ctr_off)
10391 {
10392         const size_t attr_sz = sizeof(struct perf_event_attr);
10393         struct perf_event_attr attr;
10394         char errmsg[STRERR_BUFSIZE];
10395         int type, pfd;
10396
10397         if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10398                 return -EINVAL;
10399
10400         memset(&attr, 0, attr_sz);
10401
10402         type = uprobe ? determine_uprobe_perf_type()
10403                       : determine_kprobe_perf_type();
10404         if (type < 0) {
10405                 pr_warn("failed to determine %s perf type: %s\n",
10406                         uprobe ? "uprobe" : "kprobe",
10407                         libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10408                 return type;
10409         }
10410         if (retprobe) {
10411                 int bit = uprobe ? determine_uprobe_retprobe_bit()
10412                                  : determine_kprobe_retprobe_bit();
10413
10414                 if (bit < 0) {
10415                         pr_warn("failed to determine %s retprobe bit: %s\n",
10416                                 uprobe ? "uprobe" : "kprobe",
10417                                 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10418                         return bit;
10419                 }
10420                 attr.config |= 1 << bit;
10421         }
10422         attr.size = attr_sz;
10423         attr.type = type;
10424         attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10425         attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10426         attr.config2 = offset;           /* kprobe_addr or probe_offset */
10427
10428         /* pid filter is meaningful only for uprobes */
10429         pfd = syscall(__NR_perf_event_open, &attr,
10430                       pid < 0 ? -1 : pid /* pid */,
10431                       pid == -1 ? 0 : -1 /* cpu */,
10432                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10433         return pfd >= 0 ? pfd : -errno;
10434 }
10435
10436 static int append_to_file(const char *file, const char *fmt, ...)
10437 {
10438         int fd, n, err = 0;
10439         va_list ap;
10440         char buf[1024];
10441
10442         va_start(ap, fmt);
10443         n = vsnprintf(buf, sizeof(buf), fmt, ap);
10444         va_end(ap);
10445
10446         if (n < 0 || n >= sizeof(buf))
10447                 return -EINVAL;
10448
10449         fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10450         if (fd < 0)
10451                 return -errno;
10452
10453         if (write(fd, buf, n) < 0)
10454                 err = -errno;
10455
10456         close(fd);
10457         return err;
10458 }
10459
10460 #define DEBUGFS "/sys/kernel/debug/tracing"
10461 #define TRACEFS "/sys/kernel/tracing"
10462
10463 static bool use_debugfs(void)
10464 {
10465         static int has_debugfs = -1;
10466
10467         if (has_debugfs < 0)
10468                 has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10469
10470         return has_debugfs == 1;
10471 }
10472
10473 static const char *tracefs_path(void)
10474 {
10475         return use_debugfs() ? DEBUGFS : TRACEFS;
10476 }
10477
10478 static const char *tracefs_kprobe_events(void)
10479 {
10480         return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10481 }
10482
10483 static const char *tracefs_uprobe_events(void)
10484 {
10485         return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10486 }
10487
10488 static const char *tracefs_available_filter_functions(void)
10489 {
10490         return use_debugfs() ? DEBUGFS"/available_filter_functions"
10491                              : TRACEFS"/available_filter_functions";
10492 }
10493
10494 static const char *tracefs_available_filter_functions_addrs(void)
10495 {
10496         return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10497                              : TRACEFS"/available_filter_functions_addrs";
10498 }
10499
10500 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10501                                          const char *kfunc_name, size_t offset)
10502 {
10503         static int index = 0;
10504         int i;
10505
10506         snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10507                  __sync_fetch_and_add(&index, 1));
10508
10509         /* sanitize binary_path in the probe name */
10510         for (i = 0; buf[i]; i++) {
10511                 if (!isalnum(buf[i]))
10512                         buf[i] = '_';
10513         }
10514 }
10515
10516 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10517                                    const char *kfunc_name, size_t offset)
10518 {
10519         return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10520                               retprobe ? 'r' : 'p',
10521                               retprobe ? "kretprobes" : "kprobes",
10522                               probe_name, kfunc_name, offset);
10523 }
10524
10525 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10526 {
10527         return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10528                               retprobe ? "kretprobes" : "kprobes", probe_name);
10529 }
10530
10531 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10532 {
10533         char file[256];
10534
10535         snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10536                  tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10537
10538         return parse_uint_from_file(file, "%d\n");
10539 }
10540
10541 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10542                                          const char *kfunc_name, size_t offset, int pid)
10543 {
10544         const size_t attr_sz = sizeof(struct perf_event_attr);
10545         struct perf_event_attr attr;
10546         char errmsg[STRERR_BUFSIZE];
10547         int type, pfd, err;
10548
10549         err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10550         if (err < 0) {
10551                 pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10552                         kfunc_name, offset,
10553                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10554                 return err;
10555         }
10556         type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10557         if (type < 0) {
10558                 err = type;
10559                 pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10560                         kfunc_name, offset,
10561                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10562                 goto err_clean_legacy;
10563         }
10564
10565         memset(&attr, 0, attr_sz);
10566         attr.size = attr_sz;
10567         attr.config = type;
10568         attr.type = PERF_TYPE_TRACEPOINT;
10569
10570         pfd = syscall(__NR_perf_event_open, &attr,
10571                       pid < 0 ? -1 : pid, /* pid */
10572                       pid == -1 ? 0 : -1, /* cpu */
10573                       -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10574         if (pfd < 0) {
10575                 err = -errno;
10576                 pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10577                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10578                 goto err_clean_legacy;
10579         }
10580         return pfd;
10581
10582 err_clean_legacy:
10583         /* Clear the newly added legacy kprobe_event */
10584         remove_kprobe_event_legacy(probe_name, retprobe);
10585         return err;
10586 }
10587
10588 static const char *arch_specific_syscall_pfx(void)
10589 {
10590 #if defined(__x86_64__)
10591         return "x64";
10592 #elif defined(__i386__)
10593         return "ia32";
10594 #elif defined(__s390x__)
10595         return "s390x";
10596 #elif defined(__s390__)
10597         return "s390";
10598 #elif defined(__arm__)
10599         return "arm";
10600 #elif defined(__aarch64__)
10601         return "arm64";
10602 #elif defined(__mips__)
10603         return "mips";
10604 #elif defined(__riscv)
10605         return "riscv";
10606 #elif defined(__powerpc__)
10607         return "powerpc";
10608 #elif defined(__powerpc64__)
10609         return "powerpc64";
10610 #else
10611         return NULL;
10612 #endif
10613 }
10614
10615 static int probe_kern_syscall_wrapper(void)
10616 {
10617         char syscall_name[64];
10618         const char *ksys_pfx;
10619
10620         ksys_pfx = arch_specific_syscall_pfx();
10621         if (!ksys_pfx)
10622                 return 0;
10623
10624         snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10625
10626         if (determine_kprobe_perf_type() >= 0) {
10627                 int pfd;
10628
10629                 pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10630                 if (pfd >= 0)
10631                         close(pfd);
10632
10633                 return pfd >= 0 ? 1 : 0;
10634         } else { /* legacy mode */
10635                 char probe_name[128];
10636
10637                 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10638                 if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10639                         return 0;
10640
10641                 (void)remove_kprobe_event_legacy(probe_name, false);
10642                 return 1;
10643         }
10644 }
10645
10646 struct bpf_link *
10647 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10648                                 const char *func_name,
10649                                 const struct bpf_kprobe_opts *opts)
10650 {
10651         DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10652         enum probe_attach_mode attach_mode;
10653         char errmsg[STRERR_BUFSIZE];
10654         char *legacy_probe = NULL;
10655         struct bpf_link *link;
10656         size_t offset;
10657         bool retprobe, legacy;
10658         int pfd, err;
10659
10660         if (!OPTS_VALID(opts, bpf_kprobe_opts))
10661                 return libbpf_err_ptr(-EINVAL);
10662
10663         attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10664         retprobe = OPTS_GET(opts, retprobe, false);
10665         offset = OPTS_GET(opts, offset, 0);
10666         pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10667
10668         legacy = determine_kprobe_perf_type() < 0;
10669         switch (attach_mode) {
10670         case PROBE_ATTACH_MODE_LEGACY:
10671                 legacy = true;
10672                 pe_opts.force_ioctl_attach = true;
10673                 break;
10674         case PROBE_ATTACH_MODE_PERF:
10675                 if (legacy)
10676                         return libbpf_err_ptr(-ENOTSUP);
10677                 pe_opts.force_ioctl_attach = true;
10678                 break;
10679         case PROBE_ATTACH_MODE_LINK:
10680                 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10681                         return libbpf_err_ptr(-ENOTSUP);
10682                 break;
10683         case PROBE_ATTACH_MODE_DEFAULT:
10684                 break;
10685         default:
10686                 return libbpf_err_ptr(-EINVAL);
10687         }
10688
10689         if (!legacy) {
10690                 pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10691                                             func_name, offset,
10692                                             -1 /* pid */, 0 /* ref_ctr_off */);
10693         } else {
10694                 char probe_name[256];
10695
10696                 gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10697                                              func_name, offset);
10698
10699                 legacy_probe = strdup(probe_name);
10700                 if (!legacy_probe)
10701                         return libbpf_err_ptr(-ENOMEM);
10702
10703                 pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10704                                                     offset, -1 /* pid */);
10705         }
10706         if (pfd < 0) {
10707                 err = -errno;
10708                 pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10709                         prog->name, retprobe ? "kretprobe" : "kprobe",
10710                         func_name, offset,
10711                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10712                 goto err_out;
10713         }
10714         link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10715         err = libbpf_get_error(link);
10716         if (err) {
10717                 close(pfd);
10718                 pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10719                         prog->name, retprobe ? "kretprobe" : "kprobe",
10720                         func_name, offset,
10721                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10722                 goto err_clean_legacy;
10723         }
10724         if (legacy) {
10725                 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10726
10727                 perf_link->legacy_probe_name = legacy_probe;
10728                 perf_link->legacy_is_kprobe = true;
10729                 perf_link->legacy_is_retprobe = retprobe;
10730         }
10731
10732         return link;
10733
10734 err_clean_legacy:
10735         if (legacy)
10736                 remove_kprobe_event_legacy(legacy_probe, retprobe);
10737 err_out:
10738         free(legacy_probe);
10739         return libbpf_err_ptr(err);
10740 }
10741
10742 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10743                                             bool retprobe,
10744                                             const char *func_name)
10745 {
10746         DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10747                 .retprobe = retprobe,
10748         );
10749
10750         return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10751 }
10752
10753 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10754                                               const char *syscall_name,
10755                                               const struct bpf_ksyscall_opts *opts)
10756 {
10757         LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10758         char func_name[128];
10759
10760         if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10761                 return libbpf_err_ptr(-EINVAL);
10762
10763         if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10764                 /* arch_specific_syscall_pfx() should never return NULL here
10765                  * because it is guarded by kernel_supports(). However, since
10766                  * compiler does not know that we have an explicit conditional
10767                  * as well.
10768                  */
10769                 snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10770                          arch_specific_syscall_pfx() ? : "", syscall_name);
10771         } else {
10772                 snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10773         }
10774
10775         kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10776         kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10777
10778         return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10779 }
10780
10781 /* Adapted from perf/util/string.c */
10782 bool glob_match(const char *str, const char *pat)
10783 {
10784         while (*str && *pat && *pat != '*') {
10785                 if (*pat == '?') {      /* Matches any single character */
10786                         str++;
10787                         pat++;
10788                         continue;
10789                 }
10790                 if (*str != *pat)
10791                         return false;
10792                 str++;
10793                 pat++;
10794         }
10795         /* Check wild card */
10796         if (*pat == '*') {
10797                 while (*pat == '*')
10798                         pat++;
10799                 if (!*pat) /* Tail wild card matches all */
10800                         return true;
10801                 while (*str)
10802                         if (glob_match(str++, pat))
10803                                 return true;
10804         }
10805         return !*str && !*pat;
10806 }
10807
10808 struct kprobe_multi_resolve {
10809         const char *pattern;
10810         unsigned long *addrs;
10811         size_t cap;
10812         size_t cnt;
10813 };
10814
10815 struct avail_kallsyms_data {
10816         char **syms;
10817         size_t cnt;
10818         struct kprobe_multi_resolve *res;
10819 };
10820
10821 static int avail_func_cmp(const void *a, const void *b)
10822 {
10823         return strcmp(*(const char **)a, *(const char **)b);
10824 }
10825
10826 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10827                              const char *sym_name, void *ctx)
10828 {
10829         struct avail_kallsyms_data *data = ctx;
10830         struct kprobe_multi_resolve *res = data->res;
10831         int err;
10832
10833         if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10834                 return 0;
10835
10836         err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10837         if (err)
10838                 return err;
10839
10840         res->addrs[res->cnt++] = (unsigned long)sym_addr;
10841         return 0;
10842 }
10843
10844 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10845 {
10846         const char *available_functions_file = tracefs_available_filter_functions();
10847         struct avail_kallsyms_data data;
10848         char sym_name[500];
10849         FILE *f;
10850         int err = 0, ret, i;
10851         char **syms = NULL;
10852         size_t cap = 0, cnt = 0;
10853
10854         f = fopen(available_functions_file, "re");
10855         if (!f) {
10856                 err = -errno;
10857                 pr_warn("failed to open %s: %d\n", available_functions_file, err);
10858                 return err;
10859         }
10860
10861         while (true) {
10862                 char *name;
10863
10864                 ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10865                 if (ret == EOF && feof(f))
10866                         break;
10867
10868                 if (ret != 1) {
10869                         pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10870                         err = -EINVAL;
10871                         goto cleanup;
10872                 }
10873
10874                 if (!glob_match(sym_name, res->pattern))
10875                         continue;
10876
10877                 err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10878                 if (err)
10879                         goto cleanup;
10880
10881                 name = strdup(sym_name);
10882                 if (!name) {
10883                         err = -errno;
10884                         goto cleanup;
10885                 }
10886
10887                 syms[cnt++] = name;
10888         }
10889
10890         /* no entries found, bail out */
10891         if (cnt == 0) {
10892                 err = -ENOENT;
10893                 goto cleanup;
10894         }
10895
10896         /* sort available functions */
10897         qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10898
10899         data.syms = syms;
10900         data.res = res;
10901         data.cnt = cnt;
10902         libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10903
10904         if (res->cnt == 0)
10905                 err = -ENOENT;
10906
10907 cleanup:
10908         for (i = 0; i < cnt; i++)
10909                 free((char *)syms[i]);
10910         free(syms);
10911
10912         fclose(f);
10913         return err;
10914 }
10915
10916 static bool has_available_filter_functions_addrs(void)
10917 {
10918         return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10919 }
10920
10921 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10922 {
10923         const char *available_path = tracefs_available_filter_functions_addrs();
10924         char sym_name[500];
10925         FILE *f;
10926         int ret, err = 0;
10927         unsigned long long sym_addr;
10928
10929         f = fopen(available_path, "re");
10930         if (!f) {
10931                 err = -errno;
10932                 pr_warn("failed to open %s: %d\n", available_path, err);
10933                 return err;
10934         }
10935
10936         while (true) {
10937                 ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10938                 if (ret == EOF && feof(f))
10939                         break;
10940
10941                 if (ret != 2) {
10942                         pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10943                                 ret);
10944                         err = -EINVAL;
10945                         goto cleanup;
10946                 }
10947
10948                 if (!glob_match(sym_name, res->pattern))
10949                         continue;
10950
10951                 err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10952                                         sizeof(*res->addrs), res->cnt + 1);
10953                 if (err)
10954                         goto cleanup;
10955
10956                 res->addrs[res->cnt++] = (unsigned long)sym_addr;
10957         }
10958
10959         if (res->cnt == 0)
10960                 err = -ENOENT;
10961
10962 cleanup:
10963         fclose(f);
10964         return err;
10965 }
10966
10967 struct bpf_link *
10968 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10969                                       const char *pattern,
10970                                       const struct bpf_kprobe_multi_opts *opts)
10971 {
10972         LIBBPF_OPTS(bpf_link_create_opts, lopts);
10973         struct kprobe_multi_resolve res = {
10974                 .pattern = pattern,
10975         };
10976         struct bpf_link *link = NULL;
10977         char errmsg[STRERR_BUFSIZE];
10978         const unsigned long *addrs;
10979         int err, link_fd, prog_fd;
10980         const __u64 *cookies;
10981         const char **syms;
10982         bool retprobe;
10983         size_t cnt;
10984
10985         if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10986                 return libbpf_err_ptr(-EINVAL);
10987
10988         syms    = OPTS_GET(opts, syms, false);
10989         addrs   = OPTS_GET(opts, addrs, false);
10990         cnt     = OPTS_GET(opts, cnt, false);
10991         cookies = OPTS_GET(opts, cookies, false);
10992
10993         if (!pattern && !addrs && !syms)
10994                 return libbpf_err_ptr(-EINVAL);
10995         if (pattern && (addrs || syms || cookies || cnt))
10996                 return libbpf_err_ptr(-EINVAL);
10997         if (!pattern && !cnt)
10998                 return libbpf_err_ptr(-EINVAL);
10999         if (addrs && syms)
11000                 return libbpf_err_ptr(-EINVAL);
11001
11002         if (pattern) {
11003                 if (has_available_filter_functions_addrs())
11004                         err = libbpf_available_kprobes_parse(&res);
11005                 else
11006                         err = libbpf_available_kallsyms_parse(&res);
11007                 if (err)
11008                         goto error;
11009                 addrs = res.addrs;
11010                 cnt = res.cnt;
11011         }
11012
11013         retprobe = OPTS_GET(opts, retprobe, false);
11014
11015         lopts.kprobe_multi.syms = syms;
11016         lopts.kprobe_multi.addrs = addrs;
11017         lopts.kprobe_multi.cookies = cookies;
11018         lopts.kprobe_multi.cnt = cnt;
11019         lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11020
11021         link = calloc(1, sizeof(*link));
11022         if (!link) {
11023                 err = -ENOMEM;
11024                 goto error;
11025         }
11026         link->detach = &bpf_link__detach_fd;
11027
11028         prog_fd = bpf_program__fd(prog);
11029         link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
11030         if (link_fd < 0) {
11031                 err = -errno;
11032                 pr_warn("prog '%s': failed to attach: %s\n",
11033                         prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11034                 goto error;
11035         }
11036         link->fd = link_fd;
11037         free(res.addrs);
11038         return link;
11039
11040 error:
11041         free(link);
11042         free(res.addrs);
11043         return libbpf_err_ptr(err);
11044 }
11045
11046 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11047 {
11048         DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11049         unsigned long offset = 0;
11050         const char *func_name;
11051         char *func;
11052         int n;
11053
11054         *link = NULL;
11055
11056         /* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11057         if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11058                 return 0;
11059
11060         opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11061         if (opts.retprobe)
11062                 func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11063         else
11064                 func_name = prog->sec_name + sizeof("kprobe/") - 1;
11065
11066         n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11067         if (n < 1) {
11068                 pr_warn("kprobe name is invalid: %s\n", func_name);
11069                 return -EINVAL;
11070         }
11071         if (opts.retprobe && offset != 0) {
11072                 free(func);
11073                 pr_warn("kretprobes do not support offset specification\n");
11074                 return -EINVAL;
11075         }
11076
11077         opts.offset = offset;
11078         *link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11079         free(func);
11080         return libbpf_get_error(*link);
11081 }
11082
11083 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11084 {
11085         LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11086         const char *syscall_name;
11087
11088         *link = NULL;
11089
11090         /* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11091         if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11092                 return 0;
11093
11094         opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11095         if (opts.retprobe)
11096                 syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11097         else
11098                 syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11099
11100         *link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11101         return *link ? 0 : -errno;
11102 }
11103
11104 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11105 {
11106         LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11107         const char *spec;
11108         char *pattern;
11109         int n;
11110
11111         *link = NULL;
11112
11113         /* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11114         if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11115             strcmp(prog->sec_name, "kretprobe.multi") == 0)
11116                 return 0;
11117
11118         opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11119         if (opts.retprobe)
11120                 spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11121         else
11122                 spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11123
11124         n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11125         if (n < 1) {
11126                 pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
11127                 return -EINVAL;
11128         }
11129
11130         *link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11131         free(pattern);
11132         return libbpf_get_error(*link);
11133 }
11134
11135 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11136 {
11137         char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11138         LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11139         int n, ret = -EINVAL;
11140
11141         *link = NULL;
11142
11143         n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11144                    &probe_type, &binary_path, &func_name);
11145         switch (n) {
11146         case 1:
11147                 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11148                 ret = 0;
11149                 break;
11150         case 3:
11151                 opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11152                 *link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11153                 ret = libbpf_get_error(*link);
11154                 break;
11155         default:
11156                 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11157                         prog->sec_name);
11158                 break;
11159         }
11160         free(probe_type);
11161         free(binary_path);
11162         free(func_name);
11163         return ret;
11164 }
11165
11166 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11167                                          const char *binary_path, uint64_t offset)
11168 {
11169         int i;
11170
11171         snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11172
11173         /* sanitize binary_path in the probe name */
11174         for (i = 0; buf[i]; i++) {
11175                 if (!isalnum(buf[i]))
11176                         buf[i] = '_';
11177         }
11178 }
11179
11180 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11181                                           const char *binary_path, size_t offset)
11182 {
11183         return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11184                               retprobe ? 'r' : 'p',
11185                               retprobe ? "uretprobes" : "uprobes",
11186                               probe_name, binary_path, offset);
11187 }
11188
11189 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11190 {
11191         return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11192                               retprobe ? "uretprobes" : "uprobes", probe_name);
11193 }
11194
11195 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11196 {
11197         char file[512];
11198
11199         snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11200                  tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11201
11202         return parse_uint_from_file(file, "%d\n");
11203 }
11204
11205 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11206                                          const char *binary_path, size_t offset, int pid)
11207 {
11208         const size_t attr_sz = sizeof(struct perf_event_attr);
11209         struct perf_event_attr attr;
11210         int type, pfd, err;
11211
11212         err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11213         if (err < 0) {
11214                 pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11215                         binary_path, (size_t)offset, err);
11216                 return err;
11217         }
11218         type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11219         if (type < 0) {
11220                 err = type;
11221                 pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11222                         binary_path, offset, err);
11223                 goto err_clean_legacy;
11224         }
11225
11226         memset(&attr, 0, attr_sz);
11227         attr.size = attr_sz;
11228         attr.config = type;
11229         attr.type = PERF_TYPE_TRACEPOINT;
11230
11231         pfd = syscall(__NR_perf_event_open, &attr,
11232                       pid < 0 ? -1 : pid, /* pid */
11233                       pid == -1 ? 0 : -1, /* cpu */
11234                       -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11235         if (pfd < 0) {
11236                 err = -errno;
11237                 pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11238                 goto err_clean_legacy;
11239         }
11240         return pfd;
11241
11242 err_clean_legacy:
11243         /* Clear the newly added legacy uprobe_event */
11244         remove_uprobe_event_legacy(probe_name, retprobe);
11245         return err;
11246 }
11247
11248 /* Find offset of function name in archive specified by path. Currently
11249  * supported are .zip files that do not compress their contents, as used on
11250  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11251  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11252  * library functions.
11253  *
11254  * An overview of the APK format specifically provided here:
11255  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11256  */
11257 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11258                                               const char *func_name)
11259 {
11260         struct zip_archive *archive;
11261         struct zip_entry entry;
11262         long ret;
11263         Elf *elf;
11264
11265         archive = zip_archive_open(archive_path);
11266         if (IS_ERR(archive)) {
11267                 ret = PTR_ERR(archive);
11268                 pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11269                 return ret;
11270         }
11271
11272         ret = zip_archive_find_entry(archive, file_name, &entry);
11273         if (ret) {
11274                 pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11275                         archive_path, ret);
11276                 goto out;
11277         }
11278         pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11279                  (unsigned long)entry.data_offset);
11280
11281         if (entry.compression) {
11282                 pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11283                         archive_path);
11284                 ret = -LIBBPF_ERRNO__FORMAT;
11285                 goto out;
11286         }
11287
11288         elf = elf_memory((void *)entry.data, entry.data_length);
11289         if (!elf) {
11290                 pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11291                         elf_errmsg(-1));
11292                 ret = -LIBBPF_ERRNO__LIBELF;
11293                 goto out;
11294         }
11295
11296         ret = elf_find_func_offset(elf, file_name, func_name);
11297         if (ret > 0) {
11298                 pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11299                          func_name, file_name, archive_path, entry.data_offset, ret,
11300                          ret + entry.data_offset);
11301                 ret += entry.data_offset;
11302         }
11303         elf_end(elf);
11304
11305 out:
11306         zip_archive_close(archive);
11307         return ret;
11308 }
11309
11310 static const char *arch_specific_lib_paths(void)
11311 {
11312         /*
11313          * Based on https://packages.debian.org/sid/libc6.
11314          *
11315          * Assume that the traced program is built for the same architecture
11316          * as libbpf, which should cover the vast majority of cases.
11317          */
11318 #if defined(__x86_64__)
11319         return "/lib/x86_64-linux-gnu";
11320 #elif defined(__i386__)
11321         return "/lib/i386-linux-gnu";
11322 #elif defined(__s390x__)
11323         return "/lib/s390x-linux-gnu";
11324 #elif defined(__s390__)
11325         return "/lib/s390-linux-gnu";
11326 #elif defined(__arm__) && defined(__SOFTFP__)
11327         return "/lib/arm-linux-gnueabi";
11328 #elif defined(__arm__) && !defined(__SOFTFP__)
11329         return "/lib/arm-linux-gnueabihf";
11330 #elif defined(__aarch64__)
11331         return "/lib/aarch64-linux-gnu";
11332 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11333         return "/lib/mips64el-linux-gnuabi64";
11334 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11335         return "/lib/mipsel-linux-gnu";
11336 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11337         return "/lib/powerpc64le-linux-gnu";
11338 #elif defined(__sparc__) && defined(__arch64__)
11339         return "/lib/sparc64-linux-gnu";
11340 #elif defined(__riscv) && __riscv_xlen == 64
11341         return "/lib/riscv64-linux-gnu";
11342 #else
11343         return NULL;
11344 #endif
11345 }
11346
11347 /* Get full path to program/shared library. */
11348 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11349 {
11350         const char *search_paths[3] = {};
11351         int i, perm;
11352
11353         if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11354                 search_paths[0] = getenv("LD_LIBRARY_PATH");
11355                 search_paths[1] = "/usr/lib64:/usr/lib";
11356                 search_paths[2] = arch_specific_lib_paths();
11357                 perm = R_OK;
11358         } else {
11359                 search_paths[0] = getenv("PATH");
11360                 search_paths[1] = "/usr/bin:/usr/sbin";
11361                 perm = R_OK | X_OK;
11362         }
11363
11364         for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11365                 const char *s;
11366
11367                 if (!search_paths[i])
11368                         continue;
11369                 for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11370                         char *next_path;
11371                         int seg_len;
11372
11373                         if (s[0] == ':')
11374                                 s++;
11375                         next_path = strchr(s, ':');
11376                         seg_len = next_path ? next_path - s : strlen(s);
11377                         if (!seg_len)
11378                                 continue;
11379                         snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11380                         /* ensure it has required permissions */
11381                         if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11382                                 continue;
11383                         pr_debug("resolved '%s' to '%s'\n", file, result);
11384                         return 0;
11385                 }
11386         }
11387         return -ENOENT;
11388 }
11389
11390 struct bpf_link *
11391 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11392                                  pid_t pid,
11393                                  const char *path,
11394                                  const char *func_pattern,
11395                                  const struct bpf_uprobe_multi_opts *opts)
11396 {
11397         const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11398         LIBBPF_OPTS(bpf_link_create_opts, lopts);
11399         unsigned long *resolved_offsets = NULL;
11400         int err = 0, link_fd, prog_fd;
11401         struct bpf_link *link = NULL;
11402         char errmsg[STRERR_BUFSIZE];
11403         char full_path[PATH_MAX];
11404         const __u64 *cookies;
11405         const char **syms;
11406         size_t cnt;
11407
11408         if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11409                 return libbpf_err_ptr(-EINVAL);
11410
11411         syms = OPTS_GET(opts, syms, NULL);
11412         offsets = OPTS_GET(opts, offsets, NULL);
11413         ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11414         cookies = OPTS_GET(opts, cookies, NULL);
11415         cnt = OPTS_GET(opts, cnt, 0);
11416
11417         /*
11418          * User can specify 2 mutually exclusive set of inputs:
11419          *
11420          * 1) use only path/func_pattern/pid arguments
11421          *
11422          * 2) use path/pid with allowed combinations of:
11423          *    syms/offsets/ref_ctr_offsets/cookies/cnt
11424          *
11425          *    - syms and offsets are mutually exclusive
11426          *    - ref_ctr_offsets and cookies are optional
11427          *
11428          * Any other usage results in error.
11429          */
11430
11431         if (!path)
11432                 return libbpf_err_ptr(-EINVAL);
11433         if (!func_pattern && cnt == 0)
11434                 return libbpf_err_ptr(-EINVAL);
11435
11436         if (func_pattern) {
11437                 if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11438                         return libbpf_err_ptr(-EINVAL);
11439         } else {
11440                 if (!!syms == !!offsets)
11441                         return libbpf_err_ptr(-EINVAL);
11442         }
11443
11444         if (func_pattern) {
11445                 if (!strchr(path, '/')) {
11446                         err = resolve_full_path(path, full_path, sizeof(full_path));
11447                         if (err) {
11448                                 pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11449                                         prog->name, path, err);
11450                                 return libbpf_err_ptr(err);
11451                         }
11452                         path = full_path;
11453                 }
11454
11455                 err = elf_resolve_pattern_offsets(path, func_pattern,
11456                                                   &resolved_offsets, &cnt);
11457                 if (err < 0)
11458                         return libbpf_err_ptr(err);
11459                 offsets = resolved_offsets;
11460         } else if (syms) {
11461                 err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11462                 if (err < 0)
11463                         return libbpf_err_ptr(err);
11464                 offsets = resolved_offsets;
11465         }
11466
11467         lopts.uprobe_multi.path = path;
11468         lopts.uprobe_multi.offsets = offsets;
11469         lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11470         lopts.uprobe_multi.cookies = cookies;
11471         lopts.uprobe_multi.cnt = cnt;
11472         lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11473
11474         if (pid == 0)
11475                 pid = getpid();
11476         if (pid > 0)
11477                 lopts.uprobe_multi.pid = pid;
11478
11479         link = calloc(1, sizeof(*link));
11480         if (!link) {
11481                 err = -ENOMEM;
11482                 goto error;
11483         }
11484         link->detach = &bpf_link__detach_fd;
11485
11486         prog_fd = bpf_program__fd(prog);
11487         link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
11488         if (link_fd < 0) {
11489                 err = -errno;
11490                 pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
11491                         prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11492                 goto error;
11493         }
11494         link->fd = link_fd;
11495         free(resolved_offsets);
11496         return link;
11497
11498 error:
11499         free(resolved_offsets);
11500         free(link);
11501         return libbpf_err_ptr(err);
11502 }
11503
11504 LIBBPF_API struct bpf_link *
11505 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11506                                 const char *binary_path, size_t func_offset,
11507                                 const struct bpf_uprobe_opts *opts)
11508 {
11509         const char *archive_path = NULL, *archive_sep = NULL;
11510         char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11511         DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11512         enum probe_attach_mode attach_mode;
11513         char full_path[PATH_MAX];
11514         struct bpf_link *link;
11515         size_t ref_ctr_off;
11516         int pfd, err;
11517         bool retprobe, legacy;
11518         const char *func_name;
11519
11520         if (!OPTS_VALID(opts, bpf_uprobe_opts))
11521                 return libbpf_err_ptr(-EINVAL);
11522
11523         attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11524         retprobe = OPTS_GET(opts, retprobe, false);
11525         ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11526         pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11527
11528         if (!binary_path)
11529                 return libbpf_err_ptr(-EINVAL);
11530
11531         /* Check if "binary_path" refers to an archive. */
11532         archive_sep = strstr(binary_path, "!/");
11533         if (archive_sep) {
11534                 full_path[0] = '\0';
11535                 libbpf_strlcpy(full_path, binary_path,
11536                                min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11537                 archive_path = full_path;
11538                 binary_path = archive_sep + 2;
11539         } else if (!strchr(binary_path, '/')) {
11540                 err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11541                 if (err) {
11542                         pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11543                                 prog->name, binary_path, err);
11544                         return libbpf_err_ptr(err);
11545                 }
11546                 binary_path = full_path;
11547         }
11548         func_name = OPTS_GET(opts, func_name, NULL);
11549         if (func_name) {
11550                 long sym_off;
11551
11552                 if (archive_path) {
11553                         sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11554                                                                     func_name);
11555                         binary_path = archive_path;
11556                 } else {
11557                         sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11558                 }
11559                 if (sym_off < 0)
11560                         return libbpf_err_ptr(sym_off);
11561                 func_offset += sym_off;
11562         }
11563
11564         legacy = determine_uprobe_perf_type() < 0;
11565         switch (attach_mode) {
11566         case PROBE_ATTACH_MODE_LEGACY:
11567                 legacy = true;
11568                 pe_opts.force_ioctl_attach = true;
11569                 break;
11570         case PROBE_ATTACH_MODE_PERF:
11571                 if (legacy)
11572                         return libbpf_err_ptr(-ENOTSUP);
11573                 pe_opts.force_ioctl_attach = true;
11574                 break;
11575         case PROBE_ATTACH_MODE_LINK:
11576                 if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11577                         return libbpf_err_ptr(-ENOTSUP);
11578                 break;
11579         case PROBE_ATTACH_MODE_DEFAULT:
11580                 break;
11581         default:
11582                 return libbpf_err_ptr(-EINVAL);
11583         }
11584
11585         if (!legacy) {
11586                 pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11587                                             func_offset, pid, ref_ctr_off);
11588         } else {
11589                 char probe_name[PATH_MAX + 64];
11590
11591                 if (ref_ctr_off)
11592                         return libbpf_err_ptr(-EINVAL);
11593
11594                 gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11595                                              binary_path, func_offset);
11596
11597                 legacy_probe = strdup(probe_name);
11598                 if (!legacy_probe)
11599                         return libbpf_err_ptr(-ENOMEM);
11600
11601                 pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11602                                                     binary_path, func_offset, pid);
11603         }
11604         if (pfd < 0) {
11605                 err = -errno;
11606                 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11607                         prog->name, retprobe ? "uretprobe" : "uprobe",
11608                         binary_path, func_offset,
11609                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11610                 goto err_out;
11611         }
11612
11613         link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11614         err = libbpf_get_error(link);
11615         if (err) {
11616                 close(pfd);
11617                 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11618                         prog->name, retprobe ? "uretprobe" : "uprobe",
11619                         binary_path, func_offset,
11620                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11621                 goto err_clean_legacy;
11622         }
11623         if (legacy) {
11624                 struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11625
11626                 perf_link->legacy_probe_name = legacy_probe;
11627                 perf_link->legacy_is_kprobe = false;
11628                 perf_link->legacy_is_retprobe = retprobe;
11629         }
11630         return link;
11631
11632 err_clean_legacy:
11633         if (legacy)
11634                 remove_uprobe_event_legacy(legacy_probe, retprobe);
11635 err_out:
11636         free(legacy_probe);
11637         return libbpf_err_ptr(err);
11638 }
11639
11640 /* Format of u[ret]probe section definition supporting auto-attach:
11641  * u[ret]probe/binary:function[+offset]
11642  *
11643  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11644  * full binary path via bpf_program__attach_uprobe_opts.
11645  *
11646  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11647  * specified (and auto-attach is not possible) or the above format is specified for
11648  * auto-attach.
11649  */
11650 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11651 {
11652         DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11653         char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
11654         int n, c, ret = -EINVAL;
11655         long offset = 0;
11656
11657         *link = NULL;
11658
11659         n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11660                    &probe_type, &binary_path, &func_name);
11661         switch (n) {
11662         case 1:
11663                 /* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11664                 ret = 0;
11665                 break;
11666         case 2:
11667                 pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11668                         prog->name, prog->sec_name);
11669                 break;
11670         case 3:
11671                 /* check if user specifies `+offset`, if yes, this should be
11672                  * the last part of the string, make sure sscanf read to EOL
11673                  */
11674                 func_off = strrchr(func_name, '+');
11675                 if (func_off) {
11676                         n = sscanf(func_off, "+%li%n", &offset, &c);
11677                         if (n == 1 && *(func_off + c) == '\0')
11678                                 func_off[0] = '\0';
11679                         else
11680                                 offset = 0;
11681                 }
11682                 opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11683                                 strcmp(probe_type, "uretprobe.s") == 0;
11684                 if (opts.retprobe && offset != 0) {
11685                         pr_warn("prog '%s': uretprobes do not support offset specification\n",
11686                                 prog->name);
11687                         break;
11688                 }
11689                 opts.func_name = func_name;
11690                 *link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11691                 ret = libbpf_get_error(*link);
11692                 break;
11693         default:
11694                 pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11695                         prog->sec_name);
11696                 break;
11697         }
11698         free(probe_type);
11699         free(binary_path);
11700         free(func_name);
11701
11702         return ret;
11703 }
11704
11705 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11706                                             bool retprobe, pid_t pid,
11707                                             const char *binary_path,
11708                                             size_t func_offset)
11709 {
11710         DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11711
11712         return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11713 }
11714
11715 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11716                                           pid_t pid, const char *binary_path,
11717                                           const char *usdt_provider, const char *usdt_name,
11718                                           const struct bpf_usdt_opts *opts)
11719 {
11720         char resolved_path[512];
11721         struct bpf_object *obj = prog->obj;
11722         struct bpf_link *link;
11723         __u64 usdt_cookie;
11724         int err;
11725
11726         if (!OPTS_VALID(opts, bpf_uprobe_opts))
11727                 return libbpf_err_ptr(-EINVAL);
11728
11729         if (bpf_program__fd(prog) < 0) {
11730                 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11731                         prog->name);
11732                 return libbpf_err_ptr(-EINVAL);
11733         }
11734
11735         if (!binary_path)
11736                 return libbpf_err_ptr(-EINVAL);
11737
11738         if (!strchr(binary_path, '/')) {
11739                 err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11740                 if (err) {
11741                         pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11742                                 prog->name, binary_path, err);
11743                         return libbpf_err_ptr(err);
11744                 }
11745                 binary_path = resolved_path;
11746         }
11747
11748         /* USDT manager is instantiated lazily on first USDT attach. It will
11749          * be destroyed together with BPF object in bpf_object__close().
11750          */
11751         if (IS_ERR(obj->usdt_man))
11752                 return libbpf_ptr(obj->usdt_man);
11753         if (!obj->usdt_man) {
11754                 obj->usdt_man = usdt_manager_new(obj);
11755                 if (IS_ERR(obj->usdt_man))
11756                         return libbpf_ptr(obj->usdt_man);
11757         }
11758
11759         usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11760         link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11761                                         usdt_provider, usdt_name, usdt_cookie);
11762         err = libbpf_get_error(link);
11763         if (err)
11764                 return libbpf_err_ptr(err);
11765         return link;
11766 }
11767
11768 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11769 {
11770         char *path = NULL, *provider = NULL, *name = NULL;
11771         const char *sec_name;
11772         int n, err;
11773
11774         sec_name = bpf_program__section_name(prog);
11775         if (strcmp(sec_name, "usdt") == 0) {
11776                 /* no auto-attach for just SEC("usdt") */
11777                 *link = NULL;
11778                 return 0;
11779         }
11780
11781         n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11782         if (n != 3) {
11783                 pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11784                         sec_name);
11785                 err = -EINVAL;
11786         } else {
11787                 *link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11788                                                  provider, name, NULL);
11789                 err = libbpf_get_error(*link);
11790         }
11791         free(path);
11792         free(provider);
11793         free(name);
11794         return err;
11795 }
11796
11797 static int determine_tracepoint_id(const char *tp_category,
11798                                    const char *tp_name)
11799 {
11800         char file[PATH_MAX];
11801         int ret;
11802
11803         ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11804                        tracefs_path(), tp_category, tp_name);
11805         if (ret < 0)
11806                 return -errno;
11807         if (ret >= sizeof(file)) {
11808                 pr_debug("tracepoint %s/%s path is too long\n",
11809                          tp_category, tp_name);
11810                 return -E2BIG;
11811         }
11812         return parse_uint_from_file(file, "%d\n");
11813 }
11814
11815 static int perf_event_open_tracepoint(const char *tp_category,
11816                                       const char *tp_name)
11817 {
11818         const size_t attr_sz = sizeof(struct perf_event_attr);
11819         struct perf_event_attr attr;
11820         char errmsg[STRERR_BUFSIZE];
11821         int tp_id, pfd, err;
11822
11823         tp_id = determine_tracepoint_id(tp_category, tp_name);
11824         if (tp_id < 0) {
11825                 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11826                         tp_category, tp_name,
11827                         libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11828                 return tp_id;
11829         }
11830
11831         memset(&attr, 0, attr_sz);
11832         attr.type = PERF_TYPE_TRACEPOINT;
11833         attr.size = attr_sz;
11834         attr.config = tp_id;
11835
11836         pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11837                       -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11838         if (pfd < 0) {
11839                 err = -errno;
11840                 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11841                         tp_category, tp_name,
11842                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11843                 return err;
11844         }
11845         return pfd;
11846 }
11847
11848 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11849                                                      const char *tp_category,
11850                                                      const char *tp_name,
11851                                                      const struct bpf_tracepoint_opts *opts)
11852 {
11853         DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11854         char errmsg[STRERR_BUFSIZE];
11855         struct bpf_link *link;
11856         int pfd, err;
11857
11858         if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11859                 return libbpf_err_ptr(-EINVAL);
11860
11861         pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11862
11863         pfd = perf_event_open_tracepoint(tp_category, tp_name);
11864         if (pfd < 0) {
11865                 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11866                         prog->name, tp_category, tp_name,
11867                         libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11868                 return libbpf_err_ptr(pfd);
11869         }
11870         link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11871         err = libbpf_get_error(link);
11872         if (err) {
11873                 close(pfd);
11874                 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11875                         prog->name, tp_category, tp_name,
11876                         libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11877                 return libbpf_err_ptr(err);
11878         }
11879         return link;
11880 }
11881
11882 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11883                                                 const char *tp_category,
11884                                                 const char *tp_name)
11885 {
11886         return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11887 }
11888
11889 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11890 {
11891         char *sec_name, *tp_cat, *tp_name;
11892
11893         *link = NULL;
11894
11895         /* no auto-attach for SEC("tp") or SEC("tracepoint") */
11896         if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11897                 return 0;
11898
11899         sec_name = strdup(prog->sec_name);
11900         if (!sec_name)
11901                 return -ENOMEM;
11902
11903         /* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11904         if (str_has_pfx(prog->sec_name, "tp/"))
11905                 tp_cat = sec_name + sizeof("tp/") - 1;
11906         else
11907                 tp_cat = sec_name + sizeof("tracepoint/") - 1;
11908         tp_name = strchr(tp_cat, '/');
11909         if (!tp_name) {
11910                 free(sec_name);
11911                 return -EINVAL;
11912         }
11913         *tp_name = '\0';
11914         tp_name++;
11915
11916         *link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11917         free(sec_name);
11918         return libbpf_get_error(*link);
11919 }
11920
11921 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11922                                                     const char *tp_name)
11923 {
11924         char errmsg[STRERR_BUFSIZE];
11925         struct bpf_link *link;
11926         int prog_fd, pfd;
11927
11928         prog_fd = bpf_program__fd(prog);
11929         if (prog_fd < 0) {
11930                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11931                 return libbpf_err_ptr(-EINVAL);
11932         }
11933
11934         link = calloc(1, sizeof(*link));
11935         if (!link)
11936                 return libbpf_err_ptr(-ENOMEM);
11937         link->detach = &bpf_link__detach_fd;
11938
11939         pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11940         if (pfd < 0) {
11941                 pfd = -errno;
11942                 free(link);
11943                 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11944                         prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11945                 return libbpf_err_ptr(pfd);
11946         }
11947         link->fd = pfd;
11948         return link;
11949 }
11950
11951 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11952 {
11953         static const char *const prefixes[] = {
11954                 "raw_tp",
11955                 "raw_tracepoint",
11956                 "raw_tp.w",
11957                 "raw_tracepoint.w",
11958         };
11959         size_t i;
11960         const char *tp_name = NULL;
11961
11962         *link = NULL;
11963
11964         for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11965                 size_t pfx_len;
11966
11967                 if (!str_has_pfx(prog->sec_name, prefixes[i]))
11968                         continue;
11969
11970                 pfx_len = strlen(prefixes[i]);
11971                 /* no auto-attach case of, e.g., SEC("raw_tp") */
11972                 if (prog->sec_name[pfx_len] == '\0')
11973                         return 0;
11974
11975                 if (prog->sec_name[pfx_len] != '/')
11976                         continue;
11977
11978                 tp_name = prog->sec_name + pfx_len + 1;
11979                 break;
11980         }
11981
11982         if (!tp_name) {
11983                 pr_warn("prog '%s': invalid section name '%s'\n",
11984                         prog->name, prog->sec_name);
11985                 return -EINVAL;
11986         }
11987
11988         *link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11989         return libbpf_get_error(*link);
11990 }
11991
11992 /* Common logic for all BPF program types that attach to a btf_id */
11993 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11994                                                    const struct bpf_trace_opts *opts)
11995 {
11996         LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11997         char errmsg[STRERR_BUFSIZE];
11998         struct bpf_link *link;
11999         int prog_fd, pfd;
12000
12001         if (!OPTS_VALID(opts, bpf_trace_opts))
12002                 return libbpf_err_ptr(-EINVAL);
12003
12004         prog_fd = bpf_program__fd(prog);
12005         if (prog_fd < 0) {
12006                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12007                 return libbpf_err_ptr(-EINVAL);
12008         }
12009
12010         link = calloc(1, sizeof(*link));
12011         if (!link)
12012                 return libbpf_err_ptr(-ENOMEM);
12013         link->detach = &bpf_link__detach_fd;
12014
12015         /* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12016         link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12017         pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12018         if (pfd < 0) {
12019                 pfd = -errno;
12020                 free(link);
12021                 pr_warn("prog '%s': failed to attach: %s\n",
12022                         prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12023                 return libbpf_err_ptr(pfd);
12024         }
12025         link->fd = pfd;
12026         return link;
12027 }
12028
12029 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12030 {
12031         return bpf_program__attach_btf_id(prog, NULL);
12032 }
12033
12034 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12035                                                 const struct bpf_trace_opts *opts)
12036 {
12037         return bpf_program__attach_btf_id(prog, opts);
12038 }
12039
12040 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12041 {
12042         return bpf_program__attach_btf_id(prog, NULL);
12043 }
12044
12045 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12046 {
12047         *link = bpf_program__attach_trace(prog);
12048         return libbpf_get_error(*link);
12049 }
12050
12051 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12052 {
12053         *link = bpf_program__attach_lsm(prog);
12054         return libbpf_get_error(*link);
12055 }
12056
12057 static struct bpf_link *
12058 bpf_program_attach_fd(const struct bpf_program *prog,
12059                       int target_fd, const char *target_name,
12060                       const struct bpf_link_create_opts *opts)
12061 {
12062         enum bpf_attach_type attach_type;
12063         char errmsg[STRERR_BUFSIZE];
12064         struct bpf_link *link;
12065         int prog_fd, link_fd;
12066
12067         prog_fd = bpf_program__fd(prog);
12068         if (prog_fd < 0) {
12069                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12070                 return libbpf_err_ptr(-EINVAL);
12071         }
12072
12073         link = calloc(1, sizeof(*link));
12074         if (!link)
12075                 return libbpf_err_ptr(-ENOMEM);
12076         link->detach = &bpf_link__detach_fd;
12077
12078         attach_type = bpf_program__expected_attach_type(prog);
12079         link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12080         if (link_fd < 0) {
12081                 link_fd = -errno;
12082                 free(link);
12083                 pr_warn("prog '%s': failed to attach to %s: %s\n",
12084                         prog->name, target_name,
12085                         libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12086                 return libbpf_err_ptr(link_fd);
12087         }
12088         link->fd = link_fd;
12089         return link;
12090 }
12091
12092 struct bpf_link *
12093 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12094 {
12095         return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12096 }
12097
12098 struct bpf_link *
12099 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12100 {
12101         return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12102 }
12103
12104 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12105 {
12106         /* target_fd/target_ifindex use the same field in LINK_CREATE */
12107         return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12108 }
12109
12110 struct bpf_link *
12111 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12112                         const struct bpf_tcx_opts *opts)
12113 {
12114         LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12115         __u32 relative_id;
12116         int relative_fd;
12117
12118         if (!OPTS_VALID(opts, bpf_tcx_opts))
12119                 return libbpf_err_ptr(-EINVAL);
12120
12121         relative_id = OPTS_GET(opts, relative_id, 0);
12122         relative_fd = OPTS_GET(opts, relative_fd, 0);
12123
12124         /* validate we don't have unexpected combinations of non-zero fields */
12125         if (!ifindex) {
12126                 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12127                         prog->name);
12128                 return libbpf_err_ptr(-EINVAL);
12129         }
12130         if (relative_fd && relative_id) {
12131                 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12132                         prog->name);
12133                 return libbpf_err_ptr(-EINVAL);
12134         }
12135
12136         link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12137         link_create_opts.tcx.relative_fd = relative_fd;
12138         link_create_opts.tcx.relative_id = relative_id;
12139         link_create_opts.flags = OPTS_GET(opts, flags, 0);
12140
12141         /* target_fd/target_ifindex use the same field in LINK_CREATE */
12142         return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12143 }
12144
12145 struct bpf_link *
12146 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12147                            const struct bpf_netkit_opts *opts)
12148 {
12149         LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12150         __u32 relative_id;
12151         int relative_fd;
12152
12153         if (!OPTS_VALID(opts, bpf_netkit_opts))
12154                 return libbpf_err_ptr(-EINVAL);
12155
12156         relative_id = OPTS_GET(opts, relative_id, 0);
12157         relative_fd = OPTS_GET(opts, relative_fd, 0);
12158
12159         /* validate we don't have unexpected combinations of non-zero fields */
12160         if (!ifindex) {
12161                 pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12162                         prog->name);
12163                 return libbpf_err_ptr(-EINVAL);
12164         }
12165         if (relative_fd && relative_id) {
12166                 pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12167                         prog->name);
12168                 return libbpf_err_ptr(-EINVAL);
12169         }
12170
12171         link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12172         link_create_opts.netkit.relative_fd = relative_fd;
12173         link_create_opts.netkit.relative_id = relative_id;
12174         link_create_opts.flags = OPTS_GET(opts, flags, 0);
12175
12176         return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12177 }
12178
12179 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12180                                               int target_fd,
12181                                               const char *attach_func_name)
12182 {
12183         int btf_id;
12184
12185         if (!!target_fd != !!attach_func_name) {
12186                 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12187                         prog->name);
12188                 return libbpf_err_ptr(-EINVAL);
12189         }
12190
12191         if (prog->type != BPF_PROG_TYPE_EXT) {
12192                 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12193                         prog->name);
12194                 return libbpf_err_ptr(-EINVAL);
12195         }
12196
12197         if (target_fd) {
12198                 LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12199
12200                 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12201                 if (btf_id < 0)
12202                         return libbpf_err_ptr(btf_id);
12203
12204                 target_opts.target_btf_id = btf_id;
12205
12206                 return bpf_program_attach_fd(prog, target_fd, "freplace",
12207                                              &target_opts);
12208         } else {
12209                 /* no target, so use raw_tracepoint_open for compatibility
12210                  * with old kernels
12211                  */
12212                 return bpf_program__attach_trace(prog);
12213         }
12214 }
12215
12216 struct bpf_link *
12217 bpf_program__attach_iter(const struct bpf_program *prog,
12218                          const struct bpf_iter_attach_opts *opts)
12219 {
12220         DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12221         char errmsg[STRERR_BUFSIZE];
12222         struct bpf_link *link;
12223         int prog_fd, link_fd;
12224         __u32 target_fd = 0;
12225
12226         if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12227                 return libbpf_err_ptr(-EINVAL);
12228
12229         link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12230         link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12231
12232         prog_fd = bpf_program__fd(prog);
12233         if (prog_fd < 0) {
12234                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12235                 return libbpf_err_ptr(-EINVAL);
12236         }
12237
12238         link = calloc(1, sizeof(*link));
12239         if (!link)
12240                 return libbpf_err_ptr(-ENOMEM);
12241         link->detach = &bpf_link__detach_fd;
12242
12243         link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12244                                   &link_create_opts);
12245         if (link_fd < 0) {
12246                 link_fd = -errno;
12247                 free(link);
12248                 pr_warn("prog '%s': failed to attach to iterator: %s\n",
12249                         prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12250                 return libbpf_err_ptr(link_fd);
12251         }
12252         link->fd = link_fd;
12253         return link;
12254 }
12255
12256 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12257 {
12258         *link = bpf_program__attach_iter(prog, NULL);
12259         return libbpf_get_error(*link);
12260 }
12261
12262 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12263                                                const struct bpf_netfilter_opts *opts)
12264 {
12265         LIBBPF_OPTS(bpf_link_create_opts, lopts);
12266         struct bpf_link *link;
12267         int prog_fd, link_fd;
12268
12269         if (!OPTS_VALID(opts, bpf_netfilter_opts))
12270                 return libbpf_err_ptr(-EINVAL);
12271
12272         prog_fd = bpf_program__fd(prog);
12273         if (prog_fd < 0) {
12274                 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12275                 return libbpf_err_ptr(-EINVAL);
12276         }
12277
12278         link = calloc(1, sizeof(*link));
12279         if (!link)
12280                 return libbpf_err_ptr(-ENOMEM);
12281
12282         link->detach = &bpf_link__detach_fd;
12283
12284         lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12285         lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12286         lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12287         lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12288
12289         link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12290         if (link_fd < 0) {
12291                 char errmsg[STRERR_BUFSIZE];
12292
12293                 link_fd = -errno;
12294                 free(link);
12295                 pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12296                         prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12297                 return libbpf_err_ptr(link_fd);
12298         }
12299         link->fd = link_fd;
12300
12301         return link;
12302 }
12303
12304 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12305 {
12306         struct bpf_link *link = NULL;
12307         int err;
12308
12309         if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12310                 return libbpf_err_ptr(-EOPNOTSUPP);
12311
12312         err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12313         if (err)
12314                 return libbpf_err_ptr(err);
12315
12316         /* When calling bpf_program__attach() explicitly, auto-attach support
12317          * is expected to work, so NULL returned link is considered an error.
12318          * This is different for skeleton's attach, see comment in
12319          * bpf_object__attach_skeleton().
12320          */
12321         if (!link)
12322                 return libbpf_err_ptr(-EOPNOTSUPP);
12323
12324         return link;
12325 }
12326
12327 struct bpf_link_struct_ops {
12328         struct bpf_link link;
12329         int map_fd;
12330 };
12331
12332 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12333 {
12334         struct bpf_link_struct_ops *st_link;
12335         __u32 zero = 0;
12336
12337         st_link = container_of(link, struct bpf_link_struct_ops, link);
12338
12339         if (st_link->map_fd < 0)
12340                 /* w/o a real link */
12341                 return bpf_map_delete_elem(link->fd, &zero);
12342
12343         return close(link->fd);
12344 }
12345
12346 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12347 {
12348         struct bpf_link_struct_ops *link;
12349         __u32 zero = 0;
12350         int err, fd;
12351
12352         if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12353                 return libbpf_err_ptr(-EINVAL);
12354
12355         link = calloc(1, sizeof(*link));
12356         if (!link)
12357                 return libbpf_err_ptr(-EINVAL);
12358
12359         /* kern_vdata should be prepared during the loading phase. */
12360         err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12361         /* It can be EBUSY if the map has been used to create or
12362          * update a link before.  We don't allow updating the value of
12363          * a struct_ops once it is set.  That ensures that the value
12364          * never changed.  So, it is safe to skip EBUSY.
12365          */
12366         if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12367                 free(link);
12368                 return libbpf_err_ptr(err);
12369         }
12370
12371         link->link.detach = bpf_link__detach_struct_ops;
12372
12373         if (!(map->def.map_flags & BPF_F_LINK)) {
12374                 /* w/o a real link */
12375                 link->link.fd = map->fd;
12376                 link->map_fd = -1;
12377                 return &link->link;
12378         }
12379
12380         fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12381         if (fd < 0) {
12382                 free(link);
12383                 return libbpf_err_ptr(fd);
12384         }
12385
12386         link->link.fd = fd;
12387         link->map_fd = map->fd;
12388
12389         return &link->link;
12390 }
12391
12392 /*
12393  * Swap the back struct_ops of a link with a new struct_ops map.
12394  */
12395 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12396 {
12397         struct bpf_link_struct_ops *st_ops_link;
12398         __u32 zero = 0;
12399         int err;
12400
12401         if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12402                 return -EINVAL;
12403
12404         st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12405         /* Ensure the type of a link is correct */
12406         if (st_ops_link->map_fd < 0)
12407                 return -EINVAL;
12408
12409         err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12410         /* It can be EBUSY if the map has been used to create or
12411          * update a link before.  We don't allow updating the value of
12412          * a struct_ops once it is set.  That ensures that the value
12413          * never changed.  So, it is safe to skip EBUSY.
12414          */
12415         if (err && err != -EBUSY)
12416                 return err;
12417
12418         err = bpf_link_update(link->fd, map->fd, NULL);
12419         if (err < 0)
12420                 return err;
12421
12422         st_ops_link->map_fd = map->fd;
12423
12424         return 0;
12425 }
12426
12427 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12428                                                           void *private_data);
12429
12430 static enum bpf_perf_event_ret
12431 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12432                        void **copy_mem, size_t *copy_size,
12433                        bpf_perf_event_print_t fn, void *private_data)
12434 {
12435         struct perf_event_mmap_page *header = mmap_mem;
12436         __u64 data_head = ring_buffer_read_head(header);
12437         __u64 data_tail = header->data_tail;
12438         void *base = ((__u8 *)header) + page_size;
12439         int ret = LIBBPF_PERF_EVENT_CONT;
12440         struct perf_event_header *ehdr;
12441         size_t ehdr_size;
12442
12443         while (data_head != data_tail) {
12444                 ehdr = base + (data_tail & (mmap_size - 1));
12445                 ehdr_size = ehdr->size;
12446
12447                 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12448                         void *copy_start = ehdr;
12449                         size_t len_first = base + mmap_size - copy_start;
12450                         size_t len_secnd = ehdr_size - len_first;
12451
12452                         if (*copy_size < ehdr_size) {
12453                                 free(*copy_mem);
12454                                 *copy_mem = malloc(ehdr_size);
12455                                 if (!*copy_mem) {
12456                                         *copy_size = 0;
12457                                         ret = LIBBPF_PERF_EVENT_ERROR;
12458                                         break;
12459                                 }
12460                                 *copy_size = ehdr_size;
12461                         }
12462
12463                         memcpy(*copy_mem, copy_start, len_first);
12464                         memcpy(*copy_mem + len_first, base, len_secnd);
12465                         ehdr = *copy_mem;
12466                 }
12467
12468                 ret = fn(ehdr, private_data);
12469                 data_tail += ehdr_size;
12470                 if (ret != LIBBPF_PERF_EVENT_CONT)
12471                         break;
12472         }
12473
12474         ring_buffer_write_tail(header, data_tail);
12475         return libbpf_err(ret);
12476 }
12477
12478 struct perf_buffer;
12479
12480 struct perf_buffer_params {
12481         struct perf_event_attr *attr;
12482         /* if event_cb is specified, it takes precendence */
12483         perf_buffer_event_fn event_cb;
12484         /* sample_cb and lost_cb are higher-level common-case callbacks */
12485         perf_buffer_sample_fn sample_cb;
12486         perf_buffer_lost_fn lost_cb;
12487         void *ctx;
12488         int cpu_cnt;
12489         int *cpus;
12490         int *map_keys;
12491 };
12492
12493 struct perf_cpu_buf {
12494         struct perf_buffer *pb;
12495         void *base; /* mmap()'ed memory */
12496         void *buf; /* for reconstructing segmented data */
12497         size_t buf_size;
12498         int fd;
12499         int cpu;
12500         int map_key;
12501 };
12502
12503 struct perf_buffer {
12504         perf_buffer_event_fn event_cb;
12505         perf_buffer_sample_fn sample_cb;
12506         perf_buffer_lost_fn lost_cb;
12507         void *ctx; /* passed into callbacks */
12508
12509         size_t page_size;
12510         size_t mmap_size;
12511         struct perf_cpu_buf **cpu_bufs;
12512         struct epoll_event *events;
12513         int cpu_cnt; /* number of allocated CPU buffers */
12514         int epoll_fd; /* perf event FD */
12515         int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12516 };
12517
12518 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12519                                       struct perf_cpu_buf *cpu_buf)
12520 {
12521         if (!cpu_buf)
12522                 return;
12523         if (cpu_buf->base &&
12524             munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12525                 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12526         if (cpu_buf->fd >= 0) {
12527                 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12528                 close(cpu_buf->fd);
12529         }
12530         free(cpu_buf->buf);
12531         free(cpu_buf);
12532 }
12533
12534 void perf_buffer__free(struct perf_buffer *pb)
12535 {
12536         int i;
12537
12538         if (IS_ERR_OR_NULL(pb))
12539                 return;
12540         if (pb->cpu_bufs) {
12541                 for (i = 0; i < pb->cpu_cnt; i++) {
12542                         struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12543
12544                         if (!cpu_buf)
12545                                 continue;
12546
12547                         bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12548                         perf_buffer__free_cpu_buf(pb, cpu_buf);
12549                 }
12550                 free(pb->cpu_bufs);
12551         }
12552         if (pb->epoll_fd >= 0)
12553                 close(pb->epoll_fd);
12554         free(pb->events);
12555         free(pb);
12556 }
12557
12558 static struct perf_cpu_buf *
12559 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12560                           int cpu, int map_key)
12561 {
12562         struct perf_cpu_buf *cpu_buf;
12563         char msg[STRERR_BUFSIZE];
12564         int err;
12565
12566         cpu_buf = calloc(1, sizeof(*cpu_buf));
12567         if (!cpu_buf)
12568                 return ERR_PTR(-ENOMEM);
12569
12570         cpu_buf->pb = pb;
12571         cpu_buf->cpu = cpu;
12572         cpu_buf->map_key = map_key;
12573
12574         cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12575                               -1, PERF_FLAG_FD_CLOEXEC);
12576         if (cpu_buf->fd < 0) {
12577                 err = -errno;
12578                 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12579                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12580                 goto error;
12581         }
12582
12583         cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12584                              PROT_READ | PROT_WRITE, MAP_SHARED,
12585                              cpu_buf->fd, 0);
12586         if (cpu_buf->base == MAP_FAILED) {
12587                 cpu_buf->base = NULL;
12588                 err = -errno;
12589                 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12590                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12591                 goto error;
12592         }
12593
12594         if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12595                 err = -errno;
12596                 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12597                         cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12598                 goto error;
12599         }
12600
12601         return cpu_buf;
12602
12603 error:
12604         perf_buffer__free_cpu_buf(pb, cpu_buf);
12605         return (struct perf_cpu_buf *)ERR_PTR(err);
12606 }
12607
12608 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12609                                               struct perf_buffer_params *p);
12610
12611 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12612                                      perf_buffer_sample_fn sample_cb,
12613                                      perf_buffer_lost_fn lost_cb,
12614                                      void *ctx,
12615                                      const struct perf_buffer_opts *opts)
12616 {
12617         const size_t attr_sz = sizeof(struct perf_event_attr);
12618         struct perf_buffer_params p = {};
12619         struct perf_event_attr attr;
12620         __u32 sample_period;
12621
12622         if (!OPTS_VALID(opts, perf_buffer_opts))
12623                 return libbpf_err_ptr(-EINVAL);
12624
12625         sample_period = OPTS_GET(opts, sample_period, 1);
12626         if (!sample_period)
12627                 sample_period = 1;
12628
12629         memset(&attr, 0, attr_sz);
12630         attr.size = attr_sz;
12631         attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12632         attr.type = PERF_TYPE_SOFTWARE;
12633         attr.sample_type = PERF_SAMPLE_RAW;
12634         attr.sample_period = sample_period;
12635         attr.wakeup_events = sample_period;
12636
12637         p.attr = &attr;
12638         p.sample_cb = sample_cb;
12639         p.lost_cb = lost_cb;
12640         p.ctx = ctx;
12641
12642         return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12643 }
12644
12645 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12646                                          struct perf_event_attr *attr,
12647                                          perf_buffer_event_fn event_cb, void *ctx,
12648                                          const struct perf_buffer_raw_opts *opts)
12649 {
12650         struct perf_buffer_params p = {};
12651
12652         if (!attr)
12653                 return libbpf_err_ptr(-EINVAL);
12654
12655         if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12656                 return libbpf_err_ptr(-EINVAL);
12657
12658         p.attr = attr;
12659         p.event_cb = event_cb;
12660         p.ctx = ctx;
12661         p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12662         p.cpus = OPTS_GET(opts, cpus, NULL);
12663         p.map_keys = OPTS_GET(opts, map_keys, NULL);
12664
12665         return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12666 }
12667
12668 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12669                                               struct perf_buffer_params *p)
12670 {
12671         const char *online_cpus_file = "/sys/devices/system/cpu/online";
12672         struct bpf_map_info map;
12673         char msg[STRERR_BUFSIZE];
12674         struct perf_buffer *pb;
12675         bool *online = NULL;
12676         __u32 map_info_len;
12677         int err, i, j, n;
12678
12679         if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12680                 pr_warn("page count should be power of two, but is %zu\n",
12681                         page_cnt);
12682                 return ERR_PTR(-EINVAL);
12683         }
12684
12685         /* best-effort sanity checks */
12686         memset(&map, 0, sizeof(map));
12687         map_info_len = sizeof(map);
12688         err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12689         if (err) {
12690                 err = -errno;
12691                 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12692                  * -EBADFD, -EFAULT, or -E2BIG on real error
12693                  */
12694                 if (err != -EINVAL) {
12695                         pr_warn("failed to get map info for map FD %d: %s\n",
12696                                 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12697                         return ERR_PTR(err);
12698                 }
12699                 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12700                          map_fd);
12701         } else {
12702                 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12703                         pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12704                                 map.name);
12705                         return ERR_PTR(-EINVAL);
12706                 }
12707         }
12708
12709         pb = calloc(1, sizeof(*pb));
12710         if (!pb)
12711                 return ERR_PTR(-ENOMEM);
12712
12713         pb->event_cb = p->event_cb;
12714         pb->sample_cb = p->sample_cb;
12715         pb->lost_cb = p->lost_cb;
12716         pb->ctx = p->ctx;
12717
12718         pb->page_size = getpagesize();
12719         pb->mmap_size = pb->page_size * page_cnt;
12720         pb->map_fd = map_fd;
12721
12722         pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12723         if (pb->epoll_fd < 0) {
12724                 err = -errno;
12725                 pr_warn("failed to create epoll instance: %s\n",
12726                         libbpf_strerror_r(err, msg, sizeof(msg)));
12727                 goto error;
12728         }
12729
12730         if (p->cpu_cnt > 0) {
12731                 pb->cpu_cnt = p->cpu_cnt;
12732         } else {
12733                 pb->cpu_cnt = libbpf_num_possible_cpus();
12734                 if (pb->cpu_cnt < 0) {
12735                         err = pb->cpu_cnt;
12736                         goto error;
12737                 }
12738                 if (map.max_entries && map.max_entries < pb->cpu_cnt)
12739                         pb->cpu_cnt = map.max_entries;
12740         }
12741
12742         pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12743         if (!pb->events) {
12744                 err = -ENOMEM;
12745                 pr_warn("failed to allocate events: out of memory\n");
12746                 goto error;
12747         }
12748         pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12749         if (!pb->cpu_bufs) {
12750                 err = -ENOMEM;
12751                 pr_warn("failed to allocate buffers: out of memory\n");
12752                 goto error;
12753         }
12754
12755         err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12756         if (err) {
12757                 pr_warn("failed to get online CPU mask: %d\n", err);
12758                 goto error;
12759         }
12760
12761         for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12762                 struct perf_cpu_buf *cpu_buf;
12763                 int cpu, map_key;
12764
12765                 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12766                 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12767
12768                 /* in case user didn't explicitly requested particular CPUs to
12769                  * be attached to, skip offline/not present CPUs
12770                  */
12771                 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12772                         continue;
12773
12774                 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12775                 if (IS_ERR(cpu_buf)) {
12776                         err = PTR_ERR(cpu_buf);
12777                         goto error;
12778                 }
12779
12780                 pb->cpu_bufs[j] = cpu_buf;
12781
12782                 err = bpf_map_update_elem(pb->map_fd, &map_key,
12783                                           &cpu_buf->fd, 0);
12784                 if (err) {
12785                         err = -errno;
12786                         pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12787                                 cpu, map_key, cpu_buf->fd,
12788                                 libbpf_strerror_r(err, msg, sizeof(msg)));
12789                         goto error;
12790                 }
12791
12792                 pb->events[j].events = EPOLLIN;
12793                 pb->events[j].data.ptr = cpu_buf;
12794                 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12795                               &pb->events[j]) < 0) {
12796                         err = -errno;
12797                         pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12798                                 cpu, cpu_buf->fd,
12799                                 libbpf_strerror_r(err, msg, sizeof(msg)));
12800                         goto error;
12801                 }
12802                 j++;
12803         }
12804         pb->cpu_cnt = j;
12805         free(online);
12806
12807         return pb;
12808
12809 error:
12810         free(online);
12811         if (pb)
12812                 perf_buffer__free(pb);
12813         return ERR_PTR(err);
12814 }
12815
12816 struct perf_sample_raw {
12817         struct perf_event_header header;
12818         uint32_t size;
12819         char data[];
12820 };
12821
12822 struct perf_sample_lost {
12823         struct perf_event_header header;
12824         uint64_t id;
12825         uint64_t lost;
12826         uint64_t sample_id;
12827 };
12828
12829 static enum bpf_perf_event_ret
12830 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12831 {
12832         struct perf_cpu_buf *cpu_buf = ctx;
12833         struct perf_buffer *pb = cpu_buf->pb;
12834         void *data = e;
12835
12836         /* user wants full control over parsing perf event */
12837         if (pb->event_cb)
12838                 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12839
12840         switch (e->type) {
12841         case PERF_RECORD_SAMPLE: {
12842                 struct perf_sample_raw *s = data;
12843
12844                 if (pb->sample_cb)
12845                         pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12846                 break;
12847         }
12848         case PERF_RECORD_LOST: {
12849                 struct perf_sample_lost *s = data;
12850
12851                 if (pb->lost_cb)
12852                         pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12853                 break;
12854         }
12855         default:
12856                 pr_warn("unknown perf sample type %d\n", e->type);
12857                 return LIBBPF_PERF_EVENT_ERROR;
12858         }
12859         return LIBBPF_PERF_EVENT_CONT;
12860 }
12861
12862 static int perf_buffer__process_records(struct perf_buffer *pb,
12863                                         struct perf_cpu_buf *cpu_buf)
12864 {
12865         enum bpf_perf_event_ret ret;
12866
12867         ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12868                                      pb->page_size, &cpu_buf->buf,
12869                                      &cpu_buf->buf_size,
12870                                      perf_buffer__process_record, cpu_buf);
12871         if (ret != LIBBPF_PERF_EVENT_CONT)
12872                 return ret;
12873         return 0;
12874 }
12875
12876 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12877 {
12878         return pb->epoll_fd;
12879 }
12880
12881 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12882 {
12883         int i, cnt, err;
12884
12885         cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12886         if (cnt < 0)
12887                 return -errno;
12888
12889         for (i = 0; i < cnt; i++) {
12890                 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12891
12892                 err = perf_buffer__process_records(pb, cpu_buf);
12893                 if (err) {
12894                         pr_warn("error while processing records: %d\n", err);
12895                         return libbpf_err(err);
12896                 }
12897         }
12898         return cnt;
12899 }
12900
12901 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12902  * manager.
12903  */
12904 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12905 {
12906         return pb->cpu_cnt;
12907 }
12908
12909 /*
12910  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12911  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12912  * select()/poll()/epoll() Linux syscalls.
12913  */
12914 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12915 {
12916         struct perf_cpu_buf *cpu_buf;
12917
12918         if (buf_idx >= pb->cpu_cnt)
12919                 return libbpf_err(-EINVAL);
12920
12921         cpu_buf = pb->cpu_bufs[buf_idx];
12922         if (!cpu_buf)
12923                 return libbpf_err(-ENOENT);
12924
12925         return cpu_buf->fd;
12926 }
12927
12928 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12929 {
12930         struct perf_cpu_buf *cpu_buf;
12931
12932         if (buf_idx >= pb->cpu_cnt)
12933                 return libbpf_err(-EINVAL);
12934
12935         cpu_buf = pb->cpu_bufs[buf_idx];
12936         if (!cpu_buf)
12937                 return libbpf_err(-ENOENT);
12938
12939         *buf = cpu_buf->base;
12940         *buf_size = pb->mmap_size;
12941         return 0;
12942 }
12943
12944 /*
12945  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12946  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12947  * consume, do nothing and return success.
12948  * Returns:
12949  *   - 0 on success;
12950  *   - <0 on failure.
12951  */
12952 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12953 {
12954         struct perf_cpu_buf *cpu_buf;
12955
12956         if (buf_idx >= pb->cpu_cnt)
12957                 return libbpf_err(-EINVAL);
12958
12959         cpu_buf = pb->cpu_bufs[buf_idx];
12960         if (!cpu_buf)
12961                 return libbpf_err(-ENOENT);
12962
12963         return perf_buffer__process_records(pb, cpu_buf);
12964 }
12965
12966 int perf_buffer__consume(struct perf_buffer *pb)
12967 {
12968         int i, err;
12969
12970         for (i = 0; i < pb->cpu_cnt; i++) {
12971                 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12972
12973                 if (!cpu_buf)
12974                         continue;
12975
12976                 err = perf_buffer__process_records(pb, cpu_buf);
12977                 if (err) {
12978                         pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12979                         return libbpf_err(err);
12980                 }
12981         }
12982         return 0;
12983 }
12984
12985 int bpf_program__set_attach_target(struct bpf_program *prog,
12986                                    int attach_prog_fd,
12987                                    const char *attach_func_name)
12988 {
12989         int btf_obj_fd = 0, btf_id = 0, err;
12990
12991         if (!prog || attach_prog_fd < 0)
12992                 return libbpf_err(-EINVAL);
12993
12994         if (prog->obj->loaded)
12995                 return libbpf_err(-EINVAL);
12996
12997         if (attach_prog_fd && !attach_func_name) {
12998                 /* remember attach_prog_fd and let bpf_program__load() find
12999                  * BTF ID during the program load
13000                  */
13001                 prog->attach_prog_fd = attach_prog_fd;
13002                 return 0;
13003         }
13004
13005         if (attach_prog_fd) {
13006                 btf_id = libbpf_find_prog_btf_id(attach_func_name,
13007                                                  attach_prog_fd);
13008                 if (btf_id < 0)
13009                         return libbpf_err(btf_id);
13010         } else {
13011                 if (!attach_func_name)
13012                         return libbpf_err(-EINVAL);
13013
13014                 /* load btf_vmlinux, if not yet */
13015                 err = bpf_object__load_vmlinux_btf(prog->obj, true);
13016                 if (err)
13017                         return libbpf_err(err);
13018                 err = find_kernel_btf_id(prog->obj, attach_func_name,
13019                                          prog->expected_attach_type,
13020                                          &btf_obj_fd, &btf_id);
13021                 if (err)
13022                         return libbpf_err(err);
13023         }
13024
13025         prog->attach_btf_id = btf_id;
13026         prog->attach_btf_obj_fd = btf_obj_fd;
13027         prog->attach_prog_fd = attach_prog_fd;
13028         return 0;
13029 }
13030
13031 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13032 {
13033         int err = 0, n, len, start, end = -1;
13034         bool *tmp;
13035
13036         *mask = NULL;
13037         *mask_sz = 0;
13038
13039         /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13040         while (*s) {
13041                 if (*s == ',' || *s == '\n') {
13042                         s++;
13043                         continue;
13044                 }
13045                 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13046                 if (n <= 0 || n > 2) {
13047                         pr_warn("Failed to get CPU range %s: %d\n", s, n);
13048                         err = -EINVAL;
13049                         goto cleanup;
13050                 } else if (n == 1) {
13051                         end = start;
13052                 }
13053                 if (start < 0 || start > end) {
13054                         pr_warn("Invalid CPU range [%d,%d] in %s\n",
13055                                 start, end, s);
13056                         err = -EINVAL;
13057                         goto cleanup;
13058                 }
13059                 tmp = realloc(*mask, end + 1);
13060                 if (!tmp) {
13061                         err = -ENOMEM;
13062                         goto cleanup;
13063                 }
13064                 *mask = tmp;
13065                 memset(tmp + *mask_sz, 0, start - *mask_sz);
13066                 memset(tmp + start, 1, end - start + 1);
13067                 *mask_sz = end + 1;
13068                 s += len;
13069         }
13070         if (!*mask_sz) {
13071                 pr_warn("Empty CPU range\n");
13072                 return -EINVAL;
13073         }
13074         return 0;
13075 cleanup:
13076         free(*mask);
13077         *mask = NULL;
13078         return err;
13079 }
13080
13081 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13082 {
13083         int fd, err = 0, len;
13084         char buf[128];
13085
13086         fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13087         if (fd < 0) {
13088                 err = -errno;
13089                 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13090                 return err;
13091         }
13092         len = read(fd, buf, sizeof(buf));
13093         close(fd);
13094         if (len <= 0) {
13095                 err = len ? -errno : -EINVAL;
13096                 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13097                 return err;
13098         }
13099         if (len >= sizeof(buf)) {
13100                 pr_warn("CPU mask is too big in file %s\n", fcpu);
13101                 return -E2BIG;
13102         }
13103         buf[len] = '\0';
13104
13105         return parse_cpu_mask_str(buf, mask, mask_sz);
13106 }
13107
13108 int libbpf_num_possible_cpus(void)
13109 {
13110         static const char *fcpu = "/sys/devices/system/cpu/possible";
13111         static int cpus;
13112         int err, n, i, tmp_cpus;
13113         bool *mask;
13114
13115         tmp_cpus = READ_ONCE(cpus);
13116         if (tmp_cpus > 0)
13117                 return tmp_cpus;
13118
13119         err = parse_cpu_mask_file(fcpu, &mask, &n);
13120         if (err)
13121                 return libbpf_err(err);
13122
13123         tmp_cpus = 0;
13124         for (i = 0; i < n; i++) {
13125                 if (mask[i])
13126                         tmp_cpus++;
13127         }
13128         free(mask);
13129
13130         WRITE_ONCE(cpus, tmp_cpus);
13131         return tmp_cpus;
13132 }
13133
13134 static int populate_skeleton_maps(const struct bpf_object *obj,
13135                                   struct bpf_map_skeleton *maps,
13136                                   size_t map_cnt)
13137 {
13138         int i;
13139
13140         for (i = 0; i < map_cnt; i++) {
13141                 struct bpf_map **map = maps[i].map;
13142                 const char *name = maps[i].name;
13143                 void **mmaped = maps[i].mmaped;
13144
13145                 *map = bpf_object__find_map_by_name(obj, name);
13146                 if (!*map) {
13147                         pr_warn("failed to find skeleton map '%s'\n", name);
13148                         return -ESRCH;
13149                 }
13150
13151                 /* externs shouldn't be pre-setup from user code */
13152                 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13153                         *mmaped = (*map)->mmaped;
13154         }
13155         return 0;
13156 }
13157
13158 static int populate_skeleton_progs(const struct bpf_object *obj,
13159                                    struct bpf_prog_skeleton *progs,
13160                                    size_t prog_cnt)
13161 {
13162         int i;
13163
13164         for (i = 0; i < prog_cnt; i++) {
13165                 struct bpf_program **prog = progs[i].prog;
13166                 const char *name = progs[i].name;
13167
13168                 *prog = bpf_object__find_program_by_name(obj, name);
13169                 if (!*prog) {
13170                         pr_warn("failed to find skeleton program '%s'\n", name);
13171                         return -ESRCH;
13172                 }
13173         }
13174         return 0;
13175 }
13176
13177 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13178                               const struct bpf_object_open_opts *opts)
13179 {
13180         DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13181                 .object_name = s->name,
13182         );
13183         struct bpf_object *obj;
13184         int err;
13185
13186         /* Attempt to preserve opts->object_name, unless overriden by user
13187          * explicitly. Overwriting object name for skeletons is discouraged,
13188          * as it breaks global data maps, because they contain object name
13189          * prefix as their own map name prefix. When skeleton is generated,
13190          * bpftool is making an assumption that this name will stay the same.
13191          */
13192         if (opts) {
13193                 memcpy(&skel_opts, opts, sizeof(*opts));
13194                 if (!opts->object_name)
13195                         skel_opts.object_name = s->name;
13196         }
13197
13198         obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13199         err = libbpf_get_error(obj);
13200         if (err) {
13201                 pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13202                         s->name, err);
13203                 return libbpf_err(err);
13204         }
13205
13206         *s->obj = obj;
13207         err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13208         if (err) {
13209                 pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13210                 return libbpf_err(err);
13211         }
13212
13213         err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13214         if (err) {
13215                 pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13216                 return libbpf_err(err);
13217         }
13218
13219         return 0;
13220 }
13221
13222 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13223 {
13224         int err, len, var_idx, i;
13225         const char *var_name;
13226         const struct bpf_map *map;
13227         struct btf *btf;
13228         __u32 map_type_id;
13229         const struct btf_type *map_type, *var_type;
13230         const struct bpf_var_skeleton *var_skel;
13231         struct btf_var_secinfo *var;
13232
13233         if (!s->obj)
13234                 return libbpf_err(-EINVAL);
13235
13236         btf = bpf_object__btf(s->obj);
13237         if (!btf) {
13238                 pr_warn("subskeletons require BTF at runtime (object %s)\n",
13239                         bpf_object__name(s->obj));
13240                 return libbpf_err(-errno);
13241         }
13242
13243         err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13244         if (err) {
13245                 pr_warn("failed to populate subskeleton maps: %d\n", err);
13246                 return libbpf_err(err);
13247         }
13248
13249         err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13250         if (err) {
13251                 pr_warn("failed to populate subskeleton maps: %d\n", err);
13252                 return libbpf_err(err);
13253         }
13254
13255         for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13256                 var_skel = &s->vars[var_idx];
13257                 map = *var_skel->map;
13258                 map_type_id = bpf_map__btf_value_type_id(map);
13259                 map_type = btf__type_by_id(btf, map_type_id);
13260
13261                 if (!btf_is_datasec(map_type)) {
13262                         pr_warn("type for map '%1$s' is not a datasec: %2$s",
13263                                 bpf_map__name(map),
13264                                 __btf_kind_str(btf_kind(map_type)));
13265                         return libbpf_err(-EINVAL);
13266                 }
13267
13268                 len = btf_vlen(map_type);
13269                 var = btf_var_secinfos(map_type);
13270                 for (i = 0; i < len; i++, var++) {
13271                         var_type = btf__type_by_id(btf, var->type);
13272                         var_name = btf__name_by_offset(btf, var_type->name_off);
13273                         if (strcmp(var_name, var_skel->name) == 0) {
13274                                 *var_skel->addr = map->mmaped + var->offset;
13275                                 break;
13276                         }
13277                 }
13278         }
13279         return 0;
13280 }
13281
13282 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13283 {
13284         if (!s)
13285                 return;
13286         free(s->maps);
13287         free(s->progs);
13288         free(s->vars);
13289         free(s);
13290 }
13291
13292 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13293 {
13294         int i, err;
13295
13296         err = bpf_object__load(*s->obj);
13297         if (err) {
13298                 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13299                 return libbpf_err(err);
13300         }
13301
13302         for (i = 0; i < s->map_cnt; i++) {
13303                 struct bpf_map *map = *s->maps[i].map;
13304                 size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13305                 int prot, map_fd = bpf_map__fd(map);
13306                 void **mmaped = s->maps[i].mmaped;
13307
13308                 if (!mmaped)
13309                         continue;
13310
13311                 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13312                         *mmaped = NULL;
13313                         continue;
13314                 }
13315
13316                 if (map->def.map_flags & BPF_F_RDONLY_PROG)
13317                         prot = PROT_READ;
13318                 else
13319                         prot = PROT_READ | PROT_WRITE;
13320
13321                 /* Remap anonymous mmap()-ed "map initialization image" as
13322                  * a BPF map-backed mmap()-ed memory, but preserving the same
13323                  * memory address. This will cause kernel to change process'
13324                  * page table to point to a different piece of kernel memory,
13325                  * but from userspace point of view memory address (and its
13326                  * contents, being identical at this point) will stay the
13327                  * same. This mapping will be released by bpf_object__close()
13328                  * as per normal clean up procedure, so we don't need to worry
13329                  * about it from skeleton's clean up perspective.
13330                  */
13331                 *mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13332                 if (*mmaped == MAP_FAILED) {
13333                         err = -errno;
13334                         *mmaped = NULL;
13335                         pr_warn("failed to re-mmap() map '%s': %d\n",
13336                                  bpf_map__name(map), err);
13337                         return libbpf_err(err);
13338                 }
13339         }
13340
13341         return 0;
13342 }
13343
13344 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13345 {
13346         int i, err;
13347
13348         for (i = 0; i < s->prog_cnt; i++) {
13349                 struct bpf_program *prog = *s->progs[i].prog;
13350                 struct bpf_link **link = s->progs[i].link;
13351
13352                 if (!prog->autoload || !prog->autoattach)
13353                         continue;
13354
13355                 /* auto-attaching not supported for this program */
13356                 if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13357                         continue;
13358
13359                 /* if user already set the link manually, don't attempt auto-attach */
13360                 if (*link)
13361                         continue;
13362
13363                 err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13364                 if (err) {
13365                         pr_warn("prog '%s': failed to auto-attach: %d\n",
13366                                 bpf_program__name(prog), err);
13367                         return libbpf_err(err);
13368                 }
13369
13370                 /* It's possible that for some SEC() definitions auto-attach
13371                  * is supported in some cases (e.g., if definition completely
13372                  * specifies target information), but is not in other cases.
13373                  * SEC("uprobe") is one such case. If user specified target
13374                  * binary and function name, such BPF program can be
13375                  * auto-attached. But if not, it shouldn't trigger skeleton's
13376                  * attach to fail. It should just be skipped.
13377                  * attach_fn signals such case with returning 0 (no error) and
13378                  * setting link to NULL.
13379                  */
13380         }
13381
13382         return 0;
13383 }
13384
13385 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13386 {
13387         int i;
13388
13389         for (i = 0; i < s->prog_cnt; i++) {
13390                 struct bpf_link **link = s->progs[i].link;
13391
13392                 bpf_link__destroy(*link);
13393                 *link = NULL;
13394         }
13395 }
13396
13397 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13398 {
13399         if (!s)
13400                 return;
13401
13402         if (s->progs)
13403                 bpf_object__detach_skeleton(s);
13404         if (s->obj)
13405                 bpf_object__close(*s->obj);
13406         free(s->maps);
13407         free(s->progs);
13408         free(s);
13409 }