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