blob: b337d6f29098bfda5a4f1732ce022d0413fa3f2e [file] [log] [blame]
David Brazdil0f672f62019-12-10 10:32:29 +00001// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002
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.
David Brazdil0f672f62019-12-10 10:32:29 +000010 * Copyright (C) 2019 Isovalent, Inc.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000011 */
12
David Brazdil0f672f62019-12-10 10:32:29 +000013#ifndef _GNU_SOURCE
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000014#define _GNU_SOURCE
David Brazdil0f672f62019-12-10 10:32:29 +000015#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000016#include <stdlib.h>
17#include <stdio.h>
18#include <stdarg.h>
19#include <libgen.h>
20#include <inttypes.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020021#include <limits.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000022#include <string.h>
23#include <unistd.h>
David Brazdil0f672f62019-12-10 10:32:29 +000024#include <endian.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000025#include <fcntl.h>
26#include <errno.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020027#include <ctype.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000028#include <asm/unistd.h>
29#include <linux/err.h>
30#include <linux/kernel.h>
31#include <linux/bpf.h>
32#include <linux/btf.h>
David Brazdil0f672f62019-12-10 10:32:29 +000033#include <linux/filter.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000034#include <linux/list.h>
35#include <linux/limits.h>
David Brazdil0f672f62019-12-10 10:32:29 +000036#include <linux/perf_event.h>
37#include <linux/ring_buffer.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020038#include <linux/version.h>
David Brazdil0f672f62019-12-10 10:32:29 +000039#include <sys/epoll.h>
40#include <sys/ioctl.h>
41#include <sys/mman.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000042#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/vfs.h>
David Brazdil0f672f62019-12-10 10:32:29 +000045#include <sys/utsname.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020046#include <sys/resource.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000047#include <libelf.h>
48#include <gelf.h>
Olivier Deprez157378f2022-04-04 15:47:50 +020049#include <zlib.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000050
51#include "libbpf.h"
52#include "bpf.h"
53#include "btf.h"
54#include "str_error.h"
David Brazdil0f672f62019-12-10 10:32:29 +000055#include "libbpf_internal.h"
56#include "hashmap.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000057
58#ifndef EM_BPF
59#define EM_BPF 247
60#endif
61
62#ifndef BPF_FS_MAGIC
63#define BPF_FS_MAGIC 0xcafe4a11
64#endif
65
Olivier Deprez157378f2022-04-04 15:47:50 +020066#define BPF_INSN_SZ (sizeof(struct bpf_insn))
67
David Brazdil0f672f62019-12-10 10:32:29 +000068/* vsprintf() in __base_pr() uses nonliteral format string. It may break
69 * compilation if user enables corresponding warning. Disable it explicitly.
70 */
71#pragma GCC diagnostic ignored "-Wformat-nonliteral"
72
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000073#define __printf(a, b) __attribute__((format(printf, a, b)))
74
Olivier Deprez157378f2022-04-04 15:47:50 +020075static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76static const struct btf_type *
77skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
78
David Brazdil0f672f62019-12-10 10:32:29 +000079static int __base_pr(enum libbpf_print_level level, const char *format,
80 va_list args)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000081{
David Brazdil0f672f62019-12-10 10:32:29 +000082 if (level == LIBBPF_DEBUG)
83 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000084
David Brazdil0f672f62019-12-10 10:32:29 +000085 return vfprintf(stderr, format, args);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000086}
87
David Brazdil0f672f62019-12-10 10:32:29 +000088static libbpf_print_fn_t __libbpf_pr = __base_pr;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000089
David Brazdil0f672f62019-12-10 10:32:29 +000090libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000091{
David Brazdil0f672f62019-12-10 10:32:29 +000092 libbpf_print_fn_t old_print_fn = __libbpf_pr;
93
94 __libbpf_pr = fn;
95 return old_print_fn;
96}
97
98__printf(2, 3)
99void libbpf_print(enum libbpf_print_level level, const char *format, ...)
100{
101 va_list args;
102
103 if (!__libbpf_pr)
104 return;
105
106 va_start(args, format);
107 __libbpf_pr(level, format, args);
108 va_end(args);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000109}
110
Olivier Deprez157378f2022-04-04 15:47:50 +0200111static void pr_perm_msg(int err)
112{
113 struct rlimit limit;
114 char buf[100];
115
116 if (err != -EPERM || geteuid() != 0)
117 return;
118
119 err = getrlimit(RLIMIT_MEMLOCK, &limit);
120 if (err)
121 return;
122
123 if (limit.rlim_cur == RLIM_INFINITY)
124 return;
125
126 if (limit.rlim_cur < 1024)
127 snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
128 else if (limit.rlim_cur < 1024*1024)
129 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
130 else
131 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
132
133 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
134 buf);
135}
136
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000137#define STRERR_BUFSIZE 128
138
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000139/* Copied from tools/perf/util/util.h */
140#ifndef zfree
141# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
142#endif
143
144#ifndef zclose
145# define zclose(fd) ({ \
146 int ___err = 0; \
147 if ((fd) >= 0) \
148 ___err = close((fd)); \
149 fd = -1; \
150 ___err; })
151#endif
152
David Brazdil0f672f62019-12-10 10:32:29 +0000153static inline __u64 ptr_to_u64(const void *ptr)
154{
155 return (__u64) (unsigned long) ptr;
156}
157
Olivier Deprez157378f2022-04-04 15:47:50 +0200158enum kern_feature_id {
David Brazdil0f672f62019-12-10 10:32:29 +0000159 /* v4.14: kernel support for program & map names. */
Olivier Deprez157378f2022-04-04 15:47:50 +0200160 FEAT_PROG_NAME,
David Brazdil0f672f62019-12-10 10:32:29 +0000161 /* v5.2: kernel support for global data sections. */
Olivier Deprez157378f2022-04-04 15:47:50 +0200162 FEAT_GLOBAL_DATA,
163 /* BTF support */
164 FEAT_BTF,
David Brazdil0f672f62019-12-10 10:32:29 +0000165 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
Olivier Deprez157378f2022-04-04 15:47:50 +0200166 FEAT_BTF_FUNC,
David Brazdil0f672f62019-12-10 10:32:29 +0000167 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
Olivier Deprez157378f2022-04-04 15:47:50 +0200168 FEAT_BTF_DATASEC,
169 /* BTF_FUNC_GLOBAL is supported */
170 FEAT_BTF_GLOBAL_FUNC,
171 /* BPF_F_MMAPABLE is supported for arrays */
172 FEAT_ARRAY_MMAP,
173 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
174 FEAT_EXP_ATTACH_TYPE,
175 /* bpf_probe_read_{kernel,user}[_str] helpers */
176 FEAT_PROBE_READ_KERN,
177 /* BPF_PROG_BIND_MAP is supported */
178 FEAT_PROG_BIND_MAP,
179 __FEAT_CNT,
180};
181
182static bool kernel_supports(enum kern_feature_id feat_id);
183
184enum reloc_type {
185 RELO_LD64,
186 RELO_CALL,
187 RELO_DATA,
188 RELO_EXTERN,
189};
190
191struct reloc_desc {
192 enum reloc_type type;
193 int insn_idx;
194 int map_idx;
195 int sym_off;
196 bool processed;
197};
198
199struct bpf_sec_def;
200
201typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
202 struct bpf_program *prog);
203
204struct bpf_sec_def {
205 const char *sec;
206 size_t len;
207 enum bpf_prog_type prog_type;
208 enum bpf_attach_type expected_attach_type;
209 bool is_exp_attach_type_optional;
210 bool is_attachable;
211 bool is_attach_btf;
212 bool is_sleepable;
213 attach_fn_t attach_fn;
David Brazdil0f672f62019-12-10 10:32:29 +0000214};
215
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000216/*
217 * bpf_prog should be a better name but it has been used in
218 * linux/filter.h.
219 */
220struct bpf_program {
Olivier Deprez157378f2022-04-04 15:47:50 +0200221 const struct bpf_sec_def *sec_def;
222 char *sec_name;
223 size_t sec_idx;
224 /* this program's instruction offset (in number of instructions)
225 * within its containing ELF section
226 */
227 size_t sec_insn_off;
228 /* number of original instructions in ELF section belonging to this
229 * program, not taking into account subprogram instructions possible
230 * appended later during relocation
231 */
232 size_t sec_insn_cnt;
233 /* Offset (in number of instructions) of the start of instruction
234 * belonging to this BPF program within its containing main BPF
235 * program. For the entry-point (main) BPF program, this is always
236 * zero. For a sub-program, this gets reset before each of main BPF
237 * programs are processed and relocated and is used to determined
238 * whether sub-program was already appended to the main program, and
239 * if yes, at which instruction offset.
240 */
241 size_t sub_insn_off;
242
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000243 char *name;
Olivier Deprez157378f2022-04-04 15:47:50 +0200244 /* sec_name with / replaced by _; makes recursive pinning
David Brazdil0f672f62019-12-10 10:32:29 +0000245 * in bpf_object__pin_programs easier
246 */
247 char *pin_name;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000248
Olivier Deprez157378f2022-04-04 15:47:50 +0200249 /* instructions that belong to BPF program; insns[0] is located at
250 * sec_insn_off instruction within its ELF section in ELF file, so
251 * when mapping ELF file instruction index to the local instruction,
252 * one needs to subtract sec_insn_off; and vice versa.
253 */
254 struct bpf_insn *insns;
255 /* actual number of instruction in this BPF program's image; for
256 * entry-point BPF programs this includes the size of main program
257 * itself plus all the used sub-programs, appended at the end
258 */
259 size_t insns_cnt;
260
261 struct reloc_desc *reloc_desc;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000262 int nr_reloc;
David Brazdil0f672f62019-12-10 10:32:29 +0000263 int log_level;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000264
265 struct {
266 int nr;
267 int *fds;
268 } instances;
269 bpf_program_prep_t preprocessor;
270
271 struct bpf_object *obj;
272 void *priv;
273 bpf_program_clear_priv_t clear_priv;
274
Olivier Deprez157378f2022-04-04 15:47:50 +0200275 bool load;
276 enum bpf_prog_type type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000277 enum bpf_attach_type expected_attach_type;
Olivier Deprez157378f2022-04-04 15:47:50 +0200278 int prog_ifindex;
279 __u32 attach_btf_id;
280 __u32 attach_prog_fd;
David Brazdil0f672f62019-12-10 10:32:29 +0000281 void *func_info;
282 __u32 func_info_rec_size;
283 __u32 func_info_cnt;
284
David Brazdil0f672f62019-12-10 10:32:29 +0000285 void *line_info;
286 __u32 line_info_rec_size;
287 __u32 line_info_cnt;
288 __u32 prog_flags;
289};
290
Olivier Deprez157378f2022-04-04 15:47:50 +0200291struct bpf_struct_ops {
292 const char *tname;
293 const struct btf_type *type;
294 struct bpf_program **progs;
295 __u32 *kern_func_off;
296 /* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
297 void *data;
298 /* e.g. struct bpf_struct_ops_tcp_congestion_ops in
299 * btf_vmlinux's format.
300 * struct bpf_struct_ops_tcp_congestion_ops {
301 * [... some other kernel fields ...]
302 * struct tcp_congestion_ops data;
303 * }
304 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
305 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
306 * from "data".
307 */
308 void *kern_vdata;
309 __u32 type_id;
310};
311
312#define DATA_SEC ".data"
313#define BSS_SEC ".bss"
314#define RODATA_SEC ".rodata"
315#define KCONFIG_SEC ".kconfig"
316#define KSYMS_SEC ".ksyms"
317#define STRUCT_OPS_SEC ".struct_ops"
318
David Brazdil0f672f62019-12-10 10:32:29 +0000319enum libbpf_map_type {
320 LIBBPF_MAP_UNSPEC,
321 LIBBPF_MAP_DATA,
322 LIBBPF_MAP_BSS,
323 LIBBPF_MAP_RODATA,
Olivier Deprez157378f2022-04-04 15:47:50 +0200324 LIBBPF_MAP_KCONFIG,
David Brazdil0f672f62019-12-10 10:32:29 +0000325};
326
327static const char * const libbpf_type_to_btf_name[] = {
Olivier Deprez157378f2022-04-04 15:47:50 +0200328 [LIBBPF_MAP_DATA] = DATA_SEC,
329 [LIBBPF_MAP_BSS] = BSS_SEC,
330 [LIBBPF_MAP_RODATA] = RODATA_SEC,
331 [LIBBPF_MAP_KCONFIG] = KCONFIG_SEC,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000332};
333
334struct bpf_map {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000335 char *name;
Olivier Deprez157378f2022-04-04 15:47:50 +0200336 int fd;
David Brazdil0f672f62019-12-10 10:32:29 +0000337 int sec_idx;
338 size_t sec_offset;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000339 int map_ifindex;
David Brazdil0f672f62019-12-10 10:32:29 +0000340 int inner_map_fd;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000341 struct bpf_map_def def;
Olivier Deprez157378f2022-04-04 15:47:50 +0200342 __u32 numa_node;
343 __u32 btf_var_idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000344 __u32 btf_key_type_id;
345 __u32 btf_value_type_id;
Olivier Deprez157378f2022-04-04 15:47:50 +0200346 __u32 btf_vmlinux_value_type_id;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000347 void *priv;
348 bpf_map_clear_priv_t clear_priv;
David Brazdil0f672f62019-12-10 10:32:29 +0000349 enum libbpf_map_type libbpf_type;
Olivier Deprez157378f2022-04-04 15:47:50 +0200350 void *mmaped;
351 struct bpf_struct_ops *st_ops;
352 struct bpf_map *inner_map;
353 void **init_slots;
354 int init_slots_sz;
355 char *pin_path;
356 bool pinned;
357 bool reused;
David Brazdil0f672f62019-12-10 10:32:29 +0000358};
359
Olivier Deprez157378f2022-04-04 15:47:50 +0200360enum extern_type {
361 EXT_UNKNOWN,
362 EXT_KCFG,
363 EXT_KSYM,
364};
365
366enum kcfg_type {
367 KCFG_UNKNOWN,
368 KCFG_CHAR,
369 KCFG_BOOL,
370 KCFG_INT,
371 KCFG_TRISTATE,
372 KCFG_CHAR_ARR,
373};
374
375struct extern_desc {
376 enum extern_type type;
377 int sym_idx;
378 int btf_id;
379 int sec_btf_id;
380 const char *name;
381 bool is_set;
382 bool is_weak;
383 union {
384 struct {
385 enum kcfg_type type;
386 int sz;
387 int align;
388 int data_off;
389 bool is_signed;
390 } kcfg;
391 struct {
392 unsigned long long addr;
393
394 /* target btf_id of the corresponding kernel var. */
395 int vmlinux_btf_id;
396
397 /* local btf_id of the ksym extern's type. */
398 __u32 type_id;
399 } ksym;
400 };
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000401};
402
403static LIST_HEAD(bpf_objects_list);
404
405struct bpf_object {
David Brazdil0f672f62019-12-10 10:32:29 +0000406 char name[BPF_OBJ_NAME_LEN];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000407 char license[64];
David Brazdil0f672f62019-12-10 10:32:29 +0000408 __u32 kern_version;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000409
410 struct bpf_program *programs;
411 size_t nr_programs;
412 struct bpf_map *maps;
413 size_t nr_maps;
David Brazdil0f672f62019-12-10 10:32:29 +0000414 size_t maps_cap;
Olivier Deprez157378f2022-04-04 15:47:50 +0200415
416 char *kconfig;
417 struct extern_desc *externs;
418 int nr_extern;
419 int kconfig_map_idx;
420 int rodata_map_idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000421
422 bool loaded;
Olivier Deprez157378f2022-04-04 15:47:50 +0200423 bool has_subcalls;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000424
425 /*
426 * Information when doing elf related work. Only valid if fd
427 * is valid.
428 */
429 struct {
430 int fd;
Olivier Deprez157378f2022-04-04 15:47:50 +0200431 const void *obj_buf;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000432 size_t obj_buf_sz;
433 Elf *elf;
434 GElf_Ehdr ehdr;
435 Elf_Data *symbols;
David Brazdil0f672f62019-12-10 10:32:29 +0000436 Elf_Data *data;
437 Elf_Data *rodata;
438 Elf_Data *bss;
Olivier Deprez157378f2022-04-04 15:47:50 +0200439 Elf_Data *st_ops_data;
440 size_t shstrndx; /* section index for section name strings */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000441 size_t strtabidx;
442 struct {
443 GElf_Shdr shdr;
444 Elf_Data *data;
Olivier Deprez157378f2022-04-04 15:47:50 +0200445 } *reloc_sects;
446 int nr_reloc_sects;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000447 int maps_shndx;
David Brazdil0f672f62019-12-10 10:32:29 +0000448 int btf_maps_shndx;
Olivier Deprez157378f2022-04-04 15:47:50 +0200449 __u32 btf_maps_sec_btf_id;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000450 int text_shndx;
Olivier Deprez157378f2022-04-04 15:47:50 +0200451 int symbols_shndx;
David Brazdil0f672f62019-12-10 10:32:29 +0000452 int data_shndx;
453 int rodata_shndx;
454 int bss_shndx;
Olivier Deprez157378f2022-04-04 15:47:50 +0200455 int st_ops_shndx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000456 } efile;
457 /*
458 * All loaded bpf_object is linked in a list, which is
459 * hidden to caller. bpf_objects__<func> handlers deal with
460 * all objects.
461 */
462 struct list_head list;
463
464 struct btf *btf;
Olivier Deprez157378f2022-04-04 15:47:50 +0200465 /* Parse and load BTF vmlinux if any of the programs in the object need
466 * it at load time.
467 */
468 struct btf *btf_vmlinux;
David Brazdil0f672f62019-12-10 10:32:29 +0000469 struct btf_ext *btf_ext;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000470
471 void *priv;
472 bpf_object_clear_priv_t clear_priv;
473
474 char path[];
475};
476#define obj_elf_valid(o) ((o)->efile.elf)
477
Olivier Deprez157378f2022-04-04 15:47:50 +0200478static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
479static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
480static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
481static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
482static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr);
483static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
484static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
485static int elf_sym_by_sec_off(const struct bpf_object *obj, size_t sec_idx,
486 size_t off, __u32 sym_type, GElf_Sym *sym);
487
David Brazdil0f672f62019-12-10 10:32:29 +0000488void bpf_program__unload(struct bpf_program *prog)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000489{
490 int i;
491
492 if (!prog)
493 return;
494
495 /*
496 * If the object is opened but the program was never loaded,
497 * it is possible that prog->instances.nr == -1.
498 */
499 if (prog->instances.nr > 0) {
500 for (i = 0; i < prog->instances.nr; i++)
501 zclose(prog->instances.fds[i]);
502 } else if (prog->instances.nr != -1) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200503 pr_warn("Internal error: instances.nr is %d\n",
504 prog->instances.nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000505 }
506
507 prog->instances.nr = -1;
508 zfree(&prog->instances.fds);
David Brazdil0f672f62019-12-10 10:32:29 +0000509
510 zfree(&prog->func_info);
511 zfree(&prog->line_info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000512}
513
514static void bpf_program__exit(struct bpf_program *prog)
515{
516 if (!prog)
517 return;
518
519 if (prog->clear_priv)
520 prog->clear_priv(prog, prog->priv);
521
522 prog->priv = NULL;
523 prog->clear_priv = NULL;
524
525 bpf_program__unload(prog);
526 zfree(&prog->name);
Olivier Deprez157378f2022-04-04 15:47:50 +0200527 zfree(&prog->sec_name);
David Brazdil0f672f62019-12-10 10:32:29 +0000528 zfree(&prog->pin_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000529 zfree(&prog->insns);
530 zfree(&prog->reloc_desc);
531
532 prog->nr_reloc = 0;
533 prog->insns_cnt = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +0200534 prog->sec_idx = -1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000535}
536
David Brazdil0f672f62019-12-10 10:32:29 +0000537static char *__bpf_program__pin_name(struct bpf_program *prog)
538{
539 char *name, *p;
540
Olivier Deprez157378f2022-04-04 15:47:50 +0200541 name = p = strdup(prog->sec_name);
David Brazdil0f672f62019-12-10 10:32:29 +0000542 while ((p = strchr(p, '/')))
543 *p = '_';
544
545 return name;
546}
547
Olivier Deprez157378f2022-04-04 15:47:50 +0200548static bool insn_is_subprog_call(const struct bpf_insn *insn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000549{
Olivier Deprez157378f2022-04-04 15:47:50 +0200550 return BPF_CLASS(insn->code) == BPF_JMP &&
551 BPF_OP(insn->code) == BPF_CALL &&
552 BPF_SRC(insn->code) == BPF_K &&
553 insn->src_reg == BPF_PSEUDO_CALL &&
554 insn->dst_reg == 0 &&
555 insn->off == 0;
556}
David Brazdil0f672f62019-12-10 10:32:29 +0000557
Olivier Deprez157378f2022-04-04 15:47:50 +0200558static int
559bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
560 const char *name, size_t sec_idx, const char *sec_name,
561 size_t sec_off, void *insn_data, size_t insn_data_sz)
562{
563 if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
564 pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
565 sec_name, name, sec_off, insn_data_sz);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000566 return -EINVAL;
567 }
568
David Brazdil0f672f62019-12-10 10:32:29 +0000569 memset(prog, 0, sizeof(*prog));
Olivier Deprez157378f2022-04-04 15:47:50 +0200570 prog->obj = obj;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000571
Olivier Deprez157378f2022-04-04 15:47:50 +0200572 prog->sec_idx = sec_idx;
573 prog->sec_insn_off = sec_off / BPF_INSN_SZ;
574 prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
575 /* insns_cnt can later be increased by appending used subprograms */
576 prog->insns_cnt = prog->sec_insn_cnt;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000577
Olivier Deprez157378f2022-04-04 15:47:50 +0200578 prog->type = BPF_PROG_TYPE_UNSPEC;
579 prog->load = true;
David Brazdil0f672f62019-12-10 10:32:29 +0000580
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000581 prog->instances.fds = NULL;
582 prog->instances.nr = -1;
Olivier Deprez157378f2022-04-04 15:47:50 +0200583
584 prog->sec_name = strdup(sec_name);
585 if (!prog->sec_name)
586 goto errout;
587
588 prog->name = strdup(name);
589 if (!prog->name)
590 goto errout;
591
592 prog->pin_name = __bpf_program__pin_name(prog);
593 if (!prog->pin_name)
594 goto errout;
595
596 prog->insns = malloc(insn_data_sz);
597 if (!prog->insns)
598 goto errout;
599 memcpy(prog->insns, insn_data, insn_data_sz);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000600
601 return 0;
602errout:
Olivier Deprez157378f2022-04-04 15:47:50 +0200603 pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000604 bpf_program__exit(prog);
605 return -ENOMEM;
606}
607
608static int
Olivier Deprez157378f2022-04-04 15:47:50 +0200609bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
610 const char *sec_name, int sec_idx)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000611{
Olivier Deprez157378f2022-04-04 15:47:50 +0200612 struct bpf_program *prog, *progs;
613 void *data = sec_data->d_buf;
614 size_t sec_sz = sec_data->d_size, sec_off, prog_sz;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000615 int nr_progs, err;
Olivier Deprez157378f2022-04-04 15:47:50 +0200616 const char *name;
617 GElf_Sym sym;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000618
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000619 progs = obj->programs;
620 nr_progs = obj->nr_programs;
Olivier Deprez157378f2022-04-04 15:47:50 +0200621 sec_off = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000622
Olivier Deprez157378f2022-04-04 15:47:50 +0200623 while (sec_off < sec_sz) {
624 if (elf_sym_by_sec_off(obj, sec_idx, sec_off, STT_FUNC, &sym)) {
625 pr_warn("sec '%s': failed to find program symbol at offset %zu\n",
626 sec_name, sec_off);
627 return -LIBBPF_ERRNO__FORMAT;
628 }
629
630 prog_sz = sym.st_size;
631
632 name = elf_sym_str(obj, sym.st_name);
633 if (!name) {
634 pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
635 sec_name, sec_off);
636 return -LIBBPF_ERRNO__FORMAT;
637 }
638
639 if (sec_off + prog_sz > sec_sz) {
640 pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
641 sec_name, sec_off);
642 return -LIBBPF_ERRNO__FORMAT;
643 }
644
645 pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
646 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
647
648 progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
649 if (!progs) {
650 /*
651 * In this case the original obj->programs
652 * is still valid, so don't need special treat for
653 * bpf_close_object().
654 */
655 pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
656 sec_name, name);
657 return -ENOMEM;
658 }
659 obj->programs = progs;
660
661 prog = &progs[nr_progs];
662
663 err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
664 sec_off, data + sec_off, prog_sz);
665 if (err)
666 return err;
667
668 nr_progs++;
669 obj->nr_programs = nr_progs;
670
671 sec_off += prog_sz;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000672 }
673
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000674 return 0;
675}
676
Olivier Deprez157378f2022-04-04 15:47:50 +0200677static __u32 get_kernel_version(void)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000678{
Olivier Deprez157378f2022-04-04 15:47:50 +0200679 __u32 major, minor, patch;
680 struct utsname info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000681
Olivier Deprez157378f2022-04-04 15:47:50 +0200682 uname(&info);
683 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
684 return 0;
685 return KERNEL_VERSION(major, minor, patch);
686}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000687
Olivier Deprez157378f2022-04-04 15:47:50 +0200688static const struct btf_member *
689find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
690{
691 struct btf_member *m;
692 int i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000693
Olivier Deprez157378f2022-04-04 15:47:50 +0200694 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
695 if (btf_member_bit_offset(t, i) == bit_offset)
696 return m;
697 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000698
Olivier Deprez157378f2022-04-04 15:47:50 +0200699 return NULL;
700}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000701
Olivier Deprez157378f2022-04-04 15:47:50 +0200702static const struct btf_member *
703find_member_by_name(const struct btf *btf, const struct btf_type *t,
704 const char *name)
705{
706 struct btf_member *m;
707 int i;
708
709 for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
710 if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
711 return m;
712 }
713
714 return NULL;
715}
716
717#define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
718static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
719 const char *name, __u32 kind);
720
721static int
722find_struct_ops_kern_types(const struct btf *btf, const char *tname,
723 const struct btf_type **type, __u32 *type_id,
724 const struct btf_type **vtype, __u32 *vtype_id,
725 const struct btf_member **data_member)
726{
727 const struct btf_type *kern_type, *kern_vtype;
728 const struct btf_member *kern_data_member;
729 __s32 kern_vtype_id, kern_type_id;
730 __u32 i;
731
732 kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
733 if (kern_type_id < 0) {
734 pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
735 tname);
736 return kern_type_id;
737 }
738 kern_type = btf__type_by_id(btf, kern_type_id);
739
740 /* Find the corresponding "map_value" type that will be used
741 * in map_update(BPF_MAP_TYPE_STRUCT_OPS). For example,
742 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
743 * btf_vmlinux.
744 */
745 kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
746 tname, BTF_KIND_STRUCT);
747 if (kern_vtype_id < 0) {
748 pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
749 STRUCT_OPS_VALUE_PREFIX, tname);
750 return kern_vtype_id;
751 }
752 kern_vtype = btf__type_by_id(btf, kern_vtype_id);
753
754 /* Find "struct tcp_congestion_ops" from
755 * struct bpf_struct_ops_tcp_congestion_ops {
756 * [ ... ]
757 * struct tcp_congestion_ops data;
758 * }
759 */
760 kern_data_member = btf_members(kern_vtype);
761 for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
762 if (kern_data_member->type == kern_type_id)
763 break;
764 }
765 if (i == btf_vlen(kern_vtype)) {
766 pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
767 tname, STRUCT_OPS_VALUE_PREFIX, tname);
768 return -EINVAL;
769 }
770
771 *type = kern_type;
772 *type_id = kern_type_id;
773 *vtype = kern_vtype;
774 *vtype_id = kern_vtype_id;
775 *data_member = kern_data_member;
776
777 return 0;
778}
779
780static bool bpf_map__is_struct_ops(const struct bpf_map *map)
781{
782 return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
783}
784
785/* Init the map's fields that depend on kern_btf */
786static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
787 const struct btf *btf,
788 const struct btf *kern_btf)
789{
790 const struct btf_member *member, *kern_member, *kern_data_member;
791 const struct btf_type *type, *kern_type, *kern_vtype;
792 __u32 i, kern_type_id, kern_vtype_id, kern_data_off;
793 struct bpf_struct_ops *st_ops;
794 void *data, *kern_data;
795 const char *tname;
796 int err;
797
798 st_ops = map->st_ops;
799 type = st_ops->type;
800 tname = st_ops->tname;
801 err = find_struct_ops_kern_types(kern_btf, tname,
802 &kern_type, &kern_type_id,
803 &kern_vtype, &kern_vtype_id,
804 &kern_data_member);
805 if (err)
806 return err;
807
808 pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
809 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
810
811 map->def.value_size = kern_vtype->size;
812 map->btf_vmlinux_value_type_id = kern_vtype_id;
813
814 st_ops->kern_vdata = calloc(1, kern_vtype->size);
815 if (!st_ops->kern_vdata)
816 return -ENOMEM;
817
818 data = st_ops->data;
819 kern_data_off = kern_data_member->offset / 8;
820 kern_data = st_ops->kern_vdata + kern_data_off;
821
822 member = btf_members(type);
823 for (i = 0; i < btf_vlen(type); i++, member++) {
824 const struct btf_type *mtype, *kern_mtype;
825 __u32 mtype_id, kern_mtype_id;
826 void *mdata, *kern_mdata;
827 __s64 msize, kern_msize;
828 __u32 moff, kern_moff;
829 __u32 kern_member_idx;
830 const char *mname;
831
832 mname = btf__name_by_offset(btf, member->name_off);
833 kern_member = find_member_by_name(kern_btf, kern_type, mname);
834 if (!kern_member) {
835 pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
836 map->name, mname);
837 return -ENOTSUP;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000838 }
839
Olivier Deprez157378f2022-04-04 15:47:50 +0200840 kern_member_idx = kern_member - btf_members(kern_type);
841 if (btf_member_bitfield_size(type, i) ||
842 btf_member_bitfield_size(kern_type, kern_member_idx)) {
843 pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
844 map->name, mname);
845 return -ENOTSUP;
846 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000847
Olivier Deprez157378f2022-04-04 15:47:50 +0200848 moff = member->offset / 8;
849 kern_moff = kern_member->offset / 8;
850
851 mdata = data + moff;
852 kern_mdata = kern_data + kern_moff;
853
854 mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
855 kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
856 &kern_mtype_id);
857 if (BTF_INFO_KIND(mtype->info) !=
858 BTF_INFO_KIND(kern_mtype->info)) {
859 pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
860 map->name, mname, BTF_INFO_KIND(mtype->info),
861 BTF_INFO_KIND(kern_mtype->info));
862 return -ENOTSUP;
863 }
864
865 if (btf_is_ptr(mtype)) {
866 struct bpf_program *prog;
867
868 prog = st_ops->progs[i];
869 if (!prog)
870 continue;
871
872 kern_mtype = skip_mods_and_typedefs(kern_btf,
873 kern_mtype->type,
874 &kern_mtype_id);
875
876 /* mtype->type must be a func_proto which was
877 * guaranteed in bpf_object__collect_st_ops_relos(),
878 * so only check kern_mtype for func_proto here.
879 */
880 if (!btf_is_func_proto(kern_mtype)) {
881 pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
882 map->name, mname);
883 return -ENOTSUP;
884 }
885
886 prog->attach_btf_id = kern_type_id;
887 prog->expected_attach_type = kern_member_idx;
888
889 st_ops->kern_func_off[i] = kern_data_off + kern_moff;
890
891 pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
892 map->name, mname, prog->name, moff,
893 kern_moff);
894
895 continue;
896 }
897
898 msize = btf__resolve_size(btf, mtype_id);
899 kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
900 if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
901 pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
902 map->name, mname, (ssize_t)msize,
903 (ssize_t)kern_msize);
904 return -ENOTSUP;
905 }
906
907 pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
908 map->name, mname, (unsigned int)msize,
909 moff, kern_moff);
910 memcpy(kern_mdata, mdata, msize);
911 }
912
913 return 0;
914}
915
916static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
917{
918 struct bpf_map *map;
919 size_t i;
920 int err;
921
922 for (i = 0; i < obj->nr_maps; i++) {
923 map = &obj->maps[i];
924
925 if (!bpf_map__is_struct_ops(map))
926 continue;
927
928 err = bpf_map__init_kern_struct_ops(map, obj->btf,
929 obj->btf_vmlinux);
930 if (err)
931 return err;
932 }
933
934 return 0;
935}
936
937static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
938{
939 const struct btf_type *type, *datasec;
940 const struct btf_var_secinfo *vsi;
941 struct bpf_struct_ops *st_ops;
942 const char *tname, *var_name;
943 __s32 type_id, datasec_id;
944 const struct btf *btf;
945 struct bpf_map *map;
946 __u32 i;
947
948 if (obj->efile.st_ops_shndx == -1)
949 return 0;
950
951 btf = obj->btf;
952 datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
953 BTF_KIND_DATASEC);
954 if (datasec_id < 0) {
955 pr_warn("struct_ops init: DATASEC %s not found\n",
956 STRUCT_OPS_SEC);
957 return -EINVAL;
958 }
959
960 datasec = btf__type_by_id(btf, datasec_id);
961 vsi = btf_var_secinfos(datasec);
962 for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
963 type = btf__type_by_id(obj->btf, vsi->type);
964 var_name = btf__name_by_offset(obj->btf, type->name_off);
965
966 type_id = btf__resolve_type(obj->btf, vsi->type);
967 if (type_id < 0) {
968 pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
969 vsi->type, STRUCT_OPS_SEC);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000970 return -EINVAL;
971 }
972
Olivier Deprez157378f2022-04-04 15:47:50 +0200973 type = btf__type_by_id(obj->btf, type_id);
974 tname = btf__name_by_offset(obj->btf, type->name_off);
975 if (!tname[0]) {
976 pr_warn("struct_ops init: anonymous type is not supported\n");
977 return -ENOTSUP;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000978 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200979 if (!btf_is_struct(type)) {
980 pr_warn("struct_ops init: %s is not a struct\n", tname);
981 return -EINVAL;
982 }
983
984 map = bpf_object__add_map(obj);
985 if (IS_ERR(map))
986 return PTR_ERR(map);
987
988 map->sec_idx = obj->efile.st_ops_shndx;
989 map->sec_offset = vsi->offset;
990 map->name = strdup(var_name);
991 if (!map->name)
992 return -ENOMEM;
993
994 map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
995 map->def.key_size = sizeof(int);
996 map->def.value_size = type->size;
997 map->def.max_entries = 1;
998
999 map->st_ops = calloc(1, sizeof(*map->st_ops));
1000 if (!map->st_ops)
1001 return -ENOMEM;
1002 st_ops = map->st_ops;
1003 st_ops->data = malloc(type->size);
1004 st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1005 st_ops->kern_func_off = malloc(btf_vlen(type) *
1006 sizeof(*st_ops->kern_func_off));
1007 if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1008 return -ENOMEM;
1009
1010 if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1011 pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1012 var_name, STRUCT_OPS_SEC);
1013 return -EINVAL;
1014 }
1015
1016 memcpy(st_ops->data,
1017 obj->efile.st_ops_data->d_buf + vsi->offset,
1018 type->size);
1019 st_ops->tname = tname;
1020 st_ops->type = type;
1021 st_ops->type_id = type_id;
1022
1023 pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1024 tname, type_id, var_name, vsi->offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001025 }
1026
1027 return 0;
1028}
1029
1030static struct bpf_object *bpf_object__new(const char *path,
Olivier Deprez157378f2022-04-04 15:47:50 +02001031 const void *obj_buf,
1032 size_t obj_buf_sz,
1033 const char *obj_name)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001034{
1035 struct bpf_object *obj;
David Brazdil0f672f62019-12-10 10:32:29 +00001036 char *end;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001037
1038 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1039 if (!obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001040 pr_warn("alloc memory failed for %s\n", path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001041 return ERR_PTR(-ENOMEM);
1042 }
1043
1044 strcpy(obj->path, path);
Olivier Deprez157378f2022-04-04 15:47:50 +02001045 if (obj_name) {
1046 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
1047 obj->name[sizeof(obj->name) - 1] = 0;
1048 } else {
1049 /* Using basename() GNU version which doesn't modify arg. */
1050 strncpy(obj->name, basename((void *)path),
1051 sizeof(obj->name) - 1);
1052 end = strchr(obj->name, '.');
1053 if (end)
1054 *end = 0;
1055 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001056
David Brazdil0f672f62019-12-10 10:32:29 +00001057 obj->efile.fd = -1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001058 /*
David Brazdil0f672f62019-12-10 10:32:29 +00001059 * Caller of this function should also call
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001060 * bpf_object__elf_finish() after data collection to return
1061 * obj_buf to user. If not, we should duplicate the buffer to
1062 * avoid user freeing them before elf finish.
1063 */
1064 obj->efile.obj_buf = obj_buf;
1065 obj->efile.obj_buf_sz = obj_buf_sz;
1066 obj->efile.maps_shndx = -1;
David Brazdil0f672f62019-12-10 10:32:29 +00001067 obj->efile.btf_maps_shndx = -1;
1068 obj->efile.data_shndx = -1;
1069 obj->efile.rodata_shndx = -1;
1070 obj->efile.bss_shndx = -1;
Olivier Deprez157378f2022-04-04 15:47:50 +02001071 obj->efile.st_ops_shndx = -1;
1072 obj->kconfig_map_idx = -1;
1073 obj->rodata_map_idx = -1;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001074
Olivier Deprez157378f2022-04-04 15:47:50 +02001075 obj->kern_version = get_kernel_version();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001076 obj->loaded = false;
1077
1078 INIT_LIST_HEAD(&obj->list);
1079 list_add(&obj->list, &bpf_objects_list);
1080 return obj;
1081}
1082
1083static void bpf_object__elf_finish(struct bpf_object *obj)
1084{
1085 if (!obj_elf_valid(obj))
1086 return;
1087
1088 if (obj->efile.elf) {
1089 elf_end(obj->efile.elf);
1090 obj->efile.elf = NULL;
1091 }
1092 obj->efile.symbols = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00001093 obj->efile.data = NULL;
1094 obj->efile.rodata = NULL;
1095 obj->efile.bss = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +02001096 obj->efile.st_ops_data = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001097
Olivier Deprez157378f2022-04-04 15:47:50 +02001098 zfree(&obj->efile.reloc_sects);
1099 obj->efile.nr_reloc_sects = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001100 zclose(obj->efile.fd);
1101 obj->efile.obj_buf = NULL;
1102 obj->efile.obj_buf_sz = 0;
1103}
1104
Olivier Deprez157378f2022-04-04 15:47:50 +02001105/* if libelf is old and doesn't support mmap(), fall back to read() */
1106#ifndef ELF_C_READ_MMAP
1107#define ELF_C_READ_MMAP ELF_C_READ
1108#endif
1109
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001110static int bpf_object__elf_init(struct bpf_object *obj)
1111{
1112 int err = 0;
1113 GElf_Ehdr *ep;
1114
1115 if (obj_elf_valid(obj)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001116 pr_warn("elf: init internal error\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001117 return -LIBBPF_ERRNO__LIBELF;
1118 }
1119
1120 if (obj->efile.obj_buf_sz > 0) {
1121 /*
1122 * obj_buf should have been validated by
1123 * bpf_object__open_buffer().
1124 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001125 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001126 obj->efile.obj_buf_sz);
1127 } else {
1128 obj->efile.fd = open(obj->path, O_RDONLY);
1129 if (obj->efile.fd < 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00001130 char errmsg[STRERR_BUFSIZE], *cp;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001131
David Brazdil0f672f62019-12-10 10:32:29 +00001132 err = -errno;
1133 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
Olivier Deprez157378f2022-04-04 15:47:50 +02001134 pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
David Brazdil0f672f62019-12-10 10:32:29 +00001135 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001136 }
1137
Olivier Deprez157378f2022-04-04 15:47:50 +02001138 obj->efile.elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001139 }
1140
1141 if (!obj->efile.elf) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001142 pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001143 err = -LIBBPF_ERRNO__LIBELF;
1144 goto errout;
1145 }
1146
1147 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001148 pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001149 err = -LIBBPF_ERRNO__FORMAT;
1150 goto errout;
1151 }
1152 ep = &obj->efile.ehdr;
1153
Olivier Deprez157378f2022-04-04 15:47:50 +02001154 if (elf_getshdrstrndx(obj->efile.elf, &obj->efile.shstrndx)) {
1155 pr_warn("elf: failed to get section names section index for %s: %s\n",
1156 obj->path, elf_errmsg(-1));
1157 err = -LIBBPF_ERRNO__FORMAT;
1158 goto errout;
1159 }
1160
1161 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1162 if (!elf_rawdata(elf_getscn(obj->efile.elf, obj->efile.shstrndx), NULL)) {
1163 pr_warn("elf: failed to get section names strings from %s: %s\n",
1164 obj->path, elf_errmsg(-1));
1165 err = -LIBBPF_ERRNO__FORMAT;
1166 goto errout;
1167 }
1168
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001169 /* Old LLVM set e_machine to EM_NONE */
David Brazdil0f672f62019-12-10 10:32:29 +00001170 if (ep->e_type != ET_REL ||
1171 (ep->e_machine && ep->e_machine != EM_BPF)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001172 pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001173 err = -LIBBPF_ERRNO__FORMAT;
1174 goto errout;
1175 }
1176
1177 return 0;
1178errout:
1179 bpf_object__elf_finish(obj);
1180 return err;
1181}
1182
David Brazdil0f672f62019-12-10 10:32:29 +00001183static int bpf_object__check_endianness(struct bpf_object *obj)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001184{
David Brazdil0f672f62019-12-10 10:32:29 +00001185#if __BYTE_ORDER == __LITTLE_ENDIAN
1186 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1187 return 0;
1188#elif __BYTE_ORDER == __BIG_ENDIAN
1189 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
1190 return 0;
1191#else
1192# error "Unrecognized __BYTE_ORDER__"
1193#endif
Olivier Deprez157378f2022-04-04 15:47:50 +02001194 pr_warn("elf: endianness mismatch in %s.\n", obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001195 return -LIBBPF_ERRNO__ENDIAN;
1196}
1197
1198static int
David Brazdil0f672f62019-12-10 10:32:29 +00001199bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001200{
David Brazdil0f672f62019-12-10 10:32:29 +00001201 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001202 pr_debug("license of %s is %s\n", obj->path, obj->license);
1203 return 0;
1204}
1205
1206static int
David Brazdil0f672f62019-12-10 10:32:29 +00001207bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001208{
David Brazdil0f672f62019-12-10 10:32:29 +00001209 __u32 kver;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001210
1211 if (size != sizeof(kver)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001212 pr_warn("invalid kver section in %s\n", obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001213 return -LIBBPF_ERRNO__FORMAT;
1214 }
1215 memcpy(&kver, data, sizeof(kver));
1216 obj->kern_version = kver;
David Brazdil0f672f62019-12-10 10:32:29 +00001217 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001218 return 0;
1219}
1220
David Brazdil0f672f62019-12-10 10:32:29 +00001221static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1222{
1223 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1224 type == BPF_MAP_TYPE_HASH_OF_MAPS)
1225 return true;
1226 return false;
1227}
1228
David Brazdil0f672f62019-12-10 10:32:29 +00001229int bpf_object__section_size(const struct bpf_object *obj, const char *name,
1230 __u32 *size)
1231{
1232 int ret = -ENOENT;
David Brazdil0f672f62019-12-10 10:32:29 +00001233
1234 *size = 0;
1235 if (!name) {
1236 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02001237 } else if (!strcmp(name, DATA_SEC)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001238 if (obj->efile.data)
1239 *size = obj->efile.data->d_size;
Olivier Deprez157378f2022-04-04 15:47:50 +02001240 } else if (!strcmp(name, BSS_SEC)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001241 if (obj->efile.bss)
1242 *size = obj->efile.bss->d_size;
Olivier Deprez157378f2022-04-04 15:47:50 +02001243 } else if (!strcmp(name, RODATA_SEC)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001244 if (obj->efile.rodata)
1245 *size = obj->efile.rodata->d_size;
Olivier Deprez157378f2022-04-04 15:47:50 +02001246 } else if (!strcmp(name, STRUCT_OPS_SEC)) {
1247 if (obj->efile.st_ops_data)
1248 *size = obj->efile.st_ops_data->d_size;
David Brazdil0f672f62019-12-10 10:32:29 +00001249 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02001250 Elf_Scn *scn = elf_sec_by_name(obj, name);
1251 Elf_Data *data = elf_sec_data(obj, scn);
1252
1253 if (data) {
1254 ret = 0; /* found it */
1255 *size = data->d_size;
1256 }
David Brazdil0f672f62019-12-10 10:32:29 +00001257 }
1258
1259 return *size ? 0 : ret;
1260}
1261
1262int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
1263 __u32 *off)
1264{
1265 Elf_Data *symbols = obj->efile.symbols;
1266 const char *sname;
1267 size_t si;
1268
1269 if (!name || !off)
1270 return -EINVAL;
1271
1272 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
1273 GElf_Sym sym;
1274
1275 if (!gelf_getsym(symbols, si, &sym))
1276 continue;
1277 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
1278 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
1279 continue;
1280
Olivier Deprez157378f2022-04-04 15:47:50 +02001281 sname = elf_sym_str(obj, sym.st_name);
David Brazdil0f672f62019-12-10 10:32:29 +00001282 if (!sname) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001283 pr_warn("failed to get sym name string for var %s\n",
1284 name);
David Brazdil0f672f62019-12-10 10:32:29 +00001285 return -EIO;
1286 }
1287 if (strcmp(name, sname) == 0) {
1288 *off = sym.st_value;
1289 return 0;
1290 }
1291 }
1292
1293 return -ENOENT;
1294}
1295
1296static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1297{
1298 struct bpf_map *new_maps;
1299 size_t new_cap;
1300 int i;
1301
1302 if (obj->nr_maps < obj->maps_cap)
1303 return &obj->maps[obj->nr_maps++];
1304
1305 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
Olivier Deprez157378f2022-04-04 15:47:50 +02001306 new_maps = libbpf_reallocarray(obj->maps, new_cap, sizeof(*obj->maps));
David Brazdil0f672f62019-12-10 10:32:29 +00001307 if (!new_maps) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001308 pr_warn("alloc maps for object failed\n");
David Brazdil0f672f62019-12-10 10:32:29 +00001309 return ERR_PTR(-ENOMEM);
1310 }
1311
1312 obj->maps_cap = new_cap;
1313 obj->maps = new_maps;
1314
1315 /* zero out new maps */
1316 memset(obj->maps + obj->nr_maps, 0,
1317 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
1318 /*
1319 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
1320 * when failure (zclose won't close negative fd)).
1321 */
1322 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
1323 obj->maps[i].fd = -1;
1324 obj->maps[i].inner_map_fd = -1;
1325 }
1326
1327 return &obj->maps[obj->nr_maps++];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001328}
1329
Olivier Deprez157378f2022-04-04 15:47:50 +02001330static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1331{
1332 long page_sz = sysconf(_SC_PAGE_SIZE);
1333 size_t map_sz;
1334
1335 map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1336 map_sz = roundup(map_sz, page_sz);
1337 return map_sz;
1338}
1339
1340static char *internal_map_name(struct bpf_object *obj,
1341 enum libbpf_map_type type)
1342{
1343 char map_name[BPF_OBJ_NAME_LEN], *p;
1344 const char *sfx = libbpf_type_to_btf_name[type];
1345 int sfx_len = max((size_t)7, strlen(sfx));
1346 int pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1,
1347 strlen(obj->name));
1348
1349 snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1350 sfx_len, libbpf_type_to_btf_name[type]);
1351
1352 /* sanitise map name to characters allowed by kernel */
1353 for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1354 if (!isalnum(*p) && *p != '_' && *p != '.')
1355 *p = '_';
1356
1357 return strdup(map_name);
1358}
1359
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001360static int
David Brazdil0f672f62019-12-10 10:32:29 +00001361bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
Olivier Deprez157378f2022-04-04 15:47:50 +02001362 int sec_idx, void *data, size_t data_sz)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001363{
David Brazdil0f672f62019-12-10 10:32:29 +00001364 struct bpf_map_def *def;
1365 struct bpf_map *map;
Olivier Deprez157378f2022-04-04 15:47:50 +02001366 int err;
David Brazdil0f672f62019-12-10 10:32:29 +00001367
1368 map = bpf_object__add_map(obj);
1369 if (IS_ERR(map))
1370 return PTR_ERR(map);
1371
1372 map->libbpf_type = type;
1373 map->sec_idx = sec_idx;
1374 map->sec_offset = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001375 map->name = internal_map_name(obj, type);
David Brazdil0f672f62019-12-10 10:32:29 +00001376 if (!map->name) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001377 pr_warn("failed to alloc map name\n");
David Brazdil0f672f62019-12-10 10:32:29 +00001378 return -ENOMEM;
1379 }
David Brazdil0f672f62019-12-10 10:32:29 +00001380
1381 def = &map->def;
1382 def->type = BPF_MAP_TYPE_ARRAY;
1383 def->key_size = sizeof(int);
Olivier Deprez157378f2022-04-04 15:47:50 +02001384 def->value_size = data_sz;
David Brazdil0f672f62019-12-10 10:32:29 +00001385 def->max_entries = 1;
Olivier Deprez157378f2022-04-04 15:47:50 +02001386 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1387 ? BPF_F_RDONLY_PROG : 0;
1388 def->map_flags |= BPF_F_MMAPABLE;
1389
1390 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1391 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1392
1393 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1394 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1395 if (map->mmaped == MAP_FAILED) {
1396 err = -errno;
1397 map->mmaped = NULL;
1398 pr_warn("failed to alloc map '%s' content buffer: %d\n",
1399 map->name, err);
1400 zfree(&map->name);
1401 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00001402 }
1403
Olivier Deprez157378f2022-04-04 15:47:50 +02001404 if (data)
1405 memcpy(map->mmaped, data, data_sz);
1406
David Brazdil0f672f62019-12-10 10:32:29 +00001407 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1408 return 0;
1409}
1410
1411static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1412{
1413 int err;
1414
David Brazdil0f672f62019-12-10 10:32:29 +00001415 /*
1416 * Populate obj->maps with libbpf internal maps.
1417 */
1418 if (obj->efile.data_shndx >= 0) {
1419 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1420 obj->efile.data_shndx,
Olivier Deprez157378f2022-04-04 15:47:50 +02001421 obj->efile.data->d_buf,
1422 obj->efile.data->d_size);
David Brazdil0f672f62019-12-10 10:32:29 +00001423 if (err)
1424 return err;
1425 }
1426 if (obj->efile.rodata_shndx >= 0) {
1427 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1428 obj->efile.rodata_shndx,
Olivier Deprez157378f2022-04-04 15:47:50 +02001429 obj->efile.rodata->d_buf,
1430 obj->efile.rodata->d_size);
David Brazdil0f672f62019-12-10 10:32:29 +00001431 if (err)
1432 return err;
Olivier Deprez157378f2022-04-04 15:47:50 +02001433
1434 obj->rodata_map_idx = obj->nr_maps - 1;
David Brazdil0f672f62019-12-10 10:32:29 +00001435 }
1436 if (obj->efile.bss_shndx >= 0) {
1437 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1438 obj->efile.bss_shndx,
Olivier Deprez157378f2022-04-04 15:47:50 +02001439 NULL,
1440 obj->efile.bss->d_size);
David Brazdil0f672f62019-12-10 10:32:29 +00001441 if (err)
1442 return err;
1443 }
1444 return 0;
1445}
1446
Olivier Deprez157378f2022-04-04 15:47:50 +02001447
1448static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1449 const void *name)
1450{
1451 int i;
1452
1453 for (i = 0; i < obj->nr_extern; i++) {
1454 if (strcmp(obj->externs[i].name, name) == 0)
1455 return &obj->externs[i];
1456 }
1457 return NULL;
1458}
1459
1460static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1461 char value)
1462{
1463 switch (ext->kcfg.type) {
1464 case KCFG_BOOL:
1465 if (value == 'm') {
1466 pr_warn("extern (kcfg) %s=%c should be tristate or char\n",
1467 ext->name, value);
1468 return -EINVAL;
1469 }
1470 *(bool *)ext_val = value == 'y' ? true : false;
1471 break;
1472 case KCFG_TRISTATE:
1473 if (value == 'y')
1474 *(enum libbpf_tristate *)ext_val = TRI_YES;
1475 else if (value == 'm')
1476 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1477 else /* value == 'n' */
1478 *(enum libbpf_tristate *)ext_val = TRI_NO;
1479 break;
1480 case KCFG_CHAR:
1481 *(char *)ext_val = value;
1482 break;
1483 case KCFG_UNKNOWN:
1484 case KCFG_INT:
1485 case KCFG_CHAR_ARR:
1486 default:
1487 pr_warn("extern (kcfg) %s=%c should be bool, tristate, or char\n",
1488 ext->name, value);
1489 return -EINVAL;
1490 }
1491 ext->is_set = true;
1492 return 0;
1493}
1494
1495static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1496 const char *value)
1497{
1498 size_t len;
1499
1500 if (ext->kcfg.type != KCFG_CHAR_ARR) {
1501 pr_warn("extern (kcfg) %s=%s should be char array\n", ext->name, value);
1502 return -EINVAL;
1503 }
1504
1505 len = strlen(value);
1506 if (value[len - 1] != '"') {
1507 pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1508 ext->name, value);
1509 return -EINVAL;
1510 }
1511
1512 /* strip quotes */
1513 len -= 2;
1514 if (len >= ext->kcfg.sz) {
1515 pr_warn("extern (kcfg) '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1516 ext->name, value, len, ext->kcfg.sz - 1);
1517 len = ext->kcfg.sz - 1;
1518 }
1519 memcpy(ext_val, value + 1, len);
1520 ext_val[len] = '\0';
1521 ext->is_set = true;
1522 return 0;
1523}
1524
1525static int parse_u64(const char *value, __u64 *res)
1526{
1527 char *value_end;
1528 int err;
1529
1530 errno = 0;
1531 *res = strtoull(value, &value_end, 0);
1532 if (errno) {
1533 err = -errno;
1534 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1535 return err;
1536 }
1537 if (*value_end) {
1538 pr_warn("failed to parse '%s' as integer completely\n", value);
1539 return -EINVAL;
1540 }
1541 return 0;
1542}
1543
1544static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1545{
1546 int bit_sz = ext->kcfg.sz * 8;
1547
1548 if (ext->kcfg.sz == 8)
1549 return true;
1550
1551 /* Validate that value stored in u64 fits in integer of `ext->sz`
1552 * bytes size without any loss of information. If the target integer
1553 * is signed, we rely on the following limits of integer type of
1554 * Y bits and subsequent transformation:
1555 *
1556 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1557 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1558 * 0 <= X + 2^(Y-1) < 2^Y
1559 *
1560 * For unsigned target integer, check that all the (64 - Y) bits are
1561 * zero.
1562 */
1563 if (ext->kcfg.is_signed)
1564 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1565 else
1566 return (v >> bit_sz) == 0;
1567}
1568
1569static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1570 __u64 value)
1571{
1572 if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1573 pr_warn("extern (kcfg) %s=%llu should be integer\n",
1574 ext->name, (unsigned long long)value);
1575 return -EINVAL;
1576 }
1577 if (!is_kcfg_value_in_range(ext, value)) {
1578 pr_warn("extern (kcfg) %s=%llu value doesn't fit in %d bytes\n",
1579 ext->name, (unsigned long long)value, ext->kcfg.sz);
1580 return -ERANGE;
1581 }
1582 switch (ext->kcfg.sz) {
1583 case 1: *(__u8 *)ext_val = value; break;
1584 case 2: *(__u16 *)ext_val = value; break;
1585 case 4: *(__u32 *)ext_val = value; break;
1586 case 8: *(__u64 *)ext_val = value; break;
1587 default:
1588 return -EINVAL;
1589 }
1590 ext->is_set = true;
1591 return 0;
1592}
1593
1594static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1595 char *buf, void *data)
1596{
1597 struct extern_desc *ext;
1598 char *sep, *value;
1599 int len, err = 0;
1600 void *ext_val;
1601 __u64 num;
1602
1603 if (strncmp(buf, "CONFIG_", 7))
1604 return 0;
1605
1606 sep = strchr(buf, '=');
1607 if (!sep) {
1608 pr_warn("failed to parse '%s': no separator\n", buf);
1609 return -EINVAL;
1610 }
1611
1612 /* Trim ending '\n' */
1613 len = strlen(buf);
1614 if (buf[len - 1] == '\n')
1615 buf[len - 1] = '\0';
1616 /* Split on '=' and ensure that a value is present. */
1617 *sep = '\0';
1618 if (!sep[1]) {
1619 *sep = '=';
1620 pr_warn("failed to parse '%s': no value\n", buf);
1621 return -EINVAL;
1622 }
1623
1624 ext = find_extern_by_name(obj, buf);
1625 if (!ext || ext->is_set)
1626 return 0;
1627
1628 ext_val = data + ext->kcfg.data_off;
1629 value = sep + 1;
1630
1631 switch (*value) {
1632 case 'y': case 'n': case 'm':
1633 err = set_kcfg_value_tri(ext, ext_val, *value);
1634 break;
1635 case '"':
1636 err = set_kcfg_value_str(ext, ext_val, value);
1637 break;
1638 default:
1639 /* assume integer */
1640 err = parse_u64(value, &num);
1641 if (err) {
1642 pr_warn("extern (kcfg) %s=%s should be integer\n",
1643 ext->name, value);
1644 return err;
1645 }
1646 err = set_kcfg_value_num(ext, ext_val, num);
1647 break;
1648 }
1649 if (err)
1650 return err;
1651 pr_debug("extern (kcfg) %s=%s\n", ext->name, value);
1652 return 0;
1653}
1654
1655static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1656{
1657 char buf[PATH_MAX];
1658 struct utsname uts;
1659 int len, err = 0;
1660 gzFile file;
1661
1662 uname(&uts);
1663 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1664 if (len < 0)
1665 return -EINVAL;
1666 else if (len >= PATH_MAX)
1667 return -ENAMETOOLONG;
1668
1669 /* gzopen also accepts uncompressed files. */
1670 file = gzopen(buf, "r");
1671 if (!file)
1672 file = gzopen("/proc/config.gz", "r");
1673
1674 if (!file) {
1675 pr_warn("failed to open system Kconfig\n");
1676 return -ENOENT;
1677 }
1678
1679 while (gzgets(file, buf, sizeof(buf))) {
1680 err = bpf_object__process_kconfig_line(obj, buf, data);
1681 if (err) {
1682 pr_warn("error parsing system Kconfig line '%s': %d\n",
1683 buf, err);
1684 goto out;
1685 }
1686 }
1687
1688out:
1689 gzclose(file);
1690 return err;
1691}
1692
1693static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1694 const char *config, void *data)
1695{
1696 char buf[PATH_MAX];
1697 int err = 0;
1698 FILE *file;
1699
1700 file = fmemopen((void *)config, strlen(config), "r");
1701 if (!file) {
1702 err = -errno;
1703 pr_warn("failed to open in-memory Kconfig: %d\n", err);
1704 return err;
1705 }
1706
1707 while (fgets(buf, sizeof(buf), file)) {
1708 err = bpf_object__process_kconfig_line(obj, buf, data);
1709 if (err) {
1710 pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1711 buf, err);
1712 break;
1713 }
1714 }
1715
1716 fclose(file);
1717 return err;
1718}
1719
1720static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1721{
1722 struct extern_desc *last_ext = NULL, *ext;
1723 size_t map_sz;
1724 int i, err;
1725
1726 for (i = 0; i < obj->nr_extern; i++) {
1727 ext = &obj->externs[i];
1728 if (ext->type == EXT_KCFG)
1729 last_ext = ext;
1730 }
1731
1732 if (!last_ext)
1733 return 0;
1734
1735 map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1736 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1737 obj->efile.symbols_shndx,
1738 NULL, map_sz);
1739 if (err)
1740 return err;
1741
1742 obj->kconfig_map_idx = obj->nr_maps - 1;
1743
1744 return 0;
1745}
1746
David Brazdil0f672f62019-12-10 10:32:29 +00001747static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1748{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001749 Elf_Data *symbols = obj->efile.symbols;
David Brazdil0f672f62019-12-10 10:32:29 +00001750 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
1751 Elf_Data *data = NULL;
1752 Elf_Scn *scn;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001753
1754 if (obj->efile.maps_shndx < 0)
David Brazdil0f672f62019-12-10 10:32:29 +00001755 return 0;
1756
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001757 if (!symbols)
1758 return -EINVAL;
1759
Olivier Deprez157378f2022-04-04 15:47:50 +02001760
1761 scn = elf_sec_by_idx(obj, obj->efile.maps_shndx);
1762 data = elf_sec_data(obj, scn);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001763 if (!scn || !data) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001764 pr_warn("elf: failed to get legacy map definitions for %s\n",
1765 obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001766 return -EINVAL;
1767 }
1768
1769 /*
1770 * Count number of maps. Each map has a name.
1771 * Array of maps is not supported: only the first element is
1772 * considered.
1773 *
1774 * TODO: Detect array of map and report error.
1775 */
David Brazdil0f672f62019-12-10 10:32:29 +00001776 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1777 for (i = 0; i < nr_syms; i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001778 GElf_Sym sym;
1779
1780 if (!gelf_getsym(symbols, i, &sym))
1781 continue;
1782 if (sym.st_shndx != obj->efile.maps_shndx)
1783 continue;
1784 nr_maps++;
1785 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001786 /* Assume equally sized map definitions */
Olivier Deprez157378f2022-04-04 15:47:50 +02001787 pr_debug("elf: found %d legacy map definitions (%zd bytes) in %s\n",
1788 nr_maps, data->d_size, obj->path);
David Brazdil0f672f62019-12-10 10:32:29 +00001789
Olivier Deprez157378f2022-04-04 15:47:50 +02001790 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
1791 pr_warn("elf: unable to determine legacy map definition size in %s\n",
1792 obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001793 return -EINVAL;
1794 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001795 map_def_sz = data->d_size / nr_maps;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001796
David Brazdil0f672f62019-12-10 10:32:29 +00001797 /* Fill obj->maps using data in "maps" section. */
1798 for (i = 0; i < nr_syms; i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001799 GElf_Sym sym;
1800 const char *map_name;
1801 struct bpf_map_def *def;
David Brazdil0f672f62019-12-10 10:32:29 +00001802 struct bpf_map *map;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001803
1804 if (!gelf_getsym(symbols, i, &sym))
1805 continue;
1806 if (sym.st_shndx != obj->efile.maps_shndx)
1807 continue;
1808
David Brazdil0f672f62019-12-10 10:32:29 +00001809 map = bpf_object__add_map(obj);
1810 if (IS_ERR(map))
1811 return PTR_ERR(map);
1812
Olivier Deprez157378f2022-04-04 15:47:50 +02001813 map_name = elf_sym_str(obj, sym.st_name);
David Brazdil0f672f62019-12-10 10:32:29 +00001814 if (!map_name) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001815 pr_warn("failed to get map #%d name sym string for obj %s\n",
1816 i, obj->path);
David Brazdil0f672f62019-12-10 10:32:29 +00001817 return -LIBBPF_ERRNO__FORMAT;
1818 }
1819
1820 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1821 map->sec_idx = sym.st_shndx;
1822 map->sec_offset = sym.st_value;
1823 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1824 map_name, map->sec_idx, map->sec_offset);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001825 if (sym.st_value + map_def_sz > data->d_size) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001826 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1827 obj->path, map_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001828 return -EINVAL;
1829 }
1830
David Brazdil0f672f62019-12-10 10:32:29 +00001831 map->name = strdup(map_name);
1832 if (!map->name) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001833 pr_warn("failed to alloc map name\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001834 return -ENOMEM;
1835 }
David Brazdil0f672f62019-12-10 10:32:29 +00001836 pr_debug("map %d is \"%s\"\n", i, map->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001837 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
1838 /*
1839 * If the definition of the map in the object file fits in
1840 * bpf_map_def, copy it. Any extra fields in our version
1841 * of bpf_map_def will default to zero as a result of the
1842 * calloc above.
1843 */
1844 if (map_def_sz <= sizeof(struct bpf_map_def)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001845 memcpy(&map->def, def, map_def_sz);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001846 } else {
1847 /*
1848 * Here the map structure being read is bigger than what
1849 * we expect, truncate if the excess bits are all zero.
1850 * If they are not zero, reject this map as
1851 * incompatible.
1852 */
1853 char *b;
Olivier Deprez157378f2022-04-04 15:47:50 +02001854
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001855 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1856 b < ((char *)def) + map_def_sz; b++) {
1857 if (*b != 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001858 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
1859 obj->path, map_name);
David Brazdil0f672f62019-12-10 10:32:29 +00001860 if (strict)
1861 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001862 }
1863 }
David Brazdil0f672f62019-12-10 10:32:29 +00001864 memcpy(&map->def, def, sizeof(struct bpf_map_def));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001865 }
David Brazdil0f672f62019-12-10 10:32:29 +00001866 }
1867 return 0;
1868}
1869
1870static const struct btf_type *
1871skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
1872{
1873 const struct btf_type *t = btf__type_by_id(btf, id);
1874
1875 if (res_id)
1876 *res_id = id;
1877
1878 while (btf_is_mod(t) || btf_is_typedef(t)) {
1879 if (res_id)
1880 *res_id = t->type;
1881 t = btf__type_by_id(btf, t->type);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001882 }
1883
David Brazdil0f672f62019-12-10 10:32:29 +00001884 return t;
1885}
1886
Olivier Deprez157378f2022-04-04 15:47:50 +02001887static const struct btf_type *
1888resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
1889{
1890 const struct btf_type *t;
1891
1892 t = skip_mods_and_typedefs(btf, id, NULL);
1893 if (!btf_is_ptr(t))
1894 return NULL;
1895
1896 t = skip_mods_and_typedefs(btf, t->type, res_id);
1897
1898 return btf_is_func_proto(t) ? t : NULL;
1899}
1900
1901static const char *btf_kind_str(const struct btf_type *t)
1902{
1903 switch (btf_kind(t)) {
1904 case BTF_KIND_UNKN: return "void";
1905 case BTF_KIND_INT: return "int";
1906 case BTF_KIND_PTR: return "ptr";
1907 case BTF_KIND_ARRAY: return "array";
1908 case BTF_KIND_STRUCT: return "struct";
1909 case BTF_KIND_UNION: return "union";
1910 case BTF_KIND_ENUM: return "enum";
1911 case BTF_KIND_FWD: return "fwd";
1912 case BTF_KIND_TYPEDEF: return "typedef";
1913 case BTF_KIND_VOLATILE: return "volatile";
1914 case BTF_KIND_CONST: return "const";
1915 case BTF_KIND_RESTRICT: return "restrict";
1916 case BTF_KIND_FUNC: return "func";
1917 case BTF_KIND_FUNC_PROTO: return "func_proto";
1918 case BTF_KIND_VAR: return "var";
1919 case BTF_KIND_DATASEC: return "datasec";
1920 default: return "unknown";
1921 }
1922}
1923
David Brazdil0f672f62019-12-10 10:32:29 +00001924/*
1925 * Fetch integer attribute of BTF map definition. Such attributes are
1926 * represented using a pointer to an array, in which dimensionality of array
1927 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1928 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1929 * type definition, while using only sizeof(void *) space in ELF data section.
1930 */
1931static bool get_map_field_int(const char *map_name, const struct btf *btf,
Olivier Deprez157378f2022-04-04 15:47:50 +02001932 const struct btf_member *m, __u32 *res)
1933{
David Brazdil0f672f62019-12-10 10:32:29 +00001934 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
1935 const char *name = btf__name_by_offset(btf, m->name_off);
1936 const struct btf_array *arr_info;
1937 const struct btf_type *arr_t;
1938
1939 if (!btf_is_ptr(t)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001940 pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
1941 map_name, name, btf_kind_str(t));
David Brazdil0f672f62019-12-10 10:32:29 +00001942 return false;
1943 }
1944
1945 arr_t = btf__type_by_id(btf, t->type);
1946 if (!arr_t) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001947 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1948 map_name, name, t->type);
David Brazdil0f672f62019-12-10 10:32:29 +00001949 return false;
1950 }
1951 if (!btf_is_array(arr_t)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001952 pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
1953 map_name, name, btf_kind_str(arr_t));
David Brazdil0f672f62019-12-10 10:32:29 +00001954 return false;
1955 }
1956 arr_info = btf_array(arr_t);
1957 *res = arr_info->nelems;
1958 return true;
1959}
1960
Olivier Deprez157378f2022-04-04 15:47:50 +02001961static int build_map_pin_path(struct bpf_map *map, const char *path)
David Brazdil0f672f62019-12-10 10:32:29 +00001962{
Olivier Deprez157378f2022-04-04 15:47:50 +02001963 char buf[PATH_MAX];
1964 int len;
1965
1966 if (!path)
1967 path = "/sys/fs/bpf";
1968
1969 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1970 if (len < 0)
1971 return -EINVAL;
1972 else if (len >= PATH_MAX)
1973 return -ENAMETOOLONG;
1974
1975 return bpf_map__set_pin_path(map, buf);
1976}
1977
1978
1979static int parse_btf_map_def(struct bpf_object *obj,
1980 struct bpf_map *map,
1981 const struct btf_type *def,
1982 bool strict, bool is_inner,
1983 const char *pin_root_path)
1984{
1985 const struct btf_type *t;
David Brazdil0f672f62019-12-10 10:32:29 +00001986 const struct btf_member *m;
David Brazdil0f672f62019-12-10 10:32:29 +00001987 int vlen, i;
1988
David Brazdil0f672f62019-12-10 10:32:29 +00001989 vlen = btf_vlen(def);
1990 m = btf_members(def);
1991 for (i = 0; i < vlen; i++, m++) {
1992 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1993
1994 if (!name) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001995 pr_warn("map '%s': invalid field #%d.\n", map->name, i);
David Brazdil0f672f62019-12-10 10:32:29 +00001996 return -EINVAL;
1997 }
1998 if (strcmp(name, "type") == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001999 if (!get_map_field_int(map->name, obj->btf, m,
David Brazdil0f672f62019-12-10 10:32:29 +00002000 &map->def.type))
2001 return -EINVAL;
2002 pr_debug("map '%s': found type = %u.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002003 map->name, map->def.type);
David Brazdil0f672f62019-12-10 10:32:29 +00002004 } else if (strcmp(name, "max_entries") == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002005 if (!get_map_field_int(map->name, obj->btf, m,
David Brazdil0f672f62019-12-10 10:32:29 +00002006 &map->def.max_entries))
2007 return -EINVAL;
2008 pr_debug("map '%s': found max_entries = %u.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002009 map->name, map->def.max_entries);
David Brazdil0f672f62019-12-10 10:32:29 +00002010 } else if (strcmp(name, "map_flags") == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002011 if (!get_map_field_int(map->name, obj->btf, m,
David Brazdil0f672f62019-12-10 10:32:29 +00002012 &map->def.map_flags))
2013 return -EINVAL;
2014 pr_debug("map '%s': found map_flags = %u.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002015 map->name, map->def.map_flags);
2016 } else if (strcmp(name, "numa_node") == 0) {
2017 if (!get_map_field_int(map->name, obj->btf, m, &map->numa_node))
2018 return -EINVAL;
2019 pr_debug("map '%s': found numa_node = %u.\n", map->name, map->numa_node);
David Brazdil0f672f62019-12-10 10:32:29 +00002020 } else if (strcmp(name, "key_size") == 0) {
2021 __u32 sz;
2022
Olivier Deprez157378f2022-04-04 15:47:50 +02002023 if (!get_map_field_int(map->name, obj->btf, m, &sz))
David Brazdil0f672f62019-12-10 10:32:29 +00002024 return -EINVAL;
2025 pr_debug("map '%s': found key_size = %u.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002026 map->name, sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002027 if (map->def.key_size && map->def.key_size != sz) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002028 pr_warn("map '%s': conflicting key size %u != %u.\n",
2029 map->name, map->def.key_size, sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002030 return -EINVAL;
2031 }
2032 map->def.key_size = sz;
2033 } else if (strcmp(name, "key") == 0) {
2034 __s64 sz;
2035
2036 t = btf__type_by_id(obj->btf, m->type);
2037 if (!t) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002038 pr_warn("map '%s': key type [%d] not found.\n",
2039 map->name, m->type);
David Brazdil0f672f62019-12-10 10:32:29 +00002040 return -EINVAL;
2041 }
2042 if (!btf_is_ptr(t)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002043 pr_warn("map '%s': key spec is not PTR: %s.\n",
2044 map->name, btf_kind_str(t));
David Brazdil0f672f62019-12-10 10:32:29 +00002045 return -EINVAL;
2046 }
2047 sz = btf__resolve_size(obj->btf, t->type);
2048 if (sz < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002049 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2050 map->name, t->type, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002051 return sz;
2052 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002053 pr_debug("map '%s': found key [%u], sz = %zd.\n",
2054 map->name, t->type, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002055 if (map->def.key_size && map->def.key_size != sz) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002056 pr_warn("map '%s': conflicting key size %u != %zd.\n",
2057 map->name, map->def.key_size, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002058 return -EINVAL;
2059 }
2060 map->def.key_size = sz;
2061 map->btf_key_type_id = t->type;
2062 } else if (strcmp(name, "value_size") == 0) {
2063 __u32 sz;
2064
Olivier Deprez157378f2022-04-04 15:47:50 +02002065 if (!get_map_field_int(map->name, obj->btf, m, &sz))
David Brazdil0f672f62019-12-10 10:32:29 +00002066 return -EINVAL;
2067 pr_debug("map '%s': found value_size = %u.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002068 map->name, sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002069 if (map->def.value_size && map->def.value_size != sz) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002070 pr_warn("map '%s': conflicting value size %u != %u.\n",
2071 map->name, map->def.value_size, sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002072 return -EINVAL;
2073 }
2074 map->def.value_size = sz;
2075 } else if (strcmp(name, "value") == 0) {
2076 __s64 sz;
2077
2078 t = btf__type_by_id(obj->btf, m->type);
2079 if (!t) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002080 pr_warn("map '%s': value type [%d] not found.\n",
2081 map->name, m->type);
David Brazdil0f672f62019-12-10 10:32:29 +00002082 return -EINVAL;
2083 }
2084 if (!btf_is_ptr(t)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002085 pr_warn("map '%s': value spec is not PTR: %s.\n",
2086 map->name, btf_kind_str(t));
David Brazdil0f672f62019-12-10 10:32:29 +00002087 return -EINVAL;
2088 }
2089 sz = btf__resolve_size(obj->btf, t->type);
2090 if (sz < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002091 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2092 map->name, t->type, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002093 return sz;
2094 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002095 pr_debug("map '%s': found value [%u], sz = %zd.\n",
2096 map->name, t->type, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002097 if (map->def.value_size && map->def.value_size != sz) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002098 pr_warn("map '%s': conflicting value size %u != %zd.\n",
2099 map->name, map->def.value_size, (ssize_t)sz);
David Brazdil0f672f62019-12-10 10:32:29 +00002100 return -EINVAL;
2101 }
2102 map->def.value_size = sz;
2103 map->btf_value_type_id = t->type;
Olivier Deprez157378f2022-04-04 15:47:50 +02002104 }
2105 else if (strcmp(name, "values") == 0) {
2106 int err;
2107
2108 if (is_inner) {
2109 pr_warn("map '%s': multi-level inner maps not supported.\n",
2110 map->name);
2111 return -ENOTSUP;
2112 }
2113 if (i != vlen - 1) {
2114 pr_warn("map '%s': '%s' member should be last.\n",
2115 map->name, name);
2116 return -EINVAL;
2117 }
2118 if (!bpf_map_type__is_map_in_map(map->def.type)) {
2119 pr_warn("map '%s': should be map-in-map.\n",
2120 map->name);
2121 return -ENOTSUP;
2122 }
2123 if (map->def.value_size && map->def.value_size != 4) {
2124 pr_warn("map '%s': conflicting value size %u != 4.\n",
2125 map->name, map->def.value_size);
2126 return -EINVAL;
2127 }
2128 map->def.value_size = 4;
2129 t = btf__type_by_id(obj->btf, m->type);
2130 if (!t) {
2131 pr_warn("map '%s': map-in-map inner type [%d] not found.\n",
2132 map->name, m->type);
2133 return -EINVAL;
2134 }
2135 if (!btf_is_array(t) || btf_array(t)->nelems) {
2136 pr_warn("map '%s': map-in-map inner spec is not a zero-sized array.\n",
2137 map->name);
2138 return -EINVAL;
2139 }
2140 t = skip_mods_and_typedefs(obj->btf, btf_array(t)->type,
2141 NULL);
2142 if (!btf_is_ptr(t)) {
2143 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2144 map->name, btf_kind_str(t));
2145 return -EINVAL;
2146 }
2147 t = skip_mods_and_typedefs(obj->btf, t->type, NULL);
2148 if (!btf_is_struct(t)) {
2149 pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2150 map->name, btf_kind_str(t));
2151 return -EINVAL;
2152 }
2153
2154 map->inner_map = calloc(1, sizeof(*map->inner_map));
2155 if (!map->inner_map)
2156 return -ENOMEM;
2157 map->inner_map->sec_idx = obj->efile.btf_maps_shndx;
2158 map->inner_map->name = malloc(strlen(map->name) +
2159 sizeof(".inner") + 1);
2160 if (!map->inner_map->name)
2161 return -ENOMEM;
2162 sprintf(map->inner_map->name, "%s.inner", map->name);
2163
2164 err = parse_btf_map_def(obj, map->inner_map, t, strict,
2165 true /* is_inner */, NULL);
2166 if (err)
2167 return err;
2168 } else if (strcmp(name, "pinning") == 0) {
2169 __u32 val;
2170 int err;
2171
2172 if (is_inner) {
2173 pr_debug("map '%s': inner def can't be pinned.\n",
2174 map->name);
2175 return -EINVAL;
2176 }
2177 if (!get_map_field_int(map->name, obj->btf, m, &val))
2178 return -EINVAL;
2179 pr_debug("map '%s': found pinning = %u.\n",
2180 map->name, val);
2181
2182 if (val != LIBBPF_PIN_NONE &&
2183 val != LIBBPF_PIN_BY_NAME) {
2184 pr_warn("map '%s': invalid pinning value %u.\n",
2185 map->name, val);
2186 return -EINVAL;
2187 }
2188 if (val == LIBBPF_PIN_BY_NAME) {
2189 err = build_map_pin_path(map, pin_root_path);
2190 if (err) {
2191 pr_warn("map '%s': couldn't build pin path.\n",
2192 map->name);
2193 return err;
2194 }
2195 }
David Brazdil0f672f62019-12-10 10:32:29 +00002196 } else {
2197 if (strict) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002198 pr_warn("map '%s': unknown field '%s'.\n",
2199 map->name, name);
David Brazdil0f672f62019-12-10 10:32:29 +00002200 return -ENOTSUP;
2201 }
2202 pr_debug("map '%s': ignoring unknown field '%s'.\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02002203 map->name, name);
David Brazdil0f672f62019-12-10 10:32:29 +00002204 }
2205 }
2206
2207 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002208 pr_warn("map '%s': map type isn't specified.\n", map->name);
David Brazdil0f672f62019-12-10 10:32:29 +00002209 return -EINVAL;
2210 }
2211
2212 return 0;
2213}
2214
Olivier Deprez157378f2022-04-04 15:47:50 +02002215static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2216 const struct btf_type *sec,
2217 int var_idx, int sec_idx,
2218 const Elf_Data *data, bool strict,
2219 const char *pin_root_path)
2220{
2221 const struct btf_type *var, *def;
2222 const struct btf_var_secinfo *vi;
2223 const struct btf_var *var_extra;
2224 const char *map_name;
2225 struct bpf_map *map;
2226
2227 vi = btf_var_secinfos(sec) + var_idx;
2228 var = btf__type_by_id(obj->btf, vi->type);
2229 var_extra = btf_var(var);
2230 map_name = btf__name_by_offset(obj->btf, var->name_off);
2231
2232 if (map_name == NULL || map_name[0] == '\0') {
2233 pr_warn("map #%d: empty name.\n", var_idx);
2234 return -EINVAL;
2235 }
2236 if ((__u64)vi->offset + vi->size > data->d_size) {
2237 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2238 return -EINVAL;
2239 }
2240 if (!btf_is_var(var)) {
2241 pr_warn("map '%s': unexpected var kind %s.\n",
2242 map_name, btf_kind_str(var));
2243 return -EINVAL;
2244 }
2245 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2246 var_extra->linkage != BTF_VAR_STATIC) {
2247 pr_warn("map '%s': unsupported var linkage %u.\n",
2248 map_name, var_extra->linkage);
2249 return -EOPNOTSUPP;
2250 }
2251
2252 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2253 if (!btf_is_struct(def)) {
2254 pr_warn("map '%s': unexpected def kind %s.\n",
2255 map_name, btf_kind_str(var));
2256 return -EINVAL;
2257 }
2258 if (def->size > vi->size) {
2259 pr_warn("map '%s': invalid def size.\n", map_name);
2260 return -EINVAL;
2261 }
2262
2263 map = bpf_object__add_map(obj);
2264 if (IS_ERR(map))
2265 return PTR_ERR(map);
2266 map->name = strdup(map_name);
2267 if (!map->name) {
2268 pr_warn("map '%s': failed to alloc map name.\n", map_name);
2269 return -ENOMEM;
2270 }
2271 map->libbpf_type = LIBBPF_MAP_UNSPEC;
2272 map->def.type = BPF_MAP_TYPE_UNSPEC;
2273 map->sec_idx = sec_idx;
2274 map->sec_offset = vi->offset;
2275 map->btf_var_idx = var_idx;
2276 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2277 map_name, map->sec_idx, map->sec_offset);
2278
2279 return parse_btf_map_def(obj, map, def, strict, false, pin_root_path);
2280}
2281
2282static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2283 const char *pin_root_path)
David Brazdil0f672f62019-12-10 10:32:29 +00002284{
2285 const struct btf_type *sec = NULL;
2286 int nr_types, i, vlen, err;
2287 const struct btf_type *t;
2288 const char *name;
2289 Elf_Data *data;
2290 Elf_Scn *scn;
2291
2292 if (obj->efile.btf_maps_shndx < 0)
2293 return 0;
2294
Olivier Deprez157378f2022-04-04 15:47:50 +02002295 scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2296 data = elf_sec_data(obj, scn);
David Brazdil0f672f62019-12-10 10:32:29 +00002297 if (!scn || !data) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002298 pr_warn("elf: failed to get %s map definitions for %s\n",
2299 MAPS_ELF_SEC, obj->path);
David Brazdil0f672f62019-12-10 10:32:29 +00002300 return -EINVAL;
2301 }
2302
2303 nr_types = btf__get_nr_types(obj->btf);
2304 for (i = 1; i <= nr_types; i++) {
2305 t = btf__type_by_id(obj->btf, i);
2306 if (!btf_is_datasec(t))
2307 continue;
2308 name = btf__name_by_offset(obj->btf, t->name_off);
2309 if (strcmp(name, MAPS_ELF_SEC) == 0) {
2310 sec = t;
Olivier Deprez157378f2022-04-04 15:47:50 +02002311 obj->efile.btf_maps_sec_btf_id = i;
David Brazdil0f672f62019-12-10 10:32:29 +00002312 break;
2313 }
2314 }
2315
2316 if (!sec) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002317 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
David Brazdil0f672f62019-12-10 10:32:29 +00002318 return -ENOENT;
2319 }
2320
2321 vlen = btf_vlen(sec);
2322 for (i = 0; i < vlen; i++) {
2323 err = bpf_object__init_user_btf_map(obj, sec, i,
2324 obj->efile.btf_maps_shndx,
Olivier Deprez157378f2022-04-04 15:47:50 +02002325 data, strict,
2326 pin_root_path);
David Brazdil0f672f62019-12-10 10:32:29 +00002327 if (err)
2328 return err;
2329 }
2330
2331 return 0;
2332}
2333
Olivier Deprez157378f2022-04-04 15:47:50 +02002334static int bpf_object__init_maps(struct bpf_object *obj,
2335 const struct bpf_object_open_opts *opts)
David Brazdil0f672f62019-12-10 10:32:29 +00002336{
Olivier Deprez157378f2022-04-04 15:47:50 +02002337 const char *pin_root_path;
2338 bool strict;
David Brazdil0f672f62019-12-10 10:32:29 +00002339 int err;
2340
Olivier Deprez157378f2022-04-04 15:47:50 +02002341 strict = !OPTS_GET(opts, relaxed_maps, false);
2342 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2343
David Brazdil0f672f62019-12-10 10:32:29 +00002344 err = bpf_object__init_user_maps(obj, strict);
Olivier Deprez157378f2022-04-04 15:47:50 +02002345 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2346 err = err ?: bpf_object__init_global_data_maps(obj);
2347 err = err ?: bpf_object__init_kconfig_map(obj);
2348 err = err ?: bpf_object__init_struct_ops_maps(obj);
David Brazdil0f672f62019-12-10 10:32:29 +00002349 if (err)
2350 return err;
2351
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002352 return 0;
2353}
2354
2355static bool section_have_execinstr(struct bpf_object *obj, int idx)
2356{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002357 GElf_Shdr sh;
2358
Olivier Deprez157378f2022-04-04 15:47:50 +02002359 if (elf_sec_hdr(obj, elf_sec_by_idx(obj, idx), &sh))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002360 return false;
2361
Olivier Deprez157378f2022-04-04 15:47:50 +02002362 return sh.sh_flags & SHF_EXECINSTR;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002363}
2364
Olivier Deprez157378f2022-04-04 15:47:50 +02002365static bool btf_needs_sanitization(struct bpf_object *obj)
David Brazdil0f672f62019-12-10 10:32:29 +00002366{
Olivier Deprez157378f2022-04-04 15:47:50 +02002367 bool has_func_global = kernel_supports(FEAT_BTF_GLOBAL_FUNC);
2368 bool has_datasec = kernel_supports(FEAT_BTF_DATASEC);
2369 bool has_func = kernel_supports(FEAT_BTF_FUNC);
2370
2371 return !has_func || !has_datasec || !has_func_global;
2372}
2373
2374static void bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2375{
2376 bool has_func_global = kernel_supports(FEAT_BTF_GLOBAL_FUNC);
2377 bool has_datasec = kernel_supports(FEAT_BTF_DATASEC);
2378 bool has_func = kernel_supports(FEAT_BTF_FUNC);
David Brazdil0f672f62019-12-10 10:32:29 +00002379 struct btf_type *t;
2380 int i, j, vlen;
2381
David Brazdil0f672f62019-12-10 10:32:29 +00002382 for (i = 1; i <= btf__get_nr_types(btf); i++) {
2383 t = (struct btf_type *)btf__type_by_id(btf, i);
2384
2385 if (!has_datasec && btf_is_var(t)) {
2386 /* replace VAR with INT */
2387 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2388 /*
2389 * using size = 1 is the safest choice, 4 will be too
2390 * big and cause kernel BTF validation failure if
2391 * original variable took less than 4 bytes
2392 */
2393 t->size = 1;
2394 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2395 } else if (!has_datasec && btf_is_datasec(t)) {
2396 /* replace DATASEC with STRUCT */
2397 const struct btf_var_secinfo *v = btf_var_secinfos(t);
2398 struct btf_member *m = btf_members(t);
2399 struct btf_type *vt;
2400 char *name;
2401
2402 name = (char *)btf__name_by_offset(btf, t->name_off);
2403 while (*name) {
2404 if (*name == '.')
2405 *name = '_';
2406 name++;
2407 }
2408
2409 vlen = btf_vlen(t);
2410 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2411 for (j = 0; j < vlen; j++, v++, m++) {
2412 /* order of field assignments is important */
2413 m->offset = v->offset * 8;
2414 m->type = v->type;
2415 /* preserve variable name as member name */
2416 vt = (void *)btf__type_by_id(btf, v->type);
2417 m->name_off = vt->name_off;
2418 }
2419 } else if (!has_func && btf_is_func_proto(t)) {
2420 /* replace FUNC_PROTO with ENUM */
2421 vlen = btf_vlen(t);
2422 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2423 t->size = sizeof(__u32); /* kernel enforced */
2424 } else if (!has_func && btf_is_func(t)) {
2425 /* replace FUNC with TYPEDEF */
2426 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
Olivier Deprez157378f2022-04-04 15:47:50 +02002427 } else if (!has_func_global && btf_is_func(t)) {
2428 /* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2429 t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00002430 }
2431 }
2432}
2433
Olivier Deprez157378f2022-04-04 15:47:50 +02002434static bool libbpf_needs_btf(const struct bpf_object *obj)
David Brazdil0f672f62019-12-10 10:32:29 +00002435{
Olivier Deprez157378f2022-04-04 15:47:50 +02002436 return obj->efile.btf_maps_shndx >= 0 ||
2437 obj->efile.st_ops_shndx >= 0 ||
2438 obj->nr_extern > 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002439}
2440
Olivier Deprez157378f2022-04-04 15:47:50 +02002441static bool kernel_needs_btf(const struct bpf_object *obj)
David Brazdil0f672f62019-12-10 10:32:29 +00002442{
Olivier Deprez157378f2022-04-04 15:47:50 +02002443 return obj->efile.st_ops_shndx >= 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002444}
2445
2446static int bpf_object__init_btf(struct bpf_object *obj,
2447 Elf_Data *btf_data,
2448 Elf_Data *btf_ext_data)
2449{
Olivier Deprez157378f2022-04-04 15:47:50 +02002450 int err = -ENOENT;
David Brazdil0f672f62019-12-10 10:32:29 +00002451
2452 if (btf_data) {
2453 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2454 if (IS_ERR(obj->btf)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002455 err = PTR_ERR(obj->btf);
2456 obj->btf = NULL;
2457 pr_warn("Error loading ELF section %s: %d.\n",
2458 BTF_ELF_SEC, err);
David Brazdil0f672f62019-12-10 10:32:29 +00002459 goto out;
2460 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002461 /* enforce 8-byte pointers for BPF-targeted BTFs */
2462 btf__set_pointer_size(obj->btf, 8);
2463 err = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002464 }
2465 if (btf_ext_data) {
2466 if (!obj->btf) {
2467 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2468 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2469 goto out;
2470 }
2471 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
2472 btf_ext_data->d_size);
2473 if (IS_ERR(obj->btf_ext)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002474 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
2475 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
David Brazdil0f672f62019-12-10 10:32:29 +00002476 obj->btf_ext = NULL;
2477 goto out;
2478 }
2479 }
2480out:
Olivier Deprez157378f2022-04-04 15:47:50 +02002481 if (err && libbpf_needs_btf(obj)) {
2482 pr_warn("BTF is required, but is missing or corrupted.\n");
2483 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00002484 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002485 return 0;
2486}
2487
2488static int bpf_object__finalize_btf(struct bpf_object *obj)
2489{
2490 int err;
2491
2492 if (!obj->btf)
2493 return 0;
2494
2495 err = btf__finalize_data(obj, obj->btf);
2496 if (err) {
2497 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2498 return err;
2499 }
2500
2501 return 0;
2502}
2503
2504static inline bool libbpf_prog_needs_vmlinux_btf(struct bpf_program *prog)
2505{
2506 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2507 prog->type == BPF_PROG_TYPE_LSM)
2508 return true;
2509
2510 /* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2511 * also need vmlinux BTF
2512 */
2513 if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2514 return true;
2515
2516 return false;
2517}
2518
2519static int bpf_object__load_vmlinux_btf(struct bpf_object *obj)
2520{
2521 bool need_vmlinux_btf = false;
2522 struct bpf_program *prog;
2523 int i, err;
2524
2525 /* CO-RE relocations need kernel BTF */
2526 if (obj->btf_ext && obj->btf_ext->core_relo_info.len)
2527 need_vmlinux_btf = true;
2528
2529 /* Support for typed ksyms needs kernel BTF */
2530 for (i = 0; i < obj->nr_extern; i++) {
2531 const struct extern_desc *ext;
2532
2533 ext = &obj->externs[i];
2534 if (ext->type == EXT_KSYM && ext->ksym.type_id) {
2535 need_vmlinux_btf = true;
2536 break;
2537 }
2538 }
2539
2540 bpf_object__for_each_program(prog, obj) {
2541 if (!prog->load)
2542 continue;
2543 if (libbpf_prog_needs_vmlinux_btf(prog)) {
2544 need_vmlinux_btf = true;
2545 break;
2546 }
2547 }
2548
2549 if (!need_vmlinux_btf)
2550 return 0;
2551
2552 obj->btf_vmlinux = libbpf_find_kernel_btf();
2553 if (IS_ERR(obj->btf_vmlinux)) {
2554 err = PTR_ERR(obj->btf_vmlinux);
2555 pr_warn("Error loading vmlinux BTF: %d\n", err);
2556 obj->btf_vmlinux = NULL;
2557 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00002558 }
2559 return 0;
2560}
2561
2562static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2563{
Olivier Deprez157378f2022-04-04 15:47:50 +02002564 struct btf *kern_btf = obj->btf;
2565 bool btf_mandatory, sanitize;
David Brazdil0f672f62019-12-10 10:32:29 +00002566 int err = 0;
2567
2568 if (!obj->btf)
2569 return 0;
2570
Olivier Deprez157378f2022-04-04 15:47:50 +02002571 if (!kernel_supports(FEAT_BTF)) {
2572 if (kernel_needs_btf(obj)) {
2573 err = -EOPNOTSUPP;
2574 goto report;
David Brazdil0f672f62019-12-10 10:32:29 +00002575 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002576 pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
2577 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002578 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002579
2580 sanitize = btf_needs_sanitization(obj);
2581 if (sanitize) {
2582 const void *raw_data;
2583 __u32 sz;
2584
2585 /* clone BTF to sanitize a copy and leave the original intact */
2586 raw_data = btf__get_raw_data(obj->btf, &sz);
2587 kern_btf = btf__new(raw_data, sz);
2588 if (IS_ERR(kern_btf))
2589 return PTR_ERR(kern_btf);
2590
2591 /* enforce 8-byte pointers for BPF-targeted BTFs */
2592 btf__set_pointer_size(obj->btf, 8);
2593 bpf_object__sanitize_btf(obj, kern_btf);
2594 }
2595
2596 err = btf__load(kern_btf);
2597 if (sanitize) {
2598 if (!err) {
2599 /* move fd to libbpf's BTF */
2600 btf__set_fd(obj->btf, btf__fd(kern_btf));
2601 btf__set_fd(kern_btf, -1);
2602 }
2603 btf__free(kern_btf);
2604 }
2605report:
2606 if (err) {
2607 btf_mandatory = kernel_needs_btf(obj);
2608 pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
2609 btf_mandatory ? "BTF is mandatory, can't proceed."
2610 : "BTF is optional, ignoring.");
2611 if (!btf_mandatory)
2612 err = 0;
2613 }
2614 return err;
2615}
2616
2617static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
2618{
2619 const char *name;
2620
2621 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
2622 if (!name) {
2623 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2624 off, obj->path, elf_errmsg(-1));
2625 return NULL;
2626 }
2627
2628 return name;
2629}
2630
2631static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
2632{
2633 const char *name;
2634
2635 name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
2636 if (!name) {
2637 pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
2638 off, obj->path, elf_errmsg(-1));
2639 return NULL;
2640 }
2641
2642 return name;
2643}
2644
2645static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
2646{
2647 Elf_Scn *scn;
2648
2649 scn = elf_getscn(obj->efile.elf, idx);
2650 if (!scn) {
2651 pr_warn("elf: failed to get section(%zu) from %s: %s\n",
2652 idx, obj->path, elf_errmsg(-1));
2653 return NULL;
2654 }
2655 return scn;
2656}
2657
2658static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
2659{
2660 Elf_Scn *scn = NULL;
2661 Elf *elf = obj->efile.elf;
2662 const char *sec_name;
2663
2664 while ((scn = elf_nextscn(elf, scn)) != NULL) {
2665 sec_name = elf_sec_name(obj, scn);
2666 if (!sec_name)
2667 return NULL;
2668
2669 if (strcmp(sec_name, name) != 0)
2670 continue;
2671
2672 return scn;
2673 }
2674 return NULL;
2675}
2676
2677static int elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn, GElf_Shdr *hdr)
2678{
2679 if (!scn)
2680 return -EINVAL;
2681
2682 if (gelf_getshdr(scn, hdr) != hdr) {
2683 pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
2684 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2685 return -EINVAL;
2686 }
2687
David Brazdil0f672f62019-12-10 10:32:29 +00002688 return 0;
2689}
2690
Olivier Deprez157378f2022-04-04 15:47:50 +02002691static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002692{
Olivier Deprez157378f2022-04-04 15:47:50 +02002693 const char *name;
2694 GElf_Shdr sh;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002695
Olivier Deprez157378f2022-04-04 15:47:50 +02002696 if (!scn)
2697 return NULL;
2698
2699 if (elf_sec_hdr(obj, scn, &sh))
2700 return NULL;
2701
2702 name = elf_sec_str(obj, sh.sh_name);
2703 if (!name) {
2704 pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
2705 elf_ndxscn(scn), obj->path, elf_errmsg(-1));
2706 return NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002707 }
2708
Olivier Deprez157378f2022-04-04 15:47:50 +02002709 return name;
2710}
2711
2712static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
2713{
2714 Elf_Data *data;
2715
2716 if (!scn)
2717 return NULL;
2718
2719 data = elf_getdata(scn, 0);
2720 if (!data) {
2721 pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
2722 elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
2723 obj->path, elf_errmsg(-1));
2724 return NULL;
2725 }
2726
2727 return data;
2728}
2729
2730static int elf_sym_by_sec_off(const struct bpf_object *obj, size_t sec_idx,
2731 size_t off, __u32 sym_type, GElf_Sym *sym)
2732{
2733 Elf_Data *symbols = obj->efile.symbols;
2734 size_t n = symbols->d_size / sizeof(GElf_Sym);
2735 int i;
2736
2737 for (i = 0; i < n; i++) {
2738 if (!gelf_getsym(symbols, i, sym))
2739 continue;
2740 if (sym->st_shndx != sec_idx || sym->st_value != off)
2741 continue;
2742 if (GELF_ST_TYPE(sym->st_info) != sym_type)
2743 continue;
2744 return 0;
2745 }
2746
2747 return -ENOENT;
2748}
2749
2750static bool is_sec_name_dwarf(const char *name)
2751{
2752 /* approximation, but the actual list is too long */
2753 return strncmp(name, ".debug_", sizeof(".debug_") - 1) == 0;
2754}
2755
2756static bool ignore_elf_section(GElf_Shdr *hdr, const char *name)
2757{
2758 /* no special handling of .strtab */
2759 if (hdr->sh_type == SHT_STRTAB)
2760 return true;
2761
2762 /* ignore .llvm_addrsig section as well */
2763 if (hdr->sh_type == 0x6FFF4C03 /* SHT_LLVM_ADDRSIG */)
2764 return true;
2765
2766 /* no subprograms will lead to an empty .text section, ignore it */
2767 if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
2768 strcmp(name, ".text") == 0)
2769 return true;
2770
2771 /* DWARF sections */
2772 if (is_sec_name_dwarf(name))
2773 return true;
2774
2775 if (strncmp(name, ".rel", sizeof(".rel") - 1) == 0) {
2776 name += sizeof(".rel") - 1;
2777 /* DWARF section relocations */
2778 if (is_sec_name_dwarf(name))
2779 return true;
2780
2781 /* .BTF and .BTF.ext don't need relocations */
2782 if (strcmp(name, BTF_ELF_SEC) == 0 ||
2783 strcmp(name, BTF_EXT_ELF_SEC) == 0)
2784 return true;
2785 }
2786
2787 return false;
2788}
2789
2790static int cmp_progs(const void *_a, const void *_b)
2791{
2792 const struct bpf_program *a = _a;
2793 const struct bpf_program *b = _b;
2794
2795 if (a->sec_idx != b->sec_idx)
2796 return a->sec_idx < b->sec_idx ? -1 : 1;
2797
2798 /* sec_insn_off can't be the same within the section */
2799 return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
2800}
2801
2802static int bpf_object__elf_collect(struct bpf_object *obj)
2803{
2804 Elf *elf = obj->efile.elf;
2805 Elf_Data *btf_ext_data = NULL;
2806 Elf_Data *btf_data = NULL;
2807 int idx = 0, err = 0;
2808 const char *name;
2809 Elf_Data *data;
2810 Elf_Scn *scn;
2811 GElf_Shdr sh;
2812
2813 /* a bunch of ELF parsing functionality depends on processing symbols,
2814 * so do the first pass and find the symbol table
2815 */
2816 scn = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002817 while ((scn = elf_nextscn(elf, scn)) != NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002818 if (elf_sec_hdr(obj, scn, &sh))
2819 return -LIBBPF_ERRNO__FORMAT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002820
Olivier Deprez157378f2022-04-04 15:47:50 +02002821 if (sh.sh_type == SHT_SYMTAB) {
2822 if (obj->efile.symbols) {
2823 pr_warn("elf: multiple symbol tables in %s\n", obj->path);
2824 return -LIBBPF_ERRNO__FORMAT;
2825 }
2826
2827 data = elf_sec_data(obj, scn);
2828 if (!data)
2829 return -LIBBPF_ERRNO__FORMAT;
2830
2831 obj->efile.symbols = data;
2832 obj->efile.symbols_shndx = elf_ndxscn(scn);
2833 obj->efile.strtabidx = sh.sh_link;
2834 }
2835 }
2836
2837 scn = NULL;
2838 while ((scn = elf_nextscn(elf, scn)) != NULL) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002839 idx++;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002840
Olivier Deprez157378f2022-04-04 15:47:50 +02002841 if (elf_sec_hdr(obj, scn, &sh))
David Brazdil0f672f62019-12-10 10:32:29 +00002842 return -LIBBPF_ERRNO__FORMAT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002843
Olivier Deprez157378f2022-04-04 15:47:50 +02002844 name = elf_sec_str(obj, sh.sh_name);
2845 if (!name)
David Brazdil0f672f62019-12-10 10:32:29 +00002846 return -LIBBPF_ERRNO__FORMAT;
Olivier Deprez157378f2022-04-04 15:47:50 +02002847
2848 if (ignore_elf_section(&sh, name))
2849 continue;
2850
2851 data = elf_sec_data(obj, scn);
2852 if (!data)
2853 return -LIBBPF_ERRNO__FORMAT;
2854
2855 pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002856 idx, name, (unsigned long)data->d_size,
2857 (int)sh.sh_link, (unsigned long)sh.sh_flags,
2858 (int)sh.sh_type);
2859
David Brazdil0f672f62019-12-10 10:32:29 +00002860 if (strcmp(name, "license") == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002861 err = bpf_object__init_license(obj, data->d_buf, data->d_size);
David Brazdil0f672f62019-12-10 10:32:29 +00002862 if (err)
2863 return err;
2864 } else if (strcmp(name, "version") == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002865 err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
David Brazdil0f672f62019-12-10 10:32:29 +00002866 if (err)
2867 return err;
2868 } else if (strcmp(name, "maps") == 0) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002869 obj->efile.maps_shndx = idx;
David Brazdil0f672f62019-12-10 10:32:29 +00002870 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2871 obj->efile.btf_maps_shndx = idx;
2872 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2873 btf_data = data;
2874 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
2875 btf_ext_data = data;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002876 } else if (sh.sh_type == SHT_SYMTAB) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002877 /* already processed during the first pass above */
David Brazdil0f672f62019-12-10 10:32:29 +00002878 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2879 if (sh.sh_flags & SHF_EXECINSTR) {
2880 if (strcmp(name, ".text") == 0)
2881 obj->efile.text_shndx = idx;
Olivier Deprez157378f2022-04-04 15:47:50 +02002882 err = bpf_object__add_programs(obj, data, name, idx);
2883 if (err)
David Brazdil0f672f62019-12-10 10:32:29 +00002884 return err;
Olivier Deprez157378f2022-04-04 15:47:50 +02002885 } else if (strcmp(name, DATA_SEC) == 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00002886 obj->efile.data = data;
2887 obj->efile.data_shndx = idx;
Olivier Deprez157378f2022-04-04 15:47:50 +02002888 } else if (strcmp(name, RODATA_SEC) == 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00002889 obj->efile.rodata = data;
2890 obj->efile.rodata_shndx = idx;
Olivier Deprez157378f2022-04-04 15:47:50 +02002891 } else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
2892 obj->efile.st_ops_data = data;
2893 obj->efile.st_ops_shndx = idx;
David Brazdil0f672f62019-12-10 10:32:29 +00002894 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02002895 pr_info("elf: skipping unrecognized data section(%d) %s\n",
2896 idx, name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002897 }
2898 } else if (sh.sh_type == SHT_REL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002899 int nr_sects = obj->efile.nr_reloc_sects;
2900 void *sects = obj->efile.reloc_sects;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002901 int sec = sh.sh_info; /* points to other section */
2902
2903 /* Only do relo for section with exec instructions */
Olivier Deprez157378f2022-04-04 15:47:50 +02002904 if (!section_have_execinstr(obj, sec) &&
2905 strcmp(name, ".rel" STRUCT_OPS_SEC) &&
2906 strcmp(name, ".rel" MAPS_ELF_SEC)) {
2907 pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
2908 idx, name, sec,
2909 elf_sec_name(obj, elf_sec_by_idx(obj, sec)) ?: "<?>");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002910 continue;
2911 }
2912
Olivier Deprez157378f2022-04-04 15:47:50 +02002913 sects = libbpf_reallocarray(sects, nr_sects + 1,
2914 sizeof(*obj->efile.reloc_sects));
2915 if (!sects)
David Brazdil0f672f62019-12-10 10:32:29 +00002916 return -ENOMEM;
David Brazdil0f672f62019-12-10 10:32:29 +00002917
Olivier Deprez157378f2022-04-04 15:47:50 +02002918 obj->efile.reloc_sects = sects;
2919 obj->efile.nr_reloc_sects++;
David Brazdil0f672f62019-12-10 10:32:29 +00002920
Olivier Deprez157378f2022-04-04 15:47:50 +02002921 obj->efile.reloc_sects[nr_sects].shdr = sh;
2922 obj->efile.reloc_sects[nr_sects].data = data;
2923 } else if (sh.sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
David Brazdil0f672f62019-12-10 10:32:29 +00002924 obj->efile.bss = data;
2925 obj->efile.bss_shndx = idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002926 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02002927 pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
2928 (size_t)sh.sh_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002929 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002930 }
2931
Olivier Deprez157378f2022-04-04 15:47:50 +02002932 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
2933 pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
David Brazdil0f672f62019-12-10 10:32:29 +00002934 return -LIBBPF_ERRNO__FORMAT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002935 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002936
2937 /* sort BPF programs by section name and in-section instruction offset
2938 * for faster search */
2939 qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
2940
2941 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002942}
2943
Olivier Deprez157378f2022-04-04 15:47:50 +02002944static bool sym_is_extern(const GElf_Sym *sym)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002945{
Olivier Deprez157378f2022-04-04 15:47:50 +02002946 int bind = GELF_ST_BIND(sym->st_info);
2947 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2948 return sym->st_shndx == SHN_UNDEF &&
2949 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2950 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2951}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002952
Olivier Deprez157378f2022-04-04 15:47:50 +02002953static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2954{
2955 const struct btf_type *t;
2956 const char *var_name;
2957 int i, n;
2958
2959 if (!btf)
2960 return -ESRCH;
2961
2962 n = btf__get_nr_types(btf);
2963 for (i = 1; i <= n; i++) {
2964 t = btf__type_by_id(btf, i);
2965
2966 if (!btf_is_var(t))
2967 continue;
2968
2969 var_name = btf__name_by_offset(btf, t->name_off);
2970 if (strcmp(var_name, ext_name))
2971 continue;
2972
2973 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2974 return -EINVAL;
2975
2976 return i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002977 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002978
2979 return -ENOENT;
2980}
2981
2982static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
2983 const struct btf_var_secinfo *vs;
2984 const struct btf_type *t;
2985 int i, j, n;
2986
2987 if (!btf)
2988 return -ESRCH;
2989
2990 n = btf__get_nr_types(btf);
2991 for (i = 1; i <= n; i++) {
2992 t = btf__type_by_id(btf, i);
2993
2994 if (!btf_is_datasec(t))
2995 continue;
2996
2997 vs = btf_var_secinfos(t);
2998 for (j = 0; j < btf_vlen(t); j++, vs++) {
2999 if (vs->type == ext_btf_id)
3000 return i;
3001 }
3002 }
3003
3004 return -ENOENT;
3005}
3006
3007static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3008 bool *is_signed)
3009{
3010 const struct btf_type *t;
3011 const char *name;
3012
3013 t = skip_mods_and_typedefs(btf, id, NULL);
3014 name = btf__name_by_offset(btf, t->name_off);
3015
3016 if (is_signed)
3017 *is_signed = false;
3018 switch (btf_kind(t)) {
3019 case BTF_KIND_INT: {
3020 int enc = btf_int_encoding(t);
3021
3022 if (enc & BTF_INT_BOOL)
3023 return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3024 if (is_signed)
3025 *is_signed = enc & BTF_INT_SIGNED;
3026 if (t->size == 1)
3027 return KCFG_CHAR;
3028 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3029 return KCFG_UNKNOWN;
3030 return KCFG_INT;
3031 }
3032 case BTF_KIND_ENUM:
3033 if (t->size != 4)
3034 return KCFG_UNKNOWN;
3035 if (strcmp(name, "libbpf_tristate"))
3036 return KCFG_UNKNOWN;
3037 return KCFG_TRISTATE;
3038 case BTF_KIND_ARRAY:
3039 if (btf_array(t)->nelems == 0)
3040 return KCFG_UNKNOWN;
3041 if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3042 return KCFG_UNKNOWN;
3043 return KCFG_CHAR_ARR;
3044 default:
3045 return KCFG_UNKNOWN;
3046 }
3047}
3048
3049static int cmp_externs(const void *_a, const void *_b)
3050{
3051 const struct extern_desc *a = _a;
3052 const struct extern_desc *b = _b;
3053
3054 if (a->type != b->type)
3055 return a->type < b->type ? -1 : 1;
3056
3057 if (a->type == EXT_KCFG) {
3058 /* descending order by alignment requirements */
3059 if (a->kcfg.align != b->kcfg.align)
3060 return a->kcfg.align > b->kcfg.align ? -1 : 1;
3061 /* ascending order by size, within same alignment class */
3062 if (a->kcfg.sz != b->kcfg.sz)
3063 return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3064 }
3065
3066 /* resolve ties by name */
3067 return strcmp(a->name, b->name);
3068}
3069
3070static int find_int_btf_id(const struct btf *btf)
3071{
3072 const struct btf_type *t;
3073 int i, n;
3074
3075 n = btf__get_nr_types(btf);
3076 for (i = 1; i <= n; i++) {
3077 t = btf__type_by_id(btf, i);
3078
3079 if (btf_is_int(t) && btf_int_bits(t) == 32)
3080 return i;
3081 }
3082
3083 return 0;
3084}
3085
3086static int bpf_object__collect_externs(struct bpf_object *obj)
3087{
3088 struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3089 const struct btf_type *t;
3090 struct extern_desc *ext;
3091 int i, n, off;
3092 const char *ext_name, *sec_name;
3093 Elf_Scn *scn;
3094 GElf_Shdr sh;
3095
3096 if (!obj->efile.symbols)
3097 return 0;
3098
3099 scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3100 if (elf_sec_hdr(obj, scn, &sh))
3101 return -LIBBPF_ERRNO__FORMAT;
3102
3103 n = sh.sh_size / sh.sh_entsize;
3104 pr_debug("looking for externs among %d symbols...\n", n);
3105
3106 for (i = 0; i < n; i++) {
3107 GElf_Sym sym;
3108
3109 if (!gelf_getsym(obj->efile.symbols, i, &sym))
3110 return -LIBBPF_ERRNO__FORMAT;
3111 if (!sym_is_extern(&sym))
3112 continue;
3113 ext_name = elf_sym_str(obj, sym.st_name);
3114 if (!ext_name || !ext_name[0])
3115 continue;
3116
3117 ext = obj->externs;
3118 ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3119 if (!ext)
3120 return -ENOMEM;
3121 obj->externs = ext;
3122 ext = &ext[obj->nr_extern];
3123 memset(ext, 0, sizeof(*ext));
3124 obj->nr_extern++;
3125
3126 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3127 if (ext->btf_id <= 0) {
3128 pr_warn("failed to find BTF for extern '%s': %d\n",
3129 ext_name, ext->btf_id);
3130 return ext->btf_id;
3131 }
3132 t = btf__type_by_id(obj->btf, ext->btf_id);
3133 ext->name = btf__name_by_offset(obj->btf, t->name_off);
3134 ext->sym_idx = i;
3135 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
3136
3137 ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3138 if (ext->sec_btf_id <= 0) {
3139 pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3140 ext_name, ext->btf_id, ext->sec_btf_id);
3141 return ext->sec_btf_id;
3142 }
3143 sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3144 sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3145
3146 if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3147 kcfg_sec = sec;
3148 ext->type = EXT_KCFG;
3149 ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3150 if (ext->kcfg.sz <= 0) {
3151 pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3152 ext_name, ext->kcfg.sz);
3153 return ext->kcfg.sz;
3154 }
3155 ext->kcfg.align = btf__align_of(obj->btf, t->type);
3156 if (ext->kcfg.align <= 0) {
3157 pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3158 ext_name, ext->kcfg.align);
3159 return -EINVAL;
3160 }
3161 ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3162 &ext->kcfg.is_signed);
3163 if (ext->kcfg.type == KCFG_UNKNOWN) {
3164 pr_warn("extern (kcfg) '%s' type is unsupported\n", ext_name);
3165 return -ENOTSUP;
3166 }
3167 } else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3168 ksym_sec = sec;
3169 ext->type = EXT_KSYM;
3170 skip_mods_and_typedefs(obj->btf, t->type,
3171 &ext->ksym.type_id);
3172 } else {
3173 pr_warn("unrecognized extern section '%s'\n", sec_name);
3174 return -ENOTSUP;
3175 }
3176 }
3177 pr_debug("collected %d externs total\n", obj->nr_extern);
3178
3179 if (!obj->nr_extern)
3180 return 0;
3181
3182 /* sort externs by type, for kcfg ones also by (align, size, name) */
3183 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3184
3185 /* for .ksyms section, we need to turn all externs into allocated
3186 * variables in BTF to pass kernel verification; we do this by
3187 * pretending that each extern is a 8-byte variable
3188 */
3189 if (ksym_sec) {
3190 /* find existing 4-byte integer type in BTF to use for fake
3191 * extern variables in DATASEC
3192 */
3193 int int_btf_id = find_int_btf_id(obj->btf);
3194
3195 for (i = 0; i < obj->nr_extern; i++) {
3196 ext = &obj->externs[i];
3197 if (ext->type != EXT_KSYM)
3198 continue;
3199 pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3200 i, ext->sym_idx, ext->name);
3201 }
3202
3203 sec = ksym_sec;
3204 n = btf_vlen(sec);
3205 for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3206 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3207 struct btf_type *vt;
3208
3209 vt = (void *)btf__type_by_id(obj->btf, vs->type);
3210 ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3211 ext = find_extern_by_name(obj, ext_name);
3212 if (!ext) {
3213 pr_warn("failed to find extern definition for BTF var '%s'\n",
3214 ext_name);
3215 return -ESRCH;
3216 }
3217 btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3218 vt->type = int_btf_id;
3219 vs->offset = off;
3220 vs->size = sizeof(int);
3221 }
3222 sec->size = off;
3223 }
3224
3225 if (kcfg_sec) {
3226 sec = kcfg_sec;
3227 /* for kcfg externs calculate their offsets within a .kconfig map */
3228 off = 0;
3229 for (i = 0; i < obj->nr_extern; i++) {
3230 ext = &obj->externs[i];
3231 if (ext->type != EXT_KCFG)
3232 continue;
3233
3234 ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3235 off = ext->kcfg.data_off + ext->kcfg.sz;
3236 pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3237 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3238 }
3239 sec->size = off;
3240 n = btf_vlen(sec);
3241 for (i = 0; i < n; i++) {
3242 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3243
3244 t = btf__type_by_id(obj->btf, vs->type);
3245 ext_name = btf__name_by_offset(obj->btf, t->name_off);
3246 ext = find_extern_by_name(obj, ext_name);
3247 if (!ext) {
3248 pr_warn("failed to find extern definition for BTF var '%s'\n",
3249 ext_name);
3250 return -ESRCH;
3251 }
3252 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3253 vs->offset = ext->kcfg.data_off;
3254 }
3255 }
3256 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003257}
3258
3259struct bpf_program *
David Brazdil0f672f62019-12-10 10:32:29 +00003260bpf_object__find_program_by_title(const struct bpf_object *obj,
3261 const char *title)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003262{
3263 struct bpf_program *pos;
3264
3265 bpf_object__for_each_program(pos, obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003266 if (pos->sec_name && !strcmp(pos->sec_name, title))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003267 return pos;
3268 }
3269 return NULL;
3270}
3271
Olivier Deprez157378f2022-04-04 15:47:50 +02003272static bool prog_is_subprog(const struct bpf_object *obj,
3273 const struct bpf_program *prog)
3274{
3275 /* For legacy reasons, libbpf supports an entry-point BPF programs
3276 * without SEC() attribute, i.e., those in the .text section. But if
3277 * there are 2 or more such programs in the .text section, they all
3278 * must be subprograms called from entry-point BPF programs in
3279 * designated SEC()'tions, otherwise there is no way to distinguish
3280 * which of those programs should be loaded vs which are a subprogram.
3281 * Similarly, if there is a function/program in .text and at least one
3282 * other BPF program with custom SEC() attribute, then we just assume
3283 * .text programs are subprograms (even if they are not called from
3284 * other programs), because libbpf never explicitly supported mixing
3285 * SEC()-designated BPF programs and .text entry-point BPF programs.
3286 */
3287 return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3288}
3289
3290struct bpf_program *
3291bpf_object__find_program_by_name(const struct bpf_object *obj,
3292 const char *name)
3293{
3294 struct bpf_program *prog;
3295
3296 bpf_object__for_each_program(prog, obj) {
3297 if (prog_is_subprog(obj, prog))
3298 continue;
3299 if (!strcmp(prog->name, name))
3300 return prog;
3301 }
3302 return NULL;
3303}
3304
David Brazdil0f672f62019-12-10 10:32:29 +00003305static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3306 int shndx)
3307{
3308 return shndx == obj->efile.data_shndx ||
3309 shndx == obj->efile.bss_shndx ||
3310 shndx == obj->efile.rodata_shndx;
3311}
3312
3313static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3314 int shndx)
3315{
3316 return shndx == obj->efile.maps_shndx ||
3317 shndx == obj->efile.btf_maps_shndx;
3318}
3319
David Brazdil0f672f62019-12-10 10:32:29 +00003320static enum libbpf_map_type
3321bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3322{
3323 if (shndx == obj->efile.data_shndx)
3324 return LIBBPF_MAP_DATA;
3325 else if (shndx == obj->efile.bss_shndx)
3326 return LIBBPF_MAP_BSS;
3327 else if (shndx == obj->efile.rodata_shndx)
3328 return LIBBPF_MAP_RODATA;
Olivier Deprez157378f2022-04-04 15:47:50 +02003329 else if (shndx == obj->efile.symbols_shndx)
3330 return LIBBPF_MAP_KCONFIG;
David Brazdil0f672f62019-12-10 10:32:29 +00003331 else
3332 return LIBBPF_MAP_UNSPEC;
3333}
3334
Olivier Deprez157378f2022-04-04 15:47:50 +02003335static int bpf_program__record_reloc(struct bpf_program *prog,
3336 struct reloc_desc *reloc_desc,
3337 __u32 insn_idx, const char *sym_name,
3338 const GElf_Sym *sym, const GElf_Rel *rel)
3339{
3340 struct bpf_insn *insn = &prog->insns[insn_idx];
3341 size_t map_idx, nr_maps = prog->obj->nr_maps;
3342 struct bpf_object *obj = prog->obj;
3343 __u32 shdr_idx = sym->st_shndx;
3344 enum libbpf_map_type type;
3345 const char *sym_sec_name;
3346 struct bpf_map *map;
3347
3348 reloc_desc->processed = false;
3349
3350 /* sub-program call relocation */
3351 if (insn->code == (BPF_JMP | BPF_CALL)) {
3352 if (insn->src_reg != BPF_PSEUDO_CALL) {
3353 pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3354 return -LIBBPF_ERRNO__RELOC;
3355 }
3356 /* text_shndx can be 0, if no default "main" program exists */
3357 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3358 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3359 pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3360 prog->name, sym_name, sym_sec_name);
3361 return -LIBBPF_ERRNO__RELOC;
3362 }
3363 if (sym->st_value % BPF_INSN_SZ) {
3364 pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3365 prog->name, sym_name, (size_t)sym->st_value);
3366 return -LIBBPF_ERRNO__RELOC;
3367 }
3368 reloc_desc->type = RELO_CALL;
3369 reloc_desc->insn_idx = insn_idx;
3370 reloc_desc->sym_off = sym->st_value;
3371 return 0;
3372 }
3373
3374 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
3375 pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3376 prog->name, sym_name, insn_idx, insn->code);
3377 return -LIBBPF_ERRNO__RELOC;
3378 }
3379
3380 if (sym_is_extern(sym)) {
3381 int sym_idx = GELF_R_SYM(rel->r_info);
3382 int i, n = obj->nr_extern;
3383 struct extern_desc *ext;
3384
3385 for (i = 0; i < n; i++) {
3386 ext = &obj->externs[i];
3387 if (ext->sym_idx == sym_idx)
3388 break;
3389 }
3390 if (i >= n) {
3391 pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3392 prog->name, sym_name, sym_idx);
3393 return -LIBBPF_ERRNO__RELOC;
3394 }
3395 pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3396 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3397 reloc_desc->type = RELO_EXTERN;
3398 reloc_desc->insn_idx = insn_idx;
3399 reloc_desc->sym_off = i; /* sym_off stores extern index */
3400 return 0;
3401 }
3402
3403 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3404 pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3405 prog->name, sym_name, shdr_idx);
3406 return -LIBBPF_ERRNO__RELOC;
3407 }
3408
3409 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
3410 sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3411
3412 /* generic map reference relocation */
3413 if (type == LIBBPF_MAP_UNSPEC) {
3414 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
3415 pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
3416 prog->name, sym_name, sym_sec_name);
3417 return -LIBBPF_ERRNO__RELOC;
3418 }
3419 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3420 map = &obj->maps[map_idx];
3421 if (map->libbpf_type != type ||
3422 map->sec_idx != sym->st_shndx ||
3423 map->sec_offset != sym->st_value)
3424 continue;
3425 pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
3426 prog->name, map_idx, map->name, map->sec_idx,
3427 map->sec_offset, insn_idx);
3428 break;
3429 }
3430 if (map_idx >= nr_maps) {
3431 pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
3432 prog->name, sym_sec_name, (size_t)sym->st_value);
3433 return -LIBBPF_ERRNO__RELOC;
3434 }
3435 reloc_desc->type = RELO_LD64;
3436 reloc_desc->insn_idx = insn_idx;
3437 reloc_desc->map_idx = map_idx;
3438 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
3439 return 0;
3440 }
3441
3442 /* global data map relocation */
3443 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
3444 pr_warn("prog '%s': bad data relo against section '%s'\n",
3445 prog->name, sym_sec_name);
3446 return -LIBBPF_ERRNO__RELOC;
3447 }
3448 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
3449 map = &obj->maps[map_idx];
3450 if (map->libbpf_type != type)
3451 continue;
3452 pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
3453 prog->name, map_idx, map->name, map->sec_idx,
3454 map->sec_offset, insn_idx);
3455 break;
3456 }
3457 if (map_idx >= nr_maps) {
3458 pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
3459 prog->name, sym_sec_name);
3460 return -LIBBPF_ERRNO__RELOC;
3461 }
3462
3463 reloc_desc->type = RELO_DATA;
3464 reloc_desc->insn_idx = insn_idx;
3465 reloc_desc->map_idx = map_idx;
3466 reloc_desc->sym_off = sym->st_value;
3467 return 0;
3468}
3469
3470static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
3471{
3472 return insn_idx >= prog->sec_insn_off &&
3473 insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
3474}
3475
3476static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
3477 size_t sec_idx, size_t insn_idx)
3478{
3479 int l = 0, r = obj->nr_programs - 1, m;
3480 struct bpf_program *prog;
3481
3482 while (l < r) {
3483 m = l + (r - l + 1) / 2;
3484 prog = &obj->programs[m];
3485
3486 if (prog->sec_idx < sec_idx ||
3487 (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
3488 l = m;
3489 else
3490 r = m - 1;
3491 }
3492 /* matching program could be at index l, but it still might be the
3493 * wrong one, so we need to double check conditions for the last time
3494 */
3495 prog = &obj->programs[l];
3496 if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
3497 return prog;
3498 return NULL;
3499}
3500
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003501static int
Olivier Deprez157378f2022-04-04 15:47:50 +02003502bpf_object__collect_prog_relos(struct bpf_object *obj, GElf_Shdr *shdr, Elf_Data *data)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003503{
3504 Elf_Data *symbols = obj->efile.symbols;
Olivier Deprez157378f2022-04-04 15:47:50 +02003505 const char *relo_sec_name, *sec_name;
3506 size_t sec_idx = shdr->sh_info;
3507 struct bpf_program *prog;
3508 struct reloc_desc *relos;
3509 int err, i, nrels;
3510 const char *sym_name;
3511 __u32 insn_idx;
3512 GElf_Sym sym;
3513 GElf_Rel rel;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003514
Olivier Deprez157378f2022-04-04 15:47:50 +02003515 relo_sec_name = elf_sec_str(obj, shdr->sh_name);
3516 sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
3517 if (!relo_sec_name || !sec_name)
3518 return -EINVAL;
3519
3520 pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
3521 relo_sec_name, sec_idx, sec_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003522 nrels = shdr->sh_size / shdr->sh_entsize;
3523
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003524 for (i = 0; i < nrels; i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003525 if (!gelf_getrel(data, i, &rel)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003526 pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003527 return -LIBBPF_ERRNO__FORMAT;
3528 }
David Brazdil0f672f62019-12-10 10:32:29 +00003529 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003530 pr_warn("sec '%s': symbol 0x%zx not found for relo #%d\n",
3531 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
3532 return -LIBBPF_ERRNO__FORMAT;
3533 }
3534 if (rel.r_offset % BPF_INSN_SZ) {
3535 pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
3536 relo_sec_name, (size_t)GELF_R_SYM(rel.r_info), i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003537 return -LIBBPF_ERRNO__FORMAT;
3538 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003539
Olivier Deprez157378f2022-04-04 15:47:50 +02003540 insn_idx = rel.r_offset / BPF_INSN_SZ;
3541 /* relocations against static functions are recorded as
3542 * relocations against the section that contains a function;
3543 * in such case, symbol will be STT_SECTION and sym.st_name
3544 * will point to empty string (0), so fetch section name
3545 * instead
3546 */
3547 if (GELF_ST_TYPE(sym.st_info) == STT_SECTION && sym.st_name == 0)
3548 sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym.st_shndx));
3549 else
3550 sym_name = elf_sym_str(obj, sym.st_name);
3551 sym_name = sym_name ?: "<?";
David Brazdil0f672f62019-12-10 10:32:29 +00003552
Olivier Deprez157378f2022-04-04 15:47:50 +02003553 pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
3554 relo_sec_name, i, insn_idx, sym_name);
David Brazdil0f672f62019-12-10 10:32:29 +00003555
Olivier Deprez157378f2022-04-04 15:47:50 +02003556 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
3557 if (!prog) {
3558 pr_warn("sec '%s': relo #%d: program not found in section '%s' for insn #%u\n",
3559 relo_sec_name, i, sec_name, insn_idx);
David Brazdil0f672f62019-12-10 10:32:29 +00003560 return -LIBBPF_ERRNO__RELOC;
3561 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003562
Olivier Deprez157378f2022-04-04 15:47:50 +02003563 relos = libbpf_reallocarray(prog->reloc_desc,
3564 prog->nr_reloc + 1, sizeof(*relos));
3565 if (!relos)
3566 return -ENOMEM;
3567 prog->reloc_desc = relos;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003568
Olivier Deprez157378f2022-04-04 15:47:50 +02003569 /* adjust insn_idx to local BPF program frame of reference */
3570 insn_idx -= prog->sec_insn_off;
3571 err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
3572 insn_idx, sym_name, &sym, &rel);
3573 if (err)
3574 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003575
Olivier Deprez157378f2022-04-04 15:47:50 +02003576 prog->nr_reloc++;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003577 }
3578 return 0;
3579}
3580
David Brazdil0f672f62019-12-10 10:32:29 +00003581static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003582{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003583 struct bpf_map_def *def = &map->def;
David Brazdil0f672f62019-12-10 10:32:29 +00003584 __u32 key_type_id = 0, value_type_id = 0;
3585 int ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003586
Olivier Deprez157378f2022-04-04 15:47:50 +02003587 /* if it's BTF-defined map, we don't need to search for type IDs.
3588 * For struct_ops map, it does not need btf_key_type_id and
3589 * btf_value_type_id.
3590 */
3591 if (map->sec_idx == obj->efile.btf_maps_shndx ||
3592 bpf_map__is_struct_ops(map))
David Brazdil0f672f62019-12-10 10:32:29 +00003593 return 0;
3594
3595 if (!bpf_map__is_internal(map)) {
3596 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
3597 def->value_size, &key_type_id,
3598 &value_type_id);
3599 } else {
3600 /*
3601 * LLVM annotates global data differently in BTF, that is,
3602 * only as '.data', '.bss' or '.rodata'.
3603 */
3604 ret = btf__find_by_name(obj->btf,
3605 libbpf_type_to_btf_name[map->libbpf_type]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003606 }
David Brazdil0f672f62019-12-10 10:32:29 +00003607 if (ret < 0)
3608 return ret;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003609
David Brazdil0f672f62019-12-10 10:32:29 +00003610 map->btf_key_type_id = key_type_id;
3611 map->btf_value_type_id = bpf_map__is_internal(map) ?
3612 ret : value_type_id;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003613 return 0;
3614}
3615
Olivier Deprez157378f2022-04-04 15:47:50 +02003616static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
3617{
3618 char file[PATH_MAX], buff[4096];
3619 FILE *fp;
3620 __u32 val;
3621 int err;
3622
3623 snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
3624 memset(info, 0, sizeof(*info));
3625
3626 fp = fopen(file, "r");
3627 if (!fp) {
3628 err = -errno;
3629 pr_warn("failed to open %s: %d. No procfs support?\n", file,
3630 err);
3631 return err;
3632 }
3633
3634 while (fgets(buff, sizeof(buff), fp)) {
3635 if (sscanf(buff, "map_type:\t%u", &val) == 1)
3636 info->type = val;
3637 else if (sscanf(buff, "key_size:\t%u", &val) == 1)
3638 info->key_size = val;
3639 else if (sscanf(buff, "value_size:\t%u", &val) == 1)
3640 info->value_size = val;
3641 else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
3642 info->max_entries = val;
3643 else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
3644 info->map_flags = val;
3645 }
3646
3647 fclose(fp);
3648
3649 return 0;
3650}
3651
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003652int bpf_map__reuse_fd(struct bpf_map *map, int fd)
3653{
3654 struct bpf_map_info info = {};
3655 __u32 len = sizeof(info);
3656 int new_fd, err;
3657 char *new_name;
3658
3659 err = bpf_obj_get_info_by_fd(fd, &info, &len);
Olivier Deprez157378f2022-04-04 15:47:50 +02003660 if (err && errno == EINVAL)
3661 err = bpf_get_map_info_from_fdinfo(fd, &info);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003662 if (err)
3663 return err;
3664
3665 new_name = strdup(info.name);
3666 if (!new_name)
3667 return -errno;
3668
3669 new_fd = open("/", O_RDONLY | O_CLOEXEC);
Olivier Deprez0e641232021-09-23 10:07:05 +02003670 if (new_fd < 0) {
3671 err = -errno;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003672 goto err_free_new_name;
Olivier Deprez0e641232021-09-23 10:07:05 +02003673 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003674
3675 new_fd = dup3(fd, new_fd, O_CLOEXEC);
Olivier Deprez0e641232021-09-23 10:07:05 +02003676 if (new_fd < 0) {
3677 err = -errno;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003678 goto err_close_new_fd;
Olivier Deprez0e641232021-09-23 10:07:05 +02003679 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003680
3681 err = zclose(map->fd);
Olivier Deprez0e641232021-09-23 10:07:05 +02003682 if (err) {
3683 err = -errno;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003684 goto err_close_new_fd;
Olivier Deprez0e641232021-09-23 10:07:05 +02003685 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003686 free(map->name);
3687
3688 map->fd = new_fd;
3689 map->name = new_name;
3690 map->def.type = info.type;
3691 map->def.key_size = info.key_size;
3692 map->def.value_size = info.value_size;
3693 map->def.max_entries = info.max_entries;
3694 map->def.map_flags = info.map_flags;
3695 map->btf_key_type_id = info.btf_key_type_id;
3696 map->btf_value_type_id = info.btf_value_type_id;
Olivier Deprez157378f2022-04-04 15:47:50 +02003697 map->reused = true;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003698
3699 return 0;
3700
3701err_close_new_fd:
3702 close(new_fd);
3703err_free_new_name:
3704 free(new_name);
Olivier Deprez0e641232021-09-23 10:07:05 +02003705 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003706}
3707
Olivier Deprez157378f2022-04-04 15:47:50 +02003708__u32 bpf_map__max_entries(const struct bpf_map *map)
3709{
3710 return map->def.max_entries;
3711}
3712
3713int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
3714{
3715 if (map->fd >= 0)
3716 return -EBUSY;
3717 map->def.max_entries = max_entries;
3718 return 0;
3719}
3720
David Brazdil0f672f62019-12-10 10:32:29 +00003721int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
3722{
3723 if (!map || !max_entries)
3724 return -EINVAL;
3725
Olivier Deprez157378f2022-04-04 15:47:50 +02003726 return bpf_map__set_max_entries(map, max_entries);
David Brazdil0f672f62019-12-10 10:32:29 +00003727}
3728
3729static int
Olivier Deprez157378f2022-04-04 15:47:50 +02003730bpf_object__probe_loading(struct bpf_object *obj)
David Brazdil0f672f62019-12-10 10:32:29 +00003731{
3732 struct bpf_load_program_attr attr;
3733 char *cp, errmsg[STRERR_BUFSIZE];
3734 struct bpf_insn insns[] = {
3735 BPF_MOV64_IMM(BPF_REG_0, 0),
3736 BPF_EXIT_INSN(),
3737 };
3738 int ret;
3739
3740 /* make sure basic loading works */
3741
3742 memset(&attr, 0, sizeof(attr));
3743 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3744 attr.insns = insns;
3745 attr.insns_cnt = ARRAY_SIZE(insns);
3746 attr.license = "GPL";
3747
3748 ret = bpf_load_program_xattr(&attr, NULL, 0);
3749 if (ret < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003750 ret = errno;
3751 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3752 pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
3753 "program. Make sure your kernel supports BPF "
3754 "(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
3755 "set to big enough value.\n", __func__, cp, ret);
3756 return -ret;
David Brazdil0f672f62019-12-10 10:32:29 +00003757 }
3758 close(ret);
3759
David Brazdil0f672f62019-12-10 10:32:29 +00003760 return 0;
3761}
3762
Olivier Deprez157378f2022-04-04 15:47:50 +02003763static int probe_fd(int fd)
3764{
3765 if (fd >= 0)
3766 close(fd);
3767 return fd >= 0;
3768}
3769
3770static int probe_kern_prog_name(void)
3771{
3772 struct bpf_load_program_attr attr;
3773 struct bpf_insn insns[] = {
3774 BPF_MOV64_IMM(BPF_REG_0, 0),
3775 BPF_EXIT_INSN(),
3776 };
3777 int ret;
3778
3779 /* make sure loading with name works */
3780
3781 memset(&attr, 0, sizeof(attr));
3782 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3783 attr.insns = insns;
3784 attr.insns_cnt = ARRAY_SIZE(insns);
3785 attr.license = "GPL";
3786 attr.name = "test";
3787 ret = bpf_load_program_xattr(&attr, NULL, 0);
3788 return probe_fd(ret);
3789}
3790
3791static int probe_kern_global_data(void)
David Brazdil0f672f62019-12-10 10:32:29 +00003792{
3793 struct bpf_load_program_attr prg_attr;
3794 struct bpf_create_map_attr map_attr;
3795 char *cp, errmsg[STRERR_BUFSIZE];
3796 struct bpf_insn insns[] = {
3797 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
3798 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
3799 BPF_MOV64_IMM(BPF_REG_0, 0),
3800 BPF_EXIT_INSN(),
3801 };
3802 int ret, map;
3803
3804 memset(&map_attr, 0, sizeof(map_attr));
3805 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3806 map_attr.key_size = sizeof(int);
3807 map_attr.value_size = 32;
3808 map_attr.max_entries = 1;
3809
3810 map = bpf_create_map_xattr(&map_attr);
3811 if (map < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003812 ret = -errno;
3813 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3814 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3815 __func__, cp, -ret);
3816 return ret;
David Brazdil0f672f62019-12-10 10:32:29 +00003817 }
3818
3819 insns[0].imm = map;
3820
3821 memset(&prg_attr, 0, sizeof(prg_attr));
3822 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3823 prg_attr.insns = insns;
3824 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3825 prg_attr.license = "GPL";
3826
3827 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00003828 close(map);
Olivier Deprez157378f2022-04-04 15:47:50 +02003829 return probe_fd(ret);
David Brazdil0f672f62019-12-10 10:32:29 +00003830}
3831
Olivier Deprez157378f2022-04-04 15:47:50 +02003832static int probe_kern_btf(void)
David Brazdil0f672f62019-12-10 10:32:29 +00003833{
Olivier Deprez157378f2022-04-04 15:47:50 +02003834 static const char strs[] = "\0int";
3835 __u32 types[] = {
3836 /* int */
3837 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
3838 };
3839
3840 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
3841 strs, sizeof(strs)));
3842}
3843
3844static int probe_kern_btf_func(void)
3845{
3846 static const char strs[] = "\0int\0x\0a";
David Brazdil0f672f62019-12-10 10:32:29 +00003847 /* void x(int a) {} */
3848 __u32 types[] = {
3849 /* int */
3850 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3851 /* FUNC_PROTO */ /* [2] */
3852 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3853 BTF_PARAM_ENC(7, 1),
3854 /* FUNC x */ /* [3] */
3855 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
3856 };
David Brazdil0f672f62019-12-10 10:32:29 +00003857
Olivier Deprez157378f2022-04-04 15:47:50 +02003858 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
3859 strs, sizeof(strs)));
David Brazdil0f672f62019-12-10 10:32:29 +00003860}
3861
Olivier Deprez157378f2022-04-04 15:47:50 +02003862static int probe_kern_btf_func_global(void)
David Brazdil0f672f62019-12-10 10:32:29 +00003863{
Olivier Deprez157378f2022-04-04 15:47:50 +02003864 static const char strs[] = "\0int\0x\0a";
3865 /* static void x(int a) {} */
3866 __u32 types[] = {
3867 /* int */
3868 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3869 /* FUNC_PROTO */ /* [2] */
3870 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
3871 BTF_PARAM_ENC(7, 1),
3872 /* FUNC x BTF_FUNC_GLOBAL */ /* [3] */
3873 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
3874 };
3875
3876 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
3877 strs, sizeof(strs)));
3878}
3879
3880static int probe_kern_btf_datasec(void)
3881{
3882 static const char strs[] = "\0x\0.data";
David Brazdil0f672f62019-12-10 10:32:29 +00003883 /* static int a; */
3884 __u32 types[] = {
3885 /* int */
3886 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
3887 /* VAR x */ /* [2] */
3888 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
3889 BTF_VAR_STATIC,
3890 /* DATASEC val */ /* [3] */
3891 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
3892 BTF_VAR_SECINFO_ENC(2, 0, 4),
3893 };
David Brazdil0f672f62019-12-10 10:32:29 +00003894
Olivier Deprez157378f2022-04-04 15:47:50 +02003895 return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
3896 strs, sizeof(strs)));
3897}
3898
3899static int probe_kern_array_mmap(void)
3900{
3901 struct bpf_create_map_attr attr = {
3902 .map_type = BPF_MAP_TYPE_ARRAY,
3903 .map_flags = BPF_F_MMAPABLE,
3904 .key_size = sizeof(int),
3905 .value_size = sizeof(int),
3906 .max_entries = 1,
3907 };
3908
3909 return probe_fd(bpf_create_map_xattr(&attr));
3910}
3911
3912static int probe_kern_exp_attach_type(void)
3913{
3914 struct bpf_load_program_attr attr;
3915 struct bpf_insn insns[] = {
3916 BPF_MOV64_IMM(BPF_REG_0, 0),
3917 BPF_EXIT_INSN(),
3918 };
3919
3920 memset(&attr, 0, sizeof(attr));
3921 /* use any valid combination of program type and (optional)
3922 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
3923 * to see if kernel supports expected_attach_type field for
3924 * BPF_PROG_LOAD command
3925 */
3926 attr.prog_type = BPF_PROG_TYPE_CGROUP_SOCK;
3927 attr.expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE;
3928 attr.insns = insns;
3929 attr.insns_cnt = ARRAY_SIZE(insns);
3930 attr.license = "GPL";
3931
3932 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
3933}
3934
3935static int probe_kern_probe_read_kernel(void)
3936{
3937 struct bpf_load_program_attr attr;
3938 struct bpf_insn insns[] = {
3939 BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), /* r1 = r10 (fp) */
3940 BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8), /* r1 += -8 */
3941 BPF_MOV64_IMM(BPF_REG_2, 8), /* r2 = 8 */
3942 BPF_MOV64_IMM(BPF_REG_3, 0), /* r3 = 0 */
3943 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
3944 BPF_EXIT_INSN(),
3945 };
3946
3947 memset(&attr, 0, sizeof(attr));
3948 attr.prog_type = BPF_PROG_TYPE_KPROBE;
3949 attr.insns = insns;
3950 attr.insns_cnt = ARRAY_SIZE(insns);
3951 attr.license = "GPL";
3952
3953 return probe_fd(bpf_load_program_xattr(&attr, NULL, 0));
3954}
3955
3956static int probe_prog_bind_map(void)
3957{
3958 struct bpf_load_program_attr prg_attr;
3959 struct bpf_create_map_attr map_attr;
3960 char *cp, errmsg[STRERR_BUFSIZE];
3961 struct bpf_insn insns[] = {
3962 BPF_MOV64_IMM(BPF_REG_0, 0),
3963 BPF_EXIT_INSN(),
3964 };
3965 int ret, map, prog;
3966
3967 memset(&map_attr, 0, sizeof(map_attr));
3968 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
3969 map_attr.key_size = sizeof(int);
3970 map_attr.value_size = 32;
3971 map_attr.max_entries = 1;
3972
3973 map = bpf_create_map_xattr(&map_attr);
3974 if (map < 0) {
3975 ret = -errno;
3976 cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
3977 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
3978 __func__, cp, -ret);
3979 return ret;
David Brazdil0f672f62019-12-10 10:32:29 +00003980 }
3981
Olivier Deprez157378f2022-04-04 15:47:50 +02003982 memset(&prg_attr, 0, sizeof(prg_attr));
3983 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
3984 prg_attr.insns = insns;
3985 prg_attr.insns_cnt = ARRAY_SIZE(insns);
3986 prg_attr.license = "GPL";
3987
3988 prog = bpf_load_program_xattr(&prg_attr, NULL, 0);
3989 if (prog < 0) {
3990 close(map);
3991 return 0;
3992 }
3993
3994 ret = bpf_prog_bind_map(prog, map, NULL);
3995
3996 close(map);
3997 close(prog);
3998
3999 return ret >= 0;
4000}
4001
4002enum kern_feature_result {
4003 FEAT_UNKNOWN = 0,
4004 FEAT_SUPPORTED = 1,
4005 FEAT_MISSING = 2,
4006};
4007
4008typedef int (*feature_probe_fn)(void);
4009
4010static struct kern_feature_desc {
4011 const char *desc;
4012 feature_probe_fn probe;
4013 enum kern_feature_result res;
4014} feature_probes[__FEAT_CNT] = {
4015 [FEAT_PROG_NAME] = {
4016 "BPF program name", probe_kern_prog_name,
4017 },
4018 [FEAT_GLOBAL_DATA] = {
4019 "global variables", probe_kern_global_data,
4020 },
4021 [FEAT_BTF] = {
4022 "minimal BTF", probe_kern_btf,
4023 },
4024 [FEAT_BTF_FUNC] = {
4025 "BTF functions", probe_kern_btf_func,
4026 },
4027 [FEAT_BTF_GLOBAL_FUNC] = {
4028 "BTF global function", probe_kern_btf_func_global,
4029 },
4030 [FEAT_BTF_DATASEC] = {
4031 "BTF data section and variable", probe_kern_btf_datasec,
4032 },
4033 [FEAT_ARRAY_MMAP] = {
4034 "ARRAY map mmap()", probe_kern_array_mmap,
4035 },
4036 [FEAT_EXP_ATTACH_TYPE] = {
4037 "BPF_PROG_LOAD expected_attach_type attribute",
4038 probe_kern_exp_attach_type,
4039 },
4040 [FEAT_PROBE_READ_KERN] = {
4041 "bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4042 },
4043 [FEAT_PROG_BIND_MAP] = {
4044 "BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4045 }
4046};
4047
4048static bool kernel_supports(enum kern_feature_id feat_id)
4049{
4050 struct kern_feature_desc *feat = &feature_probes[feat_id];
4051 int ret;
4052
4053 if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4054 ret = feat->probe();
4055 if (ret > 0) {
4056 WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4057 } else if (ret == 0) {
4058 WRITE_ONCE(feat->res, FEAT_MISSING);
4059 } else {
4060 pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4061 WRITE_ONCE(feat->res, FEAT_MISSING);
4062 }
4063 }
4064
4065 return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4066}
4067
4068static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4069{
4070 struct bpf_map_info map_info = {};
4071 char msg[STRERR_BUFSIZE];
4072 __u32 map_info_len;
4073 int err;
4074
4075 map_info_len = sizeof(map_info);
4076
4077 err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4078 if (err && errno == EINVAL)
4079 err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4080 if (err) {
4081 pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4082 libbpf_strerror_r(errno, msg, sizeof(msg)));
4083 return false;
4084 }
4085
4086 return (map_info.type == map->def.type &&
4087 map_info.key_size == map->def.key_size &&
4088 map_info.value_size == map->def.value_size &&
4089 map_info.max_entries == map->def.max_entries &&
4090 map_info.map_flags == map->def.map_flags);
David Brazdil0f672f62019-12-10 10:32:29 +00004091}
4092
4093static int
Olivier Deprez157378f2022-04-04 15:47:50 +02004094bpf_object__reuse_map(struct bpf_map *map)
David Brazdil0f672f62019-12-10 10:32:29 +00004095{
Olivier Deprez157378f2022-04-04 15:47:50 +02004096 char *cp, errmsg[STRERR_BUFSIZE];
4097 int err, pin_fd;
David Brazdil0f672f62019-12-10 10:32:29 +00004098
Olivier Deprez157378f2022-04-04 15:47:50 +02004099 pin_fd = bpf_obj_get(map->pin_path);
4100 if (pin_fd < 0) {
4101 err = -errno;
4102 if (err == -ENOENT) {
4103 pr_debug("found no pinned map to reuse at '%s'\n",
4104 map->pin_path);
4105 return 0;
4106 }
4107
4108 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4109 pr_warn("couldn't retrieve pinned map '%s': %s\n",
4110 map->pin_path, cp);
4111 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00004112 }
4113
Olivier Deprez157378f2022-04-04 15:47:50 +02004114 if (!map_is_reuse_compat(map, pin_fd)) {
4115 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4116 map->pin_path);
4117 close(pin_fd);
4118 return -EINVAL;
4119 }
4120
4121 err = bpf_map__reuse_fd(map, pin_fd);
4122 if (err) {
4123 close(pin_fd);
4124 return err;
4125 }
4126 map->pinned = true;
4127 pr_debug("reused pinned map at '%s'\n", map->pin_path);
4128
David Brazdil0f672f62019-12-10 10:32:29 +00004129 return 0;
4130}
4131
4132static int
4133bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4134{
Olivier Deprez157378f2022-04-04 15:47:50 +02004135 enum libbpf_map_type map_type = map->libbpf_type;
David Brazdil0f672f62019-12-10 10:32:29 +00004136 char *cp, errmsg[STRERR_BUFSIZE];
4137 int err, zero = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004138
Olivier Deprez157378f2022-04-04 15:47:50 +02004139 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4140 if (err) {
4141 err = -errno;
4142 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4143 pr_warn("Error setting initial map(%s) contents: %s\n",
4144 map->name, cp);
4145 return err;
4146 }
David Brazdil0f672f62019-12-10 10:32:29 +00004147
Olivier Deprez157378f2022-04-04 15:47:50 +02004148 /* Freeze .rodata and .kconfig map as read-only from syscall side. */
4149 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
David Brazdil0f672f62019-12-10 10:32:29 +00004150 err = bpf_map_freeze(map->fd);
4151 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004152 err = -errno;
4153 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4154 pr_warn("Error freezing map(%s) as read-only: %s\n",
4155 map->name, cp);
4156 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00004157 }
4158 }
Olivier Deprez157378f2022-04-04 15:47:50 +02004159 return 0;
4160}
4161
4162static void bpf_map__destroy(struct bpf_map *map);
4163
4164static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map)
4165{
4166 struct bpf_create_map_attr create_attr;
4167 struct bpf_map_def *def = &map->def;
4168 int err = 0;
4169
4170 memset(&create_attr, 0, sizeof(create_attr));
4171
4172 if (kernel_supports(FEAT_PROG_NAME))
4173 create_attr.name = map->name;
4174 create_attr.map_ifindex = map->map_ifindex;
4175 create_attr.map_type = def->type;
4176 create_attr.map_flags = def->map_flags;
4177 create_attr.key_size = def->key_size;
4178 create_attr.value_size = def->value_size;
4179 create_attr.numa_node = map->numa_node;
4180
4181 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !def->max_entries) {
4182 int nr_cpus;
4183
4184 nr_cpus = libbpf_num_possible_cpus();
4185 if (nr_cpus < 0) {
4186 pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
4187 map->name, nr_cpus);
4188 return nr_cpus;
4189 }
4190 pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
4191 create_attr.max_entries = nr_cpus;
4192 } else {
4193 create_attr.max_entries = def->max_entries;
4194 }
4195
4196 if (bpf_map__is_struct_ops(map))
4197 create_attr.btf_vmlinux_value_type_id =
4198 map->btf_vmlinux_value_type_id;
4199
4200 create_attr.btf_fd = 0;
4201 create_attr.btf_key_type_id = 0;
4202 create_attr.btf_value_type_id = 0;
4203 if (obj->btf && btf__fd(obj->btf) >= 0 && !bpf_map_find_btf_info(obj, map)) {
4204 create_attr.btf_fd = btf__fd(obj->btf);
4205 create_attr.btf_key_type_id = map->btf_key_type_id;
4206 create_attr.btf_value_type_id = map->btf_value_type_id;
4207 }
4208
4209 if (bpf_map_type__is_map_in_map(def->type)) {
4210 if (map->inner_map) {
4211 err = bpf_object__create_map(obj, map->inner_map);
4212 if (err) {
4213 pr_warn("map '%s': failed to create inner map: %d\n",
4214 map->name, err);
4215 return err;
4216 }
4217 map->inner_map_fd = bpf_map__fd(map->inner_map);
4218 }
4219 if (map->inner_map_fd >= 0)
4220 create_attr.inner_map_fd = map->inner_map_fd;
4221 }
4222
4223 map->fd = bpf_create_map_xattr(&create_attr);
4224 if (map->fd < 0 && (create_attr.btf_key_type_id ||
4225 create_attr.btf_value_type_id)) {
4226 char *cp, errmsg[STRERR_BUFSIZE];
4227
4228 err = -errno;
4229 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4230 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
4231 map->name, cp, err);
4232 create_attr.btf_fd = 0;
4233 create_attr.btf_key_type_id = 0;
4234 create_attr.btf_value_type_id = 0;
4235 map->btf_key_type_id = 0;
4236 map->btf_value_type_id = 0;
4237 map->fd = bpf_create_map_xattr(&create_attr);
4238 }
4239
4240 err = map->fd < 0 ? -errno : 0;
4241
4242 if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
4243 bpf_map__destroy(map->inner_map);
4244 zfree(&map->inner_map);
4245 }
4246
David Brazdil0f672f62019-12-10 10:32:29 +00004247 return err;
4248}
4249
Olivier Deprez157378f2022-04-04 15:47:50 +02004250static int init_map_slots(struct bpf_map *map)
4251{
4252 const struct bpf_map *targ_map;
4253 unsigned int i;
4254 int fd, err;
4255
4256 for (i = 0; i < map->init_slots_sz; i++) {
4257 if (!map->init_slots[i])
4258 continue;
4259
4260 targ_map = map->init_slots[i];
4261 fd = bpf_map__fd(targ_map);
4262 err = bpf_map_update_elem(map->fd, &i, &fd, 0);
4263 if (err) {
4264 err = -errno;
4265 pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
4266 map->name, i, targ_map->name,
4267 fd, err);
4268 return err;
4269 }
4270 pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
4271 map->name, i, targ_map->name, fd);
4272 }
4273
4274 zfree(&map->init_slots);
4275 map->init_slots_sz = 0;
4276
4277 return 0;
4278}
4279
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004280static int
4281bpf_object__create_maps(struct bpf_object *obj)
4282{
Olivier Deprez157378f2022-04-04 15:47:50 +02004283 struct bpf_map *map;
4284 char *cp, errmsg[STRERR_BUFSIZE];
4285 unsigned int i, j;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004286 int err;
Olivier Deprez157378f2022-04-04 15:47:50 +02004287 bool retried;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004288
4289 for (i = 0; i < obj->nr_maps; i++) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004290 map = &obj->maps[i];
4291
4292 retried = false;
4293retry:
4294 if (map->pin_path) {
4295 err = bpf_object__reuse_map(map);
4296 if (err) {
4297 pr_warn("map '%s': error reusing pinned map\n",
4298 map->name);
4299 goto err_out;
4300 }
4301 if (retried && map->fd < 0) {
4302 pr_warn("map '%s': cannot find pinned map\n",
4303 map->name);
4304 err = -ENOENT;
4305 goto err_out;
4306 }
4307 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004308
4309 if (map->fd >= 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004310 pr_debug("map '%s': skipping creation (preset fd=%d)\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004311 map->name, map->fd);
David Brazdil0f672f62019-12-10 10:32:29 +00004312 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02004313 err = bpf_object__create_map(obj, map);
4314 if (err)
David Brazdil0f672f62019-12-10 10:32:29 +00004315 goto err_out;
Olivier Deprez157378f2022-04-04 15:47:50 +02004316
4317 pr_debug("map '%s': created successfully, fd=%d\n",
4318 map->name, map->fd);
4319
4320 if (bpf_map__is_internal(map)) {
4321 err = bpf_object__populate_internal_map(obj, map);
4322 if (err < 0) {
4323 zclose(map->fd);
4324 goto err_out;
4325 }
4326 }
4327
4328 if (map->init_slots_sz) {
4329 err = init_map_slots(map);
4330 if (err < 0) {
4331 zclose(map->fd);
4332 goto err_out;
4333 }
David Brazdil0f672f62019-12-10 10:32:29 +00004334 }
4335 }
4336
Olivier Deprez157378f2022-04-04 15:47:50 +02004337 if (map->pin_path && !map->pinned) {
4338 err = bpf_map__pin(map, NULL);
4339 if (err) {
4340 zclose(map->fd);
4341 if (!retried && err == -EEXIST) {
4342 retried = true;
4343 goto retry;
4344 }
4345 pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
4346 map->name, map->pin_path, err);
4347 goto err_out;
4348 }
4349 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004350 }
4351
4352 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004353
Olivier Deprez157378f2022-04-04 15:47:50 +02004354err_out:
4355 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4356 pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
4357 pr_perm_msg(err);
4358 for (j = 0; j < i; j++)
4359 zclose(obj->maps[j].fd);
4360 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00004361}
4362
4363#define BPF_CORE_SPEC_MAX_LEN 64
4364
4365/* represents BPF CO-RE field or array element accessor */
4366struct bpf_core_accessor {
4367 __u32 type_id; /* struct/union type or array element type */
4368 __u32 idx; /* field index or array index */
4369 const char *name; /* field name or NULL for array accessor */
4370};
4371
4372struct bpf_core_spec {
4373 const struct btf *btf;
4374 /* high-level spec: named fields and array indices only */
4375 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
Olivier Deprez157378f2022-04-04 15:47:50 +02004376 /* original unresolved (no skip_mods_or_typedefs) root type ID */
4377 __u32 root_type_id;
4378 /* CO-RE relocation kind */
4379 enum bpf_core_relo_kind relo_kind;
David Brazdil0f672f62019-12-10 10:32:29 +00004380 /* high-level spec length */
4381 int len;
4382 /* raw, low-level spec: 1-to-1 with accessor spec string */
4383 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
4384 /* raw spec length */
4385 int raw_len;
Olivier Deprez157378f2022-04-04 15:47:50 +02004386 /* field bit offset represented by spec */
4387 __u32 bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004388};
4389
4390static bool str_is_empty(const char *s)
4391{
4392 return !s || !s[0];
4393}
4394
Olivier Deprez157378f2022-04-04 15:47:50 +02004395static bool is_flex_arr(const struct btf *btf,
4396 const struct bpf_core_accessor *acc,
4397 const struct btf_array *arr)
4398{
4399 const struct btf_type *t;
4400
4401 /* not a flexible array, if not inside a struct or has non-zero size */
4402 if (!acc->name || arr->nelems > 0)
4403 return false;
4404
4405 /* has to be the last member of enclosing struct */
4406 t = btf__type_by_id(btf, acc->type_id);
4407 return acc->idx == btf_vlen(t) - 1;
4408}
4409
4410static const char *core_relo_kind_str(enum bpf_core_relo_kind kind)
4411{
4412 switch (kind) {
4413 case BPF_FIELD_BYTE_OFFSET: return "byte_off";
4414 case BPF_FIELD_BYTE_SIZE: return "byte_sz";
4415 case BPF_FIELD_EXISTS: return "field_exists";
4416 case BPF_FIELD_SIGNED: return "signed";
4417 case BPF_FIELD_LSHIFT_U64: return "lshift_u64";
4418 case BPF_FIELD_RSHIFT_U64: return "rshift_u64";
4419 case BPF_TYPE_ID_LOCAL: return "local_type_id";
4420 case BPF_TYPE_ID_TARGET: return "target_type_id";
4421 case BPF_TYPE_EXISTS: return "type_exists";
4422 case BPF_TYPE_SIZE: return "type_size";
4423 case BPF_ENUMVAL_EXISTS: return "enumval_exists";
4424 case BPF_ENUMVAL_VALUE: return "enumval_value";
4425 default: return "unknown";
4426 }
4427}
4428
4429static bool core_relo_is_field_based(enum bpf_core_relo_kind kind)
4430{
4431 switch (kind) {
4432 case BPF_FIELD_BYTE_OFFSET:
4433 case BPF_FIELD_BYTE_SIZE:
4434 case BPF_FIELD_EXISTS:
4435 case BPF_FIELD_SIGNED:
4436 case BPF_FIELD_LSHIFT_U64:
4437 case BPF_FIELD_RSHIFT_U64:
4438 return true;
4439 default:
4440 return false;
4441 }
4442}
4443
4444static bool core_relo_is_type_based(enum bpf_core_relo_kind kind)
4445{
4446 switch (kind) {
4447 case BPF_TYPE_ID_LOCAL:
4448 case BPF_TYPE_ID_TARGET:
4449 case BPF_TYPE_EXISTS:
4450 case BPF_TYPE_SIZE:
4451 return true;
4452 default:
4453 return false;
4454 }
4455}
4456
4457static bool core_relo_is_enumval_based(enum bpf_core_relo_kind kind)
4458{
4459 switch (kind) {
4460 case BPF_ENUMVAL_EXISTS:
4461 case BPF_ENUMVAL_VALUE:
4462 return true;
4463 default:
4464 return false;
4465 }
4466}
4467
David Brazdil0f672f62019-12-10 10:32:29 +00004468/*
Olivier Deprez157378f2022-04-04 15:47:50 +02004469 * Turn bpf_core_relo into a low- and high-level spec representation,
David Brazdil0f672f62019-12-10 10:32:29 +00004470 * validating correctness along the way, as well as calculating resulting
Olivier Deprez157378f2022-04-04 15:47:50 +02004471 * field bit offset, specified by accessor string. Low-level spec captures
4472 * every single level of nestedness, including traversing anonymous
David Brazdil0f672f62019-12-10 10:32:29 +00004473 * struct/union members. High-level one only captures semantically meaningful
4474 * "turning points": named fields and array indicies.
4475 * E.g., for this case:
4476 *
4477 * struct sample {
4478 * int __unimportant;
4479 * struct {
4480 * int __1;
4481 * int __2;
4482 * int a[7];
4483 * };
4484 * };
4485 *
4486 * struct sample *s = ...;
4487 *
4488 * int x = &s->a[3]; // access string = '0:1:2:3'
4489 *
4490 * Low-level spec has 1:1 mapping with each element of access string (it's
4491 * just a parsed access string representation): [0, 1, 2, 3].
4492 *
4493 * High-level spec will capture only 3 points:
4494 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
4495 * - field 'a' access (corresponds to '2' in low-level spec);
4496 * - array element #3 access (corresponds to '3' in low-level spec).
4497 *
Olivier Deprez157378f2022-04-04 15:47:50 +02004498 * Type-based relocations (TYPE_EXISTS/TYPE_SIZE,
4499 * TYPE_ID_LOCAL/TYPE_ID_TARGET) don't capture any field information. Their
4500 * spec and raw_spec are kept empty.
4501 *
4502 * Enum value-based relocations (ENUMVAL_EXISTS/ENUMVAL_VALUE) use access
4503 * string to specify enumerator's value index that need to be relocated.
David Brazdil0f672f62019-12-10 10:32:29 +00004504 */
Olivier Deprez157378f2022-04-04 15:47:50 +02004505static int bpf_core_parse_spec(const struct btf *btf,
David Brazdil0f672f62019-12-10 10:32:29 +00004506 __u32 type_id,
4507 const char *spec_str,
Olivier Deprez157378f2022-04-04 15:47:50 +02004508 enum bpf_core_relo_kind relo_kind,
David Brazdil0f672f62019-12-10 10:32:29 +00004509 struct bpf_core_spec *spec)
4510{
4511 int access_idx, parsed_len, i;
Olivier Deprez157378f2022-04-04 15:47:50 +02004512 struct bpf_core_accessor *acc;
David Brazdil0f672f62019-12-10 10:32:29 +00004513 const struct btf_type *t;
4514 const char *name;
4515 __u32 id;
4516 __s64 sz;
4517
4518 if (str_is_empty(spec_str) || *spec_str == ':')
4519 return -EINVAL;
4520
4521 memset(spec, 0, sizeof(*spec));
4522 spec->btf = btf;
Olivier Deprez157378f2022-04-04 15:47:50 +02004523 spec->root_type_id = type_id;
4524 spec->relo_kind = relo_kind;
4525
4526 /* type-based relocations don't have a field access string */
4527 if (core_relo_is_type_based(relo_kind)) {
4528 if (strcmp(spec_str, "0"))
4529 return -EINVAL;
4530 return 0;
4531 }
David Brazdil0f672f62019-12-10 10:32:29 +00004532
4533 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
4534 while (*spec_str) {
4535 if (*spec_str == ':')
4536 ++spec_str;
4537 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
4538 return -EINVAL;
4539 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4540 return -E2BIG;
4541 spec_str += parsed_len;
4542 spec->raw_spec[spec->raw_len++] = access_idx;
4543 }
4544
4545 if (spec->raw_len == 0)
4546 return -EINVAL;
4547
David Brazdil0f672f62019-12-10 10:32:29 +00004548 t = skip_mods_and_typedefs(btf, type_id, &id);
4549 if (!t)
4550 return -EINVAL;
4551
4552 access_idx = spec->raw_spec[0];
Olivier Deprez157378f2022-04-04 15:47:50 +02004553 acc = &spec->spec[0];
4554 acc->type_id = id;
4555 acc->idx = access_idx;
David Brazdil0f672f62019-12-10 10:32:29 +00004556 spec->len++;
4557
Olivier Deprez157378f2022-04-04 15:47:50 +02004558 if (core_relo_is_enumval_based(relo_kind)) {
4559 if (!btf_is_enum(t) || spec->raw_len > 1 || access_idx >= btf_vlen(t))
4560 return -EINVAL;
4561
4562 /* record enumerator name in a first accessor */
4563 acc->name = btf__name_by_offset(btf, btf_enum(t)[access_idx].name_off);
4564 return 0;
4565 }
4566
4567 if (!core_relo_is_field_based(relo_kind))
4568 return -EINVAL;
4569
David Brazdil0f672f62019-12-10 10:32:29 +00004570 sz = btf__resolve_size(btf, id);
4571 if (sz < 0)
4572 return sz;
Olivier Deprez157378f2022-04-04 15:47:50 +02004573 spec->bit_offset = access_idx * sz * 8;
David Brazdil0f672f62019-12-10 10:32:29 +00004574
4575 for (i = 1; i < spec->raw_len; i++) {
4576 t = skip_mods_and_typedefs(btf, id, &id);
4577 if (!t)
4578 return -EINVAL;
4579
4580 access_idx = spec->raw_spec[i];
Olivier Deprez157378f2022-04-04 15:47:50 +02004581 acc = &spec->spec[spec->len];
David Brazdil0f672f62019-12-10 10:32:29 +00004582
4583 if (btf_is_composite(t)) {
4584 const struct btf_member *m;
Olivier Deprez157378f2022-04-04 15:47:50 +02004585 __u32 bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004586
4587 if (access_idx >= btf_vlen(t))
4588 return -EINVAL;
David Brazdil0f672f62019-12-10 10:32:29 +00004589
Olivier Deprez157378f2022-04-04 15:47:50 +02004590 bit_offset = btf_member_bit_offset(t, access_idx);
4591 spec->bit_offset += bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004592
4593 m = btf_members(t) + access_idx;
4594 if (m->name_off) {
4595 name = btf__name_by_offset(btf, m->name_off);
4596 if (str_is_empty(name))
4597 return -EINVAL;
4598
Olivier Deprez157378f2022-04-04 15:47:50 +02004599 acc->type_id = id;
4600 acc->idx = access_idx;
4601 acc->name = name;
David Brazdil0f672f62019-12-10 10:32:29 +00004602 spec->len++;
4603 }
4604
4605 id = m->type;
4606 } else if (btf_is_array(t)) {
4607 const struct btf_array *a = btf_array(t);
Olivier Deprez157378f2022-04-04 15:47:50 +02004608 bool flex;
David Brazdil0f672f62019-12-10 10:32:29 +00004609
4610 t = skip_mods_and_typedefs(btf, a->type, &id);
Olivier Deprez157378f2022-04-04 15:47:50 +02004611 if (!t)
4612 return -EINVAL;
4613
4614 flex = is_flex_arr(btf, acc - 1, a);
4615 if (!flex && access_idx >= a->nelems)
David Brazdil0f672f62019-12-10 10:32:29 +00004616 return -EINVAL;
4617
4618 spec->spec[spec->len].type_id = id;
4619 spec->spec[spec->len].idx = access_idx;
4620 spec->len++;
4621
4622 sz = btf__resolve_size(btf, id);
4623 if (sz < 0)
4624 return sz;
Olivier Deprez157378f2022-04-04 15:47:50 +02004625 spec->bit_offset += access_idx * sz * 8;
David Brazdil0f672f62019-12-10 10:32:29 +00004626 } else {
Olivier Deprez157378f2022-04-04 15:47:50 +02004627 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %s\n",
4628 type_id, spec_str, i, id, btf_kind_str(t));
David Brazdil0f672f62019-12-10 10:32:29 +00004629 return -EINVAL;
4630 }
4631 }
4632
4633 return 0;
4634}
4635
4636static bool bpf_core_is_flavor_sep(const char *s)
4637{
4638 /* check X___Y name pattern, where X and Y are not underscores */
4639 return s[0] != '_' && /* X */
4640 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
4641 s[4] != '_'; /* Y */
4642}
4643
4644/* Given 'some_struct_name___with_flavor' return the length of a name prefix
4645 * before last triple underscore. Struct name part after last triple
4646 * underscore is ignored by BPF CO-RE relocation during relocation matching.
4647 */
4648static size_t bpf_core_essential_name_len(const char *name)
4649{
4650 size_t n = strlen(name);
4651 int i;
4652
4653 for (i = n - 5; i >= 0; i--) {
4654 if (bpf_core_is_flavor_sep(name + i))
4655 return i + 1;
4656 }
4657 return n;
4658}
4659
4660/* dynamically sized list of type IDs */
4661struct ids_vec {
4662 __u32 *data;
4663 int len;
4664};
4665
4666static void bpf_core_free_cands(struct ids_vec *cand_ids)
4667{
4668 free(cand_ids->data);
4669 free(cand_ids);
4670}
4671
4672static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
4673 __u32 local_type_id,
4674 const struct btf *targ_btf)
4675{
4676 size_t local_essent_len, targ_essent_len;
4677 const char *local_name, *targ_name;
Olivier Deprez157378f2022-04-04 15:47:50 +02004678 const struct btf_type *t, *local_t;
David Brazdil0f672f62019-12-10 10:32:29 +00004679 struct ids_vec *cand_ids;
4680 __u32 *new_ids;
4681 int i, err, n;
4682
Olivier Deprez157378f2022-04-04 15:47:50 +02004683 local_t = btf__type_by_id(local_btf, local_type_id);
4684 if (!local_t)
David Brazdil0f672f62019-12-10 10:32:29 +00004685 return ERR_PTR(-EINVAL);
4686
Olivier Deprez157378f2022-04-04 15:47:50 +02004687 local_name = btf__name_by_offset(local_btf, local_t->name_off);
David Brazdil0f672f62019-12-10 10:32:29 +00004688 if (str_is_empty(local_name))
4689 return ERR_PTR(-EINVAL);
4690 local_essent_len = bpf_core_essential_name_len(local_name);
4691
4692 cand_ids = calloc(1, sizeof(*cand_ids));
4693 if (!cand_ids)
4694 return ERR_PTR(-ENOMEM);
4695
4696 n = btf__get_nr_types(targ_btf);
4697 for (i = 1; i <= n; i++) {
4698 t = btf__type_by_id(targ_btf, i);
Olivier Deprez157378f2022-04-04 15:47:50 +02004699 if (btf_kind(t) != btf_kind(local_t))
4700 continue;
4701
David Brazdil0f672f62019-12-10 10:32:29 +00004702 targ_name = btf__name_by_offset(targ_btf, t->name_off);
4703 if (str_is_empty(targ_name))
4704 continue;
4705
4706 targ_essent_len = bpf_core_essential_name_len(targ_name);
4707 if (targ_essent_len != local_essent_len)
4708 continue;
4709
4710 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004711 pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s\n",
4712 local_type_id, btf_kind_str(local_t),
4713 local_name, i, btf_kind_str(t), targ_name);
4714 new_ids = libbpf_reallocarray(cand_ids->data,
4715 cand_ids->len + 1,
4716 sizeof(*cand_ids->data));
David Brazdil0f672f62019-12-10 10:32:29 +00004717 if (!new_ids) {
4718 err = -ENOMEM;
4719 goto err_out;
4720 }
4721 cand_ids->data = new_ids;
4722 cand_ids->data[cand_ids->len++] = i;
4723 }
4724 }
4725 return cand_ids;
4726err_out:
4727 bpf_core_free_cands(cand_ids);
4728 return ERR_PTR(err);
4729}
4730
Olivier Deprez157378f2022-04-04 15:47:50 +02004731/* Check two types for compatibility for the purpose of field access
4732 * relocation. const/volatile/restrict and typedefs are skipped to ensure we
4733 * are relocating semantically compatible entities:
David Brazdil0f672f62019-12-10 10:32:29 +00004734 * - any two STRUCTs/UNIONs are compatible and can be mixed;
Olivier Deprez157378f2022-04-04 15:47:50 +02004735 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
David Brazdil0f672f62019-12-10 10:32:29 +00004736 * - any two PTRs are always compatible;
Olivier Deprez157378f2022-04-04 15:47:50 +02004737 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
4738 * least one of enums should be anonymous;
David Brazdil0f672f62019-12-10 10:32:29 +00004739 * - for ENUMs, check sizes, names are ignored;
Olivier Deprez157378f2022-04-04 15:47:50 +02004740 * - for INT, size and signedness are ignored;
David Brazdil0f672f62019-12-10 10:32:29 +00004741 * - for ARRAY, dimensionality is ignored, element types are checked for
4742 * compatibility recursively;
4743 * - everything else shouldn't be ever a target of relocation.
4744 * These rules are not set in stone and probably will be adjusted as we get
4745 * more experience with using BPF CO-RE relocations.
4746 */
4747static int bpf_core_fields_are_compat(const struct btf *local_btf,
4748 __u32 local_id,
4749 const struct btf *targ_btf,
4750 __u32 targ_id)
4751{
4752 const struct btf_type *local_type, *targ_type;
4753
4754recur:
4755 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4756 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4757 if (!local_type || !targ_type)
4758 return -EINVAL;
4759
4760 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
4761 return 1;
4762 if (btf_kind(local_type) != btf_kind(targ_type))
4763 return 0;
4764
4765 switch (btf_kind(local_type)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004766 case BTF_KIND_PTR:
4767 return 1;
Olivier Deprez157378f2022-04-04 15:47:50 +02004768 case BTF_KIND_FWD:
4769 case BTF_KIND_ENUM: {
4770 const char *local_name, *targ_name;
4771 size_t local_len, targ_len;
4772
4773 local_name = btf__name_by_offset(local_btf,
4774 local_type->name_off);
4775 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
4776 local_len = bpf_core_essential_name_len(local_name);
4777 targ_len = bpf_core_essential_name_len(targ_name);
4778 /* one of them is anonymous or both w/ same flavor-less names */
4779 return local_len == 0 || targ_len == 0 ||
4780 (local_len == targ_len &&
4781 strncmp(local_name, targ_name, local_len) == 0);
4782 }
David Brazdil0f672f62019-12-10 10:32:29 +00004783 case BTF_KIND_INT:
Olivier Deprez157378f2022-04-04 15:47:50 +02004784 /* just reject deprecated bitfield-like integers; all other
4785 * integers are by default compatible between each other
4786 */
David Brazdil0f672f62019-12-10 10:32:29 +00004787 return btf_int_offset(local_type) == 0 &&
Olivier Deprez157378f2022-04-04 15:47:50 +02004788 btf_int_offset(targ_type) == 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004789 case BTF_KIND_ARRAY:
4790 local_id = btf_array(local_type)->type;
4791 targ_id = btf_array(targ_type)->type;
4792 goto recur;
4793 default:
Olivier Deprez157378f2022-04-04 15:47:50 +02004794 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
4795 btf_kind(local_type), local_id, targ_id);
David Brazdil0f672f62019-12-10 10:32:29 +00004796 return 0;
4797 }
4798}
4799
4800/*
4801 * Given single high-level named field accessor in local type, find
4802 * corresponding high-level accessor for a target type. Along the way,
4803 * maintain low-level spec for target as well. Also keep updating target
Olivier Deprez157378f2022-04-04 15:47:50 +02004804 * bit offset.
David Brazdil0f672f62019-12-10 10:32:29 +00004805 *
4806 * Searching is performed through recursive exhaustive enumeration of all
4807 * fields of a struct/union. If there are any anonymous (embedded)
4808 * structs/unions, they are recursively searched as well. If field with
4809 * desired name is found, check compatibility between local and target types,
4810 * before returning result.
4811 *
4812 * 1 is returned, if field is found.
4813 * 0 is returned if no compatible field is found.
4814 * <0 is returned on error.
4815 */
4816static int bpf_core_match_member(const struct btf *local_btf,
4817 const struct bpf_core_accessor *local_acc,
4818 const struct btf *targ_btf,
4819 __u32 targ_id,
4820 struct bpf_core_spec *spec,
4821 __u32 *next_targ_id)
4822{
4823 const struct btf_type *local_type, *targ_type;
4824 const struct btf_member *local_member, *m;
4825 const char *local_name, *targ_name;
4826 __u32 local_id;
4827 int i, n, found;
4828
4829 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4830 if (!targ_type)
4831 return -EINVAL;
4832 if (!btf_is_composite(targ_type))
4833 return 0;
4834
4835 local_id = local_acc->type_id;
4836 local_type = btf__type_by_id(local_btf, local_id);
4837 local_member = btf_members(local_type) + local_acc->idx;
4838 local_name = btf__name_by_offset(local_btf, local_member->name_off);
4839
4840 n = btf_vlen(targ_type);
4841 m = btf_members(targ_type);
4842 for (i = 0; i < n; i++, m++) {
Olivier Deprez157378f2022-04-04 15:47:50 +02004843 __u32 bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004844
Olivier Deprez157378f2022-04-04 15:47:50 +02004845 bit_offset = btf_member_bit_offset(targ_type, i);
David Brazdil0f672f62019-12-10 10:32:29 +00004846
4847 /* too deep struct/union/array nesting */
4848 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
4849 return -E2BIG;
4850
4851 /* speculate this member will be the good one */
Olivier Deprez157378f2022-04-04 15:47:50 +02004852 spec->bit_offset += bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004853 spec->raw_spec[spec->raw_len++] = i;
4854
4855 targ_name = btf__name_by_offset(targ_btf, m->name_off);
4856 if (str_is_empty(targ_name)) {
4857 /* embedded struct/union, we need to go deeper */
4858 found = bpf_core_match_member(local_btf, local_acc,
4859 targ_btf, m->type,
4860 spec, next_targ_id);
4861 if (found) /* either found or error */
4862 return found;
4863 } else if (strcmp(local_name, targ_name) == 0) {
4864 /* matching named field */
4865 struct bpf_core_accessor *targ_acc;
4866
4867 targ_acc = &spec->spec[spec->len++];
4868 targ_acc->type_id = targ_id;
4869 targ_acc->idx = i;
4870 targ_acc->name = targ_name;
4871
4872 *next_targ_id = m->type;
4873 found = bpf_core_fields_are_compat(local_btf,
4874 local_member->type,
4875 targ_btf, m->type);
4876 if (!found)
4877 spec->len--; /* pop accessor */
4878 return found;
4879 }
4880 /* member turned out not to be what we looked for */
Olivier Deprez157378f2022-04-04 15:47:50 +02004881 spec->bit_offset -= bit_offset;
David Brazdil0f672f62019-12-10 10:32:29 +00004882 spec->raw_len--;
4883 }
4884
4885 return 0;
4886}
4887
Olivier Deprez157378f2022-04-04 15:47:50 +02004888/* Check local and target types for compatibility. This check is used for
4889 * type-based CO-RE relocations and follow slightly different rules than
4890 * field-based relocations. This function assumes that root types were already
4891 * checked for name match. Beyond that initial root-level name check, names
4892 * are completely ignored. Compatibility rules are as follows:
4893 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
4894 * kind should match for local and target types (i.e., STRUCT is not
4895 * compatible with UNION);
4896 * - for ENUMs, the size is ignored;
4897 * - for INT, size and signedness are ignored;
4898 * - for ARRAY, dimensionality is ignored, element types are checked for
4899 * compatibility recursively;
4900 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
4901 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
4902 * - FUNC_PROTOs are compatible if they have compatible signature: same
4903 * number of input args and compatible return and argument types.
4904 * These rules are not set in stone and probably will be adjusted as we get
4905 * more experience with using BPF CO-RE relocations.
4906 */
4907static int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
4908 const struct btf *targ_btf, __u32 targ_id)
4909{
4910 const struct btf_type *local_type, *targ_type;
4911 int depth = 32; /* max recursion depth */
4912
4913 /* caller made sure that names match (ignoring flavor suffix) */
4914 local_type = btf__type_by_id(local_btf, local_id);
4915 targ_type = btf__type_by_id(targ_btf, targ_id);
4916 if (btf_kind(local_type) != btf_kind(targ_type))
4917 return 0;
4918
4919recur:
4920 depth--;
4921 if (depth < 0)
4922 return -EINVAL;
4923
4924 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
4925 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
4926 if (!local_type || !targ_type)
4927 return -EINVAL;
4928
4929 if (btf_kind(local_type) != btf_kind(targ_type))
4930 return 0;
4931
4932 switch (btf_kind(local_type)) {
4933 case BTF_KIND_UNKN:
4934 case BTF_KIND_STRUCT:
4935 case BTF_KIND_UNION:
4936 case BTF_KIND_ENUM:
4937 case BTF_KIND_FWD:
4938 return 1;
4939 case BTF_KIND_INT:
4940 /* just reject deprecated bitfield-like integers; all other
4941 * integers are by default compatible between each other
4942 */
4943 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
4944 case BTF_KIND_PTR:
4945 local_id = local_type->type;
4946 targ_id = targ_type->type;
4947 goto recur;
4948 case BTF_KIND_ARRAY:
4949 local_id = btf_array(local_type)->type;
4950 targ_id = btf_array(targ_type)->type;
4951 goto recur;
4952 case BTF_KIND_FUNC_PROTO: {
4953 struct btf_param *local_p = btf_params(local_type);
4954 struct btf_param *targ_p = btf_params(targ_type);
4955 __u16 local_vlen = btf_vlen(local_type);
4956 __u16 targ_vlen = btf_vlen(targ_type);
4957 int i, err;
4958
4959 if (local_vlen != targ_vlen)
4960 return 0;
4961
4962 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
4963 skip_mods_and_typedefs(local_btf, local_p->type, &local_id);
4964 skip_mods_and_typedefs(targ_btf, targ_p->type, &targ_id);
4965 err = bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id);
4966 if (err <= 0)
4967 return err;
4968 }
4969
4970 /* tail recurse for return type check */
4971 skip_mods_and_typedefs(local_btf, local_type->type, &local_id);
4972 skip_mods_and_typedefs(targ_btf, targ_type->type, &targ_id);
4973 goto recur;
4974 }
4975 default:
4976 pr_warn("unexpected kind %s relocated, local [%d], target [%d]\n",
4977 btf_kind_str(local_type), local_id, targ_id);
4978 return 0;
4979 }
4980}
4981
David Brazdil0f672f62019-12-10 10:32:29 +00004982/*
4983 * Try to match local spec to a target type and, if successful, produce full
Olivier Deprez157378f2022-04-04 15:47:50 +02004984 * target spec (high-level, low-level + bit offset).
David Brazdil0f672f62019-12-10 10:32:29 +00004985 */
4986static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
4987 const struct btf *targ_btf, __u32 targ_id,
4988 struct bpf_core_spec *targ_spec)
4989{
4990 const struct btf_type *targ_type;
4991 const struct bpf_core_accessor *local_acc;
4992 struct bpf_core_accessor *targ_acc;
4993 int i, sz, matched;
4994
4995 memset(targ_spec, 0, sizeof(*targ_spec));
4996 targ_spec->btf = targ_btf;
Olivier Deprez157378f2022-04-04 15:47:50 +02004997 targ_spec->root_type_id = targ_id;
4998 targ_spec->relo_kind = local_spec->relo_kind;
4999
5000 if (core_relo_is_type_based(local_spec->relo_kind)) {
5001 return bpf_core_types_are_compat(local_spec->btf,
5002 local_spec->root_type_id,
5003 targ_btf, targ_id);
5004 }
David Brazdil0f672f62019-12-10 10:32:29 +00005005
5006 local_acc = &local_spec->spec[0];
5007 targ_acc = &targ_spec->spec[0];
5008
Olivier Deprez157378f2022-04-04 15:47:50 +02005009 if (core_relo_is_enumval_based(local_spec->relo_kind)) {
5010 size_t local_essent_len, targ_essent_len;
5011 const struct btf_enum *e;
5012 const char *targ_name;
5013
5014 /* has to resolve to an enum */
5015 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id, &targ_id);
5016 if (!btf_is_enum(targ_type))
5017 return 0;
5018
5019 local_essent_len = bpf_core_essential_name_len(local_acc->name);
5020
5021 for (i = 0, e = btf_enum(targ_type); i < btf_vlen(targ_type); i++, e++) {
5022 targ_name = btf__name_by_offset(targ_spec->btf, e->name_off);
5023 targ_essent_len = bpf_core_essential_name_len(targ_name);
5024 if (targ_essent_len != local_essent_len)
5025 continue;
5026 if (strncmp(local_acc->name, targ_name, local_essent_len) == 0) {
5027 targ_acc->type_id = targ_id;
5028 targ_acc->idx = i;
5029 targ_acc->name = targ_name;
5030 targ_spec->len++;
5031 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
5032 targ_spec->raw_len++;
5033 return 1;
5034 }
5035 }
5036 return 0;
5037 }
5038
5039 if (!core_relo_is_field_based(local_spec->relo_kind))
5040 return -EINVAL;
5041
David Brazdil0f672f62019-12-10 10:32:29 +00005042 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
5043 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
5044 &targ_id);
5045 if (!targ_type)
5046 return -EINVAL;
5047
5048 if (local_acc->name) {
5049 matched = bpf_core_match_member(local_spec->btf,
5050 local_acc,
5051 targ_btf, targ_id,
5052 targ_spec, &targ_id);
5053 if (matched <= 0)
5054 return matched;
5055 } else {
5056 /* for i=0, targ_id is already treated as array element
5057 * type (because it's the original struct), for others
5058 * we should find array element type first
5059 */
5060 if (i > 0) {
5061 const struct btf_array *a;
Olivier Deprez157378f2022-04-04 15:47:50 +02005062 bool flex;
David Brazdil0f672f62019-12-10 10:32:29 +00005063
5064 if (!btf_is_array(targ_type))
5065 return 0;
5066
5067 a = btf_array(targ_type);
Olivier Deprez157378f2022-04-04 15:47:50 +02005068 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
5069 if (!flex && local_acc->idx >= a->nelems)
David Brazdil0f672f62019-12-10 10:32:29 +00005070 return 0;
5071 if (!skip_mods_and_typedefs(targ_btf, a->type,
5072 &targ_id))
5073 return -EINVAL;
5074 }
5075
5076 /* too deep struct/union/array nesting */
5077 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
5078 return -E2BIG;
5079
5080 targ_acc->type_id = targ_id;
5081 targ_acc->idx = local_acc->idx;
5082 targ_acc->name = NULL;
5083 targ_spec->len++;
5084 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
5085 targ_spec->raw_len++;
5086
5087 sz = btf__resolve_size(targ_btf, targ_id);
5088 if (sz < 0)
5089 return sz;
Olivier Deprez157378f2022-04-04 15:47:50 +02005090 targ_spec->bit_offset += local_acc->idx * sz * 8;
David Brazdil0f672f62019-12-10 10:32:29 +00005091 }
5092 }
5093
5094 return 1;
5095}
5096
Olivier Deprez157378f2022-04-04 15:47:50 +02005097static int bpf_core_calc_field_relo(const struct bpf_program *prog,
5098 const struct bpf_core_relo *relo,
5099 const struct bpf_core_spec *spec,
5100 __u32 *val, __u32 *field_sz, __u32 *type_id,
5101 bool *validate)
5102{
5103 const struct bpf_core_accessor *acc;
5104 const struct btf_type *t;
5105 __u32 byte_off, byte_sz, bit_off, bit_sz, field_type_id;
5106 const struct btf_member *m;
5107 const struct btf_type *mt;
5108 bool bitfield;
5109 __s64 sz;
5110
5111 *field_sz = 0;
5112
5113 if (relo->kind == BPF_FIELD_EXISTS) {
5114 *val = spec ? 1 : 0;
5115 return 0;
5116 }
5117
5118 if (!spec)
5119 return -EUCLEAN; /* request instruction poisoning */
5120
5121 acc = &spec->spec[spec->len - 1];
5122 t = btf__type_by_id(spec->btf, acc->type_id);
5123
5124 /* a[n] accessor needs special handling */
5125 if (!acc->name) {
5126 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
5127 *val = spec->bit_offset / 8;
5128 /* remember field size for load/store mem size */
5129 sz = btf__resolve_size(spec->btf, acc->type_id);
5130 if (sz < 0)
5131 return -EINVAL;
5132 *field_sz = sz;
5133 *type_id = acc->type_id;
5134 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
5135 sz = btf__resolve_size(spec->btf, acc->type_id);
5136 if (sz < 0)
5137 return -EINVAL;
5138 *val = sz;
5139 } else {
5140 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
5141 prog->name, relo->kind, relo->insn_off / 8);
5142 return -EINVAL;
5143 }
5144 if (validate)
5145 *validate = true;
5146 return 0;
5147 }
5148
5149 m = btf_members(t) + acc->idx;
5150 mt = skip_mods_and_typedefs(spec->btf, m->type, &field_type_id);
5151 bit_off = spec->bit_offset;
5152 bit_sz = btf_member_bitfield_size(t, acc->idx);
5153
5154 bitfield = bit_sz > 0;
5155 if (bitfield) {
5156 byte_sz = mt->size;
5157 byte_off = bit_off / 8 / byte_sz * byte_sz;
5158 /* figure out smallest int size necessary for bitfield load */
5159 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
5160 if (byte_sz >= 8) {
5161 /* bitfield can't be read with 64-bit read */
5162 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
5163 prog->name, relo->kind, relo->insn_off / 8);
5164 return -E2BIG;
5165 }
5166 byte_sz *= 2;
5167 byte_off = bit_off / 8 / byte_sz * byte_sz;
5168 }
5169 } else {
5170 sz = btf__resolve_size(spec->btf, field_type_id);
5171 if (sz < 0)
5172 return -EINVAL;
5173 byte_sz = sz;
5174 byte_off = spec->bit_offset / 8;
5175 bit_sz = byte_sz * 8;
5176 }
5177
5178 /* for bitfields, all the relocatable aspects are ambiguous and we
5179 * might disagree with compiler, so turn off validation of expected
5180 * value, except for signedness
5181 */
5182 if (validate)
5183 *validate = !bitfield;
5184
5185 switch (relo->kind) {
5186 case BPF_FIELD_BYTE_OFFSET:
5187 *val = byte_off;
5188 if (!bitfield) {
5189 *field_sz = byte_sz;
5190 *type_id = field_type_id;
5191 }
5192 break;
5193 case BPF_FIELD_BYTE_SIZE:
5194 *val = byte_sz;
5195 break;
5196 case BPF_FIELD_SIGNED:
5197 /* enums will be assumed unsigned */
5198 *val = btf_is_enum(mt) ||
5199 (btf_int_encoding(mt) & BTF_INT_SIGNED);
5200 if (validate)
5201 *validate = true; /* signedness is never ambiguous */
5202 break;
5203 case BPF_FIELD_LSHIFT_U64:
5204#if __BYTE_ORDER == __LITTLE_ENDIAN
5205 *val = 64 - (bit_off + bit_sz - byte_off * 8);
5206#else
5207 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
5208#endif
5209 break;
5210 case BPF_FIELD_RSHIFT_U64:
5211 *val = 64 - bit_sz;
5212 if (validate)
5213 *validate = true; /* right shift is never ambiguous */
5214 break;
5215 case BPF_FIELD_EXISTS:
5216 default:
5217 return -EOPNOTSUPP;
5218 }
5219
5220 return 0;
5221}
5222
5223static int bpf_core_calc_type_relo(const struct bpf_core_relo *relo,
5224 const struct bpf_core_spec *spec,
5225 __u32 *val)
5226{
5227 __s64 sz;
5228
5229 /* type-based relos return zero when target type is not found */
5230 if (!spec) {
5231 *val = 0;
5232 return 0;
5233 }
5234
5235 switch (relo->kind) {
5236 case BPF_TYPE_ID_TARGET:
5237 *val = spec->root_type_id;
5238 break;
5239 case BPF_TYPE_EXISTS:
5240 *val = 1;
5241 break;
5242 case BPF_TYPE_SIZE:
5243 sz = btf__resolve_size(spec->btf, spec->root_type_id);
5244 if (sz < 0)
5245 return -EINVAL;
5246 *val = sz;
5247 break;
5248 case BPF_TYPE_ID_LOCAL:
5249 /* BPF_TYPE_ID_LOCAL is handled specially and shouldn't get here */
5250 default:
5251 return -EOPNOTSUPP;
5252 }
5253
5254 return 0;
5255}
5256
5257static int bpf_core_calc_enumval_relo(const struct bpf_core_relo *relo,
5258 const struct bpf_core_spec *spec,
5259 __u32 *val)
5260{
5261 const struct btf_type *t;
5262 const struct btf_enum *e;
5263
5264 switch (relo->kind) {
5265 case BPF_ENUMVAL_EXISTS:
5266 *val = spec ? 1 : 0;
5267 break;
5268 case BPF_ENUMVAL_VALUE:
5269 if (!spec)
5270 return -EUCLEAN; /* request instruction poisoning */
5271 t = btf__type_by_id(spec->btf, spec->spec[0].type_id);
5272 e = btf_enum(t) + spec->spec[0].idx;
5273 *val = e->val;
5274 break;
5275 default:
5276 return -EOPNOTSUPP;
5277 }
5278
5279 return 0;
5280}
5281
5282struct bpf_core_relo_res
5283{
5284 /* expected value in the instruction, unless validate == false */
5285 __u32 orig_val;
5286 /* new value that needs to be patched up to */
5287 __u32 new_val;
5288 /* relocation unsuccessful, poison instruction, but don't fail load */
5289 bool poison;
5290 /* some relocations can't be validated against orig_val */
5291 bool validate;
5292 /* for field byte offset relocations or the forms:
5293 * *(T *)(rX + <off>) = rY
5294 * rX = *(T *)(rY + <off>),
5295 * we remember original and resolved field size to adjust direct
5296 * memory loads of pointers and integers; this is necessary for 32-bit
5297 * host kernel architectures, but also allows to automatically
5298 * relocate fields that were resized from, e.g., u32 to u64, etc.
5299 */
5300 bool fail_memsz_adjust;
5301 __u32 orig_sz;
5302 __u32 orig_type_id;
5303 __u32 new_sz;
5304 __u32 new_type_id;
5305};
5306
5307/* Calculate original and target relocation values, given local and target
5308 * specs and relocation kind. These values are calculated for each candidate.
5309 * If there are multiple candidates, resulting values should all be consistent
5310 * with each other. Otherwise, libbpf will refuse to proceed due to ambiguity.
5311 * If instruction has to be poisoned, *poison will be set to true.
5312 */
5313static int bpf_core_calc_relo(const struct bpf_program *prog,
5314 const struct bpf_core_relo *relo,
5315 int relo_idx,
5316 const struct bpf_core_spec *local_spec,
5317 const struct bpf_core_spec *targ_spec,
5318 struct bpf_core_relo_res *res)
5319{
5320 int err = -EOPNOTSUPP;
5321
5322 res->orig_val = 0;
5323 res->new_val = 0;
5324 res->poison = false;
5325 res->validate = true;
5326 res->fail_memsz_adjust = false;
5327 res->orig_sz = res->new_sz = 0;
5328 res->orig_type_id = res->new_type_id = 0;
5329
5330 if (core_relo_is_field_based(relo->kind)) {
5331 err = bpf_core_calc_field_relo(prog, relo, local_spec,
5332 &res->orig_val, &res->orig_sz,
5333 &res->orig_type_id, &res->validate);
5334 err = err ?: bpf_core_calc_field_relo(prog, relo, targ_spec,
5335 &res->new_val, &res->new_sz,
5336 &res->new_type_id, NULL);
5337 if (err)
5338 goto done;
5339 /* Validate if it's safe to adjust load/store memory size.
5340 * Adjustments are performed only if original and new memory
5341 * sizes differ.
5342 */
5343 res->fail_memsz_adjust = false;
5344 if (res->orig_sz != res->new_sz) {
5345 const struct btf_type *orig_t, *new_t;
5346
5347 orig_t = btf__type_by_id(local_spec->btf, res->orig_type_id);
5348 new_t = btf__type_by_id(targ_spec->btf, res->new_type_id);
5349
5350 /* There are two use cases in which it's safe to
5351 * adjust load/store's mem size:
5352 * - reading a 32-bit kernel pointer, while on BPF
5353 * size pointers are always 64-bit; in this case
5354 * it's safe to "downsize" instruction size due to
5355 * pointer being treated as unsigned integer with
5356 * zero-extended upper 32-bits;
5357 * - reading unsigned integers, again due to
5358 * zero-extension is preserving the value correctly.
5359 *
5360 * In all other cases it's incorrect to attempt to
5361 * load/store field because read value will be
5362 * incorrect, so we poison relocated instruction.
5363 */
5364 if (btf_is_ptr(orig_t) && btf_is_ptr(new_t))
5365 goto done;
5366 if (btf_is_int(orig_t) && btf_is_int(new_t) &&
5367 btf_int_encoding(orig_t) != BTF_INT_SIGNED &&
5368 btf_int_encoding(new_t) != BTF_INT_SIGNED)
5369 goto done;
5370
5371 /* mark as invalid mem size adjustment, but this will
5372 * only be checked for LDX/STX/ST insns
5373 */
5374 res->fail_memsz_adjust = true;
5375 }
5376 } else if (core_relo_is_type_based(relo->kind)) {
5377 err = bpf_core_calc_type_relo(relo, local_spec, &res->orig_val);
5378 err = err ?: bpf_core_calc_type_relo(relo, targ_spec, &res->new_val);
5379 } else if (core_relo_is_enumval_based(relo->kind)) {
5380 err = bpf_core_calc_enumval_relo(relo, local_spec, &res->orig_val);
5381 err = err ?: bpf_core_calc_enumval_relo(relo, targ_spec, &res->new_val);
5382 }
5383
5384done:
5385 if (err == -EUCLEAN) {
5386 /* EUCLEAN is used to signal instruction poisoning request */
5387 res->poison = true;
5388 err = 0;
5389 } else if (err == -EOPNOTSUPP) {
5390 /* EOPNOTSUPP means unknown/unsupported relocation */
5391 pr_warn("prog '%s': relo #%d: unrecognized CO-RE relocation %s (%d) at insn #%d\n",
5392 prog->name, relo_idx, core_relo_kind_str(relo->kind),
5393 relo->kind, relo->insn_off / 8);
5394 }
5395
5396 return err;
5397}
5398
5399/*
5400 * Turn instruction for which CO_RE relocation failed into invalid one with
5401 * distinct signature.
5402 */
5403static void bpf_core_poison_insn(struct bpf_program *prog, int relo_idx,
5404 int insn_idx, struct bpf_insn *insn)
5405{
5406 pr_debug("prog '%s': relo #%d: substituting insn #%d w/ invalid insn\n",
5407 prog->name, relo_idx, insn_idx);
5408 insn->code = BPF_JMP | BPF_CALL;
5409 insn->dst_reg = 0;
5410 insn->src_reg = 0;
5411 insn->off = 0;
5412 /* if this instruction is reachable (not a dead code),
5413 * verifier will complain with the following message:
5414 * invalid func unknown#195896080
5415 */
5416 insn->imm = 195896080; /* => 0xbad2310 => "bad relo" */
5417}
5418
5419static bool is_ldimm64(struct bpf_insn *insn)
5420{
5421 return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
5422}
5423
5424static int insn_bpf_size_to_bytes(struct bpf_insn *insn)
5425{
5426 switch (BPF_SIZE(insn->code)) {
5427 case BPF_DW: return 8;
5428 case BPF_W: return 4;
5429 case BPF_H: return 2;
5430 case BPF_B: return 1;
5431 default: return -1;
5432 }
5433}
5434
5435static int insn_bytes_to_bpf_size(__u32 sz)
5436{
5437 switch (sz) {
5438 case 8: return BPF_DW;
5439 case 4: return BPF_W;
5440 case 2: return BPF_H;
5441 case 1: return BPF_B;
5442 default: return -1;
5443 }
5444}
5445
David Brazdil0f672f62019-12-10 10:32:29 +00005446/*
5447 * Patch relocatable BPF instruction.
David Brazdil0f672f62019-12-10 10:32:29 +00005448 *
Olivier Deprez157378f2022-04-04 15:47:50 +02005449 * Patched value is determined by relocation kind and target specification.
5450 * For existence relocations target spec will be NULL if field/type is not found.
5451 * Expected insn->imm value is determined using relocation kind and local
5452 * spec, and is checked before patching instruction. If actual insn->imm value
5453 * is wrong, bail out with error.
5454 *
5455 * Currently supported classes of BPF instruction are:
David Brazdil0f672f62019-12-10 10:32:29 +00005456 * 1. rX = <imm> (assignment with immediate operand);
5457 * 2. rX += <imm> (arithmetic operations with immediate operand);
Olivier Deprez157378f2022-04-04 15:47:50 +02005458 * 3. rX = <imm64> (load with 64-bit immediate value);
5459 * 4. rX = *(T *)(rY + <off>), where T is one of {u8, u16, u32, u64};
5460 * 5. *(T *)(rX + <off>) = rY, where T is one of {u8, u16, u32, u64};
5461 * 6. *(T *)(rX + <off>) = <imm>, where T is one of {u8, u16, u32, u64}.
David Brazdil0f672f62019-12-10 10:32:29 +00005462 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005463static int bpf_core_patch_insn(struct bpf_program *prog,
5464 const struct bpf_core_relo *relo,
5465 int relo_idx,
5466 const struct bpf_core_relo_res *res)
David Brazdil0f672f62019-12-10 10:32:29 +00005467{
Olivier Deprez157378f2022-04-04 15:47:50 +02005468 __u32 orig_val, new_val;
David Brazdil0f672f62019-12-10 10:32:29 +00005469 struct bpf_insn *insn;
5470 int insn_idx;
5471 __u8 class;
5472
Olivier Deprez157378f2022-04-04 15:47:50 +02005473 if (relo->insn_off % BPF_INSN_SZ)
David Brazdil0f672f62019-12-10 10:32:29 +00005474 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005475 insn_idx = relo->insn_off / BPF_INSN_SZ;
5476 /* adjust insn_idx from section frame of reference to the local
5477 * program's frame of reference; (sub-)program code is not yet
5478 * relocated, so it's enough to just subtract in-section offset
5479 */
5480 insn_idx = insn_idx - prog->sec_insn_off;
David Brazdil0f672f62019-12-10 10:32:29 +00005481 insn = &prog->insns[insn_idx];
5482 class = BPF_CLASS(insn->code);
5483
Olivier Deprez157378f2022-04-04 15:47:50 +02005484 if (res->poison) {
5485poison:
5486 /* poison second part of ldimm64 to avoid confusing error from
5487 * verifier about "unknown opcode 00"
5488 */
5489 if (is_ldimm64(insn))
5490 bpf_core_poison_insn(prog, relo_idx, insn_idx + 1, insn + 1);
5491 bpf_core_poison_insn(prog, relo_idx, insn_idx, insn);
5492 return 0;
5493 }
5494
5495 orig_val = res->orig_val;
5496 new_val = res->new_val;
5497
5498 switch (class) {
5499 case BPF_ALU:
5500 case BPF_ALU64:
David Brazdil0f672f62019-12-10 10:32:29 +00005501 if (BPF_SRC(insn->code) != BPF_K)
5502 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005503 if (res->validate && insn->imm != orig_val) {
5504 pr_warn("prog '%s': relo #%d: unexpected insn #%d (ALU/ALU64) value: got %u, exp %u -> %u\n",
5505 prog->name, relo_idx,
5506 insn_idx, insn->imm, orig_val, new_val);
David Brazdil0f672f62019-12-10 10:32:29 +00005507 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02005508 }
5509 orig_val = insn->imm;
5510 insn->imm = new_val;
5511 pr_debug("prog '%s': relo #%d: patched insn #%d (ALU/ALU64) imm %u -> %u\n",
5512 prog->name, relo_idx, insn_idx,
5513 orig_val, new_val);
5514 break;
5515 case BPF_LDX:
5516 case BPF_ST:
5517 case BPF_STX:
5518 if (res->validate && insn->off != orig_val) {
5519 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDX/ST/STX) value: got %u, exp %u -> %u\n",
5520 prog->name, relo_idx, insn_idx, insn->off, orig_val, new_val);
5521 return -EINVAL;
5522 }
5523 if (new_val > SHRT_MAX) {
5524 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) value too big: %u\n",
5525 prog->name, relo_idx, insn_idx, new_val);
5526 return -ERANGE;
5527 }
5528 if (res->fail_memsz_adjust) {
5529 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) accesses field incorrectly. "
5530 "Make sure you are accessing pointers, unsigned integers, or fields of matching type and size.\n",
5531 prog->name, relo_idx, insn_idx);
5532 goto poison;
5533 }
5534
5535 orig_val = insn->off;
5536 insn->off = new_val;
5537 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) off %u -> %u\n",
5538 prog->name, relo_idx, insn_idx, orig_val, new_val);
5539
5540 if (res->new_sz != res->orig_sz) {
5541 int insn_bytes_sz, insn_bpf_sz;
5542
5543 insn_bytes_sz = insn_bpf_size_to_bytes(insn);
5544 if (insn_bytes_sz != res->orig_sz) {
5545 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) unexpected mem size: got %d, exp %u\n",
5546 prog->name, relo_idx, insn_idx, insn_bytes_sz, res->orig_sz);
5547 return -EINVAL;
5548 }
5549
5550 insn_bpf_sz = insn_bytes_to_bpf_size(res->new_sz);
5551 if (insn_bpf_sz < 0) {
5552 pr_warn("prog '%s': relo #%d: insn #%d (LDX/ST/STX) invalid new mem size: %u\n",
5553 prog->name, relo_idx, insn_idx, res->new_sz);
5554 return -EINVAL;
5555 }
5556
5557 insn->code = BPF_MODE(insn->code) | insn_bpf_sz | BPF_CLASS(insn->code);
5558 pr_debug("prog '%s': relo #%d: patched insn #%d (LDX/ST/STX) mem_sz %u -> %u\n",
5559 prog->name, relo_idx, insn_idx, res->orig_sz, res->new_sz);
5560 }
5561 break;
5562 case BPF_LD: {
5563 __u64 imm;
5564
5565 if (!is_ldimm64(insn) ||
5566 insn[0].src_reg != 0 || insn[0].off != 0 ||
5567 insn_idx + 1 >= prog->insns_cnt ||
5568 insn[1].code != 0 || insn[1].dst_reg != 0 ||
5569 insn[1].src_reg != 0 || insn[1].off != 0) {
5570 pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) has unexpected form\n",
5571 prog->name, relo_idx, insn_idx);
5572 return -EINVAL;
5573 }
5574
5575 imm = insn[0].imm + ((__u64)insn[1].imm << 32);
5576 if (res->validate && imm != orig_val) {
5577 pr_warn("prog '%s': relo #%d: unexpected insn #%d (LDIMM64) value: got %llu, exp %u -> %u\n",
5578 prog->name, relo_idx,
5579 insn_idx, (unsigned long long)imm,
5580 orig_val, new_val);
5581 return -EINVAL;
5582 }
5583
5584 insn[0].imm = new_val;
5585 insn[1].imm = 0; /* currently only 32-bit values are supported */
5586 pr_debug("prog '%s': relo #%d: patched insn #%d (LDIMM64) imm64 %llu -> %u\n",
5587 prog->name, relo_idx, insn_idx,
5588 (unsigned long long)imm, new_val);
5589 break;
5590 }
5591 default:
5592 pr_warn("prog '%s': relo #%d: trying to relocate unrecognized insn #%d, code:0x%x, src:0x%x, dst:0x%x, off:0x%x, imm:0x%x\n",
5593 prog->name, relo_idx, insn_idx, insn->code,
5594 insn->src_reg, insn->dst_reg, insn->off, insn->imm);
David Brazdil0f672f62019-12-10 10:32:29 +00005595 return -EINVAL;
5596 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005597
David Brazdil0f672f62019-12-10 10:32:29 +00005598 return 0;
5599}
5600
David Brazdil0f672f62019-12-10 10:32:29 +00005601/* Output spec definition in the format:
5602 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
5603 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
5604 */
5605static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
5606{
5607 const struct btf_type *t;
Olivier Deprez157378f2022-04-04 15:47:50 +02005608 const struct btf_enum *e;
David Brazdil0f672f62019-12-10 10:32:29 +00005609 const char *s;
5610 __u32 type_id;
5611 int i;
5612
Olivier Deprez157378f2022-04-04 15:47:50 +02005613 type_id = spec->root_type_id;
David Brazdil0f672f62019-12-10 10:32:29 +00005614 t = btf__type_by_id(spec->btf, type_id);
5615 s = btf__name_by_offset(spec->btf, t->name_off);
David Brazdil0f672f62019-12-10 10:32:29 +00005616
Olivier Deprez157378f2022-04-04 15:47:50 +02005617 libbpf_print(level, "[%u] %s %s", type_id, btf_kind_str(t), str_is_empty(s) ? "<anon>" : s);
David Brazdil0f672f62019-12-10 10:32:29 +00005618
Olivier Deprez157378f2022-04-04 15:47:50 +02005619 if (core_relo_is_type_based(spec->relo_kind))
5620 return;
David Brazdil0f672f62019-12-10 10:32:29 +00005621
Olivier Deprez157378f2022-04-04 15:47:50 +02005622 if (core_relo_is_enumval_based(spec->relo_kind)) {
5623 t = skip_mods_and_typedefs(spec->btf, type_id, NULL);
5624 e = btf_enum(t) + spec->raw_spec[0];
5625 s = btf__name_by_offset(spec->btf, e->name_off);
5626
5627 libbpf_print(level, "::%s = %u", s, e->val);
5628 return;
David Brazdil0f672f62019-12-10 10:32:29 +00005629 }
5630
Olivier Deprez157378f2022-04-04 15:47:50 +02005631 if (core_relo_is_field_based(spec->relo_kind)) {
5632 for (i = 0; i < spec->len; i++) {
5633 if (spec->spec[i].name)
5634 libbpf_print(level, ".%s", spec->spec[i].name);
5635 else if (i > 0 || spec->spec[i].idx > 0)
5636 libbpf_print(level, "[%u]", spec->spec[i].idx);
5637 }
5638
5639 libbpf_print(level, " (");
5640 for (i = 0; i < spec->raw_len; i++)
5641 libbpf_print(level, "%s%d", i == 0 ? "" : ":", spec->raw_spec[i]);
5642
5643 if (spec->bit_offset % 8)
5644 libbpf_print(level, " @ offset %u.%u)",
5645 spec->bit_offset / 8, spec->bit_offset % 8);
5646 else
5647 libbpf_print(level, " @ offset %u)", spec->bit_offset / 8);
5648 return;
5649 }
David Brazdil0f672f62019-12-10 10:32:29 +00005650}
5651
5652static size_t bpf_core_hash_fn(const void *key, void *ctx)
5653{
5654 return (size_t)key;
5655}
5656
5657static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5658{
5659 return k1 == k2;
5660}
5661
5662static void *u32_as_hash_key(__u32 x)
5663{
5664 return (void *)(uintptr_t)x;
5665}
5666
5667/*
5668 * CO-RE relocate single instruction.
5669 *
5670 * The outline and important points of the algorithm:
5671 * 1. For given local type, find corresponding candidate target types.
5672 * Candidate type is a type with the same "essential" name, ignoring
5673 * everything after last triple underscore (___). E.g., `sample`,
5674 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
5675 * for each other. Names with triple underscore are referred to as
5676 * "flavors" and are useful, among other things, to allow to
5677 * specify/support incompatible variations of the same kernel struct, which
5678 * might differ between different kernel versions and/or build
5679 * configurations.
5680 *
5681 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
5682 * converter, when deduplicated BTF of a kernel still contains more than
5683 * one different types with the same name. In that case, ___2, ___3, etc
5684 * are appended starting from second name conflict. But start flavors are
5685 * also useful to be defined "locally", in BPF program, to extract same
5686 * data from incompatible changes between different kernel
5687 * versions/configurations. For instance, to handle field renames between
5688 * kernel versions, one can use two flavors of the struct name with the
5689 * same common name and use conditional relocations to extract that field,
5690 * depending on target kernel version.
5691 * 2. For each candidate type, try to match local specification to this
5692 * candidate target type. Matching involves finding corresponding
5693 * high-level spec accessors, meaning that all named fields should match,
5694 * as well as all array accesses should be within the actual bounds. Also,
5695 * types should be compatible (see bpf_core_fields_are_compat for details).
5696 * 3. It is supported and expected that there might be multiple flavors
5697 * matching the spec. As long as all the specs resolve to the same set of
Olivier Deprez157378f2022-04-04 15:47:50 +02005698 * offsets across all candidates, there is no error. If there is any
David Brazdil0f672f62019-12-10 10:32:29 +00005699 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
5700 * imprefection of BTF deduplication, which can cause slight duplication of
5701 * the same BTF type, if some directly or indirectly referenced (by
5702 * pointer) type gets resolved to different actual types in different
5703 * object files. If such situation occurs, deduplicated BTF will end up
5704 * with two (or more) structurally identical types, which differ only in
5705 * types they refer to through pointer. This should be OK in most cases and
5706 * is not an error.
5707 * 4. Candidate types search is performed by linearly scanning through all
5708 * types in target BTF. It is anticipated that this is overall more
5709 * efficient memory-wise and not significantly worse (if not better)
5710 * CPU-wise compared to prebuilding a map from all local type names to
5711 * a list of candidate type names. It's also sped up by caching resolved
5712 * list of matching candidates per each local "root" type ID, that has at
Olivier Deprez157378f2022-04-04 15:47:50 +02005713 * least one bpf_core_relo associated with it. This list is shared
David Brazdil0f672f62019-12-10 10:32:29 +00005714 * between multiple relocations for the same type ID and is updated as some
5715 * of the candidates are pruned due to structural incompatibility.
5716 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005717static int bpf_core_apply_relo(struct bpf_program *prog,
5718 const struct bpf_core_relo *relo,
5719 int relo_idx,
5720 const struct btf *local_btf,
5721 const struct btf *targ_btf,
5722 struct hashmap *cand_cache)
David Brazdil0f672f62019-12-10 10:32:29 +00005723{
Olivier Deprez157378f2022-04-04 15:47:50 +02005724 struct bpf_core_spec local_spec, cand_spec, targ_spec = {};
David Brazdil0f672f62019-12-10 10:32:29 +00005725 const void *type_key = u32_as_hash_key(relo->type_id);
Olivier Deprez157378f2022-04-04 15:47:50 +02005726 struct bpf_core_relo_res cand_res, targ_res;
5727 const struct btf_type *local_type;
5728 const char *local_name;
David Brazdil0f672f62019-12-10 10:32:29 +00005729 struct ids_vec *cand_ids;
5730 __u32 local_id, cand_id;
5731 const char *spec_str;
5732 int i, j, err;
5733
5734 local_id = relo->type_id;
5735 local_type = btf__type_by_id(local_btf, local_id);
5736 if (!local_type)
5737 return -EINVAL;
5738
5739 local_name = btf__name_by_offset(local_btf, local_type->name_off);
Olivier Deprez157378f2022-04-04 15:47:50 +02005740 if (!local_name)
David Brazdil0f672f62019-12-10 10:32:29 +00005741 return -EINVAL;
5742
5743 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
5744 if (str_is_empty(spec_str))
5745 return -EINVAL;
5746
Olivier Deprez157378f2022-04-04 15:47:50 +02005747 err = bpf_core_parse_spec(local_btf, local_id, spec_str, relo->kind, &local_spec);
David Brazdil0f672f62019-12-10 10:32:29 +00005748 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005749 pr_warn("prog '%s': relo #%d: parsing [%d] %s %s + %s failed: %d\n",
5750 prog->name, relo_idx, local_id, btf_kind_str(local_type),
5751 str_is_empty(local_name) ? "<anon>" : local_name,
5752 spec_str, err);
David Brazdil0f672f62019-12-10 10:32:29 +00005753 return -EINVAL;
5754 }
5755
Olivier Deprez157378f2022-04-04 15:47:50 +02005756 pr_debug("prog '%s': relo #%d: kind <%s> (%d), spec is ", prog->name,
5757 relo_idx, core_relo_kind_str(relo->kind), relo->kind);
David Brazdil0f672f62019-12-10 10:32:29 +00005758 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
5759 libbpf_print(LIBBPF_DEBUG, "\n");
5760
Olivier Deprez157378f2022-04-04 15:47:50 +02005761 /* TYPE_ID_LOCAL relo is special and doesn't need candidate search */
5762 if (relo->kind == BPF_TYPE_ID_LOCAL) {
5763 targ_res.validate = true;
5764 targ_res.poison = false;
5765 targ_res.orig_val = local_spec.root_type_id;
5766 targ_res.new_val = local_spec.root_type_id;
5767 goto patch_insn;
5768 }
5769
5770 /* libbpf doesn't support candidate search for anonymous types */
5771 if (str_is_empty(spec_str)) {
5772 pr_warn("prog '%s': relo #%d: <%s> (%d) relocation doesn't support anonymous types\n",
5773 prog->name, relo_idx, core_relo_kind_str(relo->kind), relo->kind);
5774 return -EOPNOTSUPP;
5775 }
5776
David Brazdil0f672f62019-12-10 10:32:29 +00005777 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
5778 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
5779 if (IS_ERR(cand_ids)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005780 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld",
5781 prog->name, relo_idx, local_id, btf_kind_str(local_type),
5782 local_name, PTR_ERR(cand_ids));
David Brazdil0f672f62019-12-10 10:32:29 +00005783 return PTR_ERR(cand_ids);
5784 }
5785 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
5786 if (err) {
5787 bpf_core_free_cands(cand_ids);
5788 return err;
5789 }
5790 }
5791
5792 for (i = 0, j = 0; i < cand_ids->len; i++) {
5793 cand_id = cand_ids->data[i];
Olivier Deprez157378f2022-04-04 15:47:50 +02005794 err = bpf_core_spec_match(&local_spec, targ_btf, cand_id, &cand_spec);
David Brazdil0f672f62019-12-10 10:32:29 +00005795 if (err < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005796 pr_warn("prog '%s': relo #%d: error matching candidate #%d ",
5797 prog->name, relo_idx, i);
5798 bpf_core_dump_spec(LIBBPF_WARN, &cand_spec);
5799 libbpf_print(LIBBPF_WARN, ": %d\n", err);
David Brazdil0f672f62019-12-10 10:32:29 +00005800 return err;
5801 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005802
5803 pr_debug("prog '%s': relo #%d: %s candidate #%d ", prog->name,
5804 relo_idx, err == 0 ? "non-matching" : "matching", i);
5805 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
5806 libbpf_print(LIBBPF_DEBUG, "\n");
5807
David Brazdil0f672f62019-12-10 10:32:29 +00005808 if (err == 0)
5809 continue;
5810
Olivier Deprez157378f2022-04-04 15:47:50 +02005811 err = bpf_core_calc_relo(prog, relo, relo_idx, &local_spec, &cand_spec, &cand_res);
5812 if (err)
5813 return err;
5814
David Brazdil0f672f62019-12-10 10:32:29 +00005815 if (j == 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005816 targ_res = cand_res;
David Brazdil0f672f62019-12-10 10:32:29 +00005817 targ_spec = cand_spec;
Olivier Deprez157378f2022-04-04 15:47:50 +02005818 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
5819 /* if there are many field relo candidates, they
5820 * should all resolve to the same bit offset
David Brazdil0f672f62019-12-10 10:32:29 +00005821 */
Olivier Deprez157378f2022-04-04 15:47:50 +02005822 pr_warn("prog '%s': relo #%d: field offset ambiguity: %u != %u\n",
5823 prog->name, relo_idx, cand_spec.bit_offset,
5824 targ_spec.bit_offset);
5825 return -EINVAL;
5826 } else if (cand_res.poison != targ_res.poison || cand_res.new_val != targ_res.new_val) {
5827 /* all candidates should result in the same relocation
5828 * decision and value, otherwise it's dangerous to
5829 * proceed due to ambiguity
5830 */
5831 pr_warn("prog '%s': relo #%d: relocation decision ambiguity: %s %u != %s %u\n",
5832 prog->name, relo_idx,
5833 cand_res.poison ? "failure" : "success", cand_res.new_val,
5834 targ_res.poison ? "failure" : "success", targ_res.new_val);
David Brazdil0f672f62019-12-10 10:32:29 +00005835 return -EINVAL;
5836 }
5837
Olivier Deprez157378f2022-04-04 15:47:50 +02005838 cand_ids->data[j++] = cand_spec.root_type_id;
David Brazdil0f672f62019-12-10 10:32:29 +00005839 }
5840
Olivier Deprez157378f2022-04-04 15:47:50 +02005841 /*
5842 * For BPF_FIELD_EXISTS relo or when used BPF program has field
5843 * existence checks or kernel version/config checks, it's expected
5844 * that we might not find any candidates. In this case, if field
5845 * wasn't found in any candidate, the list of candidates shouldn't
5846 * change at all, we'll just handle relocating appropriately,
5847 * depending on relo's kind.
5848 */
5849 if (j > 0)
5850 cand_ids->len = j;
5851
5852 /*
5853 * If no candidates were found, it might be both a programmer error,
5854 * as well as expected case, depending whether instruction w/
5855 * relocation is guarded in some way that makes it unreachable (dead
5856 * code) if relocation can't be resolved. This is handled in
5857 * bpf_core_patch_insn() uniformly by replacing that instruction with
5858 * BPF helper call insn (using invalid helper ID). If that instruction
5859 * is indeed unreachable, then it will be ignored and eliminated by
5860 * verifier. If it was an error, then verifier will complain and point
5861 * to a specific instruction number in its log.
5862 */
5863 if (j == 0) {
5864 pr_debug("prog '%s': relo #%d: no matching targets found\n",
5865 prog->name, relo_idx);
5866
5867 /* calculate single target relo result explicitly */
5868 err = bpf_core_calc_relo(prog, relo, relo_idx, &local_spec, NULL, &targ_res);
5869 if (err)
5870 return err;
David Brazdil0f672f62019-12-10 10:32:29 +00005871 }
5872
Olivier Deprez157378f2022-04-04 15:47:50 +02005873patch_insn:
5874 /* bpf_core_patch_insn() should know how to handle missing targ_spec */
5875 err = bpf_core_patch_insn(prog, relo, relo_idx, &targ_res);
David Brazdil0f672f62019-12-10 10:32:29 +00005876 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005877 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
5878 prog->name, relo_idx, relo->insn_off, err);
David Brazdil0f672f62019-12-10 10:32:29 +00005879 return -EINVAL;
5880 }
5881
5882 return 0;
5883}
5884
5885static int
Olivier Deprez157378f2022-04-04 15:47:50 +02005886bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
David Brazdil0f672f62019-12-10 10:32:29 +00005887{
5888 const struct btf_ext_info_sec *sec;
Olivier Deprez157378f2022-04-04 15:47:50 +02005889 const struct bpf_core_relo *rec;
David Brazdil0f672f62019-12-10 10:32:29 +00005890 const struct btf_ext_info *seg;
5891 struct hashmap_entry *entry;
5892 struct hashmap *cand_cache = NULL;
5893 struct bpf_program *prog;
5894 struct btf *targ_btf;
5895 const char *sec_name;
Olivier Deprez157378f2022-04-04 15:47:50 +02005896 int i, err = 0, insn_idx, sec_idx;
5897
5898 if (obj->btf_ext->core_relo_info.len == 0)
5899 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00005900
5901 if (targ_btf_path)
Olivier Deprez157378f2022-04-04 15:47:50 +02005902 targ_btf = btf__parse(targ_btf_path, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +00005903 else
Olivier Deprez157378f2022-04-04 15:47:50 +02005904 targ_btf = obj->btf_vmlinux;
5905 if (IS_ERR_OR_NULL(targ_btf)) {
5906 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
David Brazdil0f672f62019-12-10 10:32:29 +00005907 return PTR_ERR(targ_btf);
5908 }
5909
5910 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5911 if (IS_ERR(cand_cache)) {
5912 err = PTR_ERR(cand_cache);
5913 goto out;
5914 }
5915
Olivier Deprez157378f2022-04-04 15:47:50 +02005916 seg = &obj->btf_ext->core_relo_info;
David Brazdil0f672f62019-12-10 10:32:29 +00005917 for_each_btf_ext_sec(seg, sec) {
5918 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5919 if (str_is_empty(sec_name)) {
5920 err = -EINVAL;
5921 goto out;
5922 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005923 /* bpf_object's ELF is gone by now so it's not easy to find
5924 * section index by section name, but we can find *any*
5925 * bpf_program within desired section name and use it's
5926 * prog->sec_idx to do a proper search by section index and
5927 * instruction offset
5928 */
5929 prog = NULL;
5930 for (i = 0; i < obj->nr_programs; i++) {
5931 prog = &obj->programs[i];
5932 if (strcmp(prog->sec_name, sec_name) == 0)
5933 break;
David Brazdil0f672f62019-12-10 10:32:29 +00005934 }
Olivier Deprez157378f2022-04-04 15:47:50 +02005935 if (!prog) {
5936 pr_warn("sec '%s': failed to find a BPF program\n", sec_name);
5937 return -ENOENT;
5938 }
5939 sec_idx = prog->sec_idx;
David Brazdil0f672f62019-12-10 10:32:29 +00005940
Olivier Deprez157378f2022-04-04 15:47:50 +02005941 pr_debug("sec '%s': found %d CO-RE relocations\n",
David Brazdil0f672f62019-12-10 10:32:29 +00005942 sec_name, sec->num_info);
5943
5944 for_each_btf_ext_rec(seg, sec, i, rec) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005945 insn_idx = rec->insn_off / BPF_INSN_SZ;
5946 prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5947 if (!prog) {
5948 pr_warn("sec '%s': failed to find program at insn #%d for CO-RE offset relocation #%d\n",
5949 sec_name, insn_idx, i);
5950 err = -EINVAL;
5951 goto out;
5952 }
5953 /* no need to apply CO-RE relocation if the program is
5954 * not going to be loaded
5955 */
5956 if (!prog->load)
5957 continue;
5958
5959 err = bpf_core_apply_relo(prog, rec, i, obj->btf,
5960 targ_btf, cand_cache);
David Brazdil0f672f62019-12-10 10:32:29 +00005961 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02005962 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5963 prog->name, i, err);
David Brazdil0f672f62019-12-10 10:32:29 +00005964 goto out;
5965 }
5966 }
5967 }
5968
5969out:
Olivier Deprez157378f2022-04-04 15:47:50 +02005970 /* obj->btf_vmlinux is freed at the end of object load phase */
5971 if (targ_btf != obj->btf_vmlinux)
5972 btf__free(targ_btf);
David Brazdil0f672f62019-12-10 10:32:29 +00005973 if (!IS_ERR_OR_NULL(cand_cache)) {
5974 hashmap__for_each_entry(cand_cache, entry, i) {
5975 bpf_core_free_cands(entry->value);
5976 }
5977 hashmap__free(cand_cache);
5978 }
5979 return err;
5980}
5981
Olivier Deprez157378f2022-04-04 15:47:50 +02005982/* Relocate data references within program code:
5983 * - map references;
5984 * - global variable references;
5985 * - extern references.
5986 */
David Brazdil0f672f62019-12-10 10:32:29 +00005987static int
Olivier Deprez157378f2022-04-04 15:47:50 +02005988bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
David Brazdil0f672f62019-12-10 10:32:29 +00005989{
Olivier Deprez157378f2022-04-04 15:47:50 +02005990 int i;
David Brazdil0f672f62019-12-10 10:32:29 +00005991
Olivier Deprez157378f2022-04-04 15:47:50 +02005992 for (i = 0; i < prog->nr_reloc; i++) {
5993 struct reloc_desc *relo = &prog->reloc_desc[i];
5994 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5995 struct extern_desc *ext;
David Brazdil0f672f62019-12-10 10:32:29 +00005996
Olivier Deprez157378f2022-04-04 15:47:50 +02005997 switch (relo->type) {
5998 case RELO_LD64:
5999 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6000 insn[0].imm = obj->maps[relo->map_idx].fd;
6001 relo->processed = true;
6002 break;
6003 case RELO_DATA:
6004 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6005 insn[1].imm = insn[0].imm + relo->sym_off;
6006 insn[0].imm = obj->maps[relo->map_idx].fd;
6007 relo->processed = true;
6008 break;
6009 case RELO_EXTERN:
6010 ext = &obj->externs[relo->sym_off];
6011 if (ext->type == EXT_KCFG) {
6012 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6013 insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6014 insn[1].imm = ext->kcfg.data_off;
6015 } else /* EXT_KSYM */ {
6016 if (ext->ksym.type_id) { /* typed ksyms */
6017 insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6018 insn[0].imm = ext->ksym.vmlinux_btf_id;
6019 } else { /* typeless ksyms */
6020 insn[0].imm = (__u32)ext->ksym.addr;
6021 insn[1].imm = ext->ksym.addr >> 32;
6022 }
6023 }
6024 relo->processed = true;
6025 break;
6026 case RELO_CALL:
6027 /* will be handled as a follow up pass */
6028 break;
6029 default:
6030 pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6031 prog->name, i, relo->type);
6032 return -EINVAL;
6033 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006034 }
6035
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006036 return 0;
6037}
6038
Olivier Deprez157378f2022-04-04 15:47:50 +02006039static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6040 const struct bpf_program *prog,
6041 const struct btf_ext_info *ext_info,
6042 void **prog_info, __u32 *prog_rec_cnt,
6043 __u32 *prog_rec_sz)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006044{
Olivier Deprez157378f2022-04-04 15:47:50 +02006045 void *copy_start = NULL, *copy_end = NULL;
6046 void *rec, *rec_end, *new_prog_info;
6047 const struct btf_ext_info_sec *sec;
6048 size_t old_sz, new_sz;
6049 const char *sec_name;
6050 int i, off_adj;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006051
Olivier Deprez157378f2022-04-04 15:47:50 +02006052 for_each_btf_ext_sec(ext_info, sec) {
6053 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6054 if (!sec_name)
6055 return -EINVAL;
6056 if (strcmp(sec_name, prog->sec_name) != 0)
6057 continue;
6058
6059 for_each_btf_ext_rec(ext_info, sec, i, rec) {
6060 __u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6061
6062 if (insn_off < prog->sec_insn_off)
6063 continue;
6064 if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6065 break;
6066
6067 if (!copy_start)
6068 copy_start = rec;
6069 copy_end = rec + ext_info->rec_size;
6070 }
6071
6072 if (!copy_start)
6073 return -ENOENT;
6074
6075 /* append func/line info of a given (sub-)program to the main
6076 * program func/line info
6077 */
6078 old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6079 new_sz = old_sz + (copy_end - copy_start);
6080 new_prog_info = realloc(*prog_info, new_sz);
6081 if (!new_prog_info)
6082 return -ENOMEM;
6083 *prog_info = new_prog_info;
6084 *prog_rec_cnt = new_sz / ext_info->rec_size;
6085 memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6086
6087 /* Kernel instruction offsets are in units of 8-byte
6088 * instructions, while .BTF.ext instruction offsets generated
6089 * by Clang are in units of bytes. So convert Clang offsets
6090 * into kernel offsets and adjust offset according to program
6091 * relocated position.
6092 */
6093 off_adj = prog->sub_insn_off - prog->sec_insn_off;
6094 rec = new_prog_info + old_sz;
6095 rec_end = new_prog_info + new_sz;
6096 for (; rec < rec_end; rec += ext_info->rec_size) {
6097 __u32 *insn_off = rec;
6098
6099 *insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6100 }
6101 *prog_rec_sz = ext_info->rec_size;
David Brazdil0f672f62019-12-10 10:32:29 +00006102 return 0;
David Brazdil0f672f62019-12-10 10:32:29 +00006103 }
6104
Olivier Deprez157378f2022-04-04 15:47:50 +02006105 return -ENOENT;
6106}
6107
6108static int
6109reloc_prog_func_and_line_info(const struct bpf_object *obj,
6110 struct bpf_program *main_prog,
6111 const struct bpf_program *prog)
6112{
6113 int err;
6114
6115 /* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6116 * supprot func/line info
6117 */
6118 if (!obj->btf_ext || !kernel_supports(FEAT_BTF_FUNC))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006119 return 0;
6120
Olivier Deprez157378f2022-04-04 15:47:50 +02006121 /* only attempt func info relocation if main program's func_info
6122 * relocation was successful
6123 */
6124 if (main_prog != prog && !main_prog->func_info)
6125 goto line_info;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006126
Olivier Deprez157378f2022-04-04 15:47:50 +02006127 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6128 &main_prog->func_info,
6129 &main_prog->func_info_cnt,
6130 &main_prog->func_info_rec_size);
6131 if (err) {
6132 if (err != -ENOENT) {
6133 pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6134 prog->name, err);
6135 return err;
6136 }
6137 if (main_prog->func_info) {
6138 /*
6139 * Some info has already been found but has problem
6140 * in the last btf_ext reloc. Must have to error out.
6141 */
6142 pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6143 return err;
6144 }
6145 /* Have problem loading the very first info. Ignore the rest. */
6146 pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6147 prog->name);
6148 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006149
Olivier Deprez157378f2022-04-04 15:47:50 +02006150line_info:
6151 /* don't relocate line info if main program's relocation failed */
6152 if (main_prog != prog && !main_prog->line_info)
6153 return 0;
6154
6155 err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6156 &main_prog->line_info,
6157 &main_prog->line_info_cnt,
6158 &main_prog->line_info_rec_size);
6159 if (err) {
6160 if (err != -ENOENT) {
6161 pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6162 prog->name, err);
6163 return err;
6164 }
6165 if (main_prog->line_info) {
6166 /*
6167 * Some info has already been found but has problem
6168 * in the last btf_ext reloc. Must have to error out.
6169 */
6170 pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6171 return err;
6172 }
6173 /* Have problem loading the very first info. Ignore the rest. */
6174 pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6175 prog->name);
6176 }
6177 return 0;
6178}
6179
6180static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6181{
6182 size_t insn_idx = *(const size_t *)key;
6183 const struct reloc_desc *relo = elem;
6184
6185 if (insn_idx == relo->insn_idx)
6186 return 0;
6187 return insn_idx < relo->insn_idx ? -1 : 1;
6188}
6189
6190static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6191{
6192 return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6193 sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6194}
6195
6196static int
6197bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6198 struct bpf_program *prog)
6199{
6200 size_t sub_insn_idx, insn_idx, new_cnt;
6201 struct bpf_program *subprog;
6202 struct bpf_insn *insns, *insn;
6203 struct reloc_desc *relo;
6204 int err;
6205
6206 err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6207 if (err)
6208 return err;
6209
6210 for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6211 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6212 if (!insn_is_subprog_call(insn))
6213 continue;
6214
6215 relo = find_prog_insn_relo(prog, insn_idx);
6216 if (relo && relo->type != RELO_CALL) {
6217 pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6218 prog->name, insn_idx, relo->type);
6219 return -LIBBPF_ERRNO__RELOC;
6220 }
6221 if (relo) {
6222 /* sub-program instruction index is a combination of
6223 * an offset of a symbol pointed to by relocation and
6224 * call instruction's imm field; for global functions,
6225 * call always has imm = -1, but for static functions
6226 * relocation is against STT_SECTION and insn->imm
6227 * points to a start of a static function
6228 */
6229 sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6230 } else {
6231 /* if subprogram call is to a static function within
6232 * the same ELF section, there won't be any relocation
6233 * emitted, but it also means there is no additional
6234 * offset necessary, insns->imm is relative to
6235 * instruction's original position within the section
6236 */
6237 sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6238 }
6239
6240 /* we enforce that sub-programs should be in .text section */
6241 subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6242 if (!subprog) {
6243 pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6244 prog->name);
6245 return -LIBBPF_ERRNO__RELOC;
6246 }
6247
6248 /* if it's the first call instruction calling into this
6249 * subprogram (meaning this subprog hasn't been processed
6250 * yet) within the context of current main program:
6251 * - append it at the end of main program's instructions blog;
6252 * - process is recursively, while current program is put on hold;
6253 * - if that subprogram calls some other not yet processes
6254 * subprogram, same thing will happen recursively until
6255 * there are no more unprocesses subprograms left to append
6256 * and relocate.
6257 */
6258 if (subprog->sub_insn_off == 0) {
6259 subprog->sub_insn_off = main_prog->insns_cnt;
6260
6261 new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6262 insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6263 if (!insns) {
6264 pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6265 return -ENOMEM;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006266 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006267 main_prog->insns = insns;
6268 main_prog->insns_cnt = new_cnt;
David Brazdil0f672f62019-12-10 10:32:29 +00006269
Olivier Deprez157378f2022-04-04 15:47:50 +02006270 memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6271 subprog->insns_cnt * sizeof(*insns));
6272
6273 pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6274 main_prog->name, subprog->insns_cnt, subprog->name);
6275
6276 err = bpf_object__reloc_code(obj, main_prog, subprog);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006277 if (err)
6278 return err;
6279 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006280
6281 /* main_prog->insns memory could have been re-allocated, so
6282 * calculate pointer again
6283 */
6284 insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6285 /* calculate correct instruction position within current main
6286 * prog; each main prog can have a different set of
6287 * subprograms appended (potentially in different order as
6288 * well), so position of any subprog can be different for
6289 * different main programs */
6290 insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6291
6292 if (relo)
6293 relo->processed = true;
6294
6295 pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6296 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006297 }
6298
Olivier Deprez157378f2022-04-04 15:47:50 +02006299 return 0;
6300}
6301
6302/*
6303 * Relocate sub-program calls.
6304 *
6305 * Algorithm operates as follows. Each entry-point BPF program (referred to as
6306 * main prog) is processed separately. For each subprog (non-entry functions,
6307 * that can be called from either entry progs or other subprogs) gets their
6308 * sub_insn_off reset to zero. This serves as indicator that this subprogram
6309 * hasn't been yet appended and relocated within current main prog. Once its
6310 * relocated, sub_insn_off will point at the position within current main prog
6311 * where given subprog was appended. This will further be used to relocate all
6312 * the call instructions jumping into this subprog.
6313 *
6314 * We start with main program and process all call instructions. If the call
6315 * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6316 * is zero), subprog instructions are appended at the end of main program's
6317 * instruction array. Then main program is "put on hold" while we recursively
6318 * process newly appended subprogram. If that subprogram calls into another
6319 * subprogram that hasn't been appended, new subprogram is appended again to
6320 * the *main* prog's instructions (subprog's instructions are always left
6321 * untouched, as they need to be in unmodified state for subsequent main progs
6322 * and subprog instructions are always sent only as part of a main prog) and
6323 * the process continues recursively. Once all the subprogs called from a main
6324 * prog or any of its subprogs are appended (and relocated), all their
6325 * positions within finalized instructions array are known, so it's easy to
6326 * rewrite call instructions with correct relative offsets, corresponding to
6327 * desired target subprog.
6328 *
6329 * Its important to realize that some subprogs might not be called from some
6330 * main prog and any of its called/used subprogs. Those will keep their
6331 * subprog->sub_insn_off as zero at all times and won't be appended to current
6332 * main prog and won't be relocated within the context of current main prog.
6333 * They might still be used from other main progs later.
6334 *
6335 * Visually this process can be shown as below. Suppose we have two main
6336 * programs mainA and mainB and BPF object contains three subprogs: subA,
6337 * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6338 * subC both call subB:
6339 *
6340 * +--------+ +-------+
6341 * | v v |
6342 * +--+---+ +--+-+-+ +---+--+
6343 * | subA | | subB | | subC |
6344 * +--+---+ +------+ +---+--+
6345 * ^ ^
6346 * | |
6347 * +---+-------+ +------+----+
6348 * | mainA | | mainB |
6349 * +-----------+ +-----------+
6350 *
6351 * We'll start relocating mainA, will find subA, append it and start
6352 * processing sub A recursively:
6353 *
6354 * +-----------+------+
6355 * | mainA | subA |
6356 * +-----------+------+
6357 *
6358 * At this point we notice that subB is used from subA, so we append it and
6359 * relocate (there are no further subcalls from subB):
6360 *
6361 * +-----------+------+------+
6362 * | mainA | subA | subB |
6363 * +-----------+------+------+
6364 *
6365 * At this point, we relocate subA calls, then go one level up and finish with
6366 * relocatin mainA calls. mainA is done.
6367 *
6368 * For mainB process is similar but results in different order. We start with
6369 * mainB and skip subA and subB, as mainB never calls them (at least
6370 * directly), but we see subC is needed, so we append and start processing it:
6371 *
6372 * +-----------+------+
6373 * | mainB | subC |
6374 * +-----------+------+
6375 * Now we see subC needs subB, so we go back to it, append and relocate it:
6376 *
6377 * +-----------+------+------+
6378 * | mainB | subC | subB |
6379 * +-----------+------+------+
6380 *
6381 * At this point we unwind recursion, relocate calls in subC, then in mainB.
6382 */
6383static int
6384bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6385{
6386 struct bpf_program *subprog;
6387 int i, j, err;
6388
6389 /* mark all subprogs as not relocated (yet) within the context of
6390 * current main program
6391 */
6392 for (i = 0; i < obj->nr_programs; i++) {
6393 subprog = &obj->programs[i];
6394 if (!prog_is_subprog(obj, subprog))
6395 continue;
6396
6397 subprog->sub_insn_off = 0;
6398 for (j = 0; j < subprog->nr_reloc; j++)
6399 if (subprog->reloc_desc[j].type == RELO_CALL)
6400 subprog->reloc_desc[j].processed = false;
6401 }
6402
6403 err = bpf_object__reloc_code(obj, prog, prog);
6404 if (err)
6405 return err;
6406
6407
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006408 return 0;
6409}
6410
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006411static int
David Brazdil0f672f62019-12-10 10:32:29 +00006412bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006413{
6414 struct bpf_program *prog;
6415 size_t i;
6416 int err;
6417
David Brazdil0f672f62019-12-10 10:32:29 +00006418 if (obj->btf_ext) {
6419 err = bpf_object__relocate_core(obj, targ_btf_path);
6420 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006421 pr_warn("failed to perform CO-RE relocations: %d\n",
6422 err);
David Brazdil0f672f62019-12-10 10:32:29 +00006423 return err;
6424 }
6425 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006426 /* relocate data references first for all programs and sub-programs,
6427 * as they don't change relative to code locations, so subsequent
6428 * subprogram processing won't need to re-calculate any of them
6429 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006430 for (i = 0; i < obj->nr_programs; i++) {
6431 prog = &obj->programs[i];
Olivier Deprez157378f2022-04-04 15:47:50 +02006432 err = bpf_object__relocate_data(obj, prog);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006433 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006434 pr_warn("prog '%s': failed to relocate data references: %d\n",
6435 prog->name, err);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006436 return err;
6437 }
6438 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006439 /* now relocate subprogram calls and append used subprograms to main
6440 * programs; each copy of subprogram code needs to be relocated
6441 * differently for each main program, because its code location might
6442 * have changed
6443 */
6444 for (i = 0; i < obj->nr_programs; i++) {
6445 prog = &obj->programs[i];
6446 /* sub-program's sub-calls are relocated within the context of
6447 * its main program only
6448 */
6449 if (prog_is_subprog(obj, prog))
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 /* free up relocation descriptors */
6460 for (i = 0; i < obj->nr_programs; i++) {
6461 prog = &obj->programs[i];
6462 zfree(&prog->reloc_desc);
6463 prog->nr_reloc = 0;
6464 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006465 return 0;
6466}
6467
Olivier Deprez157378f2022-04-04 15:47:50 +02006468static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6469 GElf_Shdr *shdr, Elf_Data *data);
6470
6471static int bpf_object__collect_map_relos(struct bpf_object *obj,
6472 GElf_Shdr *shdr, Elf_Data *data)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006473{
Olivier Deprez157378f2022-04-04 15:47:50 +02006474 const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6475 int i, j, nrels, new_sz;
6476 const struct btf_var_secinfo *vi = NULL;
6477 const struct btf_type *sec, *var, *def;
6478 struct bpf_map *map = NULL, *targ_map;
6479 const struct btf_member *member;
6480 const char *name, *mname;
6481 Elf_Data *symbols;
6482 unsigned int moff;
6483 GElf_Sym sym;
6484 GElf_Rel rel;
6485 void *tmp;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006486
Olivier Deprez157378f2022-04-04 15:47:50 +02006487 if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6488 return -EINVAL;
6489 sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6490 if (!sec)
6491 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006492
Olivier Deprez157378f2022-04-04 15:47:50 +02006493 symbols = obj->efile.symbols;
6494 nrels = shdr->sh_size / shdr->sh_entsize;
6495 for (i = 0; i < nrels; i++) {
6496 if (!gelf_getrel(data, i, &rel)) {
6497 pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6498 return -LIBBPF_ERRNO__FORMAT;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006499 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006500 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
6501 pr_warn(".maps relo #%d: symbol %zx not found\n",
6502 i, (size_t)GELF_R_SYM(rel.r_info));
6503 return -LIBBPF_ERRNO__FORMAT;
6504 }
6505 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
6506 if (sym.st_shndx != obj->efile.btf_maps_shndx) {
6507 pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6508 i, name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006509 return -LIBBPF_ERRNO__RELOC;
6510 }
6511
Olivier Deprez157378f2022-04-04 15:47:50 +02006512 pr_debug(".maps relo #%d: for %zd value %zd rel.r_offset %zu name %d ('%s')\n",
6513 i, (ssize_t)(rel.r_info >> 32), (size_t)sym.st_value,
6514 (size_t)rel.r_offset, sym.st_name, name);
6515
6516 for (j = 0; j < obj->nr_maps; j++) {
6517 map = &obj->maps[j];
6518 if (map->sec_idx != obj->efile.btf_maps_shndx)
6519 continue;
6520
6521 vi = btf_var_secinfos(sec) + map->btf_var_idx;
6522 if (vi->offset <= rel.r_offset &&
6523 rel.r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6524 break;
6525 }
6526 if (j == obj->nr_maps) {
6527 pr_warn(".maps relo #%d: cannot find map '%s' at rel.r_offset %zu\n",
6528 i, name, (size_t)rel.r_offset);
6529 return -EINVAL;
6530 }
6531
6532 if (!bpf_map_type__is_map_in_map(map->def.type))
6533 return -EINVAL;
6534 if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6535 map->def.key_size != sizeof(int)) {
6536 pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6537 i, map->name, sizeof(int));
6538 return -EINVAL;
6539 }
6540
6541 targ_map = bpf_object__find_map_by_name(obj, name);
6542 if (!targ_map)
6543 return -ESRCH;
6544
6545 var = btf__type_by_id(obj->btf, vi->type);
6546 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6547 if (btf_vlen(def) == 0)
6548 return -EINVAL;
6549 member = btf_members(def) + btf_vlen(def) - 1;
6550 mname = btf__name_by_offset(obj->btf, member->name_off);
6551 if (strcmp(mname, "values"))
6552 return -EINVAL;
6553
6554 moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6555 if (rel.r_offset - vi->offset < moff)
6556 return -EINVAL;
6557
6558 moff = rel.r_offset - vi->offset - moff;
6559 /* here we use BPF pointer size, which is always 64 bit, as we
6560 * are parsing ELF that was built for BPF target
6561 */
6562 if (moff % bpf_ptr_sz)
6563 return -EINVAL;
6564 moff /= bpf_ptr_sz;
6565 if (moff >= map->init_slots_sz) {
6566 new_sz = moff + 1;
6567 tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6568 if (!tmp)
6569 return -ENOMEM;
6570 map->init_slots = tmp;
6571 memset(map->init_slots + map->init_slots_sz, 0,
6572 (new_sz - map->init_slots_sz) * host_ptr_sz);
6573 map->init_slots_sz = new_sz;
6574 }
6575 map->init_slots[moff] = targ_map;
6576
6577 pr_debug(".maps relo #%d: map '%s' slot [%d] points to map '%s'\n",
6578 i, map->name, moff, name);
6579 }
6580
6581 return 0;
6582}
6583
6584static int cmp_relocs(const void *_a, const void *_b)
6585{
6586 const struct reloc_desc *a = _a;
6587 const struct reloc_desc *b = _b;
6588
6589 if (a->insn_idx != b->insn_idx)
6590 return a->insn_idx < b->insn_idx ? -1 : 1;
6591
6592 /* no two relocations should have the same insn_idx, but ... */
6593 if (a->type != b->type)
6594 return a->type < b->type ? -1 : 1;
6595
6596 return 0;
6597}
6598
6599static int bpf_object__collect_relos(struct bpf_object *obj)
6600{
6601 int i, err;
6602
6603 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
6604 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
6605 Elf_Data *data = obj->efile.reloc_sects[i].data;
6606 int idx = shdr->sh_info;
6607
6608 if (shdr->sh_type != SHT_REL) {
6609 pr_warn("internal error at %d\n", __LINE__);
6610 return -LIBBPF_ERRNO__INTERNAL;
6611 }
6612
6613 if (idx == obj->efile.st_ops_shndx)
6614 err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6615 else if (idx == obj->efile.btf_maps_shndx)
6616 err = bpf_object__collect_map_relos(obj, shdr, data);
6617 else
6618 err = bpf_object__collect_prog_relos(obj, shdr, data);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006619 if (err)
6620 return err;
6621 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006622
6623 for (i = 0; i < obj->nr_programs; i++) {
6624 struct bpf_program *p = &obj->programs[i];
6625
6626 if (!p->nr_reloc)
6627 continue;
6628
6629 qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6630 }
6631 return 0;
6632}
6633
6634static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6635{
6636 if (BPF_CLASS(insn->code) == BPF_JMP &&
6637 BPF_OP(insn->code) == BPF_CALL &&
6638 BPF_SRC(insn->code) == BPF_K &&
6639 insn->src_reg == 0 &&
6640 insn->dst_reg == 0) {
6641 *func_id = insn->imm;
6642 return true;
6643 }
6644 return false;
6645}
6646
6647static int bpf_object__sanitize_prog(struct bpf_object* obj, struct bpf_program *prog)
6648{
6649 struct bpf_insn *insn = prog->insns;
6650 enum bpf_func_id func_id;
6651 int i;
6652
6653 for (i = 0; i < prog->insns_cnt; i++, insn++) {
6654 if (!insn_is_helper_call(insn, &func_id))
6655 continue;
6656
6657 /* on kernels that don't yet support
6658 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6659 * to bpf_probe_read() which works well for old kernels
6660 */
6661 switch (func_id) {
6662 case BPF_FUNC_probe_read_kernel:
6663 case BPF_FUNC_probe_read_user:
6664 if (!kernel_supports(FEAT_PROBE_READ_KERN))
6665 insn->imm = BPF_FUNC_probe_read;
6666 break;
6667 case BPF_FUNC_probe_read_kernel_str:
6668 case BPF_FUNC_probe_read_user_str:
6669 if (!kernel_supports(FEAT_PROBE_READ_KERN))
6670 insn->imm = BPF_FUNC_probe_read_str;
6671 break;
6672 default:
6673 break;
6674 }
6675 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006676 return 0;
6677}
6678
6679static int
David Brazdil0f672f62019-12-10 10:32:29 +00006680load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
6681 char *license, __u32 kern_version, int *pfd)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006682{
6683 struct bpf_load_program_attr load_attr;
6684 char *cp, errmsg[STRERR_BUFSIZE];
Olivier Deprez157378f2022-04-04 15:47:50 +02006685 size_t log_buf_size = 0;
6686 char *log_buf = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00006687 int btf_fd, ret;
6688
6689 if (!insns || !insns_cnt)
6690 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006691
6692 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
David Brazdil0f672f62019-12-10 10:32:29 +00006693 load_attr.prog_type = prog->type;
Olivier Deprez157378f2022-04-04 15:47:50 +02006694 /* old kernels might not support specifying expected_attach_type */
6695 if (!kernel_supports(FEAT_EXP_ATTACH_TYPE) && prog->sec_def &&
6696 prog->sec_def->is_exp_attach_type_optional)
6697 load_attr.expected_attach_type = 0;
6698 else
6699 load_attr.expected_attach_type = prog->expected_attach_type;
6700 if (kernel_supports(FEAT_PROG_NAME))
David Brazdil0f672f62019-12-10 10:32:29 +00006701 load_attr.name = prog->name;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006702 load_attr.insns = insns;
6703 load_attr.insns_cnt = insns_cnt;
6704 load_attr.license = license;
Olivier Deprez157378f2022-04-04 15:47:50 +02006705 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
6706 prog->type == BPF_PROG_TYPE_LSM) {
6707 load_attr.attach_btf_id = prog->attach_btf_id;
6708 } else if (prog->type == BPF_PROG_TYPE_TRACING ||
6709 prog->type == BPF_PROG_TYPE_EXT) {
6710 load_attr.attach_prog_fd = prog->attach_prog_fd;
6711 load_attr.attach_btf_id = prog->attach_btf_id;
6712 } else {
6713 load_attr.kern_version = kern_version;
6714 load_attr.prog_ifindex = prog->prog_ifindex;
6715 }
6716 /* specify func_info/line_info only if kernel supports them */
6717 btf_fd = bpf_object__btf_fd(prog->obj);
6718 if (btf_fd >= 0 && kernel_supports(FEAT_BTF_FUNC)) {
6719 load_attr.prog_btf_fd = btf_fd;
6720 load_attr.func_info = prog->func_info;
6721 load_attr.func_info_rec_size = prog->func_info_rec_size;
6722 load_attr.func_info_cnt = prog->func_info_cnt;
6723 load_attr.line_info = prog->line_info;
6724 load_attr.line_info_rec_size = prog->line_info_rec_size;
6725 load_attr.line_info_cnt = prog->line_info_cnt;
6726 }
David Brazdil0f672f62019-12-10 10:32:29 +00006727 load_attr.log_level = prog->log_level;
6728 load_attr.prog_flags = prog->prog_flags;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006729
David Brazdil0f672f62019-12-10 10:32:29 +00006730retry_load:
Olivier Deprez157378f2022-04-04 15:47:50 +02006731 if (log_buf_size) {
6732 log_buf = malloc(log_buf_size);
6733 if (!log_buf)
6734 return -ENOMEM;
6735
6736 *log_buf = 0;
6737 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006738
David Brazdil0f672f62019-12-10 10:32:29 +00006739 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006740
6741 if (ret >= 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006742 if (log_buf && load_attr.log_level)
David Brazdil0f672f62019-12-10 10:32:29 +00006743 pr_debug("verifier log:\n%s", log_buf);
Olivier Deprez157378f2022-04-04 15:47:50 +02006744
6745 if (prog->obj->rodata_map_idx >= 0 &&
6746 kernel_supports(FEAT_PROG_BIND_MAP)) {
6747 struct bpf_map *rodata_map =
6748 &prog->obj->maps[prog->obj->rodata_map_idx];
6749
6750 if (bpf_prog_bind_map(ret, bpf_map__fd(rodata_map), NULL)) {
6751 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6752 pr_warn("prog '%s': failed to bind .rodata map: %s\n",
6753 prog->name, cp);
6754 /* Don't fail hard if can't bind rodata. */
6755 }
6756 }
6757
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006758 *pfd = ret;
6759 ret = 0;
6760 goto out;
6761 }
6762
Olivier Deprez157378f2022-04-04 15:47:50 +02006763 if (!log_buf || errno == ENOSPC) {
6764 log_buf_size = max((size_t)BPF_LOG_BUF_SIZE,
6765 log_buf_size << 1);
6766
David Brazdil0f672f62019-12-10 10:32:29 +00006767 free(log_buf);
6768 goto retry_load;
6769 }
Olivier Deprez157378f2022-04-04 15:47:50 +02006770 ret = errno ? -errno : -LIBBPF_ERRNO__LOAD;
David Brazdil0f672f62019-12-10 10:32:29 +00006771 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Olivier Deprez157378f2022-04-04 15:47:50 +02006772 pr_warn("load bpf program failed: %s\n", cp);
6773 pr_perm_msg(ret);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006774
6775 if (log_buf && log_buf[0] != '\0') {
6776 ret = -LIBBPF_ERRNO__VERIFY;
Olivier Deprez157378f2022-04-04 15:47:50 +02006777 pr_warn("-- BEGIN DUMP LOG ---\n");
6778 pr_warn("\n%s\n", log_buf);
6779 pr_warn("-- END LOG --\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006780 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006781 pr_warn("Program too large (%zu insns), at most %d insns\n",
6782 load_attr.insns_cnt, BPF_MAXINSNS);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006783 ret = -LIBBPF_ERRNO__PROG2BIG;
Olivier Deprez157378f2022-04-04 15:47:50 +02006784 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006785 /* Wrong program type? */
Olivier Deprez157378f2022-04-04 15:47:50 +02006786 int fd;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006787
Olivier Deprez157378f2022-04-04 15:47:50 +02006788 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
6789 load_attr.expected_attach_type = 0;
6790 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
6791 if (fd >= 0) {
6792 close(fd);
6793 ret = -LIBBPF_ERRNO__PROGTYPE;
6794 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006795 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006796 }
6797
6798out:
6799 free(log_buf);
6800 return ret;
6801}
6802
Olivier Deprez157378f2022-04-04 15:47:50 +02006803static int libbpf_find_attach_btf_id(struct bpf_program *prog);
6804
6805int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006806{
Olivier Deprez157378f2022-04-04 15:47:50 +02006807 int err = 0, fd, i, btf_id;
6808
6809 if (prog->obj->loaded) {
6810 pr_warn("prog '%s': can't load after object was loaded\n", prog->name);
6811 return -EINVAL;
6812 }
6813
6814 if ((prog->type == BPF_PROG_TYPE_TRACING ||
6815 prog->type == BPF_PROG_TYPE_LSM ||
6816 prog->type == BPF_PROG_TYPE_EXT) && !prog->attach_btf_id) {
6817 btf_id = libbpf_find_attach_btf_id(prog);
6818 if (btf_id <= 0)
6819 return btf_id;
6820 prog->attach_btf_id = btf_id;
6821 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006822
6823 if (prog->instances.nr < 0 || !prog->instances.fds) {
6824 if (prog->preprocessor) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006825 pr_warn("Internal error: can't load program '%s'\n",
6826 prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006827 return -LIBBPF_ERRNO__INTERNAL;
6828 }
6829
6830 prog->instances.fds = malloc(sizeof(int));
6831 if (!prog->instances.fds) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006832 pr_warn("Not enough memory for BPF fds\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006833 return -ENOMEM;
6834 }
6835 prog->instances.nr = 1;
6836 prog->instances.fds[0] = -1;
6837 }
6838
6839 if (!prog->preprocessor) {
6840 if (prog->instances.nr != 1) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006841 pr_warn("prog '%s': inconsistent nr(%d) != 1\n",
6842 prog->name, prog->instances.nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006843 }
David Brazdil0f672f62019-12-10 10:32:29 +00006844 err = load_program(prog, prog->insns, prog->insns_cnt,
Olivier Deprez157378f2022-04-04 15:47:50 +02006845 license, kern_ver, &fd);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006846 if (!err)
6847 prog->instances.fds[0] = fd;
6848 goto out;
6849 }
6850
6851 for (i = 0; i < prog->instances.nr; i++) {
6852 struct bpf_prog_prep_result result;
6853 bpf_program_prep_t preprocessor = prog->preprocessor;
6854
David Brazdil0f672f62019-12-10 10:32:29 +00006855 memset(&result, 0, sizeof(result));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006856 err = preprocessor(prog, i, prog->insns,
6857 prog->insns_cnt, &result);
6858 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006859 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
6860 i, prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006861 goto out;
6862 }
6863
6864 if (!result.new_insn_ptr || !result.new_insn_cnt) {
6865 pr_debug("Skip loading the %dth instance of program '%s'\n",
Olivier Deprez157378f2022-04-04 15:47:50 +02006866 i, prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006867 prog->instances.fds[i] = -1;
6868 if (result.pfd)
6869 *result.pfd = -1;
6870 continue;
6871 }
6872
David Brazdil0f672f62019-12-10 10:32:29 +00006873 err = load_program(prog, result.new_insn_ptr,
Olivier Deprez157378f2022-04-04 15:47:50 +02006874 result.new_insn_cnt, license, kern_ver, &fd);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006875 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006876 pr_warn("Loading the %dth instance of program '%s' failed\n",
6877 i, prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006878 goto out;
6879 }
6880
6881 if (result.pfd)
6882 *result.pfd = fd;
6883 prog->instances.fds[i] = fd;
6884 }
6885out:
6886 if (err)
Olivier Deprez157378f2022-04-04 15:47:50 +02006887 pr_warn("failed to load program '%s'\n", prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006888 zfree(&prog->insns);
6889 prog->insns_cnt = 0;
6890 return err;
6891}
6892
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006893static int
David Brazdil0f672f62019-12-10 10:32:29 +00006894bpf_object__load_progs(struct bpf_object *obj, int log_level)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006895{
Olivier Deprez157378f2022-04-04 15:47:50 +02006896 struct bpf_program *prog;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006897 size_t i;
6898 int err;
6899
6900 for (i = 0; i < obj->nr_programs; i++) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006901 prog = &obj->programs[i];
6902 err = bpf_object__sanitize_prog(obj, prog);
6903 if (err)
6904 return err;
6905 }
6906
6907 for (i = 0; i < obj->nr_programs; i++) {
6908 prog = &obj->programs[i];
6909 if (prog_is_subprog(obj, prog))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006910 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02006911 if (!prog->load) {
6912 pr_debug("prog '%s': skipped loading\n", prog->name);
6913 continue;
6914 }
6915 prog->log_level |= log_level;
6916 err = bpf_program__load(prog, obj->license, obj->kern_version);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006917 if (err)
6918 return err;
6919 }
6920 return 0;
6921}
6922
Olivier Deprez157378f2022-04-04 15:47:50 +02006923static const struct bpf_sec_def *find_sec_def(const char *sec_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006924
6925static struct bpf_object *
Olivier Deprez157378f2022-04-04 15:47:50 +02006926__bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
6927 const struct bpf_object_open_opts *opts)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006928{
Olivier Deprez157378f2022-04-04 15:47:50 +02006929 const char *obj_name, *kconfig;
6930 struct bpf_program *prog;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006931 struct bpf_object *obj;
Olivier Deprez157378f2022-04-04 15:47:50 +02006932 char tmp_name[64];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006933 int err;
6934
6935 if (elf_version(EV_CURRENT) == EV_NONE) {
Olivier Deprez157378f2022-04-04 15:47:50 +02006936 pr_warn("failed to init libelf for %s\n",
6937 path ? : "(mem buf)");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006938 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
6939 }
6940
Olivier Deprez157378f2022-04-04 15:47:50 +02006941 if (!OPTS_VALID(opts, bpf_object_open_opts))
6942 return ERR_PTR(-EINVAL);
6943
6944 obj_name = OPTS_GET(opts, object_name, NULL);
6945 if (obj_buf) {
6946 if (!obj_name) {
6947 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
6948 (unsigned long)obj_buf,
6949 (unsigned long)obj_buf_sz);
6950 obj_name = tmp_name;
6951 }
6952 path = obj_name;
6953 pr_debug("loading object '%s' from buffer\n", obj_name);
6954 }
6955
6956 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006957 if (IS_ERR(obj))
6958 return obj;
6959
Olivier Deprez157378f2022-04-04 15:47:50 +02006960 kconfig = OPTS_GET(opts, kconfig, NULL);
6961 if (kconfig) {
6962 obj->kconfig = strdup(kconfig);
6963 if (!obj->kconfig) {
6964 err = -ENOMEM;
6965 goto out;
6966 }
6967 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006968
Olivier Deprez157378f2022-04-04 15:47:50 +02006969 err = bpf_object__elf_init(obj);
6970 err = err ? : bpf_object__check_endianness(obj);
6971 err = err ? : bpf_object__elf_collect(obj);
6972 err = err ? : bpf_object__collect_externs(obj);
6973 err = err ? : bpf_object__finalize_btf(obj);
6974 err = err ? : bpf_object__init_maps(obj, opts);
6975 err = err ? : bpf_object__collect_relos(obj);
6976 if (err)
6977 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006978 bpf_object__elf_finish(obj);
Olivier Deprez157378f2022-04-04 15:47:50 +02006979
6980 bpf_object__for_each_program(prog, obj) {
6981 prog->sec_def = find_sec_def(prog->sec_name);
6982 if (!prog->sec_def)
6983 /* couldn't guess, but user might manually specify */
6984 continue;
6985
6986 if (prog->sec_def->is_sleepable)
6987 prog->prog_flags |= BPF_F_SLEEPABLE;
6988 bpf_program__set_type(prog, prog->sec_def->prog_type);
6989 bpf_program__set_expected_attach_type(prog,
6990 prog->sec_def->expected_attach_type);
6991
6992 if (prog->sec_def->prog_type == BPF_PROG_TYPE_TRACING ||
6993 prog->sec_def->prog_type == BPF_PROG_TYPE_EXT)
6994 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
6995 }
6996
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00006997 return obj;
6998out:
6999 bpf_object__close(obj);
7000 return ERR_PTR(err);
7001}
7002
Olivier Deprez157378f2022-04-04 15:47:50 +02007003static struct bpf_object *
7004__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007005{
Olivier Deprez157378f2022-04-04 15:47:50 +02007006 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7007 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
7008 );
7009
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007010 /* param validation */
7011 if (!attr->file)
7012 return NULL;
7013
7014 pr_debug("loading %s\n", attr->file);
Olivier Deprez157378f2022-04-04 15:47:50 +02007015 return __bpf_object__open(attr->file, NULL, 0, &opts);
David Brazdil0f672f62019-12-10 10:32:29 +00007016}
7017
7018struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
7019{
7020 return __bpf_object__open_xattr(attr, 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007021}
7022
7023struct bpf_object *bpf_object__open(const char *path)
7024{
7025 struct bpf_object_open_attr attr = {
7026 .file = path,
7027 .prog_type = BPF_PROG_TYPE_UNSPEC,
7028 };
7029
7030 return bpf_object__open_xattr(&attr);
7031}
7032
Olivier Deprez157378f2022-04-04 15:47:50 +02007033struct bpf_object *
7034bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007035{
Olivier Deprez157378f2022-04-04 15:47:50 +02007036 if (!path)
7037 return ERR_PTR(-EINVAL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007038
Olivier Deprez157378f2022-04-04 15:47:50 +02007039 pr_debug("loading %s\n", path);
7040
7041 return __bpf_object__open(path, NULL, 0, opts);
7042}
7043
7044struct bpf_object *
7045bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7046 const struct bpf_object_open_opts *opts)
7047{
7048 if (!obj_buf || obj_buf_sz == 0)
7049 return ERR_PTR(-EINVAL);
7050
7051 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
7052}
7053
7054struct bpf_object *
7055bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
7056 const char *name)
7057{
7058 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
7059 .object_name = name,
7060 /* wrong default, but backwards-compatible */
7061 .relaxed_maps = true,
7062 );
7063
7064 /* returning NULL is wrong, but backwards-compatible */
7065 if (!obj_buf || obj_buf_sz == 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007066 return NULL;
7067
Olivier Deprez157378f2022-04-04 15:47:50 +02007068 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007069}
7070
7071int bpf_object__unload(struct bpf_object *obj)
7072{
7073 size_t i;
7074
7075 if (!obj)
7076 return -EINVAL;
7077
Olivier Deprez157378f2022-04-04 15:47:50 +02007078 for (i = 0; i < obj->nr_maps; i++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007079 zclose(obj->maps[i].fd);
Olivier Deprez157378f2022-04-04 15:47:50 +02007080 if (obj->maps[i].st_ops)
7081 zfree(&obj->maps[i].st_ops->kern_vdata);
7082 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007083
7084 for (i = 0; i < obj->nr_programs; i++)
7085 bpf_program__unload(&obj->programs[i]);
7086
7087 return 0;
7088}
7089
Olivier Deprez157378f2022-04-04 15:47:50 +02007090static int bpf_object__sanitize_maps(struct bpf_object *obj)
7091{
7092 struct bpf_map *m;
7093
7094 bpf_object__for_each_map(m, obj) {
7095 if (!bpf_map__is_internal(m))
7096 continue;
7097 if (!kernel_supports(FEAT_GLOBAL_DATA)) {
7098 pr_warn("kernel doesn't support global data\n");
7099 return -ENOTSUP;
7100 }
7101 if (!kernel_supports(FEAT_ARRAY_MMAP))
7102 m->def.map_flags ^= BPF_F_MMAPABLE;
7103 }
7104
7105 return 0;
7106}
7107
7108static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7109{
7110 char sym_type, sym_name[500];
7111 unsigned long long sym_addr;
7112 struct extern_desc *ext;
7113 int ret, err = 0;
7114 FILE *f;
7115
7116 f = fopen("/proc/kallsyms", "r");
7117 if (!f) {
7118 err = -errno;
7119 pr_warn("failed to open /proc/kallsyms: %d\n", err);
7120 return err;
7121 }
7122
7123 while (true) {
7124 ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7125 &sym_addr, &sym_type, sym_name);
7126 if (ret == EOF && feof(f))
7127 break;
7128 if (ret != 3) {
7129 pr_warn("failed to read kallsyms entry: %d\n", ret);
7130 err = -EINVAL;
7131 goto out;
7132 }
7133
7134 ext = find_extern_by_name(obj, sym_name);
7135 if (!ext || ext->type != EXT_KSYM)
7136 continue;
7137
7138 if (ext->is_set && ext->ksym.addr != sym_addr) {
7139 pr_warn("extern (ksym) '%s' resolution is ambiguous: 0x%llx or 0x%llx\n",
7140 sym_name, ext->ksym.addr, sym_addr);
7141 err = -EINVAL;
7142 goto out;
7143 }
7144 if (!ext->is_set) {
7145 ext->is_set = true;
7146 ext->ksym.addr = sym_addr;
7147 pr_debug("extern (ksym) %s=0x%llx\n", sym_name, sym_addr);
7148 }
7149 }
7150
7151out:
7152 fclose(f);
7153 return err;
7154}
7155
7156static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7157{
7158 struct extern_desc *ext;
7159 int i, id;
7160
7161 for (i = 0; i < obj->nr_extern; i++) {
7162 const struct btf_type *targ_var, *targ_type;
7163 __u32 targ_type_id, local_type_id;
7164 const char *targ_var_name;
7165 int ret;
7166
7167 ext = &obj->externs[i];
7168 if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7169 continue;
7170
7171 id = btf__find_by_name_kind(obj->btf_vmlinux, ext->name,
7172 BTF_KIND_VAR);
7173 if (id <= 0) {
7174 pr_warn("extern (ksym) '%s': failed to find BTF ID in vmlinux BTF.\n",
7175 ext->name);
7176 return -ESRCH;
7177 }
7178
7179 /* find local type_id */
7180 local_type_id = ext->ksym.type_id;
7181
7182 /* find target type_id */
7183 targ_var = btf__type_by_id(obj->btf_vmlinux, id);
7184 targ_var_name = btf__name_by_offset(obj->btf_vmlinux,
7185 targ_var->name_off);
7186 targ_type = skip_mods_and_typedefs(obj->btf_vmlinux,
7187 targ_var->type,
7188 &targ_type_id);
7189
7190 ret = bpf_core_types_are_compat(obj->btf, local_type_id,
7191 obj->btf_vmlinux, targ_type_id);
7192 if (ret <= 0) {
7193 const struct btf_type *local_type;
7194 const char *targ_name, *local_name;
7195
7196 local_type = btf__type_by_id(obj->btf, local_type_id);
7197 local_name = btf__name_by_offset(obj->btf,
7198 local_type->name_off);
7199 targ_name = btf__name_by_offset(obj->btf_vmlinux,
7200 targ_type->name_off);
7201
7202 pr_warn("extern (ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7203 ext->name, local_type_id,
7204 btf_kind_str(local_type), local_name, targ_type_id,
7205 btf_kind_str(targ_type), targ_name);
7206 return -EINVAL;
7207 }
7208
7209 ext->is_set = true;
7210 ext->ksym.vmlinux_btf_id = id;
7211 pr_debug("extern (ksym) '%s': resolved to [%d] %s %s\n",
7212 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7213 }
7214 return 0;
7215}
7216
7217static int bpf_object__resolve_externs(struct bpf_object *obj,
7218 const char *extra_kconfig)
7219{
7220 bool need_config = false, need_kallsyms = false;
7221 bool need_vmlinux_btf = false;
7222 struct extern_desc *ext;
7223 void *kcfg_data = NULL;
7224 int err, i;
7225
7226 if (obj->nr_extern == 0)
7227 return 0;
7228
7229 if (obj->kconfig_map_idx >= 0)
7230 kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7231
7232 for (i = 0; i < obj->nr_extern; i++) {
7233 ext = &obj->externs[i];
7234
7235 if (ext->type == EXT_KCFG &&
7236 strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7237 void *ext_val = kcfg_data + ext->kcfg.data_off;
7238 __u32 kver = get_kernel_version();
7239
7240 if (!kver) {
7241 pr_warn("failed to get kernel version\n");
7242 return -EINVAL;
7243 }
7244 err = set_kcfg_value_num(ext, ext_val, kver);
7245 if (err)
7246 return err;
7247 pr_debug("extern (kcfg) %s=0x%x\n", ext->name, kver);
7248 } else if (ext->type == EXT_KCFG &&
7249 strncmp(ext->name, "CONFIG_", 7) == 0) {
7250 need_config = true;
7251 } else if (ext->type == EXT_KSYM) {
7252 if (ext->ksym.type_id)
7253 need_vmlinux_btf = true;
7254 else
7255 need_kallsyms = true;
7256 } else {
7257 pr_warn("unrecognized extern '%s'\n", ext->name);
7258 return -EINVAL;
7259 }
7260 }
7261 if (need_config && extra_kconfig) {
7262 err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7263 if (err)
7264 return -EINVAL;
7265 need_config = false;
7266 for (i = 0; i < obj->nr_extern; i++) {
7267 ext = &obj->externs[i];
7268 if (ext->type == EXT_KCFG && !ext->is_set) {
7269 need_config = true;
7270 break;
7271 }
7272 }
7273 }
7274 if (need_config) {
7275 err = bpf_object__read_kconfig_file(obj, kcfg_data);
7276 if (err)
7277 return -EINVAL;
7278 }
7279 if (need_kallsyms) {
7280 err = bpf_object__read_kallsyms_file(obj);
7281 if (err)
7282 return -EINVAL;
7283 }
7284 if (need_vmlinux_btf) {
7285 err = bpf_object__resolve_ksyms_btf_id(obj);
7286 if (err)
7287 return -EINVAL;
7288 }
7289 for (i = 0; i < obj->nr_extern; i++) {
7290 ext = &obj->externs[i];
7291
7292 if (!ext->is_set && !ext->is_weak) {
7293 pr_warn("extern %s (strong) not resolved\n", ext->name);
7294 return -ESRCH;
7295 } else if (!ext->is_set) {
7296 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
7297 ext->name);
7298 }
7299 }
7300
7301 return 0;
7302}
7303
David Brazdil0f672f62019-12-10 10:32:29 +00007304int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007305{
David Brazdil0f672f62019-12-10 10:32:29 +00007306 struct bpf_object *obj;
Olivier Deprez157378f2022-04-04 15:47:50 +02007307 int err, i;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007308
David Brazdil0f672f62019-12-10 10:32:29 +00007309 if (!attr)
7310 return -EINVAL;
7311 obj = attr->obj;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007312 if (!obj)
7313 return -EINVAL;
7314
7315 if (obj->loaded) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007316 pr_warn("object '%s': load can't be attempted twice\n", obj->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007317 return -EINVAL;
7318 }
7319
Olivier Deprez157378f2022-04-04 15:47:50 +02007320 err = bpf_object__probe_loading(obj);
7321 err = err ? : bpf_object__load_vmlinux_btf(obj);
7322 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7323 err = err ? : bpf_object__sanitize_and_load_btf(obj);
7324 err = err ? : bpf_object__sanitize_maps(obj);
7325 err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7326 err = err ? : bpf_object__create_maps(obj);
7327 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
7328 err = err ? : bpf_object__load_progs(obj, attr->log_level);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007329
Olivier Deprez157378f2022-04-04 15:47:50 +02007330 btf__free(obj->btf_vmlinux);
7331 obj->btf_vmlinux = NULL;
7332
7333 obj->loaded = true; /* doesn't matter if successfully or not */
7334
7335 if (err)
7336 goto out;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007337
7338 return 0;
7339out:
Olivier Deprez157378f2022-04-04 15:47:50 +02007340 /* unpin any maps that were auto-pinned during load */
7341 for (i = 0; i < obj->nr_maps; i++)
7342 if (obj->maps[i].pinned && !obj->maps[i].reused)
7343 bpf_map__unpin(&obj->maps[i], NULL);
7344
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007345 bpf_object__unload(obj);
Olivier Deprez157378f2022-04-04 15:47:50 +02007346 pr_warn("failed to load object '%s'\n", obj->path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007347 return err;
7348}
7349
David Brazdil0f672f62019-12-10 10:32:29 +00007350int bpf_object__load(struct bpf_object *obj)
7351{
7352 struct bpf_object_load_attr attr = {
7353 .obj = obj,
7354 };
7355
7356 return bpf_object__load_xattr(&attr);
7357}
7358
Olivier Deprez157378f2022-04-04 15:47:50 +02007359static int make_parent_dir(const char *path)
7360{
7361 char *cp, errmsg[STRERR_BUFSIZE];
7362 char *dname, *dir;
7363 int err = 0;
7364
7365 dname = strdup(path);
7366 if (dname == NULL)
7367 return -ENOMEM;
7368
7369 dir = dirname(dname);
7370 if (mkdir(dir, 0700) && errno != EEXIST)
7371 err = -errno;
7372
7373 free(dname);
7374 if (err) {
7375 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7376 pr_warn("failed to mkdir %s: %s\n", path, cp);
7377 }
7378 return err;
7379}
7380
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007381static int check_path(const char *path)
7382{
7383 char *cp, errmsg[STRERR_BUFSIZE];
7384 struct statfs st_fs;
7385 char *dname, *dir;
7386 int err = 0;
7387
7388 if (path == NULL)
7389 return -EINVAL;
7390
7391 dname = strdup(path);
7392 if (dname == NULL)
7393 return -ENOMEM;
7394
7395 dir = dirname(dname);
7396 if (statfs(dir, &st_fs)) {
David Brazdil0f672f62019-12-10 10:32:29 +00007397 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Olivier Deprez157378f2022-04-04 15:47:50 +02007398 pr_warn("failed to statfs %s: %s\n", dir, cp);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007399 err = -errno;
7400 }
7401 free(dname);
7402
7403 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007404 pr_warn("specified path %s is not on BPF FS\n", path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007405 err = -EINVAL;
7406 }
7407
7408 return err;
7409}
7410
7411int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
7412 int instance)
7413{
7414 char *cp, errmsg[STRERR_BUFSIZE];
7415 int err;
7416
Olivier Deprez157378f2022-04-04 15:47:50 +02007417 err = make_parent_dir(path);
7418 if (err)
7419 return err;
7420
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007421 err = check_path(path);
7422 if (err)
7423 return err;
7424
7425 if (prog == NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007426 pr_warn("invalid program pointer\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007427 return -EINVAL;
7428 }
7429
7430 if (instance < 0 || instance >= prog->instances.nr) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007431 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7432 instance, prog->name, prog->instances.nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007433 return -EINVAL;
7434 }
7435
7436 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007437 err = -errno;
7438 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7439 pr_warn("failed to pin program: %s\n", cp);
7440 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007441 }
7442 pr_debug("pinned program '%s'\n", path);
7443
7444 return 0;
7445}
7446
David Brazdil0f672f62019-12-10 10:32:29 +00007447int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
7448 int instance)
7449{
7450 int err;
7451
7452 err = check_path(path);
7453 if (err)
7454 return err;
7455
7456 if (prog == NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007457 pr_warn("invalid program pointer\n");
David Brazdil0f672f62019-12-10 10:32:29 +00007458 return -EINVAL;
7459 }
7460
7461 if (instance < 0 || instance >= prog->instances.nr) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007462 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
7463 instance, prog->name, prog->instances.nr);
David Brazdil0f672f62019-12-10 10:32:29 +00007464 return -EINVAL;
7465 }
7466
7467 err = unlink(path);
7468 if (err != 0)
7469 return -errno;
7470 pr_debug("unpinned program '%s'\n", path);
7471
7472 return 0;
7473}
7474
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007475int bpf_program__pin(struct bpf_program *prog, const char *path)
7476{
7477 int i, err;
7478
Olivier Deprez157378f2022-04-04 15:47:50 +02007479 err = make_parent_dir(path);
7480 if (err)
7481 return err;
7482
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007483 err = check_path(path);
7484 if (err)
7485 return err;
7486
7487 if (prog == NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007488 pr_warn("invalid program pointer\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007489 return -EINVAL;
7490 }
7491
7492 if (prog->instances.nr <= 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007493 pr_warn("no instances of prog %s to pin\n", prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007494 return -EINVAL;
7495 }
7496
David Brazdil0f672f62019-12-10 10:32:29 +00007497 if (prog->instances.nr == 1) {
7498 /* don't create subdirs when pinning single instance */
7499 return bpf_program__pin_instance(prog, path, 0);
7500 }
7501
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007502 for (i = 0; i < prog->instances.nr; i++) {
7503 char buf[PATH_MAX];
7504 int len;
7505
7506 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
David Brazdil0f672f62019-12-10 10:32:29 +00007507 if (len < 0) {
7508 err = -EINVAL;
7509 goto err_unpin;
7510 } else if (len >= PATH_MAX) {
7511 err = -ENAMETOOLONG;
7512 goto err_unpin;
7513 }
7514
7515 err = bpf_program__pin_instance(prog, buf, i);
7516 if (err)
7517 goto err_unpin;
7518 }
7519
7520 return 0;
7521
7522err_unpin:
7523 for (i = i - 1; i >= 0; i--) {
7524 char buf[PATH_MAX];
7525 int len;
7526
7527 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
7528 if (len < 0)
7529 continue;
7530 else if (len >= PATH_MAX)
7531 continue;
7532
7533 bpf_program__unpin_instance(prog, buf, i);
7534 }
7535
7536 rmdir(path);
7537
7538 return err;
7539}
7540
7541int bpf_program__unpin(struct bpf_program *prog, const char *path)
7542{
7543 int i, err;
7544
7545 err = check_path(path);
7546 if (err)
7547 return err;
7548
7549 if (prog == NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007550 pr_warn("invalid program pointer\n");
David Brazdil0f672f62019-12-10 10:32:29 +00007551 return -EINVAL;
7552 }
7553
7554 if (prog->instances.nr <= 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007555 pr_warn("no instances of prog %s to pin\n", prog->name);
David Brazdil0f672f62019-12-10 10:32:29 +00007556 return -EINVAL;
7557 }
7558
7559 if (prog->instances.nr == 1) {
7560 /* don't create subdirs when pinning single instance */
7561 return bpf_program__unpin_instance(prog, path, 0);
7562 }
7563
7564 for (i = 0; i < prog->instances.nr; i++) {
7565 char buf[PATH_MAX];
7566 int len;
7567
7568 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007569 if (len < 0)
7570 return -EINVAL;
7571 else if (len >= PATH_MAX)
7572 return -ENAMETOOLONG;
7573
David Brazdil0f672f62019-12-10 10:32:29 +00007574 err = bpf_program__unpin_instance(prog, buf, i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007575 if (err)
7576 return err;
7577 }
7578
David Brazdil0f672f62019-12-10 10:32:29 +00007579 err = rmdir(path);
7580 if (err)
7581 return -errno;
7582
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007583 return 0;
7584}
7585
7586int bpf_map__pin(struct bpf_map *map, const char *path)
7587{
7588 char *cp, errmsg[STRERR_BUFSIZE];
7589 int err;
7590
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007591 if (map == NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007592 pr_warn("invalid map pointer\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007593 return -EINVAL;
7594 }
7595
Olivier Deprez157378f2022-04-04 15:47:50 +02007596 if (map->pin_path) {
7597 if (path && strcmp(path, map->pin_path)) {
7598 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7599 bpf_map__name(map), map->pin_path, path);
7600 return -EINVAL;
7601 } else if (map->pinned) {
7602 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7603 bpf_map__name(map), map->pin_path);
7604 return 0;
7605 }
7606 } else {
7607 if (!path) {
7608 pr_warn("missing a path to pin map '%s' at\n",
7609 bpf_map__name(map));
7610 return -EINVAL;
7611 } else if (map->pinned) {
7612 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7613 return -EEXIST;
7614 }
7615
7616 map->pin_path = strdup(path);
7617 if (!map->pin_path) {
7618 err = -errno;
7619 goto out_err;
7620 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007621 }
7622
Olivier Deprez157378f2022-04-04 15:47:50 +02007623 err = make_parent_dir(map->pin_path);
7624 if (err)
7625 return err;
7626
7627 err = check_path(map->pin_path);
7628 if (err)
7629 return err;
7630
7631 if (bpf_obj_pin(map->fd, map->pin_path)) {
7632 err = -errno;
7633 goto out_err;
7634 }
7635
7636 map->pinned = true;
7637 pr_debug("pinned map '%s'\n", map->pin_path);
David Brazdil0f672f62019-12-10 10:32:29 +00007638
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007639 return 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02007640
7641out_err:
7642 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7643 pr_warn("failed to pin map: %s\n", cp);
7644 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007645}
7646
David Brazdil0f672f62019-12-10 10:32:29 +00007647int bpf_map__unpin(struct bpf_map *map, const char *path)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007648{
David Brazdil0f672f62019-12-10 10:32:29 +00007649 int err;
7650
Olivier Deprez157378f2022-04-04 15:47:50 +02007651 if (map == NULL) {
7652 pr_warn("invalid map pointer\n");
7653 return -EINVAL;
7654 }
7655
7656 if (map->pin_path) {
7657 if (path && strcmp(path, map->pin_path)) {
7658 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7659 bpf_map__name(map), map->pin_path, path);
7660 return -EINVAL;
7661 }
7662 path = map->pin_path;
7663 } else if (!path) {
7664 pr_warn("no path to unpin map '%s' from\n",
7665 bpf_map__name(map));
7666 return -EINVAL;
7667 }
7668
David Brazdil0f672f62019-12-10 10:32:29 +00007669 err = check_path(path);
7670 if (err)
7671 return err;
7672
David Brazdil0f672f62019-12-10 10:32:29 +00007673 err = unlink(path);
7674 if (err != 0)
7675 return -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +02007676
7677 map->pinned = false;
7678 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
David Brazdil0f672f62019-12-10 10:32:29 +00007679
7680 return 0;
7681}
7682
Olivier Deprez157378f2022-04-04 15:47:50 +02007683int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7684{
7685 char *new = NULL;
7686
7687 if (path) {
7688 new = strdup(path);
7689 if (!new)
7690 return -errno;
7691 }
7692
7693 free(map->pin_path);
7694 map->pin_path = new;
7695 return 0;
7696}
7697
7698const char *bpf_map__get_pin_path(const struct bpf_map *map)
7699{
7700 return map->pin_path;
7701}
7702
7703bool bpf_map__is_pinned(const struct bpf_map *map)
7704{
7705 return map->pinned;
7706}
7707
7708static void sanitize_pin_path(char *s)
7709{
7710 /* bpffs disallows periods in path names */
7711 while (*s) {
7712 if (*s == '.')
7713 *s = '_';
7714 s++;
7715 }
7716}
7717
David Brazdil0f672f62019-12-10 10:32:29 +00007718int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7719{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007720 struct bpf_map *map;
7721 int err;
7722
7723 if (!obj)
7724 return -ENOENT;
7725
7726 if (!obj->loaded) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007727 pr_warn("object not yet loaded; load it first\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007728 return -ENOENT;
7729 }
7730
David Brazdil0f672f62019-12-10 10:32:29 +00007731 bpf_object__for_each_map(map, obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007732 char *pin_path = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00007733 char buf[PATH_MAX];
David Brazdil0f672f62019-12-10 10:32:29 +00007734
Olivier Deprez157378f2022-04-04 15:47:50 +02007735 if (path) {
7736 int len;
7737
7738 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7739 bpf_map__name(map));
7740 if (len < 0) {
7741 err = -EINVAL;
7742 goto err_unpin_maps;
7743 } else if (len >= PATH_MAX) {
7744 err = -ENAMETOOLONG;
7745 goto err_unpin_maps;
7746 }
7747 sanitize_pin_path(buf);
7748 pin_path = buf;
7749 } else if (!map->pin_path) {
7750 continue;
David Brazdil0f672f62019-12-10 10:32:29 +00007751 }
7752
Olivier Deprez157378f2022-04-04 15:47:50 +02007753 err = bpf_map__pin(map, pin_path);
David Brazdil0f672f62019-12-10 10:32:29 +00007754 if (err)
7755 goto err_unpin_maps;
7756 }
7757
7758 return 0;
7759
7760err_unpin_maps:
7761 while ((map = bpf_map__prev(map, obj))) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007762 if (!map->pin_path)
David Brazdil0f672f62019-12-10 10:32:29 +00007763 continue;
7764
Olivier Deprez157378f2022-04-04 15:47:50 +02007765 bpf_map__unpin(map, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +00007766 }
7767
7768 return err;
7769}
7770
7771int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
7772{
7773 struct bpf_map *map;
7774 int err;
7775
7776 if (!obj)
7777 return -ENOENT;
7778
7779 bpf_object__for_each_map(map, obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007780 char *pin_path = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007781 char buf[PATH_MAX];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007782
Olivier Deprez157378f2022-04-04 15:47:50 +02007783 if (path) {
7784 int len;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007785
Olivier Deprez157378f2022-04-04 15:47:50 +02007786 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7787 bpf_map__name(map));
7788 if (len < 0)
7789 return -EINVAL;
7790 else if (len >= PATH_MAX)
7791 return -ENAMETOOLONG;
7792 sanitize_pin_path(buf);
7793 pin_path = buf;
7794 } else if (!map->pin_path) {
7795 continue;
7796 }
7797
7798 err = bpf_map__unpin(map, pin_path);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007799 if (err)
7800 return err;
7801 }
7802
David Brazdil0f672f62019-12-10 10:32:29 +00007803 return 0;
7804}
7805
7806int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
7807{
7808 struct bpf_program *prog;
7809 int err;
7810
7811 if (!obj)
7812 return -ENOENT;
7813
7814 if (!obj->loaded) {
Olivier Deprez157378f2022-04-04 15:47:50 +02007815 pr_warn("object not yet loaded; load it first\n");
David Brazdil0f672f62019-12-10 10:32:29 +00007816 return -ENOENT;
7817 }
7818
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007819 bpf_object__for_each_program(prog, obj) {
7820 char buf[PATH_MAX];
7821 int len;
7822
7823 len = snprintf(buf, PATH_MAX, "%s/%s", path,
David Brazdil0f672f62019-12-10 10:32:29 +00007824 prog->pin_name);
7825 if (len < 0) {
7826 err = -EINVAL;
7827 goto err_unpin_programs;
7828 } else if (len >= PATH_MAX) {
7829 err = -ENAMETOOLONG;
7830 goto err_unpin_programs;
7831 }
7832
7833 err = bpf_program__pin(prog, buf);
7834 if (err)
7835 goto err_unpin_programs;
7836 }
7837
7838 return 0;
7839
7840err_unpin_programs:
7841 while ((prog = bpf_program__prev(prog, obj))) {
7842 char buf[PATH_MAX];
7843 int len;
7844
7845 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7846 prog->pin_name);
7847 if (len < 0)
7848 continue;
7849 else if (len >= PATH_MAX)
7850 continue;
7851
7852 bpf_program__unpin(prog, buf);
7853 }
7854
7855 return err;
7856}
7857
7858int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
7859{
7860 struct bpf_program *prog;
7861 int err;
7862
7863 if (!obj)
7864 return -ENOENT;
7865
7866 bpf_object__for_each_program(prog, obj) {
7867 char buf[PATH_MAX];
7868 int len;
7869
7870 len = snprintf(buf, PATH_MAX, "%s/%s", path,
7871 prog->pin_name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007872 if (len < 0)
7873 return -EINVAL;
7874 else if (len >= PATH_MAX)
7875 return -ENAMETOOLONG;
7876
David Brazdil0f672f62019-12-10 10:32:29 +00007877 err = bpf_program__unpin(prog, buf);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007878 if (err)
7879 return err;
7880 }
7881
7882 return 0;
7883}
7884
David Brazdil0f672f62019-12-10 10:32:29 +00007885int bpf_object__pin(struct bpf_object *obj, const char *path)
7886{
7887 int err;
7888
7889 err = bpf_object__pin_maps(obj, path);
7890 if (err)
7891 return err;
7892
7893 err = bpf_object__pin_programs(obj, path);
7894 if (err) {
7895 bpf_object__unpin_maps(obj, path);
7896 return err;
7897 }
7898
7899 return 0;
7900}
7901
Olivier Deprez157378f2022-04-04 15:47:50 +02007902static void bpf_map__destroy(struct bpf_map *map)
7903{
7904 if (map->clear_priv)
7905 map->clear_priv(map, map->priv);
7906 map->priv = NULL;
7907 map->clear_priv = NULL;
7908
7909 if (map->inner_map) {
7910 bpf_map__destroy(map->inner_map);
7911 zfree(&map->inner_map);
7912 }
7913
7914 zfree(&map->init_slots);
7915 map->init_slots_sz = 0;
7916
7917 if (map->mmaped) {
7918 munmap(map->mmaped, bpf_map_mmap_sz(map));
7919 map->mmaped = NULL;
7920 }
7921
7922 if (map->st_ops) {
7923 zfree(&map->st_ops->data);
7924 zfree(&map->st_ops->progs);
7925 zfree(&map->st_ops->kern_func_off);
7926 zfree(&map->st_ops);
7927 }
7928
7929 zfree(&map->name);
7930 zfree(&map->pin_path);
7931
7932 if (map->fd >= 0)
7933 zclose(map->fd);
7934}
7935
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007936void bpf_object__close(struct bpf_object *obj)
7937{
7938 size_t i;
7939
Olivier Deprez157378f2022-04-04 15:47:50 +02007940 if (IS_ERR_OR_NULL(obj))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007941 return;
7942
7943 if (obj->clear_priv)
7944 obj->clear_priv(obj, obj->priv);
7945
7946 bpf_object__elf_finish(obj);
7947 bpf_object__unload(obj);
7948 btf__free(obj->btf);
David Brazdil0f672f62019-12-10 10:32:29 +00007949 btf_ext__free(obj->btf_ext);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007950
Olivier Deprez157378f2022-04-04 15:47:50 +02007951 for (i = 0; i < obj->nr_maps; i++)
7952 bpf_map__destroy(&obj->maps[i]);
David Brazdil0f672f62019-12-10 10:32:29 +00007953
Olivier Deprez157378f2022-04-04 15:47:50 +02007954 zfree(&obj->kconfig);
7955 zfree(&obj->externs);
7956 obj->nr_extern = 0;
7957
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007958 zfree(&obj->maps);
7959 obj->nr_maps = 0;
7960
7961 if (obj->programs && obj->nr_programs) {
7962 for (i = 0; i < obj->nr_programs; i++)
7963 bpf_program__exit(&obj->programs[i]);
7964 }
7965 zfree(&obj->programs);
7966
7967 list_del(&obj->list);
7968 free(obj);
7969}
7970
7971struct bpf_object *
7972bpf_object__next(struct bpf_object *prev)
7973{
7974 struct bpf_object *next;
7975
7976 if (!prev)
7977 next = list_first_entry(&bpf_objects_list,
7978 struct bpf_object,
7979 list);
7980 else
7981 next = list_next_entry(prev, list);
7982
7983 /* Empty list is noticed here so don't need checking on entry. */
7984 if (&next->list == &bpf_objects_list)
7985 return NULL;
7986
7987 return next;
7988}
7989
David Brazdil0f672f62019-12-10 10:32:29 +00007990const char *bpf_object__name(const struct bpf_object *obj)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007991{
Olivier Deprez157378f2022-04-04 15:47:50 +02007992 return obj ? obj->name : ERR_PTR(-EINVAL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007993}
7994
David Brazdil0f672f62019-12-10 10:32:29 +00007995unsigned int bpf_object__kversion(const struct bpf_object *obj)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007996{
7997 return obj ? obj->kern_version : 0;
7998}
7999
David Brazdil0f672f62019-12-10 10:32:29 +00008000struct btf *bpf_object__btf(const struct bpf_object *obj)
8001{
8002 return obj ? obj->btf : NULL;
8003}
8004
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008005int bpf_object__btf_fd(const struct bpf_object *obj)
8006{
8007 return obj->btf ? btf__fd(obj->btf) : -1;
8008}
8009
8010int bpf_object__set_priv(struct bpf_object *obj, void *priv,
8011 bpf_object_clear_priv_t clear_priv)
8012{
8013 if (obj->priv && obj->clear_priv)
8014 obj->clear_priv(obj, obj->priv);
8015
8016 obj->priv = priv;
8017 obj->clear_priv = clear_priv;
8018 return 0;
8019}
8020
David Brazdil0f672f62019-12-10 10:32:29 +00008021void *bpf_object__priv(const struct bpf_object *obj)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008022{
8023 return obj ? obj->priv : ERR_PTR(-EINVAL);
8024}
8025
8026static struct bpf_program *
David Brazdil0f672f62019-12-10 10:32:29 +00008027__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8028 bool forward)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008029{
David Brazdil0f672f62019-12-10 10:32:29 +00008030 size_t nr_programs = obj->nr_programs;
8031 ssize_t idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008032
David Brazdil0f672f62019-12-10 10:32:29 +00008033 if (!nr_programs)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008034 return NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008035
David Brazdil0f672f62019-12-10 10:32:29 +00008036 if (!p)
8037 /* Iter from the beginning */
8038 return forward ? &obj->programs[0] :
8039 &obj->programs[nr_programs - 1];
8040
8041 if (p->obj != obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008042 pr_warn("error: program handler doesn't match object\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008043 return NULL;
8044 }
8045
David Brazdil0f672f62019-12-10 10:32:29 +00008046 idx = (p - obj->programs) + (forward ? 1 : -1);
8047 if (idx >= obj->nr_programs || idx < 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008048 return NULL;
8049 return &obj->programs[idx];
8050}
8051
8052struct bpf_program *
David Brazdil0f672f62019-12-10 10:32:29 +00008053bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008054{
8055 struct bpf_program *prog = prev;
8056
8057 do {
David Brazdil0f672f62019-12-10 10:32:29 +00008058 prog = __bpf_program__iter(prog, obj, true);
Olivier Deprez157378f2022-04-04 15:47:50 +02008059 } while (prog && prog_is_subprog(obj, prog));
David Brazdil0f672f62019-12-10 10:32:29 +00008060
8061 return prog;
8062}
8063
8064struct bpf_program *
8065bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
8066{
8067 struct bpf_program *prog = next;
8068
8069 do {
8070 prog = __bpf_program__iter(prog, obj, false);
Olivier Deprez157378f2022-04-04 15:47:50 +02008071 } while (prog && prog_is_subprog(obj, prog));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008072
8073 return prog;
8074}
8075
8076int bpf_program__set_priv(struct bpf_program *prog, void *priv,
8077 bpf_program_clear_priv_t clear_priv)
8078{
8079 if (prog->priv && prog->clear_priv)
8080 prog->clear_priv(prog, prog->priv);
8081
8082 prog->priv = priv;
8083 prog->clear_priv = clear_priv;
8084 return 0;
8085}
8086
David Brazdil0f672f62019-12-10 10:32:29 +00008087void *bpf_program__priv(const struct bpf_program *prog)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008088{
8089 return prog ? prog->priv : ERR_PTR(-EINVAL);
8090}
8091
8092void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8093{
8094 prog->prog_ifindex = ifindex;
8095}
8096
Olivier Deprez157378f2022-04-04 15:47:50 +02008097const char *bpf_program__name(const struct bpf_program *prog)
8098{
8099 return prog->name;
8100}
8101
8102const char *bpf_program__section_name(const struct bpf_program *prog)
8103{
8104 return prog->sec_name;
8105}
8106
David Brazdil0f672f62019-12-10 10:32:29 +00008107const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008108{
8109 const char *title;
8110
Olivier Deprez157378f2022-04-04 15:47:50 +02008111 title = prog->sec_name;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008112 if (needs_copy) {
8113 title = strdup(title);
8114 if (!title) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008115 pr_warn("failed to strdup program title\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008116 return ERR_PTR(-ENOMEM);
8117 }
8118 }
8119
8120 return title;
8121}
8122
Olivier Deprez157378f2022-04-04 15:47:50 +02008123bool bpf_program__autoload(const struct bpf_program *prog)
8124{
8125 return prog->load;
8126}
8127
8128int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8129{
8130 if (prog->obj->loaded)
8131 return -EINVAL;
8132
8133 prog->load = autoload;
8134 return 0;
8135}
8136
David Brazdil0f672f62019-12-10 10:32:29 +00008137int bpf_program__fd(const struct bpf_program *prog)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008138{
8139 return bpf_program__nth_fd(prog, 0);
8140}
8141
Olivier Deprez157378f2022-04-04 15:47:50 +02008142size_t bpf_program__size(const struct bpf_program *prog)
8143{
8144 return prog->insns_cnt * BPF_INSN_SZ;
8145}
8146
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008147int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
8148 bpf_program_prep_t prep)
8149{
8150 int *instances_fds;
8151
8152 if (nr_instances <= 0 || !prep)
8153 return -EINVAL;
8154
8155 if (prog->instances.nr > 0 || prog->instances.fds) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008156 pr_warn("Can't set pre-processor after loading\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008157 return -EINVAL;
8158 }
8159
8160 instances_fds = malloc(sizeof(int) * nr_instances);
8161 if (!instances_fds) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008162 pr_warn("alloc memory failed for fds\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008163 return -ENOMEM;
8164 }
8165
8166 /* fill all fd with -1 */
8167 memset(instances_fds, -1, sizeof(int) * nr_instances);
8168
8169 prog->instances.nr = nr_instances;
8170 prog->instances.fds = instances_fds;
8171 prog->preprocessor = prep;
8172 return 0;
8173}
8174
David Brazdil0f672f62019-12-10 10:32:29 +00008175int bpf_program__nth_fd(const struct bpf_program *prog, int n)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008176{
8177 int fd;
8178
8179 if (!prog)
8180 return -EINVAL;
8181
8182 if (n >= prog->instances.nr || n < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008183 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
8184 n, prog->name, prog->instances.nr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008185 return -EINVAL;
8186 }
8187
8188 fd = prog->instances.fds[n];
8189 if (fd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008190 pr_warn("%dth instance of program '%s' is invalid\n",
8191 n, prog->name);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008192 return -ENOENT;
8193 }
8194
8195 return fd;
8196}
8197
Olivier Deprez157378f2022-04-04 15:47:50 +02008198enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
8199{
8200 return prog->type;
8201}
8202
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008203void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8204{
8205 prog->type = type;
8206}
8207
David Brazdil0f672f62019-12-10 10:32:29 +00008208static bool bpf_program__is_type(const struct bpf_program *prog,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008209 enum bpf_prog_type type)
8210{
8211 return prog ? (prog->type == type) : false;
8212}
8213
David Brazdil0f672f62019-12-10 10:32:29 +00008214#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
8215int bpf_program__set_##NAME(struct bpf_program *prog) \
8216{ \
8217 if (!prog) \
8218 return -EINVAL; \
8219 bpf_program__set_type(prog, TYPE); \
8220 return 0; \
8221} \
8222 \
8223bool bpf_program__is_##NAME(const struct bpf_program *prog) \
8224{ \
8225 return bpf_program__is_type(prog, TYPE); \
8226} \
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008227
8228BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
Olivier Deprez157378f2022-04-04 15:47:50 +02008229BPF_PROG_TYPE_FNS(lsm, BPF_PROG_TYPE_LSM);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008230BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
8231BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
8232BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
8233BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
8234BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
8235BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
8236BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
Olivier Deprez157378f2022-04-04 15:47:50 +02008237BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
8238BPF_PROG_TYPE_FNS(struct_ops, BPF_PROG_TYPE_STRUCT_OPS);
8239BPF_PROG_TYPE_FNS(extension, BPF_PROG_TYPE_EXT);
8240BPF_PROG_TYPE_FNS(sk_lookup, BPF_PROG_TYPE_SK_LOOKUP);
8241
8242enum bpf_attach_type
8243bpf_program__get_expected_attach_type(struct bpf_program *prog)
8244{
8245 return prog->expected_attach_type;
8246}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008247
8248void bpf_program__set_expected_attach_type(struct bpf_program *prog,
8249 enum bpf_attach_type type)
8250{
8251 prog->expected_attach_type = type;
8252}
8253
Olivier Deprez157378f2022-04-04 15:47:50 +02008254#define BPF_PROG_SEC_IMPL(string, ptype, eatype, eatype_optional, \
8255 attachable, attach_btf) \
8256 { \
8257 .sec = string, \
8258 .len = sizeof(string) - 1, \
8259 .prog_type = ptype, \
8260 .expected_attach_type = eatype, \
8261 .is_exp_attach_type_optional = eatype_optional, \
8262 .is_attachable = attachable, \
8263 .is_attach_btf = attach_btf, \
8264 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008265
David Brazdil0f672f62019-12-10 10:32:29 +00008266/* Programs that can NOT be attached. */
Olivier Deprez157378f2022-04-04 15:47:50 +02008267#define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008268
David Brazdil0f672f62019-12-10 10:32:29 +00008269/* Programs that can be attached. */
8270#define BPF_APROG_SEC(string, ptype, atype) \
Olivier Deprez157378f2022-04-04 15:47:50 +02008271 BPF_PROG_SEC_IMPL(string, ptype, atype, true, 1, 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008272
David Brazdil0f672f62019-12-10 10:32:29 +00008273/* Programs that must specify expected attach type at load time. */
8274#define BPF_EAPROG_SEC(string, ptype, eatype) \
Olivier Deprez157378f2022-04-04 15:47:50 +02008275 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 1, 0)
8276
8277/* Programs that use BTF to identify attach point */
8278#define BPF_PROG_BTF(string, ptype, eatype) \
8279 BPF_PROG_SEC_IMPL(string, ptype, eatype, false, 0, 1)
David Brazdil0f672f62019-12-10 10:32:29 +00008280
8281/* Programs that can be attached but attach type can't be identified by section
8282 * name. Kept for backward compatibility.
8283 */
8284#define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008285
Olivier Deprez157378f2022-04-04 15:47:50 +02008286#define SEC_DEF(sec_pfx, ptype, ...) { \
8287 .sec = sec_pfx, \
8288 .len = sizeof(sec_pfx) - 1, \
8289 .prog_type = BPF_PROG_TYPE_##ptype, \
8290 __VA_ARGS__ \
8291}
8292
8293static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
8294 struct bpf_program *prog);
8295static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
8296 struct bpf_program *prog);
8297static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
8298 struct bpf_program *prog);
8299static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
8300 struct bpf_program *prog);
8301static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
8302 struct bpf_program *prog);
8303static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
8304 struct bpf_program *prog);
8305
8306static const struct bpf_sec_def section_defs[] = {
David Brazdil0f672f62019-12-10 10:32:29 +00008307 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
Olivier Deprez157378f2022-04-04 15:47:50 +02008308 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
8309 SEC_DEF("kprobe/", KPROBE,
8310 .attach_fn = attach_kprobe),
8311 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
8312 SEC_DEF("kretprobe/", KPROBE,
8313 .attach_fn = attach_kprobe),
8314 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
David Brazdil0f672f62019-12-10 10:32:29 +00008315 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
8316 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
Olivier Deprez157378f2022-04-04 15:47:50 +02008317 SEC_DEF("tracepoint/", TRACEPOINT,
8318 .attach_fn = attach_tp),
8319 SEC_DEF("tp/", TRACEPOINT,
8320 .attach_fn = attach_tp),
8321 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
8322 .attach_fn = attach_raw_tp),
8323 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
8324 .attach_fn = attach_raw_tp),
8325 SEC_DEF("tp_btf/", TRACING,
8326 .expected_attach_type = BPF_TRACE_RAW_TP,
8327 .is_attach_btf = true,
8328 .attach_fn = attach_trace),
8329 SEC_DEF("fentry/", TRACING,
8330 .expected_attach_type = BPF_TRACE_FENTRY,
8331 .is_attach_btf = true,
8332 .attach_fn = attach_trace),
8333 SEC_DEF("fmod_ret/", TRACING,
8334 .expected_attach_type = BPF_MODIFY_RETURN,
8335 .is_attach_btf = true,
8336 .attach_fn = attach_trace),
8337 SEC_DEF("fexit/", TRACING,
8338 .expected_attach_type = BPF_TRACE_FEXIT,
8339 .is_attach_btf = true,
8340 .attach_fn = attach_trace),
8341 SEC_DEF("fentry.s/", TRACING,
8342 .expected_attach_type = BPF_TRACE_FENTRY,
8343 .is_attach_btf = true,
8344 .is_sleepable = true,
8345 .attach_fn = attach_trace),
8346 SEC_DEF("fmod_ret.s/", TRACING,
8347 .expected_attach_type = BPF_MODIFY_RETURN,
8348 .is_attach_btf = true,
8349 .is_sleepable = true,
8350 .attach_fn = attach_trace),
8351 SEC_DEF("fexit.s/", TRACING,
8352 .expected_attach_type = BPF_TRACE_FEXIT,
8353 .is_attach_btf = true,
8354 .is_sleepable = true,
8355 .attach_fn = attach_trace),
8356 SEC_DEF("freplace/", EXT,
8357 .is_attach_btf = true,
8358 .attach_fn = attach_trace),
8359 SEC_DEF("lsm/", LSM,
8360 .is_attach_btf = true,
8361 .expected_attach_type = BPF_LSM_MAC,
8362 .attach_fn = attach_lsm),
8363 SEC_DEF("lsm.s/", LSM,
8364 .is_attach_btf = true,
8365 .is_sleepable = true,
8366 .expected_attach_type = BPF_LSM_MAC,
8367 .attach_fn = attach_lsm),
8368 SEC_DEF("iter/", TRACING,
8369 .expected_attach_type = BPF_TRACE_ITER,
8370 .is_attach_btf = true,
8371 .attach_fn = attach_iter),
8372 BPF_EAPROG_SEC("xdp_devmap/", BPF_PROG_TYPE_XDP,
8373 BPF_XDP_DEVMAP),
8374 BPF_EAPROG_SEC("xdp_cpumap/", BPF_PROG_TYPE_XDP,
8375 BPF_XDP_CPUMAP),
8376 BPF_APROG_SEC("xdp", BPF_PROG_TYPE_XDP,
8377 BPF_XDP),
David Brazdil0f672f62019-12-10 10:32:29 +00008378 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
8379 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
8380 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
8381 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
8382 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
8383 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
8384 BPF_CGROUP_INET_INGRESS),
8385 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
8386 BPF_CGROUP_INET_EGRESS),
8387 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
Olivier Deprez157378f2022-04-04 15:47:50 +02008388 BPF_EAPROG_SEC("cgroup/sock_create", BPF_PROG_TYPE_CGROUP_SOCK,
8389 BPF_CGROUP_INET_SOCK_CREATE),
8390 BPF_EAPROG_SEC("cgroup/sock_release", BPF_PROG_TYPE_CGROUP_SOCK,
8391 BPF_CGROUP_INET_SOCK_RELEASE),
David Brazdil0f672f62019-12-10 10:32:29 +00008392 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
8393 BPF_CGROUP_INET_SOCK_CREATE),
8394 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
8395 BPF_CGROUP_INET4_POST_BIND),
8396 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
8397 BPF_CGROUP_INET6_POST_BIND),
8398 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
8399 BPF_CGROUP_DEVICE),
8400 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
8401 BPF_CGROUP_SOCK_OPS),
8402 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
8403 BPF_SK_SKB_STREAM_PARSER),
8404 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
8405 BPF_SK_SKB_STREAM_VERDICT),
8406 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
8407 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
8408 BPF_SK_MSG_VERDICT),
8409 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
8410 BPF_LIRC_MODE2),
8411 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
8412 BPF_FLOW_DISSECTOR),
8413 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8414 BPF_CGROUP_INET4_BIND),
8415 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8416 BPF_CGROUP_INET6_BIND),
8417 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8418 BPF_CGROUP_INET4_CONNECT),
8419 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8420 BPF_CGROUP_INET6_CONNECT),
8421 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8422 BPF_CGROUP_UDP4_SENDMSG),
8423 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8424 BPF_CGROUP_UDP6_SENDMSG),
8425 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8426 BPF_CGROUP_UDP4_RECVMSG),
8427 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8428 BPF_CGROUP_UDP6_RECVMSG),
Olivier Deprez157378f2022-04-04 15:47:50 +02008429 BPF_EAPROG_SEC("cgroup/getpeername4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8430 BPF_CGROUP_INET4_GETPEERNAME),
8431 BPF_EAPROG_SEC("cgroup/getpeername6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8432 BPF_CGROUP_INET6_GETPEERNAME),
8433 BPF_EAPROG_SEC("cgroup/getsockname4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8434 BPF_CGROUP_INET4_GETSOCKNAME),
8435 BPF_EAPROG_SEC("cgroup/getsockname6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
8436 BPF_CGROUP_INET6_GETSOCKNAME),
David Brazdil0f672f62019-12-10 10:32:29 +00008437 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
8438 BPF_CGROUP_SYSCTL),
8439 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8440 BPF_CGROUP_GETSOCKOPT),
8441 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
8442 BPF_CGROUP_SETSOCKOPT),
Olivier Deprez157378f2022-04-04 15:47:50 +02008443 BPF_PROG_SEC("struct_ops", BPF_PROG_TYPE_STRUCT_OPS),
8444 BPF_EAPROG_SEC("sk_lookup/", BPF_PROG_TYPE_SK_LOOKUP,
8445 BPF_SK_LOOKUP),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008446};
8447
David Brazdil0f672f62019-12-10 10:32:29 +00008448#undef BPF_PROG_SEC_IMPL
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008449#undef BPF_PROG_SEC
David Brazdil0f672f62019-12-10 10:32:29 +00008450#undef BPF_APROG_SEC
8451#undef BPF_EAPROG_SEC
8452#undef BPF_APROG_COMPAT
Olivier Deprez157378f2022-04-04 15:47:50 +02008453#undef SEC_DEF
David Brazdil0f672f62019-12-10 10:32:29 +00008454
8455#define MAX_TYPE_NAME_SIZE 32
8456
Olivier Deprez157378f2022-04-04 15:47:50 +02008457static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8458{
8459 int i, n = ARRAY_SIZE(section_defs);
8460
8461 for (i = 0; i < n; i++) {
8462 if (strncmp(sec_name,
8463 section_defs[i].sec, section_defs[i].len))
8464 continue;
8465 return &section_defs[i];
8466 }
8467 return NULL;
8468}
8469
David Brazdil0f672f62019-12-10 10:32:29 +00008470static char *libbpf_get_type_names(bool attach_type)
8471{
Olivier Deprez157378f2022-04-04 15:47:50 +02008472 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
David Brazdil0f672f62019-12-10 10:32:29 +00008473 char *buf;
8474
8475 buf = malloc(len);
8476 if (!buf)
8477 return NULL;
8478
8479 buf[0] = '\0';
8480 /* Forge string buf with all available names */
Olivier Deprez157378f2022-04-04 15:47:50 +02008481 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8482 if (attach_type && !section_defs[i].is_attachable)
David Brazdil0f672f62019-12-10 10:32:29 +00008483 continue;
8484
Olivier Deprez157378f2022-04-04 15:47:50 +02008485 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
David Brazdil0f672f62019-12-10 10:32:29 +00008486 free(buf);
8487 return NULL;
8488 }
8489 strcat(buf, " ");
Olivier Deprez157378f2022-04-04 15:47:50 +02008490 strcat(buf, section_defs[i].sec);
David Brazdil0f672f62019-12-10 10:32:29 +00008491 }
8492
8493 return buf;
8494}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008495
8496int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8497 enum bpf_attach_type *expected_attach_type)
8498{
Olivier Deprez157378f2022-04-04 15:47:50 +02008499 const struct bpf_sec_def *sec_def;
David Brazdil0f672f62019-12-10 10:32:29 +00008500 char *type_names;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008501
8502 if (!name)
8503 return -EINVAL;
8504
Olivier Deprez157378f2022-04-04 15:47:50 +02008505 sec_def = find_sec_def(name);
8506 if (sec_def) {
8507 *prog_type = sec_def->prog_type;
8508 *expected_attach_type = sec_def->expected_attach_type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008509 return 0;
8510 }
Olivier Deprez157378f2022-04-04 15:47:50 +02008511
8512 pr_debug("failed to guess program type from ELF section '%s'\n", name);
David Brazdil0f672f62019-12-10 10:32:29 +00008513 type_names = libbpf_get_type_names(false);
8514 if (type_names != NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008515 pr_debug("supported section(type) names are:%s\n", type_names);
David Brazdil0f672f62019-12-10 10:32:29 +00008516 free(type_names);
8517 }
8518
Olivier Deprez157378f2022-04-04 15:47:50 +02008519 return -ESRCH;
8520}
8521
8522static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8523 size_t offset)
8524{
8525 struct bpf_map *map;
8526 size_t i;
8527
8528 for (i = 0; i < obj->nr_maps; i++) {
8529 map = &obj->maps[i];
8530 if (!bpf_map__is_struct_ops(map))
8531 continue;
8532 if (map->sec_offset <= offset &&
8533 offset - map->sec_offset < map->def.value_size)
8534 return map;
8535 }
8536
8537 return NULL;
8538}
8539
8540/* Collect the reloc from ELF and populate the st_ops->progs[] */
8541static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8542 GElf_Shdr *shdr, Elf_Data *data)
8543{
8544 const struct btf_member *member;
8545 struct bpf_struct_ops *st_ops;
8546 struct bpf_program *prog;
8547 unsigned int shdr_idx;
8548 const struct btf *btf;
8549 struct bpf_map *map;
8550 Elf_Data *symbols;
8551 unsigned int moff, insn_idx;
8552 const char *name;
8553 __u32 member_idx;
8554 GElf_Sym sym;
8555 GElf_Rel rel;
8556 int i, nrels;
8557
8558 symbols = obj->efile.symbols;
8559 btf = obj->btf;
8560 nrels = shdr->sh_size / shdr->sh_entsize;
8561 for (i = 0; i < nrels; i++) {
8562 if (!gelf_getrel(data, i, &rel)) {
8563 pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8564 return -LIBBPF_ERRNO__FORMAT;
8565 }
8566
8567 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
8568 pr_warn("struct_ops reloc: symbol %zx not found\n",
8569 (size_t)GELF_R_SYM(rel.r_info));
8570 return -LIBBPF_ERRNO__FORMAT;
8571 }
8572
8573 name = elf_sym_str(obj, sym.st_name) ?: "<?>";
8574 map = find_struct_ops_map_by_offset(obj, rel.r_offset);
8575 if (!map) {
8576 pr_warn("struct_ops reloc: cannot find map at rel.r_offset %zu\n",
8577 (size_t)rel.r_offset);
8578 return -EINVAL;
8579 }
8580
8581 moff = rel.r_offset - map->sec_offset;
8582 shdr_idx = sym.st_shndx;
8583 st_ops = map->st_ops;
8584 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",
8585 map->name,
8586 (long long)(rel.r_info >> 32),
8587 (long long)sym.st_value,
8588 shdr_idx, (size_t)rel.r_offset,
8589 map->sec_offset, sym.st_name, name);
8590
8591 if (shdr_idx >= SHN_LORESERVE) {
8592 pr_warn("struct_ops reloc %s: rel.r_offset %zu shdr_idx %u unsupported non-static function\n",
8593 map->name, (size_t)rel.r_offset, shdr_idx);
8594 return -LIBBPF_ERRNO__RELOC;
8595 }
8596 if (sym.st_value % BPF_INSN_SZ) {
8597 pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8598 map->name, (unsigned long long)sym.st_value);
8599 return -LIBBPF_ERRNO__FORMAT;
8600 }
8601 insn_idx = sym.st_value / BPF_INSN_SZ;
8602
8603 member = find_member_by_offset(st_ops->type, moff * 8);
8604 if (!member) {
8605 pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8606 map->name, moff);
8607 return -EINVAL;
8608 }
8609 member_idx = member - btf_members(st_ops->type);
8610 name = btf__name_by_offset(btf, member->name_off);
8611
8612 if (!resolve_func_ptr(btf, member->type, NULL)) {
8613 pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8614 map->name, name);
8615 return -EINVAL;
8616 }
8617
8618 prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8619 if (!prog) {
8620 pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8621 map->name, shdr_idx, name);
8622 return -EINVAL;
8623 }
8624
8625 if (prog->type == BPF_PROG_TYPE_UNSPEC) {
8626 const struct bpf_sec_def *sec_def;
8627
8628 sec_def = find_sec_def(prog->sec_name);
8629 if (sec_def &&
8630 sec_def->prog_type != BPF_PROG_TYPE_STRUCT_OPS) {
8631 /* for pr_warn */
8632 prog->type = sec_def->prog_type;
8633 goto invalid_prog;
8634 }
8635
8636 prog->type = BPF_PROG_TYPE_STRUCT_OPS;
8637 prog->attach_btf_id = st_ops->type_id;
8638 prog->expected_attach_type = member_idx;
8639 } else if (prog->type != BPF_PROG_TYPE_STRUCT_OPS ||
8640 prog->attach_btf_id != st_ops->type_id ||
8641 prog->expected_attach_type != member_idx) {
8642 goto invalid_prog;
8643 }
8644 st_ops->progs[member_idx] = prog;
8645 }
8646
8647 return 0;
8648
8649invalid_prog:
8650 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",
8651 map->name, prog->name, prog->sec_name, prog->type,
8652 prog->attach_btf_id, prog->expected_attach_type, name);
David Brazdil0f672f62019-12-10 10:32:29 +00008653 return -EINVAL;
8654}
8655
Olivier Deprez157378f2022-04-04 15:47:50 +02008656#define BTF_TRACE_PREFIX "btf_trace_"
8657#define BTF_LSM_PREFIX "bpf_lsm_"
8658#define BTF_ITER_PREFIX "bpf_iter_"
8659#define BTF_MAX_NAME_SIZE 128
8660
8661static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8662 const char *name, __u32 kind)
8663{
8664 char btf_type_name[BTF_MAX_NAME_SIZE];
8665 int ret;
8666
8667 ret = snprintf(btf_type_name, sizeof(btf_type_name),
8668 "%s%s", prefix, name);
8669 /* snprintf returns the number of characters written excluding the
8670 * the terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8671 * indicates truncation.
8672 */
8673 if (ret < 0 || ret >= sizeof(btf_type_name))
8674 return -ENAMETOOLONG;
8675 return btf__find_by_name_kind(btf, btf_type_name, kind);
8676}
8677
8678static inline int __find_vmlinux_btf_id(struct btf *btf, const char *name,
8679 enum bpf_attach_type attach_type)
8680{
8681 int err;
8682
8683 if (attach_type == BPF_TRACE_RAW_TP)
8684 err = find_btf_by_prefix_kind(btf, BTF_TRACE_PREFIX, name,
8685 BTF_KIND_TYPEDEF);
8686 else if (attach_type == BPF_LSM_MAC)
8687 err = find_btf_by_prefix_kind(btf, BTF_LSM_PREFIX, name,
8688 BTF_KIND_FUNC);
8689 else if (attach_type == BPF_TRACE_ITER)
8690 err = find_btf_by_prefix_kind(btf, BTF_ITER_PREFIX, name,
8691 BTF_KIND_FUNC);
8692 else
8693 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8694
8695 if (err <= 0)
8696 pr_warn("%s is not found in vmlinux BTF\n", name);
8697
8698 return err;
8699}
8700
8701int libbpf_find_vmlinux_btf_id(const char *name,
8702 enum bpf_attach_type attach_type)
8703{
8704 struct btf *btf;
8705 int err;
8706
8707 btf = libbpf_find_kernel_btf();
8708 if (IS_ERR(btf)) {
8709 pr_warn("vmlinux BTF is not found\n");
8710 return -EINVAL;
8711 }
8712
8713 err = __find_vmlinux_btf_id(btf, name, attach_type);
8714 btf__free(btf);
8715 return err;
8716}
8717
8718static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
8719{
8720 struct bpf_prog_info_linear *info_linear;
8721 struct bpf_prog_info *info;
8722 struct btf *btf = NULL;
8723 int err = -EINVAL;
8724
8725 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
8726 if (IS_ERR_OR_NULL(info_linear)) {
8727 pr_warn("failed get_prog_info_linear for FD %d\n",
8728 attach_prog_fd);
8729 return -EINVAL;
8730 }
8731 info = &info_linear->info;
8732 if (!info->btf_id) {
8733 pr_warn("The target program doesn't have BTF\n");
8734 goto out;
8735 }
8736 if (btf__get_from_id(info->btf_id, &btf)) {
8737 pr_warn("Failed to get BTF of the program\n");
8738 goto out;
8739 }
8740 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
8741 btf__free(btf);
8742 if (err <= 0) {
8743 pr_warn("%s is not found in prog's BTF\n", name);
8744 goto out;
8745 }
8746out:
8747 free(info_linear);
8748 return err;
8749}
8750
8751static int libbpf_find_attach_btf_id(struct bpf_program *prog)
8752{
8753 enum bpf_attach_type attach_type = prog->expected_attach_type;
8754 __u32 attach_prog_fd = prog->attach_prog_fd;
8755 const char *name = prog->sec_name;
8756 int i, err;
8757
8758 if (!name)
8759 return -EINVAL;
8760
8761 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8762 if (!section_defs[i].is_attach_btf)
8763 continue;
8764 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
8765 continue;
8766 if (attach_prog_fd)
8767 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
8768 attach_prog_fd);
8769 else
8770 err = __find_vmlinux_btf_id(prog->obj->btf_vmlinux,
8771 name + section_defs[i].len,
8772 attach_type);
8773 return err;
8774 }
8775 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
8776 return -ESRCH;
8777}
8778
David Brazdil0f672f62019-12-10 10:32:29 +00008779int libbpf_attach_type_by_name(const char *name,
8780 enum bpf_attach_type *attach_type)
8781{
8782 char *type_names;
8783 int i;
8784
8785 if (!name)
8786 return -EINVAL;
8787
Olivier Deprez157378f2022-04-04 15:47:50 +02008788 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8789 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
David Brazdil0f672f62019-12-10 10:32:29 +00008790 continue;
Olivier Deprez157378f2022-04-04 15:47:50 +02008791 if (!section_defs[i].is_attachable)
David Brazdil0f672f62019-12-10 10:32:29 +00008792 return -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +02008793 *attach_type = section_defs[i].expected_attach_type;
David Brazdil0f672f62019-12-10 10:32:29 +00008794 return 0;
8795 }
Olivier Deprez157378f2022-04-04 15:47:50 +02008796 pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
David Brazdil0f672f62019-12-10 10:32:29 +00008797 type_names = libbpf_get_type_names(true);
8798 if (type_names != NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008799 pr_debug("attachable section(type) names are:%s\n", type_names);
David Brazdil0f672f62019-12-10 10:32:29 +00008800 free(type_names);
8801 }
8802
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008803 return -EINVAL;
8804}
8805
David Brazdil0f672f62019-12-10 10:32:29 +00008806int bpf_map__fd(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008807{
8808 return map ? map->fd : -EINVAL;
8809}
8810
David Brazdil0f672f62019-12-10 10:32:29 +00008811const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008812{
8813 return map ? &map->def : ERR_PTR(-EINVAL);
8814}
8815
David Brazdil0f672f62019-12-10 10:32:29 +00008816const char *bpf_map__name(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008817{
8818 return map ? map->name : NULL;
8819}
8820
Olivier Deprez157378f2022-04-04 15:47:50 +02008821enum bpf_map_type bpf_map__type(const struct bpf_map *map)
8822{
8823 return map->def.type;
8824}
8825
8826int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
8827{
8828 if (map->fd >= 0)
8829 return -EBUSY;
8830 map->def.type = type;
8831 return 0;
8832}
8833
8834__u32 bpf_map__map_flags(const struct bpf_map *map)
8835{
8836 return map->def.map_flags;
8837}
8838
8839int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
8840{
8841 if (map->fd >= 0)
8842 return -EBUSY;
8843 map->def.map_flags = flags;
8844 return 0;
8845}
8846
8847__u32 bpf_map__numa_node(const struct bpf_map *map)
8848{
8849 return map->numa_node;
8850}
8851
8852int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
8853{
8854 if (map->fd >= 0)
8855 return -EBUSY;
8856 map->numa_node = numa_node;
8857 return 0;
8858}
8859
8860__u32 bpf_map__key_size(const struct bpf_map *map)
8861{
8862 return map->def.key_size;
8863}
8864
8865int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
8866{
8867 if (map->fd >= 0)
8868 return -EBUSY;
8869 map->def.key_size = size;
8870 return 0;
8871}
8872
8873__u32 bpf_map__value_size(const struct bpf_map *map)
8874{
8875 return map->def.value_size;
8876}
8877
8878int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
8879{
8880 if (map->fd >= 0)
8881 return -EBUSY;
8882 map->def.value_size = size;
8883 return 0;
8884}
8885
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008886__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
8887{
8888 return map ? map->btf_key_type_id : 0;
8889}
8890
8891__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
8892{
8893 return map ? map->btf_value_type_id : 0;
8894}
8895
8896int bpf_map__set_priv(struct bpf_map *map, void *priv,
8897 bpf_map_clear_priv_t clear_priv)
8898{
8899 if (!map)
8900 return -EINVAL;
8901
8902 if (map->priv) {
8903 if (map->clear_priv)
8904 map->clear_priv(map, map->priv);
8905 }
8906
8907 map->priv = priv;
8908 map->clear_priv = clear_priv;
8909 return 0;
8910}
8911
David Brazdil0f672f62019-12-10 10:32:29 +00008912void *bpf_map__priv(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008913{
8914 return map ? map->priv : ERR_PTR(-EINVAL);
8915}
8916
Olivier Deprez157378f2022-04-04 15:47:50 +02008917int bpf_map__set_initial_value(struct bpf_map *map,
8918 const void *data, size_t size)
8919{
8920 if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
8921 size != map->def.value_size || map->fd >= 0)
8922 return -EINVAL;
8923
8924 memcpy(map->mmaped, data, size);
8925 return 0;
8926}
8927
David Brazdil0f672f62019-12-10 10:32:29 +00008928bool bpf_map__is_offload_neutral(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008929{
8930 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
8931}
8932
David Brazdil0f672f62019-12-10 10:32:29 +00008933bool bpf_map__is_internal(const struct bpf_map *map)
8934{
8935 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
8936}
8937
Olivier Deprez157378f2022-04-04 15:47:50 +02008938__u32 bpf_map__ifindex(const struct bpf_map *map)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008939{
Olivier Deprez157378f2022-04-04 15:47:50 +02008940 return map->map_ifindex;
8941}
8942
8943int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
8944{
8945 if (map->fd >= 0)
8946 return -EBUSY;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008947 map->map_ifindex = ifindex;
Olivier Deprez157378f2022-04-04 15:47:50 +02008948 return 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008949}
8950
David Brazdil0f672f62019-12-10 10:32:29 +00008951int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008952{
David Brazdil0f672f62019-12-10 10:32:29 +00008953 if (!bpf_map_type__is_map_in_map(map->def.type)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008954 pr_warn("error: unsupported map type\n");
David Brazdil0f672f62019-12-10 10:32:29 +00008955 return -EINVAL;
8956 }
8957 if (map->inner_map_fd != -1) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008958 pr_warn("error: inner_map_fd already specified\n");
David Brazdil0f672f62019-12-10 10:32:29 +00008959 return -EINVAL;
8960 }
8961 map->inner_map_fd = fd;
8962 return 0;
8963}
8964
8965static struct bpf_map *
8966__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
8967{
8968 ssize_t idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008969 struct bpf_map *s, *e;
8970
8971 if (!obj || !obj->maps)
8972 return NULL;
8973
8974 s = obj->maps;
8975 e = obj->maps + obj->nr_maps;
8976
David Brazdil0f672f62019-12-10 10:32:29 +00008977 if ((m < s) || (m >= e)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02008978 pr_warn("error in %s: map handler doesn't belong to object\n",
8979 __func__);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008980 return NULL;
8981 }
8982
David Brazdil0f672f62019-12-10 10:32:29 +00008983 idx = (m - obj->maps) + i;
8984 if (idx >= obj->nr_maps || idx < 0)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00008985 return NULL;
8986 return &obj->maps[idx];
8987}
8988
8989struct bpf_map *
David Brazdil0f672f62019-12-10 10:32:29 +00008990bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
8991{
8992 if (prev == NULL)
8993 return obj->maps;
8994
8995 return __bpf_map__iter(prev, obj, 1);
8996}
8997
8998struct bpf_map *
8999bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
9000{
9001 if (next == NULL) {
9002 if (!obj->nr_maps)
9003 return NULL;
9004 return obj->maps + obj->nr_maps - 1;
9005 }
9006
9007 return __bpf_map__iter(next, obj, -1);
9008}
9009
9010struct bpf_map *
9011bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009012{
9013 struct bpf_map *pos;
9014
David Brazdil0f672f62019-12-10 10:32:29 +00009015 bpf_object__for_each_map(pos, obj) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009016 if (pos->name && !strcmp(pos->name, name))
9017 return pos;
9018 }
9019 return NULL;
9020}
9021
David Brazdil0f672f62019-12-10 10:32:29 +00009022int
9023bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9024{
9025 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9026}
9027
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009028struct bpf_map *
9029bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
9030{
David Brazdil0f672f62019-12-10 10:32:29 +00009031 return ERR_PTR(-ENOTSUP);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009032}
9033
9034long libbpf_get_error(const void *ptr)
9035{
David Brazdil0f672f62019-12-10 10:32:29 +00009036 return PTR_ERR_OR_ZERO(ptr);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009037}
9038
9039int bpf_prog_load(const char *file, enum bpf_prog_type type,
9040 struct bpf_object **pobj, int *prog_fd)
9041{
9042 struct bpf_prog_load_attr attr;
9043
9044 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
9045 attr.file = file;
9046 attr.prog_type = type;
9047 attr.expected_attach_type = 0;
9048
9049 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
9050}
9051
9052int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
9053 struct bpf_object **pobj, int *prog_fd)
9054{
David Brazdil0f672f62019-12-10 10:32:29 +00009055 struct bpf_object_open_attr open_attr = {};
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009056 struct bpf_program *prog, *first_prog = NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009057 struct bpf_object *obj;
9058 struct bpf_map *map;
9059 int err;
9060
9061 if (!attr)
9062 return -EINVAL;
9063 if (!attr->file)
9064 return -EINVAL;
9065
David Brazdil0f672f62019-12-10 10:32:29 +00009066 open_attr.file = attr->file;
9067 open_attr.prog_type = attr->prog_type;
9068
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009069 obj = bpf_object__open_xattr(&open_attr);
9070 if (IS_ERR_OR_NULL(obj))
9071 return -ENOENT;
9072
9073 bpf_object__for_each_program(prog, obj) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009074 enum bpf_attach_type attach_type = attr->expected_attach_type;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009075 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02009076 * to preserve backwards compatibility, bpf_prog_load treats
9077 * attr->prog_type, if specified, as an override to whatever
9078 * bpf_object__open guessed
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009079 */
Olivier Deprez157378f2022-04-04 15:47:50 +02009080 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
9081 bpf_program__set_type(prog, attr->prog_type);
9082 bpf_program__set_expected_attach_type(prog,
9083 attach_type);
9084 }
9085 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
9086 /*
9087 * we haven't guessed from section name and user
9088 * didn't provide a fallback type, too bad...
9089 */
9090 bpf_object__close(obj);
9091 return -EINVAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009092 }
9093
Olivier Deprez157378f2022-04-04 15:47:50 +02009094 prog->prog_ifindex = attr->ifindex;
David Brazdil0f672f62019-12-10 10:32:29 +00009095 prog->log_level = attr->log_level;
Olivier Deprez157378f2022-04-04 15:47:50 +02009096 prog->prog_flags |= attr->prog_flags;
David Brazdil0f672f62019-12-10 10:32:29 +00009097 if (!first_prog)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009098 first_prog = prog;
9099 }
9100
David Brazdil0f672f62019-12-10 10:32:29 +00009101 bpf_object__for_each_map(map, obj) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009102 if (!bpf_map__is_offload_neutral(map))
9103 map->map_ifindex = attr->ifindex;
9104 }
9105
9106 if (!first_prog) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009107 pr_warn("object file doesn't contain bpf program\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009108 bpf_object__close(obj);
9109 return -ENOENT;
9110 }
9111
9112 err = bpf_object__load(obj);
9113 if (err) {
9114 bpf_object__close(obj);
Olivier Deprez157378f2022-04-04 15:47:50 +02009115 return err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009116 }
9117
9118 *pobj = obj;
9119 *prog_fd = bpf_program__fd(first_prog);
9120 return 0;
9121}
9122
David Brazdil0f672f62019-12-10 10:32:29 +00009123struct bpf_link {
Olivier Deprez157378f2022-04-04 15:47:50 +02009124 int (*detach)(struct bpf_link *link);
David Brazdil0f672f62019-12-10 10:32:29 +00009125 int (*destroy)(struct bpf_link *link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009126 char *pin_path; /* NULL, if not pinned */
9127 int fd; /* hook FD, -1 if not applicable */
9128 bool disconnected;
David Brazdil0f672f62019-12-10 10:32:29 +00009129};
9130
Olivier Deprez157378f2022-04-04 15:47:50 +02009131/* Replace link's underlying BPF program with the new one */
9132int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9133{
9134 return bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9135}
9136
9137/* Release "ownership" of underlying BPF resource (typically, BPF program
9138 * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9139 * link, when destructed through bpf_link__destroy() call won't attempt to
9140 * detach/unregisted that BPF resource. This is useful in situations where,
9141 * say, attached BPF program has to outlive userspace program that attached it
9142 * in the system. Depending on type of BPF program, though, there might be
9143 * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9144 * exit of userspace program doesn't trigger automatic detachment and clean up
9145 * inside the kernel.
9146 */
9147void bpf_link__disconnect(struct bpf_link *link)
9148{
9149 link->disconnected = true;
9150}
9151
David Brazdil0f672f62019-12-10 10:32:29 +00009152int bpf_link__destroy(struct bpf_link *link)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009153{
Olivier Deprez157378f2022-04-04 15:47:50 +02009154 int err = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00009155
Olivier Deprez157378f2022-04-04 15:47:50 +02009156 if (IS_ERR_OR_NULL(link))
David Brazdil0f672f62019-12-10 10:32:29 +00009157 return 0;
9158
Olivier Deprez157378f2022-04-04 15:47:50 +02009159 if (!link->disconnected && link->detach)
9160 err = link->detach(link);
9161 if (link->destroy)
9162 link->destroy(link);
9163 if (link->pin_path)
9164 free(link->pin_path);
David Brazdil0f672f62019-12-10 10:32:29 +00009165 free(link);
9166
9167 return err;
9168}
9169
Olivier Deprez157378f2022-04-04 15:47:50 +02009170int bpf_link__fd(const struct bpf_link *link)
David Brazdil0f672f62019-12-10 10:32:29 +00009171{
Olivier Deprez157378f2022-04-04 15:47:50 +02009172 return link->fd;
9173}
9174
9175const char *bpf_link__pin_path(const struct bpf_link *link)
9176{
9177 return link->pin_path;
9178}
9179
9180static int bpf_link__detach_fd(struct bpf_link *link)
9181{
9182 return close(link->fd);
9183}
9184
9185struct bpf_link *bpf_link__open(const char *path)
9186{
9187 struct bpf_link *link;
9188 int fd;
9189
9190 fd = bpf_obj_get(path);
9191 if (fd < 0) {
9192 fd = -errno;
9193 pr_warn("failed to open link at %s: %d\n", path, fd);
9194 return ERR_PTR(fd);
9195 }
9196
9197 link = calloc(1, sizeof(*link));
9198 if (!link) {
9199 close(fd);
9200 return ERR_PTR(-ENOMEM);
9201 }
9202 link->detach = &bpf_link__detach_fd;
9203 link->fd = fd;
9204
9205 link->pin_path = strdup(path);
9206 if (!link->pin_path) {
9207 bpf_link__destroy(link);
9208 return ERR_PTR(-ENOMEM);
9209 }
9210
9211 return link;
9212}
9213
9214int bpf_link__detach(struct bpf_link *link)
9215{
9216 return bpf_link_detach(link->fd) ? -errno : 0;
9217}
9218
9219int bpf_link__pin(struct bpf_link *link, const char *path)
9220{
David Brazdil0f672f62019-12-10 10:32:29 +00009221 int err;
9222
Olivier Deprez157378f2022-04-04 15:47:50 +02009223 if (link->pin_path)
9224 return -EBUSY;
9225 err = make_parent_dir(path);
9226 if (err)
9227 return err;
9228 err = check_path(path);
9229 if (err)
9230 return err;
9231
9232 link->pin_path = strdup(path);
9233 if (!link->pin_path)
9234 return -ENOMEM;
9235
9236 if (bpf_obj_pin(link->fd, link->pin_path)) {
9237 err = -errno;
9238 zfree(&link->pin_path);
9239 return err;
9240 }
9241
9242 pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9243 return 0;
9244}
9245
9246int bpf_link__unpin(struct bpf_link *link)
9247{
9248 int err;
9249
9250 if (!link->pin_path)
9251 return -EINVAL;
9252
9253 err = unlink(link->pin_path);
9254 if (err != 0)
9255 return -errno;
9256
9257 pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9258 zfree(&link->pin_path);
9259 return 0;
9260}
9261
9262static int bpf_link__detach_perf_event(struct bpf_link *link)
9263{
9264 int err;
9265
9266 err = ioctl(link->fd, PERF_EVENT_IOC_DISABLE, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00009267 if (err)
9268 err = -errno;
9269
Olivier Deprez157378f2022-04-04 15:47:50 +02009270 close(link->fd);
David Brazdil0f672f62019-12-10 10:32:29 +00009271 return err;
9272}
9273
9274struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
9275 int pfd)
9276{
9277 char errmsg[STRERR_BUFSIZE];
Olivier Deprez157378f2022-04-04 15:47:50 +02009278 struct bpf_link *link;
David Brazdil0f672f62019-12-10 10:32:29 +00009279 int prog_fd, err;
9280
9281 if (pfd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009282 pr_warn("prog '%s': invalid perf event FD %d\n",
9283 prog->name, pfd);
David Brazdil0f672f62019-12-10 10:32:29 +00009284 return ERR_PTR(-EINVAL);
9285 }
9286 prog_fd = bpf_program__fd(prog);
9287 if (prog_fd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009288 pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9289 prog->name);
David Brazdil0f672f62019-12-10 10:32:29 +00009290 return ERR_PTR(-EINVAL);
9291 }
9292
Olivier Deprez157378f2022-04-04 15:47:50 +02009293 link = calloc(1, sizeof(*link));
David Brazdil0f672f62019-12-10 10:32:29 +00009294 if (!link)
9295 return ERR_PTR(-ENOMEM);
Olivier Deprez157378f2022-04-04 15:47:50 +02009296 link->detach = &bpf_link__detach_perf_event;
David Brazdil0f672f62019-12-10 10:32:29 +00009297 link->fd = pfd;
9298
9299 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9300 err = -errno;
9301 free(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009302 pr_warn("prog '%s': failed to attach to pfd %d: %s\n",
9303 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9304 if (err == -EPROTO)
9305 pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9306 prog->name, pfd);
David Brazdil0f672f62019-12-10 10:32:29 +00009307 return ERR_PTR(err);
9308 }
9309 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9310 err = -errno;
9311 free(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009312 pr_warn("prog '%s': failed to enable pfd %d: %s\n",
9313 prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009314 return ERR_PTR(err);
9315 }
Olivier Deprez157378f2022-04-04 15:47:50 +02009316 return link;
David Brazdil0f672f62019-12-10 10:32:29 +00009317}
9318
9319/*
9320 * this function is expected to parse integer in the range of [0, 2^31-1] from
9321 * given file using scanf format string fmt. If actual parsed value is
9322 * negative, the result might be indistinguishable from error
9323 */
9324static int parse_uint_from_file(const char *file, const char *fmt)
9325{
9326 char buf[STRERR_BUFSIZE];
9327 int err, ret;
9328 FILE *f;
9329
9330 f = fopen(file, "r");
9331 if (!f) {
9332 err = -errno;
9333 pr_debug("failed to open '%s': %s\n", file,
9334 libbpf_strerror_r(err, buf, sizeof(buf)));
9335 return err;
9336 }
9337 err = fscanf(f, fmt, &ret);
9338 if (err != 1) {
9339 err = err == EOF ? -EIO : -errno;
9340 pr_debug("failed to parse '%s': %s\n", file,
9341 libbpf_strerror_r(err, buf, sizeof(buf)));
9342 fclose(f);
9343 return err;
9344 }
9345 fclose(f);
9346 return ret;
9347}
9348
9349static int determine_kprobe_perf_type(void)
9350{
9351 const char *file = "/sys/bus/event_source/devices/kprobe/type";
9352
9353 return parse_uint_from_file(file, "%d\n");
9354}
9355
9356static int determine_uprobe_perf_type(void)
9357{
9358 const char *file = "/sys/bus/event_source/devices/uprobe/type";
9359
9360 return parse_uint_from_file(file, "%d\n");
9361}
9362
9363static int determine_kprobe_retprobe_bit(void)
9364{
9365 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9366
9367 return parse_uint_from_file(file, "config:%d\n");
9368}
9369
9370static int determine_uprobe_retprobe_bit(void)
9371{
9372 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9373
9374 return parse_uint_from_file(file, "config:%d\n");
9375}
9376
9377static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9378 uint64_t offset, int pid)
9379{
9380 struct perf_event_attr attr = {};
9381 char errmsg[STRERR_BUFSIZE];
9382 int type, pfd, err;
9383
9384 type = uprobe ? determine_uprobe_perf_type()
9385 : determine_kprobe_perf_type();
9386 if (type < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009387 pr_warn("failed to determine %s perf type: %s\n",
9388 uprobe ? "uprobe" : "kprobe",
9389 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009390 return type;
9391 }
9392 if (retprobe) {
9393 int bit = uprobe ? determine_uprobe_retprobe_bit()
9394 : determine_kprobe_retprobe_bit();
9395
9396 if (bit < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009397 pr_warn("failed to determine %s retprobe bit: %s\n",
9398 uprobe ? "uprobe" : "kprobe",
9399 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009400 return bit;
9401 }
9402 attr.config |= 1 << bit;
9403 }
9404 attr.size = sizeof(attr);
9405 attr.type = type;
9406 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9407 attr.config2 = offset; /* kprobe_addr or probe_offset */
9408
9409 /* pid filter is meaningful only for uprobes */
9410 pfd = syscall(__NR_perf_event_open, &attr,
9411 pid < 0 ? -1 : pid /* pid */,
9412 pid == -1 ? 0 : -1 /* cpu */,
9413 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9414 if (pfd < 0) {
9415 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +02009416 pr_warn("%s perf_event_open() failed: %s\n",
9417 uprobe ? "uprobe" : "kprobe",
9418 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009419 return err;
9420 }
9421 return pfd;
9422}
9423
9424struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
9425 bool retprobe,
9426 const char *func_name)
9427{
9428 char errmsg[STRERR_BUFSIZE];
9429 struct bpf_link *link;
9430 int pfd, err;
9431
9432 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
9433 0 /* offset */, -1 /* pid */);
9434 if (pfd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009435 pr_warn("prog '%s': failed to create %s '%s' perf event: %s\n",
9436 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9437 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009438 return ERR_PTR(pfd);
9439 }
9440 link = bpf_program__attach_perf_event(prog, pfd);
9441 if (IS_ERR(link)) {
9442 close(pfd);
9443 err = PTR_ERR(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009444 pr_warn("prog '%s': failed to attach to %s '%s': %s\n",
9445 prog->name, retprobe ? "kretprobe" : "kprobe", func_name,
9446 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009447 return link;
9448 }
9449 return link;
9450}
9451
Olivier Deprez157378f2022-04-04 15:47:50 +02009452static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
9453 struct bpf_program *prog)
9454{
9455 const char *func_name;
9456 bool retprobe;
9457
9458 func_name = prog->sec_name + sec->len;
9459 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
9460
9461 return bpf_program__attach_kprobe(prog, retprobe, func_name);
9462}
9463
David Brazdil0f672f62019-12-10 10:32:29 +00009464struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
9465 bool retprobe, pid_t pid,
9466 const char *binary_path,
9467 size_t func_offset)
9468{
9469 char errmsg[STRERR_BUFSIZE];
9470 struct bpf_link *link;
9471 int pfd, err;
9472
9473 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
9474 binary_path, func_offset, pid);
9475 if (pfd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009476 pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
9477 prog->name, retprobe ? "uretprobe" : "uprobe",
9478 binary_path, func_offset,
9479 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009480 return ERR_PTR(pfd);
9481 }
9482 link = bpf_program__attach_perf_event(prog, pfd);
9483 if (IS_ERR(link)) {
9484 close(pfd);
9485 err = PTR_ERR(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009486 pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
9487 prog->name, retprobe ? "uretprobe" : "uprobe",
9488 binary_path, func_offset,
9489 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009490 return link;
9491 }
9492 return link;
9493}
9494
9495static int determine_tracepoint_id(const char *tp_category,
9496 const char *tp_name)
9497{
9498 char file[PATH_MAX];
9499 int ret;
9500
9501 ret = snprintf(file, sizeof(file),
9502 "/sys/kernel/debug/tracing/events/%s/%s/id",
9503 tp_category, tp_name);
9504 if (ret < 0)
9505 return -errno;
9506 if (ret >= sizeof(file)) {
9507 pr_debug("tracepoint %s/%s path is too long\n",
9508 tp_category, tp_name);
9509 return -E2BIG;
9510 }
9511 return parse_uint_from_file(file, "%d\n");
9512}
9513
9514static int perf_event_open_tracepoint(const char *tp_category,
9515 const char *tp_name)
9516{
9517 struct perf_event_attr attr = {};
9518 char errmsg[STRERR_BUFSIZE];
9519 int tp_id, pfd, err;
9520
9521 tp_id = determine_tracepoint_id(tp_category, tp_name);
9522 if (tp_id < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009523 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
9524 tp_category, tp_name,
9525 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009526 return tp_id;
9527 }
9528
9529 attr.type = PERF_TYPE_TRACEPOINT;
9530 attr.size = sizeof(attr);
9531 attr.config = tp_id;
9532
9533 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
9534 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9535 if (pfd < 0) {
9536 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +02009537 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
9538 tp_category, tp_name,
9539 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009540 return err;
9541 }
9542 return pfd;
9543}
9544
9545struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
9546 const char *tp_category,
9547 const char *tp_name)
9548{
9549 char errmsg[STRERR_BUFSIZE];
9550 struct bpf_link *link;
9551 int pfd, err;
9552
9553 pfd = perf_event_open_tracepoint(tp_category, tp_name);
9554 if (pfd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009555 pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
9556 prog->name, tp_category, tp_name,
9557 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009558 return ERR_PTR(pfd);
9559 }
9560 link = bpf_program__attach_perf_event(prog, pfd);
9561 if (IS_ERR(link)) {
9562 close(pfd);
9563 err = PTR_ERR(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009564 pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
9565 prog->name, tp_category, tp_name,
9566 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009567 return link;
9568 }
9569 return link;
9570}
9571
Olivier Deprez157378f2022-04-04 15:47:50 +02009572static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
9573 struct bpf_program *prog)
David Brazdil0f672f62019-12-10 10:32:29 +00009574{
Olivier Deprez157378f2022-04-04 15:47:50 +02009575 char *sec_name, *tp_cat, *tp_name;
9576 struct bpf_link *link;
David Brazdil0f672f62019-12-10 10:32:29 +00009577
Olivier Deprez157378f2022-04-04 15:47:50 +02009578 sec_name = strdup(prog->sec_name);
9579 if (!sec_name)
9580 return ERR_PTR(-ENOMEM);
9581
9582 /* extract "tp/<category>/<name>" */
9583 tp_cat = sec_name + sec->len;
9584 tp_name = strchr(tp_cat, '/');
9585 if (!tp_name) {
9586 link = ERR_PTR(-EINVAL);
9587 goto out;
9588 }
9589 *tp_name = '\0';
9590 tp_name++;
9591
9592 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
9593out:
9594 free(sec_name);
9595 return link;
David Brazdil0f672f62019-12-10 10:32:29 +00009596}
9597
9598struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
9599 const char *tp_name)
9600{
9601 char errmsg[STRERR_BUFSIZE];
Olivier Deprez157378f2022-04-04 15:47:50 +02009602 struct bpf_link *link;
David Brazdil0f672f62019-12-10 10:32:29 +00009603 int prog_fd, pfd;
9604
9605 prog_fd = bpf_program__fd(prog);
9606 if (prog_fd < 0) {
Olivier Deprez157378f2022-04-04 15:47:50 +02009607 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
David Brazdil0f672f62019-12-10 10:32:29 +00009608 return ERR_PTR(-EINVAL);
9609 }
9610
Olivier Deprez157378f2022-04-04 15:47:50 +02009611 link = calloc(1, sizeof(*link));
David Brazdil0f672f62019-12-10 10:32:29 +00009612 if (!link)
9613 return ERR_PTR(-ENOMEM);
Olivier Deprez157378f2022-04-04 15:47:50 +02009614 link->detach = &bpf_link__detach_fd;
David Brazdil0f672f62019-12-10 10:32:29 +00009615
9616 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
9617 if (pfd < 0) {
9618 pfd = -errno;
9619 free(link);
Olivier Deprez157378f2022-04-04 15:47:50 +02009620 pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
9621 prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
9622 return ERR_PTR(pfd);
9623 }
9624 link->fd = pfd;
9625 return link;
9626}
9627
9628static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
9629 struct bpf_program *prog)
9630{
9631 const char *tp_name = prog->sec_name + sec->len;
9632
9633 return bpf_program__attach_raw_tracepoint(prog, tp_name);
9634}
9635
9636/* Common logic for all BPF program types that attach to a btf_id */
9637static struct bpf_link *bpf_program__attach_btf_id(struct bpf_program *prog)
9638{
9639 char errmsg[STRERR_BUFSIZE];
9640 struct bpf_link *link;
9641 int prog_fd, pfd;
9642
9643 prog_fd = bpf_program__fd(prog);
9644 if (prog_fd < 0) {
9645 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9646 return ERR_PTR(-EINVAL);
9647 }
9648
9649 link = calloc(1, sizeof(*link));
9650 if (!link)
9651 return ERR_PTR(-ENOMEM);
9652 link->detach = &bpf_link__detach_fd;
9653
9654 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
9655 if (pfd < 0) {
9656 pfd = -errno;
9657 free(link);
9658 pr_warn("prog '%s': failed to attach: %s\n",
9659 prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
David Brazdil0f672f62019-12-10 10:32:29 +00009660 return ERR_PTR(pfd);
9661 }
9662 link->fd = pfd;
9663 return (struct bpf_link *)link;
9664}
9665
Olivier Deprez157378f2022-04-04 15:47:50 +02009666struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
9667{
9668 return bpf_program__attach_btf_id(prog);
9669}
9670
9671struct bpf_link *bpf_program__attach_lsm(struct bpf_program *prog)
9672{
9673 return bpf_program__attach_btf_id(prog);
9674}
9675
9676static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
9677 struct bpf_program *prog)
9678{
9679 return bpf_program__attach_trace(prog);
9680}
9681
9682static struct bpf_link *attach_lsm(const struct bpf_sec_def *sec,
9683 struct bpf_program *prog)
9684{
9685 return bpf_program__attach_lsm(prog);
9686}
9687
9688static struct bpf_link *attach_iter(const struct bpf_sec_def *sec,
9689 struct bpf_program *prog)
9690{
9691 return bpf_program__attach_iter(prog, NULL);
9692}
9693
9694static struct bpf_link *
9695bpf_program__attach_fd(struct bpf_program *prog, int target_fd, int btf_id,
9696 const char *target_name)
9697{
9698 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
9699 .target_btf_id = btf_id);
9700 enum bpf_attach_type attach_type;
9701 char errmsg[STRERR_BUFSIZE];
9702 struct bpf_link *link;
9703 int prog_fd, link_fd;
9704
9705 prog_fd = bpf_program__fd(prog);
9706 if (prog_fd < 0) {
9707 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9708 return ERR_PTR(-EINVAL);
9709 }
9710
9711 link = calloc(1, sizeof(*link));
9712 if (!link)
9713 return ERR_PTR(-ENOMEM);
9714 link->detach = &bpf_link__detach_fd;
9715
9716 attach_type = bpf_program__get_expected_attach_type(prog);
9717 link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
9718 if (link_fd < 0) {
9719 link_fd = -errno;
9720 free(link);
9721 pr_warn("prog '%s': failed to attach to %s: %s\n",
9722 prog->name, target_name,
9723 libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9724 return ERR_PTR(link_fd);
9725 }
9726 link->fd = link_fd;
9727 return link;
9728}
9729
9730struct bpf_link *
9731bpf_program__attach_cgroup(struct bpf_program *prog, int cgroup_fd)
9732{
9733 return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
9734}
9735
9736struct bpf_link *
9737bpf_program__attach_netns(struct bpf_program *prog, int netns_fd)
9738{
9739 return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
9740}
9741
9742struct bpf_link *bpf_program__attach_xdp(struct bpf_program *prog, int ifindex)
9743{
9744 /* target_fd/target_ifindex use the same field in LINK_CREATE */
9745 return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
9746}
9747
9748struct bpf_link *bpf_program__attach_freplace(struct bpf_program *prog,
9749 int target_fd,
9750 const char *attach_func_name)
9751{
9752 int btf_id;
9753
9754 if (!!target_fd != !!attach_func_name) {
9755 pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
9756 prog->name);
9757 return ERR_PTR(-EINVAL);
9758 }
9759
9760 if (prog->type != BPF_PROG_TYPE_EXT) {
9761 pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
9762 prog->name);
9763 return ERR_PTR(-EINVAL);
9764 }
9765
9766 if (target_fd) {
9767 btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
9768 if (btf_id < 0)
9769 return ERR_PTR(btf_id);
9770
9771 return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
9772 } else {
9773 /* no target, so use raw_tracepoint_open for compatibility
9774 * with old kernels
9775 */
9776 return bpf_program__attach_trace(prog);
9777 }
9778}
9779
9780struct bpf_link *
9781bpf_program__attach_iter(struct bpf_program *prog,
9782 const struct bpf_iter_attach_opts *opts)
9783{
9784 DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
9785 char errmsg[STRERR_BUFSIZE];
9786 struct bpf_link *link;
9787 int prog_fd, link_fd;
9788 __u32 target_fd = 0;
9789
9790 if (!OPTS_VALID(opts, bpf_iter_attach_opts))
9791 return ERR_PTR(-EINVAL);
9792
9793 link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
9794 link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
9795
9796 prog_fd = bpf_program__fd(prog);
9797 if (prog_fd < 0) {
9798 pr_warn("prog '%s': can't attach before loaded\n", prog->name);
9799 return ERR_PTR(-EINVAL);
9800 }
9801
9802 link = calloc(1, sizeof(*link));
9803 if (!link)
9804 return ERR_PTR(-ENOMEM);
9805 link->detach = &bpf_link__detach_fd;
9806
9807 link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
9808 &link_create_opts);
9809 if (link_fd < 0) {
9810 link_fd = -errno;
9811 free(link);
9812 pr_warn("prog '%s': failed to attach to iterator: %s\n",
9813 prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
9814 return ERR_PTR(link_fd);
9815 }
9816 link->fd = link_fd;
9817 return link;
9818}
9819
9820struct bpf_link *bpf_program__attach(struct bpf_program *prog)
9821{
9822 const struct bpf_sec_def *sec_def;
9823
9824 sec_def = find_sec_def(prog->sec_name);
9825 if (!sec_def || !sec_def->attach_fn)
9826 return ERR_PTR(-ESRCH);
9827
9828 return sec_def->attach_fn(sec_def, prog);
9829}
9830
9831static int bpf_link__detach_struct_ops(struct bpf_link *link)
9832{
9833 __u32 zero = 0;
9834
9835 if (bpf_map_delete_elem(link->fd, &zero))
9836 return -errno;
9837
9838 return 0;
9839}
9840
9841struct bpf_link *bpf_map__attach_struct_ops(struct bpf_map *map)
9842{
9843 struct bpf_struct_ops *st_ops;
9844 struct bpf_link *link;
9845 __u32 i, zero = 0;
9846 int err;
9847
9848 if (!bpf_map__is_struct_ops(map) || map->fd == -1)
9849 return ERR_PTR(-EINVAL);
9850
9851 link = calloc(1, sizeof(*link));
9852 if (!link)
9853 return ERR_PTR(-EINVAL);
9854
9855 st_ops = map->st_ops;
9856 for (i = 0; i < btf_vlen(st_ops->type); i++) {
9857 struct bpf_program *prog = st_ops->progs[i];
9858 void *kern_data;
9859 int prog_fd;
9860
9861 if (!prog)
9862 continue;
9863
9864 prog_fd = bpf_program__fd(prog);
9865 kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9866 *(unsigned long *)kern_data = prog_fd;
9867 }
9868
9869 err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
9870 if (err) {
9871 err = -errno;
9872 free(link);
9873 return ERR_PTR(err);
9874 }
9875
9876 link->detach = bpf_link__detach_struct_ops;
9877 link->fd = map->fd;
9878
9879 return link;
9880}
9881
David Brazdil0f672f62019-12-10 10:32:29 +00009882enum bpf_perf_event_ret
9883bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
9884 void **copy_mem, size_t *copy_size,
9885 bpf_perf_event_print_t fn, void *private_data)
9886{
9887 struct perf_event_mmap_page *header = mmap_mem;
9888 __u64 data_head = ring_buffer_read_head(header);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009889 __u64 data_tail = header->data_tail;
David Brazdil0f672f62019-12-10 10:32:29 +00009890 void *base = ((__u8 *)header) + page_size;
9891 int ret = LIBBPF_PERF_EVENT_CONT;
9892 struct perf_event_header *ehdr;
9893 size_t ehdr_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009894
David Brazdil0f672f62019-12-10 10:32:29 +00009895 while (data_head != data_tail) {
9896 ehdr = base + (data_tail & (mmap_size - 1));
9897 ehdr_size = ehdr->size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009898
David Brazdil0f672f62019-12-10 10:32:29 +00009899 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
9900 void *copy_start = ehdr;
9901 size_t len_first = base + mmap_size - copy_start;
9902 size_t len_secnd = ehdr_size - len_first;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009903
David Brazdil0f672f62019-12-10 10:32:29 +00009904 if (*copy_size < ehdr_size) {
9905 free(*copy_mem);
9906 *copy_mem = malloc(ehdr_size);
9907 if (!*copy_mem) {
9908 *copy_size = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009909 ret = LIBBPF_PERF_EVENT_ERROR;
9910 break;
9911 }
David Brazdil0f672f62019-12-10 10:32:29 +00009912 *copy_size = ehdr_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009913 }
9914
David Brazdil0f672f62019-12-10 10:32:29 +00009915 memcpy(*copy_mem, copy_start, len_first);
9916 memcpy(*copy_mem + len_first, base, len_secnd);
9917 ehdr = *copy_mem;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009918 }
9919
David Brazdil0f672f62019-12-10 10:32:29 +00009920 ret = fn(ehdr, private_data);
9921 data_tail += ehdr_size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009922 if (ret != LIBBPF_PERF_EVENT_CONT)
9923 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009924 }
9925
David Brazdil0f672f62019-12-10 10:32:29 +00009926 ring_buffer_write_tail(header, data_tail);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00009927 return ret;
9928}
David Brazdil0f672f62019-12-10 10:32:29 +00009929
9930struct perf_buffer;
9931
9932struct perf_buffer_params {
9933 struct perf_event_attr *attr;
9934 /* if event_cb is specified, it takes precendence */
9935 perf_buffer_event_fn event_cb;
9936 /* sample_cb and lost_cb are higher-level common-case callbacks */
9937 perf_buffer_sample_fn sample_cb;
9938 perf_buffer_lost_fn lost_cb;
9939 void *ctx;
9940 int cpu_cnt;
9941 int *cpus;
9942 int *map_keys;
9943};
9944
9945struct perf_cpu_buf {
9946 struct perf_buffer *pb;
9947 void *base; /* mmap()'ed memory */
9948 void *buf; /* for reconstructing segmented data */
9949 size_t buf_size;
9950 int fd;
9951 int cpu;
9952 int map_key;
9953};
9954
9955struct perf_buffer {
9956 perf_buffer_event_fn event_cb;
9957 perf_buffer_sample_fn sample_cb;
9958 perf_buffer_lost_fn lost_cb;
9959 void *ctx; /* passed into callbacks */
9960
9961 size_t page_size;
9962 size_t mmap_size;
9963 struct perf_cpu_buf **cpu_bufs;
9964 struct epoll_event *events;
Olivier Deprez157378f2022-04-04 15:47:50 +02009965 int cpu_cnt; /* number of allocated CPU buffers */
David Brazdil0f672f62019-12-10 10:32:29 +00009966 int epoll_fd; /* perf event FD */
9967 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
9968};
9969
9970static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
9971 struct perf_cpu_buf *cpu_buf)
9972{
9973 if (!cpu_buf)
9974 return;
9975 if (cpu_buf->base &&
9976 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
Olivier Deprez157378f2022-04-04 15:47:50 +02009977 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
David Brazdil0f672f62019-12-10 10:32:29 +00009978 if (cpu_buf->fd >= 0) {
9979 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
9980 close(cpu_buf->fd);
9981 }
9982 free(cpu_buf->buf);
9983 free(cpu_buf);
9984}
9985
9986void perf_buffer__free(struct perf_buffer *pb)
9987{
9988 int i;
9989
Olivier Deprez157378f2022-04-04 15:47:50 +02009990 if (IS_ERR_OR_NULL(pb))
David Brazdil0f672f62019-12-10 10:32:29 +00009991 return;
9992 if (pb->cpu_bufs) {
Olivier Deprez0e641232021-09-23 10:07:05 +02009993 for (i = 0; i < pb->cpu_cnt; i++) {
David Brazdil0f672f62019-12-10 10:32:29 +00009994 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
9995
Olivier Deprez0e641232021-09-23 10:07:05 +02009996 if (!cpu_buf)
9997 continue;
9998
David Brazdil0f672f62019-12-10 10:32:29 +00009999 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
10000 perf_buffer__free_cpu_buf(pb, cpu_buf);
10001 }
10002 free(pb->cpu_bufs);
10003 }
10004 if (pb->epoll_fd >= 0)
10005 close(pb->epoll_fd);
10006 free(pb->events);
10007 free(pb);
10008}
10009
10010static struct perf_cpu_buf *
10011perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
10012 int cpu, int map_key)
10013{
10014 struct perf_cpu_buf *cpu_buf;
10015 char msg[STRERR_BUFSIZE];
10016 int err;
10017
10018 cpu_buf = calloc(1, sizeof(*cpu_buf));
10019 if (!cpu_buf)
10020 return ERR_PTR(-ENOMEM);
10021
10022 cpu_buf->pb = pb;
10023 cpu_buf->cpu = cpu;
10024 cpu_buf->map_key = map_key;
10025
10026 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
10027 -1, PERF_FLAG_FD_CLOEXEC);
10028 if (cpu_buf->fd < 0) {
10029 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010030 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
10031 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010032 goto error;
10033 }
10034
10035 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
10036 PROT_READ | PROT_WRITE, MAP_SHARED,
10037 cpu_buf->fd, 0);
10038 if (cpu_buf->base == MAP_FAILED) {
10039 cpu_buf->base = NULL;
10040 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010041 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
10042 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010043 goto error;
10044 }
10045
10046 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10047 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010048 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
10049 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010050 goto error;
10051 }
10052
10053 return cpu_buf;
10054
10055error:
10056 perf_buffer__free_cpu_buf(pb, cpu_buf);
10057 return (struct perf_cpu_buf *)ERR_PTR(err);
10058}
10059
10060static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10061 struct perf_buffer_params *p);
10062
10063struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
10064 const struct perf_buffer_opts *opts)
10065{
10066 struct perf_buffer_params p = {};
10067 struct perf_event_attr attr = { 0, };
10068
Olivier Deprez157378f2022-04-04 15:47:50 +020010069 attr.config = PERF_COUNT_SW_BPF_OUTPUT;
David Brazdil0f672f62019-12-10 10:32:29 +000010070 attr.type = PERF_TYPE_SOFTWARE;
10071 attr.sample_type = PERF_SAMPLE_RAW;
10072 attr.sample_period = 1;
10073 attr.wakeup_events = 1;
10074
10075 p.attr = &attr;
10076 p.sample_cb = opts ? opts->sample_cb : NULL;
10077 p.lost_cb = opts ? opts->lost_cb : NULL;
10078 p.ctx = opts ? opts->ctx : NULL;
10079
10080 return __perf_buffer__new(map_fd, page_cnt, &p);
10081}
10082
10083struct perf_buffer *
10084perf_buffer__new_raw(int map_fd, size_t page_cnt,
10085 const struct perf_buffer_raw_opts *opts)
10086{
10087 struct perf_buffer_params p = {};
10088
10089 p.attr = opts->attr;
10090 p.event_cb = opts->event_cb;
10091 p.ctx = opts->ctx;
10092 p.cpu_cnt = opts->cpu_cnt;
10093 p.cpus = opts->cpus;
10094 p.map_keys = opts->map_keys;
10095
10096 return __perf_buffer__new(map_fd, page_cnt, &p);
10097}
10098
10099static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
10100 struct perf_buffer_params *p)
10101{
Olivier Deprez157378f2022-04-04 15:47:50 +020010102 const char *online_cpus_file = "/sys/devices/system/cpu/online";
10103 struct bpf_map_info map;
David Brazdil0f672f62019-12-10 10:32:29 +000010104 char msg[STRERR_BUFSIZE];
10105 struct perf_buffer *pb;
Olivier Deprez157378f2022-04-04 15:47:50 +020010106 bool *online = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +000010107 __u32 map_info_len;
Olivier Deprez157378f2022-04-04 15:47:50 +020010108 int err, i, j, n;
David Brazdil0f672f62019-12-10 10:32:29 +000010109
10110 if (page_cnt & (page_cnt - 1)) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010111 pr_warn("page count should be power of two, but is %zu\n",
10112 page_cnt);
David Brazdil0f672f62019-12-10 10:32:29 +000010113 return ERR_PTR(-EINVAL);
10114 }
10115
Olivier Deprez157378f2022-04-04 15:47:50 +020010116 /* best-effort sanity checks */
10117 memset(&map, 0, sizeof(map));
David Brazdil0f672f62019-12-10 10:32:29 +000010118 map_info_len = sizeof(map);
10119 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
10120 if (err) {
10121 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010122 /* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
10123 * -EBADFD, -EFAULT, or -E2BIG on real error
10124 */
10125 if (err != -EINVAL) {
10126 pr_warn("failed to get map info for map FD %d: %s\n",
10127 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
10128 return ERR_PTR(err);
10129 }
10130 pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
10131 map_fd);
10132 } else {
10133 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
10134 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
10135 map.name);
10136 return ERR_PTR(-EINVAL);
10137 }
David Brazdil0f672f62019-12-10 10:32:29 +000010138 }
10139
10140 pb = calloc(1, sizeof(*pb));
10141 if (!pb)
10142 return ERR_PTR(-ENOMEM);
10143
10144 pb->event_cb = p->event_cb;
10145 pb->sample_cb = p->sample_cb;
10146 pb->lost_cb = p->lost_cb;
10147 pb->ctx = p->ctx;
10148
10149 pb->page_size = getpagesize();
10150 pb->mmap_size = pb->page_size * page_cnt;
10151 pb->map_fd = map_fd;
10152
10153 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
10154 if (pb->epoll_fd < 0) {
10155 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010156 pr_warn("failed to create epoll instance: %s\n",
10157 libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010158 goto error;
10159 }
10160
10161 if (p->cpu_cnt > 0) {
10162 pb->cpu_cnt = p->cpu_cnt;
10163 } else {
10164 pb->cpu_cnt = libbpf_num_possible_cpus();
10165 if (pb->cpu_cnt < 0) {
10166 err = pb->cpu_cnt;
10167 goto error;
10168 }
Olivier Deprez157378f2022-04-04 15:47:50 +020010169 if (map.max_entries && map.max_entries < pb->cpu_cnt)
David Brazdil0f672f62019-12-10 10:32:29 +000010170 pb->cpu_cnt = map.max_entries;
10171 }
10172
10173 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
10174 if (!pb->events) {
10175 err = -ENOMEM;
Olivier Deprez157378f2022-04-04 15:47:50 +020010176 pr_warn("failed to allocate events: out of memory\n");
David Brazdil0f672f62019-12-10 10:32:29 +000010177 goto error;
10178 }
10179 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
10180 if (!pb->cpu_bufs) {
10181 err = -ENOMEM;
Olivier Deprez157378f2022-04-04 15:47:50 +020010182 pr_warn("failed to allocate buffers: out of memory\n");
David Brazdil0f672f62019-12-10 10:32:29 +000010183 goto error;
10184 }
10185
Olivier Deprez157378f2022-04-04 15:47:50 +020010186 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
10187 if (err) {
10188 pr_warn("failed to get online CPU mask: %d\n", err);
10189 goto error;
10190 }
10191
10192 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
David Brazdil0f672f62019-12-10 10:32:29 +000010193 struct perf_cpu_buf *cpu_buf;
10194 int cpu, map_key;
10195
10196 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
10197 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
10198
Olivier Deprez157378f2022-04-04 15:47:50 +020010199 /* in case user didn't explicitly requested particular CPUs to
10200 * be attached to, skip offline/not present CPUs
10201 */
10202 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
10203 continue;
10204
David Brazdil0f672f62019-12-10 10:32:29 +000010205 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
10206 if (IS_ERR(cpu_buf)) {
10207 err = PTR_ERR(cpu_buf);
10208 goto error;
10209 }
10210
Olivier Deprez157378f2022-04-04 15:47:50 +020010211 pb->cpu_bufs[j] = cpu_buf;
David Brazdil0f672f62019-12-10 10:32:29 +000010212
10213 err = bpf_map_update_elem(pb->map_fd, &map_key,
10214 &cpu_buf->fd, 0);
10215 if (err) {
10216 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010217 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
10218 cpu, map_key, cpu_buf->fd,
10219 libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010220 goto error;
10221 }
10222
Olivier Deprez157378f2022-04-04 15:47:50 +020010223 pb->events[j].events = EPOLLIN;
10224 pb->events[j].data.ptr = cpu_buf;
David Brazdil0f672f62019-12-10 10:32:29 +000010225 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
Olivier Deprez157378f2022-04-04 15:47:50 +020010226 &pb->events[j]) < 0) {
David Brazdil0f672f62019-12-10 10:32:29 +000010227 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010228 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
10229 cpu, cpu_buf->fd,
10230 libbpf_strerror_r(err, msg, sizeof(msg)));
David Brazdil0f672f62019-12-10 10:32:29 +000010231 goto error;
10232 }
Olivier Deprez157378f2022-04-04 15:47:50 +020010233 j++;
David Brazdil0f672f62019-12-10 10:32:29 +000010234 }
Olivier Deprez157378f2022-04-04 15:47:50 +020010235 pb->cpu_cnt = j;
10236 free(online);
David Brazdil0f672f62019-12-10 10:32:29 +000010237
10238 return pb;
10239
10240error:
Olivier Deprez157378f2022-04-04 15:47:50 +020010241 free(online);
David Brazdil0f672f62019-12-10 10:32:29 +000010242 if (pb)
10243 perf_buffer__free(pb);
10244 return ERR_PTR(err);
10245}
10246
10247struct perf_sample_raw {
10248 struct perf_event_header header;
10249 uint32_t size;
Olivier Deprez157378f2022-04-04 15:47:50 +020010250 char data[];
David Brazdil0f672f62019-12-10 10:32:29 +000010251};
10252
10253struct perf_sample_lost {
10254 struct perf_event_header header;
10255 uint64_t id;
10256 uint64_t lost;
10257 uint64_t sample_id;
10258};
10259
10260static enum bpf_perf_event_ret
10261perf_buffer__process_record(struct perf_event_header *e, void *ctx)
10262{
10263 struct perf_cpu_buf *cpu_buf = ctx;
10264 struct perf_buffer *pb = cpu_buf->pb;
10265 void *data = e;
10266
10267 /* user wants full control over parsing perf event */
10268 if (pb->event_cb)
10269 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
10270
10271 switch (e->type) {
10272 case PERF_RECORD_SAMPLE: {
10273 struct perf_sample_raw *s = data;
10274
10275 if (pb->sample_cb)
10276 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
10277 break;
10278 }
10279 case PERF_RECORD_LOST: {
10280 struct perf_sample_lost *s = data;
10281
10282 if (pb->lost_cb)
10283 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
10284 break;
10285 }
10286 default:
Olivier Deprez157378f2022-04-04 15:47:50 +020010287 pr_warn("unknown perf sample type %d\n", e->type);
David Brazdil0f672f62019-12-10 10:32:29 +000010288 return LIBBPF_PERF_EVENT_ERROR;
10289 }
10290 return LIBBPF_PERF_EVENT_CONT;
10291}
10292
10293static int perf_buffer__process_records(struct perf_buffer *pb,
10294 struct perf_cpu_buf *cpu_buf)
10295{
10296 enum bpf_perf_event_ret ret;
10297
10298 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
10299 pb->page_size, &cpu_buf->buf,
10300 &cpu_buf->buf_size,
10301 perf_buffer__process_record, cpu_buf);
10302 if (ret != LIBBPF_PERF_EVENT_CONT)
10303 return ret;
10304 return 0;
10305}
10306
Olivier Deprez157378f2022-04-04 15:47:50 +020010307int perf_buffer__epoll_fd(const struct perf_buffer *pb)
10308{
10309 return pb->epoll_fd;
10310}
10311
David Brazdil0f672f62019-12-10 10:32:29 +000010312int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
10313{
10314 int i, cnt, err;
10315
10316 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
10317 for (i = 0; i < cnt; i++) {
10318 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
10319
10320 err = perf_buffer__process_records(pb, cpu_buf);
10321 if (err) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010322 pr_warn("error while processing records: %d\n", err);
David Brazdil0f672f62019-12-10 10:32:29 +000010323 return err;
10324 }
10325 }
10326 return cnt < 0 ? -errno : cnt;
10327}
10328
Olivier Deprez157378f2022-04-04 15:47:50 +020010329/* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
10330 * manager.
10331 */
10332size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
10333{
10334 return pb->cpu_cnt;
10335}
10336
10337/*
10338 * Return perf_event FD of a ring buffer in *buf_idx* slot of
10339 * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
10340 * select()/poll()/epoll() Linux syscalls.
10341 */
10342int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
10343{
10344 struct perf_cpu_buf *cpu_buf;
10345
10346 if (buf_idx >= pb->cpu_cnt)
10347 return -EINVAL;
10348
10349 cpu_buf = pb->cpu_bufs[buf_idx];
10350 if (!cpu_buf)
10351 return -ENOENT;
10352
10353 return cpu_buf->fd;
10354}
10355
10356/*
10357 * Consume data from perf ring buffer corresponding to slot *buf_idx* in
10358 * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
10359 * consume, do nothing and return success.
10360 * Returns:
10361 * - 0 on success;
10362 * - <0 on failure.
10363 */
10364int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
10365{
10366 struct perf_cpu_buf *cpu_buf;
10367
10368 if (buf_idx >= pb->cpu_cnt)
10369 return -EINVAL;
10370
10371 cpu_buf = pb->cpu_bufs[buf_idx];
10372 if (!cpu_buf)
10373 return -ENOENT;
10374
10375 return perf_buffer__process_records(pb, cpu_buf);
10376}
10377
10378int perf_buffer__consume(struct perf_buffer *pb)
10379{
10380 int i, err;
10381
10382 for (i = 0; i < pb->cpu_cnt; i++) {
10383 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
10384
10385 if (!cpu_buf)
10386 continue;
10387
10388 err = perf_buffer__process_records(pb, cpu_buf);
10389 if (err) {
10390 pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
10391 return err;
10392 }
10393 }
10394 return 0;
10395}
10396
David Brazdil0f672f62019-12-10 10:32:29 +000010397struct bpf_prog_info_array_desc {
10398 int array_offset; /* e.g. offset of jited_prog_insns */
10399 int count_offset; /* e.g. offset of jited_prog_len */
10400 int size_offset; /* > 0: offset of rec size,
10401 * < 0: fix size of -size_offset
10402 */
10403};
10404
10405static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
10406 [BPF_PROG_INFO_JITED_INSNS] = {
10407 offsetof(struct bpf_prog_info, jited_prog_insns),
10408 offsetof(struct bpf_prog_info, jited_prog_len),
10409 -1,
10410 },
10411 [BPF_PROG_INFO_XLATED_INSNS] = {
10412 offsetof(struct bpf_prog_info, xlated_prog_insns),
10413 offsetof(struct bpf_prog_info, xlated_prog_len),
10414 -1,
10415 },
10416 [BPF_PROG_INFO_MAP_IDS] = {
10417 offsetof(struct bpf_prog_info, map_ids),
10418 offsetof(struct bpf_prog_info, nr_map_ids),
10419 -(int)sizeof(__u32),
10420 },
10421 [BPF_PROG_INFO_JITED_KSYMS] = {
10422 offsetof(struct bpf_prog_info, jited_ksyms),
10423 offsetof(struct bpf_prog_info, nr_jited_ksyms),
10424 -(int)sizeof(__u64),
10425 },
10426 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
10427 offsetof(struct bpf_prog_info, jited_func_lens),
10428 offsetof(struct bpf_prog_info, nr_jited_func_lens),
10429 -(int)sizeof(__u32),
10430 },
10431 [BPF_PROG_INFO_FUNC_INFO] = {
10432 offsetof(struct bpf_prog_info, func_info),
10433 offsetof(struct bpf_prog_info, nr_func_info),
10434 offsetof(struct bpf_prog_info, func_info_rec_size),
10435 },
10436 [BPF_PROG_INFO_LINE_INFO] = {
10437 offsetof(struct bpf_prog_info, line_info),
10438 offsetof(struct bpf_prog_info, nr_line_info),
10439 offsetof(struct bpf_prog_info, line_info_rec_size),
10440 },
10441 [BPF_PROG_INFO_JITED_LINE_INFO] = {
10442 offsetof(struct bpf_prog_info, jited_line_info),
10443 offsetof(struct bpf_prog_info, nr_jited_line_info),
10444 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
10445 },
10446 [BPF_PROG_INFO_PROG_TAGS] = {
10447 offsetof(struct bpf_prog_info, prog_tags),
10448 offsetof(struct bpf_prog_info, nr_prog_tags),
10449 -(int)sizeof(__u8) * BPF_TAG_SIZE,
10450 },
10451
10452};
10453
Olivier Deprez157378f2022-04-04 15:47:50 +020010454static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
10455 int offset)
David Brazdil0f672f62019-12-10 10:32:29 +000010456{
10457 __u32 *array = (__u32 *)info;
10458
10459 if (offset >= 0)
10460 return array[offset / sizeof(__u32)];
10461 return -(int)offset;
10462}
10463
Olivier Deprez157378f2022-04-04 15:47:50 +020010464static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
10465 int offset)
David Brazdil0f672f62019-12-10 10:32:29 +000010466{
10467 __u64 *array = (__u64 *)info;
10468
10469 if (offset >= 0)
10470 return array[offset / sizeof(__u64)];
10471 return -(int)offset;
10472}
10473
10474static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
10475 __u32 val)
10476{
10477 __u32 *array = (__u32 *)info;
10478
10479 if (offset >= 0)
10480 array[offset / sizeof(__u32)] = val;
10481}
10482
10483static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
10484 __u64 val)
10485{
10486 __u64 *array = (__u64 *)info;
10487
10488 if (offset >= 0)
10489 array[offset / sizeof(__u64)] = val;
10490}
10491
10492struct bpf_prog_info_linear *
10493bpf_program__get_prog_info_linear(int fd, __u64 arrays)
10494{
10495 struct bpf_prog_info_linear *info_linear;
10496 struct bpf_prog_info info = {};
10497 __u32 info_len = sizeof(info);
10498 __u32 data_len = 0;
10499 int i, err;
10500 void *ptr;
10501
10502 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
10503 return ERR_PTR(-EINVAL);
10504
10505 /* step 1: get array dimensions */
10506 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
10507 if (err) {
10508 pr_debug("can't get prog info: %s", strerror(errno));
10509 return ERR_PTR(-EFAULT);
10510 }
10511
10512 /* step 2: calculate total size of all arrays */
10513 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10514 bool include_array = (arrays & (1UL << i)) > 0;
10515 struct bpf_prog_info_array_desc *desc;
10516 __u32 count, size;
10517
10518 desc = bpf_prog_info_array_desc + i;
10519
10520 /* kernel is too old to support this field */
10521 if (info_len < desc->array_offset + sizeof(__u32) ||
10522 info_len < desc->count_offset + sizeof(__u32) ||
10523 (desc->size_offset > 0 && info_len < desc->size_offset))
10524 include_array = false;
10525
10526 if (!include_array) {
10527 arrays &= ~(1UL << i); /* clear the bit */
10528 continue;
10529 }
10530
10531 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10532 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10533
10534 data_len += count * size;
10535 }
10536
10537 /* step 3: allocate continuous memory */
10538 data_len = roundup(data_len, sizeof(__u64));
10539 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
10540 if (!info_linear)
10541 return ERR_PTR(-ENOMEM);
10542
10543 /* step 4: fill data to info_linear->info */
10544 info_linear->arrays = arrays;
10545 memset(&info_linear->info, 0, sizeof(info));
10546 ptr = info_linear->data;
10547
10548 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10549 struct bpf_prog_info_array_desc *desc;
10550 __u32 count, size;
10551
10552 if ((arrays & (1UL << i)) == 0)
10553 continue;
10554
10555 desc = bpf_prog_info_array_desc + i;
10556 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10557 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10558 bpf_prog_info_set_offset_u32(&info_linear->info,
10559 desc->count_offset, count);
10560 bpf_prog_info_set_offset_u32(&info_linear->info,
10561 desc->size_offset, size);
10562 bpf_prog_info_set_offset_u64(&info_linear->info,
10563 desc->array_offset,
10564 ptr_to_u64(ptr));
10565 ptr += count * size;
10566 }
10567
10568 /* step 5: call syscall again to get required arrays */
10569 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
10570 if (err) {
10571 pr_debug("can't get prog info: %s", strerror(errno));
10572 free(info_linear);
10573 return ERR_PTR(-EFAULT);
10574 }
10575
10576 /* step 6: verify the data */
10577 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10578 struct bpf_prog_info_array_desc *desc;
10579 __u32 v1, v2;
10580
10581 if ((arrays & (1UL << i)) == 0)
10582 continue;
10583
10584 desc = bpf_prog_info_array_desc + i;
10585 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
10586 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10587 desc->count_offset);
10588 if (v1 != v2)
Olivier Deprez157378f2022-04-04 15:47:50 +020010589 pr_warn("%s: mismatch in element count\n", __func__);
David Brazdil0f672f62019-12-10 10:32:29 +000010590
10591 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
10592 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
10593 desc->size_offset);
10594 if (v1 != v2)
Olivier Deprez157378f2022-04-04 15:47:50 +020010595 pr_warn("%s: mismatch in rec size\n", __func__);
David Brazdil0f672f62019-12-10 10:32:29 +000010596 }
10597
10598 /* step 7: update info_len and data_len */
10599 info_linear->info_len = sizeof(struct bpf_prog_info);
10600 info_linear->data_len = data_len;
10601
10602 return info_linear;
10603}
10604
10605void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
10606{
10607 int i;
10608
10609 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10610 struct bpf_prog_info_array_desc *desc;
10611 __u64 addr, offs;
10612
10613 if ((info_linear->arrays & (1UL << i)) == 0)
10614 continue;
10615
10616 desc = bpf_prog_info_array_desc + i;
10617 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
10618 desc->array_offset);
10619 offs = addr - ptr_to_u64(info_linear->data);
10620 bpf_prog_info_set_offset_u64(&info_linear->info,
10621 desc->array_offset, offs);
10622 }
10623}
10624
10625void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
10626{
10627 int i;
10628
10629 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
10630 struct bpf_prog_info_array_desc *desc;
10631 __u64 addr, offs;
10632
10633 if ((info_linear->arrays & (1UL << i)) == 0)
10634 continue;
10635
10636 desc = bpf_prog_info_array_desc + i;
10637 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
10638 desc->array_offset);
10639 addr = offs + ptr_to_u64(info_linear->data);
10640 bpf_prog_info_set_offset_u64(&info_linear->info,
10641 desc->array_offset, addr);
10642 }
10643}
10644
Olivier Deprez157378f2022-04-04 15:47:50 +020010645int bpf_program__set_attach_target(struct bpf_program *prog,
10646 int attach_prog_fd,
10647 const char *attach_func_name)
10648{
10649 int btf_id;
10650
10651 if (!prog || attach_prog_fd < 0 || !attach_func_name)
10652 return -EINVAL;
10653
10654 if (attach_prog_fd)
10655 btf_id = libbpf_find_prog_btf_id(attach_func_name,
10656 attach_prog_fd);
10657 else
10658 btf_id = libbpf_find_vmlinux_btf_id(attach_func_name,
10659 prog->expected_attach_type);
10660
10661 if (btf_id < 0)
10662 return btf_id;
10663
10664 prog->attach_btf_id = btf_id;
10665 prog->attach_prog_fd = attach_prog_fd;
10666 return 0;
10667}
10668
Olivier Deprez0e641232021-09-23 10:07:05 +020010669int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
10670{
10671 int err = 0, n, len, start, end = -1;
10672 bool *tmp;
10673
10674 *mask = NULL;
10675 *mask_sz = 0;
10676
10677 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
10678 while (*s) {
10679 if (*s == ',' || *s == '\n') {
10680 s++;
10681 continue;
10682 }
10683 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
10684 if (n <= 0 || n > 2) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010685 pr_warn("Failed to get CPU range %s: %d\n", s, n);
Olivier Deprez0e641232021-09-23 10:07:05 +020010686 err = -EINVAL;
10687 goto cleanup;
10688 } else if (n == 1) {
10689 end = start;
10690 }
10691 if (start < 0 || start > end) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010692 pr_warn("Invalid CPU range [%d,%d] in %s\n",
10693 start, end, s);
Olivier Deprez0e641232021-09-23 10:07:05 +020010694 err = -EINVAL;
10695 goto cleanup;
10696 }
10697 tmp = realloc(*mask, end + 1);
10698 if (!tmp) {
10699 err = -ENOMEM;
10700 goto cleanup;
10701 }
10702 *mask = tmp;
10703 memset(tmp + *mask_sz, 0, start - *mask_sz);
10704 memset(tmp + start, 1, end - start + 1);
10705 *mask_sz = end + 1;
10706 s += len;
10707 }
10708 if (!*mask_sz) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010709 pr_warn("Empty CPU range\n");
Olivier Deprez0e641232021-09-23 10:07:05 +020010710 return -EINVAL;
10711 }
10712 return 0;
10713cleanup:
10714 free(*mask);
10715 *mask = NULL;
10716 return err;
10717}
10718
10719int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
10720{
10721 int fd, err = 0, len;
10722 char buf[128];
10723
10724 fd = open(fcpu, O_RDONLY);
10725 if (fd < 0) {
10726 err = -errno;
Olivier Deprez157378f2022-04-04 15:47:50 +020010727 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
Olivier Deprez0e641232021-09-23 10:07:05 +020010728 return err;
10729 }
10730 len = read(fd, buf, sizeof(buf));
10731 close(fd);
10732 if (len <= 0) {
10733 err = len ? -errno : -EINVAL;
Olivier Deprez157378f2022-04-04 15:47:50 +020010734 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
Olivier Deprez0e641232021-09-23 10:07:05 +020010735 return err;
10736 }
10737 if (len >= sizeof(buf)) {
Olivier Deprez157378f2022-04-04 15:47:50 +020010738 pr_warn("CPU mask is too big in file %s\n", fcpu);
Olivier Deprez0e641232021-09-23 10:07:05 +020010739 return -E2BIG;
10740 }
10741 buf[len] = '\0';
10742
10743 return parse_cpu_mask_str(buf, mask, mask_sz);
10744}
10745
David Brazdil0f672f62019-12-10 10:32:29 +000010746int libbpf_num_possible_cpus(void)
10747{
10748 static const char *fcpu = "/sys/devices/system/cpu/possible";
David Brazdil0f672f62019-12-10 10:32:29 +000010749 static int cpus;
Olivier Deprez0e641232021-09-23 10:07:05 +020010750 int err, n, i, tmp_cpus;
10751 bool *mask;
David Brazdil0f672f62019-12-10 10:32:29 +000010752
10753 tmp_cpus = READ_ONCE(cpus);
10754 if (tmp_cpus > 0)
10755 return tmp_cpus;
10756
Olivier Deprez0e641232021-09-23 10:07:05 +020010757 err = parse_cpu_mask_file(fcpu, &mask, &n);
10758 if (err)
10759 return err;
David Brazdil0f672f62019-12-10 10:32:29 +000010760
Olivier Deprez0e641232021-09-23 10:07:05 +020010761 tmp_cpus = 0;
10762 for (i = 0; i < n; i++) {
10763 if (mask[i])
10764 tmp_cpus++;
David Brazdil0f672f62019-12-10 10:32:29 +000010765 }
Olivier Deprez0e641232021-09-23 10:07:05 +020010766 free(mask);
David Brazdil0f672f62019-12-10 10:32:29 +000010767
10768 WRITE_ONCE(cpus, tmp_cpus);
10769 return tmp_cpus;
10770}
Olivier Deprez157378f2022-04-04 15:47:50 +020010771
10772int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
10773 const struct bpf_object_open_opts *opts)
10774{
10775 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
10776 .object_name = s->name,
10777 );
10778 struct bpf_object *obj;
10779 int i;
10780
10781 /* Attempt to preserve opts->object_name, unless overriden by user
10782 * explicitly. Overwriting object name for skeletons is discouraged,
10783 * as it breaks global data maps, because they contain object name
10784 * prefix as their own map name prefix. When skeleton is generated,
10785 * bpftool is making an assumption that this name will stay the same.
10786 */
10787 if (opts) {
10788 memcpy(&skel_opts, opts, sizeof(*opts));
10789 if (!opts->object_name)
10790 skel_opts.object_name = s->name;
10791 }
10792
10793 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
10794 if (IS_ERR(obj)) {
10795 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
10796 s->name, PTR_ERR(obj));
10797 return PTR_ERR(obj);
10798 }
10799
10800 *s->obj = obj;
10801
10802 for (i = 0; i < s->map_cnt; i++) {
10803 struct bpf_map **map = s->maps[i].map;
10804 const char *name = s->maps[i].name;
10805 void **mmaped = s->maps[i].mmaped;
10806
10807 *map = bpf_object__find_map_by_name(obj, name);
10808 if (!*map) {
10809 pr_warn("failed to find skeleton map '%s'\n", name);
10810 return -ESRCH;
10811 }
10812
10813 /* externs shouldn't be pre-setup from user code */
10814 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
10815 *mmaped = (*map)->mmaped;
10816 }
10817
10818 for (i = 0; i < s->prog_cnt; i++) {
10819 struct bpf_program **prog = s->progs[i].prog;
10820 const char *name = s->progs[i].name;
10821
10822 *prog = bpf_object__find_program_by_name(obj, name);
10823 if (!*prog) {
10824 pr_warn("failed to find skeleton program '%s'\n", name);
10825 return -ESRCH;
10826 }
10827 }
10828
10829 return 0;
10830}
10831
10832int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
10833{
10834 int i, err;
10835
10836 err = bpf_object__load(*s->obj);
10837 if (err) {
10838 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
10839 return err;
10840 }
10841
10842 for (i = 0; i < s->map_cnt; i++) {
10843 struct bpf_map *map = *s->maps[i].map;
10844 size_t mmap_sz = bpf_map_mmap_sz(map);
10845 int prot, map_fd = bpf_map__fd(map);
10846 void **mmaped = s->maps[i].mmaped;
10847
10848 if (!mmaped)
10849 continue;
10850
10851 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
10852 *mmaped = NULL;
10853 continue;
10854 }
10855
10856 if (map->def.map_flags & BPF_F_RDONLY_PROG)
10857 prot = PROT_READ;
10858 else
10859 prot = PROT_READ | PROT_WRITE;
10860
10861 /* Remap anonymous mmap()-ed "map initialization image" as
10862 * a BPF map-backed mmap()-ed memory, but preserving the same
10863 * memory address. This will cause kernel to change process'
10864 * page table to point to a different piece of kernel memory,
10865 * but from userspace point of view memory address (and its
10866 * contents, being identical at this point) will stay the
10867 * same. This mapping will be released by bpf_object__close()
10868 * as per normal clean up procedure, so we don't need to worry
10869 * about it from skeleton's clean up perspective.
10870 */
10871 *mmaped = mmap(map->mmaped, mmap_sz, prot,
10872 MAP_SHARED | MAP_FIXED, map_fd, 0);
10873 if (*mmaped == MAP_FAILED) {
10874 err = -errno;
10875 *mmaped = NULL;
10876 pr_warn("failed to re-mmap() map '%s': %d\n",
10877 bpf_map__name(map), err);
10878 return err;
10879 }
10880 }
10881
10882 return 0;
10883}
10884
10885int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
10886{
10887 int i;
10888
10889 for (i = 0; i < s->prog_cnt; i++) {
10890 struct bpf_program *prog = *s->progs[i].prog;
10891 struct bpf_link **link = s->progs[i].link;
10892 const struct bpf_sec_def *sec_def;
10893
10894 if (!prog->load)
10895 continue;
10896
10897 sec_def = find_sec_def(prog->sec_name);
10898 if (!sec_def || !sec_def->attach_fn)
10899 continue;
10900
10901 *link = sec_def->attach_fn(sec_def, prog);
10902 if (IS_ERR(*link)) {
10903 pr_warn("failed to auto-attach program '%s': %ld\n",
10904 bpf_program__name(prog), PTR_ERR(*link));
10905 return PTR_ERR(*link);
10906 }
10907 }
10908
10909 return 0;
10910}
10911
10912void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
10913{
10914 int i;
10915
10916 for (i = 0; i < s->prog_cnt; i++) {
10917 struct bpf_link **link = s->progs[i].link;
10918
10919 bpf_link__destroy(*link);
10920 *link = NULL;
10921 }
10922}
10923
10924void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
10925{
10926 if (s->progs)
10927 bpf_object__detach_skeleton(s);
10928 if (s->obj)
10929 bpf_object__close(*s->obj);
10930 free(s->maps);
10931 free(s->progs);
10932 free(s);
10933}