blob: 3fe42d6b0c2ff7188c657976d5ad496d58987f07 [file] [log] [blame]
Alexei Starovoitov1bc38b82018-10-05 16:40:00 -07001// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
Eric Leblond6061a3d2018-01-30 21:55:03 +01002
Wang Nan1b76c132015-07-01 02:13:51 +00003/*
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.
Joe Stringerf3675402017-01-26 13:19:56 -08009 * Copyright (C) 2017 Nicira, Inc.
Daniel Borkmannd8599002019-04-09 23:20:13 +020010 * Copyright (C) 2019 Isovalent, Inc.
Wang Nan1b76c132015-07-01 02:13:51 +000011 */
12
Yonghong Songb4269952018-11-29 15:31:45 -080013#ifndef _GNU_SOURCE
Jakub Kicinski531b0142018-07-10 14:43:05 -070014#define _GNU_SOURCE
Yonghong Songb4269952018-11-29 15:31:45 -080015#endif
Wang Nan1b76c132015-07-01 02:13:51 +000016#include <stdlib.h>
Wang Nanb3f59d62015-07-01 02:13:52 +000017#include <stdio.h>
18#include <stdarg.h>
Joe Stringerf3675402017-01-26 13:19:56 -080019#include <libgen.h>
Wang Nan34090912015-07-01 02:14:02 +000020#include <inttypes.h>
Wang Nanb3f59d62015-07-01 02:13:52 +000021#include <string.h>
Wang Nan1b76c132015-07-01 02:13:51 +000022#include <unistd.h>
Arnaldo Carvalho de Melocdb2f922019-07-19 11:34:06 -030023#include <endian.h>
Wang Nan1a5e3fb2015-07-01 02:13:53 +000024#include <fcntl.h>
25#include <errno.h>
Wang Nan1b76c132015-07-01 02:13:51 +000026#include <asm/unistd.h>
Joe Stringere28ff1a2017-01-22 17:11:25 -080027#include <linux/err.h>
Wang Nancb1e5e92015-07-01 02:13:57 +000028#include <linux/kernel.h>
Wang Nan1b76c132015-07-01 02:13:51 +000029#include <linux/bpf.h>
Martin KaFai Lau38d5d3b2018-07-24 08:40:22 -070030#include <linux/btf.h>
Stanislav Fomichev47eff612018-11-20 17:11:19 -080031#include <linux/filter.h>
Wang Nan9a208ef2015-07-01 02:14:10 +000032#include <linux/list.h>
Joe Stringerf3675402017-01-26 13:19:56 -080033#include <linux/limits.h>
Yonghong Song438363c2018-10-09 16:14:47 -070034#include <linux/perf_event.h>
Daniel Borkmanna64af0e2018-10-19 15:51:03 +020035#include <linux/ring_buffer.h>
Andrii Nakryiko5e61f272019-10-04 15:40:34 -070036#include <linux/version.h>
Andrii Nakryikofb84b822019-07-06 11:06:24 -070037#include <sys/epoll.h>
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -070038#include <sys/ioctl.h>
Andrii Nakryikofb84b822019-07-06 11:06:24 -070039#include <sys/mman.h>
Joe Stringerf3675402017-01-26 13:19:56 -080040#include <sys/stat.h>
41#include <sys/types.h>
42#include <sys/vfs.h>
Andrii Nakryikoddc7c302019-08-07 14:39:51 -070043#include <sys/utsname.h>
Toke Høiland-Jørgensendc3a2d22019-12-16 19:12:04 +010044#include <sys/resource.h>
Jakub Kicinski531b0142018-07-10 14:43:05 -070045#include <tools/libc_compat.h>
Wang Nan1a5e3fb2015-07-01 02:13:53 +000046#include <libelf.h>
47#include <gelf.h>
Andrii Nakryiko166750b2019-12-13 17:47:08 -080048#include <zlib.h>
Wang Nan1b76c132015-07-01 02:13:51 +000049
50#include "libbpf.h"
Wang Nan52d33522015-07-01 02:14:04 +000051#include "bpf.h"
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -070052#include "btf.h"
Arnaldo Carvalho de Melo6d419072018-09-14 16:47:14 -030053#include "str_error.h"
Andrii Nakryikod7c4b392019-05-10 14:13:15 -070054#include "libbpf_internal.h"
Andrii Nakryikoddc7c302019-08-07 14:39:51 -070055#include "hashmap.h"
Wang Nanb3f59d62015-07-01 02:13:52 +000056
Wang Nan9b161372016-07-18 06:01:08 +000057#ifndef EM_BPF
58#define EM_BPF 247
59#endif
60
Joe Stringerf3675402017-01-26 13:19:56 -080061#ifndef BPF_FS_MAGIC
62#define BPF_FS_MAGIC 0xcafe4a11
63#endif
64
Andrey Ignatovff466b52019-04-06 22:37:34 -070065/* vsprintf() in __base_pr() uses nonliteral format string. It may break
66 * compilation if user enables corresponding warning. Disable it explicitly.
67 */
68#pragma GCC diagnostic ignored "-Wformat-nonliteral"
69
Wang Nanb3f59d62015-07-01 02:13:52 +000070#define __printf(a, b) __attribute__((format(printf, a, b)))
71
Stanislav Fomicheva8a1f7d2019-02-04 16:20:55 -080072static int __base_pr(enum libbpf_print_level level, const char *format,
73 va_list args)
Wang Nanb3f59d62015-07-01 02:13:52 +000074{
Yonghong Song6f1ae8b2019-02-01 16:14:17 -080075 if (level == LIBBPF_DEBUG)
76 return 0;
77
Stanislav Fomicheva8a1f7d2019-02-04 16:20:55 -080078 return vfprintf(stderr, format, args);
Wang Nanb3f59d62015-07-01 02:13:52 +000079}
80
Stanislav Fomicheva8a1f7d2019-02-04 16:20:55 -080081static libbpf_print_fn_t __libbpf_pr = __base_pr;
Wang Nanb3f59d62015-07-01 02:13:52 +000082
Andrii Nakryikoe87fd8b2019-07-27 20:25:26 -070083libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
Wang Nanb3f59d62015-07-01 02:13:52 +000084{
Andrii Nakryikoe87fd8b2019-07-27 20:25:26 -070085 libbpf_print_fn_t old_print_fn = __libbpf_pr;
86
Yonghong Song6f1ae8b2019-02-01 16:14:17 -080087 __libbpf_pr = fn;
Andrii Nakryikoe87fd8b2019-07-27 20:25:26 -070088 return old_print_fn;
Wang Nanb3f59d62015-07-01 02:13:52 +000089}
Wang Nan1a5e3fb2015-07-01 02:13:53 +000090
Yonghong Song8461ef82019-02-01 16:14:14 -080091__printf(2, 3)
92void libbpf_print(enum libbpf_print_level level, const char *format, ...)
93{
94 va_list args;
95
Yonghong Song6f1ae8b2019-02-01 16:14:17 -080096 if (!__libbpf_pr)
97 return;
98
Yonghong Song8461ef82019-02-01 16:14:14 -080099 va_start(args, format);
Yonghong Song6f1ae8b2019-02-01 16:14:17 -0800100 __libbpf_pr(level, format, args);
Yonghong Song8461ef82019-02-01 16:14:14 -0800101 va_end(args);
102}
103
Toke Høiland-Jørgensendc3a2d22019-12-16 19:12:04 +0100104static void pr_perm_msg(int err)
105{
106 struct rlimit limit;
107 char buf[100];
108
109 if (err != -EPERM || geteuid() != 0)
110 return;
111
112 err = getrlimit(RLIMIT_MEMLOCK, &limit);
113 if (err)
114 return;
115
116 if (limit.rlim_cur == RLIM_INFINITY)
117 return;
118
119 if (limit.rlim_cur < 1024)
120 snprintf(buf, sizeof(buf), "%lu bytes", limit.rlim_cur);
121 else if (limit.rlim_cur < 1024*1024)
122 snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
123 else
124 snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
125
126 pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
127 buf);
128}
129
Wang Nan6371ca3b2015-11-06 13:49:37 +0000130#define STRERR_BUFSIZE 128
131
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000132/* Copied from tools/perf/util/util.h */
133#ifndef zfree
134# define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
135#endif
136
137#ifndef zclose
138# define zclose(fd) ({ \
139 int ___err = 0; \
140 if ((fd) >= 0) \
141 ___err = close((fd)); \
142 fd = -1; \
143 ___err; })
144#endif
145
146#ifdef HAVE_LIBELF_MMAP_SUPPORT
147# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ_MMAP
148#else
149# define LIBBPF_ELF_C_READ_MMAP ELF_C_READ
150#endif
151
Song Liu34be16462019-03-11 22:30:38 -0700152static inline __u64 ptr_to_u64(const void *ptr)
153{
154 return (__u64) (unsigned long) ptr;
155}
156
Stanislav Fomichev47eff612018-11-20 17:11:19 -0800157struct bpf_capabilities {
158 /* v4.14: kernel support for program & map names. */
159 __u32 name:1;
Daniel Borkmann8837fe52019-04-24 00:45:56 +0200160 /* v5.2: kernel support for global data sections. */
161 __u32 global_data:1;
Andrii Nakryikod7c4b392019-05-10 14:13:15 -0700162 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
163 __u32 btf_func:1;
164 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
165 __u32 btf_datasec:1;
Andrii Nakryiko7fe74b42019-11-17 09:28:05 -0800166 /* BPF_F_MMAPABLE is supported for arrays */
167 __u32 array_mmap:1;
Stanislav Fomichev47eff612018-11-20 17:11:19 -0800168};
169
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800170enum reloc_type {
171 RELO_LD64,
172 RELO_CALL,
173 RELO_DATA,
174 RELO_EXTERN,
175};
176
177struct reloc_desc {
178 enum reloc_type type;
179 int insn_idx;
180 int map_idx;
181 int sym_off;
182};
183
Wang Nana5b8bd42015-07-01 02:14:00 +0000184/*
185 * bpf_prog should be a better name but it has been used in
186 * linux/filter.h.
187 */
188struct bpf_program {
189 /* Index in elf obj file, for relocation use. */
190 int idx;
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700191 char *name;
David Beckettf0307a72018-05-16 14:02:49 -0700192 int prog_ifindex;
Wang Nana5b8bd42015-07-01 02:14:00 +0000193 char *section_name;
Stanislav Fomichev33a2c752018-11-09 08:21:43 -0800194 /* section_name with / replaced by _; makes recursive pinning
195 * in bpf_object__pin_programs easier
196 */
197 char *pin_name;
Wang Nana5b8bd42015-07-01 02:14:00 +0000198 struct bpf_insn *insns;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -0800199 size_t insns_cnt, main_prog_cnt;
Wang Nan5f44e4c82016-07-13 10:44:01 +0000200 enum bpf_prog_type type;
Wang Nan34090912015-07-01 02:14:02 +0000201
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800202 struct reloc_desc *reloc_desc;
Wang Nan34090912015-07-01 02:14:02 +0000203 int nr_reloc;
Alexei Starovoitovda11b412019-04-01 21:27:47 -0700204 int log_level;
Wang Nan55cffde2015-07-01 02:14:07 +0000205
Wang Nanb5805632015-11-16 12:10:09 +0000206 struct {
207 int nr;
208 int *fds;
209 } instances;
210 bpf_program_prep_t preprocessor;
Wang Nanaa9b1ac2015-07-01 02:14:08 +0000211
212 struct bpf_object *obj;
213 void *priv;
214 bpf_program_clear_priv_t clear_priv;
Andrey Ignatovd7be1432018-03-30 15:08:01 -0700215
216 enum bpf_attach_type expected_attach_type;
Alexei Starovoitov12a86542019-10-30 15:32:12 -0700217 __u32 attach_btf_id;
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -0800218 __u32 attach_prog_fd;
Yonghong Song2993e052018-11-19 15:29:16 -0800219 void *func_info;
220 __u32 func_info_rec_size;
Martin KaFai Lauf0187f02018-12-07 16:42:29 -0800221 __u32 func_info_cnt;
Stanislav Fomichev47eff612018-11-20 17:11:19 -0800222
223 struct bpf_capabilities *caps;
Martin KaFai Lau3d650142018-12-07 16:42:31 -0800224
225 void *line_info;
226 __u32 line_info_rec_size;
227 __u32 line_info_cnt;
Jiong Wang04656192019-05-24 23:25:19 +0100228 __u32 prog_flags;
Wang Nana5b8bd42015-07-01 02:14:00 +0000229};
230
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800231#define DATA_SEC ".data"
232#define BSS_SEC ".bss"
233#define RODATA_SEC ".rodata"
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800234#define EXTERN_SEC ".extern"
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800235
Daniel Borkmannd8599002019-04-09 23:20:13 +0200236enum libbpf_map_type {
237 LIBBPF_MAP_UNSPEC,
238 LIBBPF_MAP_DATA,
239 LIBBPF_MAP_BSS,
240 LIBBPF_MAP_RODATA,
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800241 LIBBPF_MAP_EXTERN,
Daniel Borkmannd8599002019-04-09 23:20:13 +0200242};
243
244static const char * const libbpf_type_to_btf_name[] = {
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800245 [LIBBPF_MAP_DATA] = DATA_SEC,
246 [LIBBPF_MAP_BSS] = BSS_SEC,
247 [LIBBPF_MAP_RODATA] = RODATA_SEC,
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800248 [LIBBPF_MAP_EXTERN] = EXTERN_SEC,
Daniel Borkmannd8599002019-04-09 23:20:13 +0200249};
250
Wang Nan9d759a92015-11-27 08:47:35 +0000251struct bpf_map {
Wang Nan561bbcc2015-11-27 08:47:36 +0000252 char *name;
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -0800253 int fd;
Andrii Nakryikodb488142019-06-17 12:26:54 -0700254 int sec_idx;
255 size_t sec_offset;
David Beckettf0307a72018-05-16 14:02:49 -0700256 int map_ifindex;
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -0800257 int inner_map_fd;
Wang Nan9d759a92015-11-27 08:47:35 +0000258 struct bpf_map_def def;
Martin KaFai Lau5b891af2018-07-24 08:40:21 -0700259 __u32 btf_key_type_id;
260 __u32 btf_value_type_id;
Wang Nan9d759a92015-11-27 08:47:35 +0000261 void *priv;
262 bpf_map_clear_priv_t clear_priv;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200263 enum libbpf_map_type libbpf_type;
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800264 void *mmaped;
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +0100265 char *pin_path;
266 bool pinned;
Toke Høiland-Jørgensenec6d5f472019-11-09 21:37:27 +0100267 bool reused;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200268};
269
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800270enum extern_type {
271 EXT_UNKNOWN,
272 EXT_CHAR,
273 EXT_BOOL,
274 EXT_INT,
275 EXT_TRISTATE,
276 EXT_CHAR_ARR,
277};
278
279struct extern_desc {
280 const char *name;
281 int sym_idx;
282 int btf_id;
283 enum extern_type type;
284 int sz;
285 int align;
286 int data_off;
287 bool is_signed;
288 bool is_weak;
289 bool is_set;
290};
291
Wang Nan9a208ef2015-07-01 02:14:10 +0000292static LIST_HEAD(bpf_objects_list);
293
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000294struct bpf_object {
Daniel Borkmannd8599002019-04-09 23:20:13 +0200295 char name[BPF_OBJ_NAME_LEN];
Wang Nancb1e5e92015-07-01 02:13:57 +0000296 char license[64];
Yonghong Song438363c2018-10-09 16:14:47 -0700297 __u32 kern_version;
Wang Nan0b3d1ef2015-07-01 02:13:58 +0000298
Wang Nana5b8bd42015-07-01 02:14:00 +0000299 struct bpf_program *programs;
300 size_t nr_programs;
Wang Nan9d759a92015-11-27 08:47:35 +0000301 struct bpf_map *maps;
302 size_t nr_maps;
Andrii Nakryikobf829272019-06-17 12:26:53 -0700303 size_t maps_cap;
Wang Nan9d759a92015-11-27 08:47:35 +0000304
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800305 char *kconfig_path;
306 struct extern_desc *externs;
307 int nr_extern;
308 int extern_map_idx;
309
Wang Nan52d33522015-07-01 02:14:04 +0000310 bool loaded;
Jakub Kicinski9a94f272018-06-28 14:41:38 -0700311 bool has_pseudo_calls;
Andrii Nakryiko62561eb2019-10-15 11:28:47 -0700312 bool relaxed_core_relocs;
Wang Nana5b8bd42015-07-01 02:14:00 +0000313
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000314 /*
315 * Information when doing elf related work. Only valid if fd
316 * is valid.
317 */
318 struct {
319 int fd;
Andrii Nakryiko5e61f272019-10-04 15:40:34 -0700320 const void *obj_buf;
Wang Nan6c956392015-07-01 02:13:54 +0000321 size_t obj_buf_sz;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000322 Elf *elf;
323 GElf_Ehdr ehdr;
Wang Nanbec7d682015-07-01 02:13:59 +0000324 Elf_Data *symbols;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200325 Elf_Data *data;
326 Elf_Data *rodata;
327 Elf_Data *bss;
Wang Nan77ba9a52015-12-08 02:25:30 +0000328 size_t strtabidx;
Wang Nanb62f06e2015-07-01 02:14:01 +0000329 struct {
330 GElf_Shdr shdr;
331 Elf_Data *data;
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -0800332 } *reloc_sects;
333 int nr_reloc_sects;
Wang Nan666810e2016-01-25 09:55:49 +0000334 int maps_shndx;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -0700335 int btf_maps_shndx;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -0800336 int text_shndx;
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800337 int symbols_shndx;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200338 int data_shndx;
339 int rodata_shndx;
340 int bss_shndx;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000341 } efile;
Wang Nan9a208ef2015-07-01 02:14:10 +0000342 /*
343 * All loaded bpf_object is linked in a list, which is
344 * hidden to caller. bpf_objects__<func> handlers deal with
345 * all objects.
346 */
347 struct list_head list;
Wang Nan10931d22016-11-26 07:03:26 +0000348
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -0700349 struct btf *btf;
Yonghong Song2993e052018-11-19 15:29:16 -0800350 struct btf_ext *btf_ext;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -0700351
Wang Nan10931d22016-11-26 07:03:26 +0000352 void *priv;
353 bpf_object_clear_priv_t clear_priv;
354
Stanislav Fomichev47eff612018-11-20 17:11:19 -0800355 struct bpf_capabilities caps;
356
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000357 char path[];
358};
359#define obj_elf_valid(o) ((o)->efile.elf)
360
Joe Stringer29cd77f2018-10-02 13:35:39 -0700361void bpf_program__unload(struct bpf_program *prog)
Wang Nan55cffde2015-07-01 02:14:07 +0000362{
Wang Nanb5805632015-11-16 12:10:09 +0000363 int i;
364
Wang Nan55cffde2015-07-01 02:14:07 +0000365 if (!prog)
366 return;
367
Wang Nanb5805632015-11-16 12:10:09 +0000368 /*
369 * If the object is opened but the program was never loaded,
370 * it is possible that prog->instances.nr == -1.
371 */
372 if (prog->instances.nr > 0) {
373 for (i = 0; i < prog->instances.nr; i++)
374 zclose(prog->instances.fds[i]);
375 } else if (prog->instances.nr != -1) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800376 pr_warn("Internal error: instances.nr is %d\n",
377 prog->instances.nr);
Wang Nanb5805632015-11-16 12:10:09 +0000378 }
379
380 prog->instances.nr = -1;
381 zfree(&prog->instances.fds);
Yonghong Song2993e052018-11-19 15:29:16 -0800382
Yonghong Song2993e052018-11-19 15:29:16 -0800383 zfree(&prog->func_info);
Prashant Bhole07a09d12018-12-17 16:57:50 +0900384 zfree(&prog->line_info);
Wang Nan55cffde2015-07-01 02:14:07 +0000385}
386
Wang Nana5b8bd42015-07-01 02:14:00 +0000387static void bpf_program__exit(struct bpf_program *prog)
388{
389 if (!prog)
390 return;
391
Wang Nanaa9b1ac2015-07-01 02:14:08 +0000392 if (prog->clear_priv)
393 prog->clear_priv(prog, prog->priv);
394
395 prog->priv = NULL;
396 prog->clear_priv = NULL;
397
Wang Nan55cffde2015-07-01 02:14:07 +0000398 bpf_program__unload(prog);
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700399 zfree(&prog->name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000400 zfree(&prog->section_name);
Stanislav Fomichev33a2c752018-11-09 08:21:43 -0800401 zfree(&prog->pin_name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000402 zfree(&prog->insns);
Wang Nan34090912015-07-01 02:14:02 +0000403 zfree(&prog->reloc_desc);
404
405 prog->nr_reloc = 0;
Wang Nana5b8bd42015-07-01 02:14:00 +0000406 prog->insns_cnt = 0;
407 prog->idx = -1;
408}
409
Stanislav Fomichev33a2c752018-11-09 08:21:43 -0800410static char *__bpf_program__pin_name(struct bpf_program *prog)
411{
412 char *name, *p;
413
414 name = p = strdup(prog->section_name);
415 while ((p = strchr(p, '/')))
416 *p = '_';
417
418 return name;
419}
420
Wang Nana5b8bd42015-07-01 02:14:00 +0000421static int
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700422bpf_program__init(void *data, size_t size, char *section_name, int idx,
423 struct bpf_program *prog)
Wang Nana5b8bd42015-07-01 02:14:00 +0000424{
Andrii Nakryiko8ca990c2019-05-29 10:36:03 -0700425 const size_t bpf_insn_sz = sizeof(struct bpf_insn);
426
427 if (size == 0 || size % bpf_insn_sz) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800428 pr_warn("corrupted section '%s', size: %zu\n",
429 section_name, size);
Wang Nana5b8bd42015-07-01 02:14:00 +0000430 return -EINVAL;
431 }
432
Andrii Nakryiko1ad9cbb2019-02-13 10:25:53 -0800433 memset(prog, 0, sizeof(*prog));
Wang Nana5b8bd42015-07-01 02:14:00 +0000434
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700435 prog->section_name = strdup(section_name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000436 if (!prog->section_name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800437 pr_warn("failed to alloc name for prog under section(%d) %s\n",
438 idx, section_name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000439 goto errout;
440 }
441
Stanislav Fomichev33a2c752018-11-09 08:21:43 -0800442 prog->pin_name = __bpf_program__pin_name(prog);
443 if (!prog->pin_name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800444 pr_warn("failed to alloc pin name for prog under section(%d) %s\n",
445 idx, section_name);
Stanislav Fomichev33a2c752018-11-09 08:21:43 -0800446 goto errout;
447 }
448
Wang Nana5b8bd42015-07-01 02:14:00 +0000449 prog->insns = malloc(size);
450 if (!prog->insns) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800451 pr_warn("failed to alloc insns for prog under section %s\n",
452 section_name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000453 goto errout;
454 }
Andrii Nakryiko8ca990c2019-05-29 10:36:03 -0700455 prog->insns_cnt = size / bpf_insn_sz;
456 memcpy(prog->insns, data, size);
Wang Nana5b8bd42015-07-01 02:14:00 +0000457 prog->idx = idx;
Wang Nanb5805632015-11-16 12:10:09 +0000458 prog->instances.fds = NULL;
459 prog->instances.nr = -1;
Nikita V. Shirokov47ae7e32018-11-23 12:58:12 -0800460 prog->type = BPF_PROG_TYPE_UNSPEC;
Wang Nana5b8bd42015-07-01 02:14:00 +0000461
462 return 0;
463errout:
464 bpf_program__exit(prog);
465 return -ENOMEM;
466}
467
468static int
469bpf_object__add_program(struct bpf_object *obj, void *data, size_t size,
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700470 char *section_name, int idx)
Wang Nana5b8bd42015-07-01 02:14:00 +0000471{
472 struct bpf_program prog, *progs;
473 int nr_progs, err;
474
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700475 err = bpf_program__init(data, size, section_name, idx, &prog);
Wang Nana5b8bd42015-07-01 02:14:00 +0000476 if (err)
477 return err;
478
Stanislav Fomichev47eff612018-11-20 17:11:19 -0800479 prog.caps = &obj->caps;
Wang Nana5b8bd42015-07-01 02:14:00 +0000480 progs = obj->programs;
481 nr_progs = obj->nr_programs;
482
Jakub Kicinski531b0142018-07-10 14:43:05 -0700483 progs = reallocarray(progs, nr_progs + 1, sizeof(progs[0]));
Wang Nana5b8bd42015-07-01 02:14:00 +0000484 if (!progs) {
485 /*
486 * In this case the original obj->programs
487 * is still valid, so don't need special treat for
488 * bpf_close_object().
489 */
Kefeng Wangbe180102019-10-21 13:55:32 +0800490 pr_warn("failed to alloc a new program under section '%s'\n",
491 section_name);
Wang Nana5b8bd42015-07-01 02:14:00 +0000492 bpf_program__exit(&prog);
493 return -ENOMEM;
494 }
495
496 pr_debug("found program %s\n", prog.section_name);
497 obj->programs = progs;
498 obj->nr_programs = nr_progs + 1;
Wang Nanaa9b1ac2015-07-01 02:14:08 +0000499 prog.obj = obj;
Wang Nana5b8bd42015-07-01 02:14:00 +0000500 progs[nr_progs] = prog;
501 return 0;
502}
503
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700504static int
505bpf_object__init_prog_names(struct bpf_object *obj)
506{
507 Elf_Data *symbols = obj->efile.symbols;
508 struct bpf_program *prog;
509 size_t pi, si;
510
511 for (pi = 0; pi < obj->nr_programs; pi++) {
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -0800512 const char *name = NULL;
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700513
514 prog = &obj->programs[pi];
515
516 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym) && !name;
517 si++) {
518 GElf_Sym sym;
519
520 if (!gelf_getsym(symbols, si, &sym))
521 continue;
522 if (sym.st_shndx != prog->idx)
523 continue;
Roman Gushchinfe4d44b2017-12-13 15:18:52 +0000524 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL)
525 continue;
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700526
527 name = elf_strptr(obj->efile.elf,
528 obj->efile.strtabidx,
529 sym.st_name);
530 if (!name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800531 pr_warn("failed to get sym name string for prog %s\n",
532 prog->section_name);
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700533 return -LIBBPF_ERRNO__LIBELF;
534 }
535 }
536
Jakub Kicinski9a94f272018-06-28 14:41:38 -0700537 if (!name && prog->idx == obj->efile.text_shndx)
538 name = ".text";
539
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700540 if (!name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800541 pr_warn("failed to find sym for prog %s\n",
542 prog->section_name);
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700543 return -EINVAL;
544 }
Jakub Kicinski9a94f272018-06-28 14:41:38 -0700545
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700546 prog->name = strdup(name);
547 if (!prog->name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800548 pr_warn("failed to allocate memory for prog sym %s\n",
549 name);
Martin KaFai Lau88cda1c2017-09-27 14:37:54 -0700550 return -ENOMEM;
551 }
552 }
553
554 return 0;
555}
556
Andrii Nakryiko5e61f272019-10-04 15:40:34 -0700557static __u32 get_kernel_version(void)
558{
559 __u32 major, minor, patch;
560 struct utsname info;
561
562 uname(&info);
563 if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
564 return 0;
565 return KERNEL_VERSION(major, minor, patch);
566}
567
Wang Nan6c956392015-07-01 02:13:54 +0000568static struct bpf_object *bpf_object__new(const char *path,
Andrii Nakryiko5e61f272019-10-04 15:40:34 -0700569 const void *obj_buf,
Andrii Nakryiko2ce84502019-10-04 15:40:35 -0700570 size_t obj_buf_sz,
571 const char *obj_name)
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000572{
573 struct bpf_object *obj;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200574 char *end;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000575
576 obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
577 if (!obj) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800578 pr_warn("alloc memory failed for %s\n", path);
Wang Nan6371ca3b2015-11-06 13:49:37 +0000579 return ERR_PTR(-ENOMEM);
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000580 }
581
582 strcpy(obj->path, path);
Andrii Nakryiko2ce84502019-10-04 15:40:35 -0700583 if (obj_name) {
584 strncpy(obj->name, obj_name, sizeof(obj->name) - 1);
585 obj->name[sizeof(obj->name) - 1] = 0;
586 } else {
587 /* Using basename() GNU version which doesn't modify arg. */
588 strncpy(obj->name, basename((void *)path),
589 sizeof(obj->name) - 1);
590 end = strchr(obj->name, '.');
591 if (end)
592 *end = 0;
593 }
Wang Nan6c956392015-07-01 02:13:54 +0000594
Daniel Borkmannd8599002019-04-09 23:20:13 +0200595 obj->efile.fd = -1;
Wang Nan6c956392015-07-01 02:13:54 +0000596 /*
Andrii Nakryiko76e10222019-05-29 10:36:10 -0700597 * Caller of this function should also call
Wang Nan6c956392015-07-01 02:13:54 +0000598 * bpf_object__elf_finish() after data collection to return
599 * obj_buf to user. If not, we should duplicate the buffer to
600 * avoid user freeing them before elf finish.
601 */
602 obj->efile.obj_buf = obj_buf;
603 obj->efile.obj_buf_sz = obj_buf_sz;
Wang Nan666810e2016-01-25 09:55:49 +0000604 obj->efile.maps_shndx = -1;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -0700605 obj->efile.btf_maps_shndx = -1;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200606 obj->efile.data_shndx = -1;
607 obj->efile.rodata_shndx = -1;
608 obj->efile.bss_shndx = -1;
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800609 obj->extern_map_idx = -1;
Wang Nan6c956392015-07-01 02:13:54 +0000610
Andrii Nakryiko5e61f272019-10-04 15:40:34 -0700611 obj->kern_version = get_kernel_version();
Wang Nan52d33522015-07-01 02:14:04 +0000612 obj->loaded = false;
Wang Nan9a208ef2015-07-01 02:14:10 +0000613
614 INIT_LIST_HEAD(&obj->list);
615 list_add(&obj->list, &bpf_objects_list);
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000616 return obj;
617}
618
619static void bpf_object__elf_finish(struct bpf_object *obj)
620{
621 if (!obj_elf_valid(obj))
622 return;
623
624 if (obj->efile.elf) {
625 elf_end(obj->efile.elf);
626 obj->efile.elf = NULL;
627 }
Wang Nanbec7d682015-07-01 02:13:59 +0000628 obj->efile.symbols = NULL;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200629 obj->efile.data = NULL;
630 obj->efile.rodata = NULL;
631 obj->efile.bss = NULL;
Wang Nanb62f06e2015-07-01 02:14:01 +0000632
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -0800633 zfree(&obj->efile.reloc_sects);
634 obj->efile.nr_reloc_sects = 0;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000635 zclose(obj->efile.fd);
Wang Nan6c956392015-07-01 02:13:54 +0000636 obj->efile.obj_buf = NULL;
637 obj->efile.obj_buf_sz = 0;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000638}
639
640static int bpf_object__elf_init(struct bpf_object *obj)
641{
642 int err = 0;
643 GElf_Ehdr *ep;
644
645 if (obj_elf_valid(obj)) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800646 pr_warn("elf init: internal error\n");
Wang Nan6371ca3b2015-11-06 13:49:37 +0000647 return -LIBBPF_ERRNO__LIBELF;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000648 }
649
Wang Nan6c956392015-07-01 02:13:54 +0000650 if (obj->efile.obj_buf_sz > 0) {
651 /*
652 * obj_buf should have been validated by
653 * bpf_object__open_buffer().
654 */
Andrii Nakryiko5e61f272019-10-04 15:40:34 -0700655 obj->efile.elf = elf_memory((char *)obj->efile.obj_buf,
Wang Nan6c956392015-07-01 02:13:54 +0000656 obj->efile.obj_buf_sz);
657 } else {
658 obj->efile.fd = open(obj->path, O_RDONLY);
659 if (obj->efile.fd < 0) {
Andrii Nakryikobe5c5d42019-05-29 10:36:04 -0700660 char errmsg[STRERR_BUFSIZE], *cp;
Thomas Richter1ce6a9f2018-07-30 10:53:23 +0200661
Andrii Nakryikobe5c5d42019-05-29 10:36:04 -0700662 err = -errno;
663 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +0800664 pr_warn("failed to open %s: %s\n", obj->path, cp);
Andrii Nakryikobe5c5d42019-05-29 10:36:04 -0700665 return err;
Wang Nan6c956392015-07-01 02:13:54 +0000666 }
667
668 obj->efile.elf = elf_begin(obj->efile.fd,
Andrii Nakryiko76e10222019-05-29 10:36:10 -0700669 LIBBPF_ELF_C_READ_MMAP, NULL);
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000670 }
671
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000672 if (!obj->efile.elf) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800673 pr_warn("failed to open %s as ELF file\n", obj->path);
Wang Nan6371ca3b2015-11-06 13:49:37 +0000674 err = -LIBBPF_ERRNO__LIBELF;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000675 goto errout;
676 }
677
678 if (!gelf_getehdr(obj->efile.elf, &obj->efile.ehdr)) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800679 pr_warn("failed to get EHDR from %s\n", obj->path);
Wang Nan6371ca3b2015-11-06 13:49:37 +0000680 err = -LIBBPF_ERRNO__FORMAT;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000681 goto errout;
682 }
683 ep = &obj->efile.ehdr;
684
Wang Nan9b161372016-07-18 06:01:08 +0000685 /* Old LLVM set e_machine to EM_NONE */
Andrii Nakryiko76e10222019-05-29 10:36:10 -0700686 if (ep->e_type != ET_REL ||
687 (ep->e_machine && ep->e_machine != EM_BPF)) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800688 pr_warn("%s is not an eBPF object file\n", obj->path);
Wang Nan6371ca3b2015-11-06 13:49:37 +0000689 err = -LIBBPF_ERRNO__FORMAT;
Wang Nan1a5e3fb2015-07-01 02:13:53 +0000690 goto errout;
691 }
692
693 return 0;
694errout:
695 bpf_object__elf_finish(obj);
696 return err;
697}
698
Andrii Nakryiko12ef5632019-05-29 10:36:05 -0700699static int bpf_object__check_endianness(struct bpf_object *obj)
Wang Nancc4228d2015-07-01 02:13:55 +0000700{
Arnaldo Carvalho de Melocdb2f922019-07-19 11:34:06 -0300701#if __BYTE_ORDER == __LITTLE_ENDIAN
Andrii Nakryiko12ef5632019-05-29 10:36:05 -0700702 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
703 return 0;
Arnaldo Carvalho de Melocdb2f922019-07-19 11:34:06 -0300704#elif __BYTE_ORDER == __BIG_ENDIAN
Andrii Nakryiko12ef5632019-05-29 10:36:05 -0700705 if (obj->efile.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
706 return 0;
707#else
708# error "Unrecognized __BYTE_ORDER__"
709#endif
Kefeng Wangbe180102019-10-21 13:55:32 +0800710 pr_warn("endianness mismatch.\n");
Wang Nan6371ca3b2015-11-06 13:49:37 +0000711 return -LIBBPF_ERRNO__ENDIAN;
Wang Nancc4228d2015-07-01 02:13:55 +0000712}
713
Wang Nancb1e5e92015-07-01 02:13:57 +0000714static int
Andrii Nakryiko399dc652019-05-29 10:36:11 -0700715bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
Wang Nancb1e5e92015-07-01 02:13:57 +0000716{
Andrii Nakryiko399dc652019-05-29 10:36:11 -0700717 memcpy(obj->license, data, min(size, sizeof(obj->license) - 1));
Wang Nancb1e5e92015-07-01 02:13:57 +0000718 pr_debug("license of %s is %s\n", obj->path, obj->license);
719 return 0;
720}
721
John Fastabend54b86252019-10-18 07:41:26 -0700722static int
723bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
724{
725 __u32 kver;
726
727 if (size != sizeof(kver)) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800728 pr_warn("invalid kver section in %s\n", obj->path);
John Fastabend54b86252019-10-18 07:41:26 -0700729 return -LIBBPF_ERRNO__FORMAT;
730 }
731 memcpy(&kver, data, sizeof(kver));
732 obj->kern_version = kver;
733 pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
734 return 0;
735}
736
Eric Leblond4708bbd2016-11-15 04:05:47 +0000737static int compare_bpf_map(const void *_a, const void *_b)
738{
739 const struct bpf_map *a = _a;
740 const struct bpf_map *b = _b;
741
Andrii Nakryikodb488142019-06-17 12:26:54 -0700742 if (a->sec_idx != b->sec_idx)
743 return a->sec_idx - b->sec_idx;
744 return a->sec_offset - b->sec_offset;
Eric Leblond4708bbd2016-11-15 04:05:47 +0000745}
746
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -0800747static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
748{
749 if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
750 type == BPF_MAP_TYPE_HASH_OF_MAPS)
751 return true;
752 return false;
753}
754
Daniel Borkmann1713d682019-04-09 23:20:14 +0200755static int bpf_object_search_section_size(const struct bpf_object *obj,
756 const char *name, size_t *d_size)
757{
758 const GElf_Ehdr *ep = &obj->efile.ehdr;
759 Elf *elf = obj->efile.elf;
760 Elf_Scn *scn = NULL;
761 int idx = 0;
762
763 while ((scn = elf_nextscn(elf, scn)) != NULL) {
764 const char *sec_name;
765 Elf_Data *data;
766 GElf_Shdr sh;
767
768 idx++;
769 if (gelf_getshdr(scn, &sh) != &sh) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800770 pr_warn("failed to get section(%d) header from %s\n",
771 idx, obj->path);
Daniel Borkmann1713d682019-04-09 23:20:14 +0200772 return -EIO;
773 }
774
775 sec_name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
776 if (!sec_name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800777 pr_warn("failed to get section(%d) name from %s\n",
778 idx, obj->path);
Daniel Borkmann1713d682019-04-09 23:20:14 +0200779 return -EIO;
780 }
781
782 if (strcmp(name, sec_name))
783 continue;
784
785 data = elf_getdata(scn, 0);
786 if (!data) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800787 pr_warn("failed to get section(%d) data from %s(%s)\n",
788 idx, name, obj->path);
Daniel Borkmann1713d682019-04-09 23:20:14 +0200789 return -EIO;
790 }
791
792 *d_size = data->d_size;
793 return 0;
794 }
795
796 return -ENOENT;
797}
798
799int bpf_object__section_size(const struct bpf_object *obj, const char *name,
800 __u32 *size)
801{
802 int ret = -ENOENT;
803 size_t d_size;
804
805 *size = 0;
806 if (!name) {
807 return -EINVAL;
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800808 } else if (!strcmp(name, DATA_SEC)) {
Daniel Borkmann1713d682019-04-09 23:20:14 +0200809 if (obj->efile.data)
810 *size = obj->efile.data->d_size;
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800811 } else if (!strcmp(name, BSS_SEC)) {
Daniel Borkmann1713d682019-04-09 23:20:14 +0200812 if (obj->efile.bss)
813 *size = obj->efile.bss->d_size;
Andrii Nakryikoac9d1382019-12-13 17:47:07 -0800814 } else if (!strcmp(name, RODATA_SEC)) {
Daniel Borkmann1713d682019-04-09 23:20:14 +0200815 if (obj->efile.rodata)
816 *size = obj->efile.rodata->d_size;
817 } else {
818 ret = bpf_object_search_section_size(obj, name, &d_size);
819 if (!ret)
820 *size = d_size;
821 }
822
823 return *size ? 0 : ret;
824}
825
826int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
827 __u32 *off)
828{
829 Elf_Data *symbols = obj->efile.symbols;
830 const char *sname;
831 size_t si;
832
833 if (!name || !off)
834 return -EINVAL;
835
836 for (si = 0; si < symbols->d_size / sizeof(GElf_Sym); si++) {
837 GElf_Sym sym;
838
839 if (!gelf_getsym(symbols, si, &sym))
840 continue;
841 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL ||
842 GELF_ST_TYPE(sym.st_info) != STT_OBJECT)
843 continue;
844
845 sname = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
846 sym.st_name);
847 if (!sname) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800848 pr_warn("failed to get sym name string for var %s\n",
849 name);
Daniel Borkmann1713d682019-04-09 23:20:14 +0200850 return -EIO;
851 }
852 if (strcmp(name, sname) == 0) {
853 *off = sym.st_value;
854 return 0;
855 }
856 }
857
858 return -ENOENT;
859}
860
Andrii Nakryikobf829272019-06-17 12:26:53 -0700861static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
Daniel Borkmannd8599002019-04-09 23:20:13 +0200862{
Andrii Nakryikobf829272019-06-17 12:26:53 -0700863 struct bpf_map *new_maps;
864 size_t new_cap;
865 int i;
866
867 if (obj->nr_maps < obj->maps_cap)
868 return &obj->maps[obj->nr_maps++];
869
Ivan Khoronzhuk95064972019-06-26 13:38:37 +0300870 new_cap = max((size_t)4, obj->maps_cap * 3 / 2);
Andrii Nakryikobf829272019-06-17 12:26:53 -0700871 new_maps = realloc(obj->maps, new_cap * sizeof(*obj->maps));
872 if (!new_maps) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800873 pr_warn("alloc maps for object failed\n");
Andrii Nakryikobf829272019-06-17 12:26:53 -0700874 return ERR_PTR(-ENOMEM);
875 }
876
877 obj->maps_cap = new_cap;
878 obj->maps = new_maps;
879
880 /* zero out new maps */
881 memset(obj->maps + obj->nr_maps, 0,
882 (obj->maps_cap - obj->nr_maps) * sizeof(*obj->maps));
883 /*
884 * fill all fd with -1 so won't close incorrect fd (fd=0 is stdin)
885 * when failure (zclose won't close negative fd)).
886 */
887 for (i = obj->nr_maps; i < obj->maps_cap; i++) {
888 obj->maps[i].fd = -1;
889 obj->maps[i].inner_map_fd = -1;
890 }
891
892 return &obj->maps[obj->nr_maps++];
Daniel Borkmannd8599002019-04-09 23:20:13 +0200893}
894
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800895static size_t bpf_map_mmap_sz(const struct bpf_map *map)
896{
897 long page_sz = sysconf(_SC_PAGE_SIZE);
898 size_t map_sz;
899
900 map_sz = roundup(map->def.value_size, 8) * map->def.max_entries;
901 map_sz = roundup(map_sz, page_sz);
902 return map_sz;
903}
904
Daniel Borkmannd8599002019-04-09 23:20:13 +0200905static int
Andrii Nakryikobf829272019-06-17 12:26:53 -0700906bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800907 int sec_idx, void *data, size_t data_sz)
Daniel Borkmannd8599002019-04-09 23:20:13 +0200908{
Daniel Borkmannd8599002019-04-09 23:20:13 +0200909 char map_name[BPF_OBJ_NAME_LEN];
Andrii Nakryikobf829272019-06-17 12:26:53 -0700910 struct bpf_map_def *def;
911 struct bpf_map *map;
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800912 int err;
Andrii Nakryikobf829272019-06-17 12:26:53 -0700913
914 map = bpf_object__add_map(obj);
915 if (IS_ERR(map))
916 return PTR_ERR(map);
Daniel Borkmannd8599002019-04-09 23:20:13 +0200917
918 map->libbpf_type = type;
Andrii Nakryikodb488142019-06-17 12:26:54 -0700919 map->sec_idx = sec_idx;
920 map->sec_offset = 0;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200921 snprintf(map_name, sizeof(map_name), "%.8s%.7s", obj->name,
922 libbpf_type_to_btf_name[type]);
923 map->name = strdup(map_name);
924 if (!map->name) {
Kefeng Wangbe180102019-10-21 13:55:32 +0800925 pr_warn("failed to alloc map name\n");
Daniel Borkmannd8599002019-04-09 23:20:13 +0200926 return -ENOMEM;
927 }
928
Andrii Nakryikobf829272019-06-17 12:26:53 -0700929 def = &map->def;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200930 def->type = BPF_MAP_TYPE_ARRAY;
931 def->key_size = sizeof(int);
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800932 def->value_size = data_sz;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200933 def->max_entries = 1;
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800934 def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_EXTERN
935 ? BPF_F_RDONLY_PROG : 0;
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -0800936 def->map_flags |= BPF_F_MMAPABLE;
Andrii Nakryiko7fe74b42019-11-17 09:28:05 -0800937
938 pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
939 map_name, map->sec_idx, map->sec_offset, def->map_flags);
940
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800941 map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
942 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
943 if (map->mmaped == MAP_FAILED) {
944 err = -errno;
945 map->mmaped = NULL;
946 pr_warn("failed to alloc map '%s' content buffer: %d\n",
947 map->name, err);
948 zfree(&map->name);
949 return err;
Daniel Borkmannd8599002019-04-09 23:20:13 +0200950 }
951
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800952 if (data)
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800953 memcpy(map->mmaped, data, data_sz);
954
Andrii Nakryikoe1d1dc42019-04-16 11:47:17 -0700955 pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
Daniel Borkmannd8599002019-04-09 23:20:13 +0200956 return 0;
957}
958
Andrii Nakryikobf829272019-06-17 12:26:53 -0700959static int bpf_object__init_global_data_maps(struct bpf_object *obj)
Eric Leblond4708bbd2016-11-15 04:05:47 +0000960{
Andrii Nakryikobf829272019-06-17 12:26:53 -0700961 int err;
962
Andrii Nakryikobf829272019-06-17 12:26:53 -0700963 /*
964 * Populate obj->maps with libbpf internal maps.
965 */
966 if (obj->efile.data_shndx >= 0) {
967 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
Andrii Nakryikodb488142019-06-17 12:26:54 -0700968 obj->efile.data_shndx,
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800969 obj->efile.data->d_buf,
970 obj->efile.data->d_size);
Andrii Nakryikobf829272019-06-17 12:26:53 -0700971 if (err)
972 return err;
973 }
974 if (obj->efile.rodata_shndx >= 0) {
975 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
Andrii Nakryikodb488142019-06-17 12:26:54 -0700976 obj->efile.rodata_shndx,
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800977 obj->efile.rodata->d_buf,
978 obj->efile.rodata->d_size);
Andrii Nakryikobf829272019-06-17 12:26:53 -0700979 if (err)
980 return err;
981 }
982 if (obj->efile.bss_shndx >= 0) {
983 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
Andrii Nakryikodb488142019-06-17 12:26:54 -0700984 obj->efile.bss_shndx,
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -0800985 NULL,
986 obj->efile.bss->d_size);
Andrii Nakryikobf829272019-06-17 12:26:53 -0700987 if (err)
988 return err;
989 }
990 return 0;
991}
992
Andrii Nakryiko166750b2019-12-13 17:47:08 -0800993
994static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
995 const void *name)
996{
997 int i;
998
999 for (i = 0; i < obj->nr_extern; i++) {
1000 if (strcmp(obj->externs[i].name, name) == 0)
1001 return &obj->externs[i];
1002 }
1003 return NULL;
1004}
1005
1006static int set_ext_value_tri(struct extern_desc *ext, void *ext_val,
1007 char value)
1008{
1009 switch (ext->type) {
1010 case EXT_BOOL:
1011 if (value == 'm') {
1012 pr_warn("extern %s=%c should be tristate or char\n",
1013 ext->name, value);
1014 return -EINVAL;
1015 }
1016 *(bool *)ext_val = value == 'y' ? true : false;
1017 break;
1018 case EXT_TRISTATE:
1019 if (value == 'y')
1020 *(enum libbpf_tristate *)ext_val = TRI_YES;
1021 else if (value == 'm')
1022 *(enum libbpf_tristate *)ext_val = TRI_MODULE;
1023 else /* value == 'n' */
1024 *(enum libbpf_tristate *)ext_val = TRI_NO;
1025 break;
1026 case EXT_CHAR:
1027 *(char *)ext_val = value;
1028 break;
1029 case EXT_UNKNOWN:
1030 case EXT_INT:
1031 case EXT_CHAR_ARR:
1032 default:
1033 pr_warn("extern %s=%c should be bool, tristate, or char\n",
1034 ext->name, value);
1035 return -EINVAL;
1036 }
1037 ext->is_set = true;
1038 return 0;
1039}
1040
1041static int set_ext_value_str(struct extern_desc *ext, char *ext_val,
1042 const char *value)
1043{
1044 size_t len;
1045
1046 if (ext->type != EXT_CHAR_ARR) {
1047 pr_warn("extern %s=%s should char array\n", ext->name, value);
1048 return -EINVAL;
1049 }
1050
1051 len = strlen(value);
1052 if (value[len - 1] != '"') {
1053 pr_warn("extern '%s': invalid string config '%s'\n",
1054 ext->name, value);
1055 return -EINVAL;
1056 }
1057
1058 /* strip quotes */
1059 len -= 2;
1060 if (len >= ext->sz) {
1061 pr_warn("extern '%s': long string config %s of (%zu bytes) truncated to %d bytes\n",
1062 ext->name, value, len, ext->sz - 1);
1063 len = ext->sz - 1;
1064 }
1065 memcpy(ext_val, value + 1, len);
1066 ext_val[len] = '\0';
1067 ext->is_set = true;
1068 return 0;
1069}
1070
1071static int parse_u64(const char *value, __u64 *res)
1072{
1073 char *value_end;
1074 int err;
1075
1076 errno = 0;
1077 *res = strtoull(value, &value_end, 0);
1078 if (errno) {
1079 err = -errno;
1080 pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1081 return err;
1082 }
1083 if (*value_end) {
1084 pr_warn("failed to parse '%s' as integer completely\n", value);
1085 return -EINVAL;
1086 }
1087 return 0;
1088}
1089
1090static bool is_ext_value_in_range(const struct extern_desc *ext, __u64 v)
1091{
1092 int bit_sz = ext->sz * 8;
1093
1094 if (ext->sz == 8)
1095 return true;
1096
1097 /* Validate that value stored in u64 fits in integer of `ext->sz`
1098 * bytes size without any loss of information. If the target integer
1099 * is signed, we rely on the following limits of integer type of
1100 * Y bits and subsequent transformation:
1101 *
1102 * -2^(Y-1) <= X <= 2^(Y-1) - 1
1103 * 0 <= X + 2^(Y-1) <= 2^Y - 1
1104 * 0 <= X + 2^(Y-1) < 2^Y
1105 *
1106 * For unsigned target integer, check that all the (64 - Y) bits are
1107 * zero.
1108 */
1109 if (ext->is_signed)
1110 return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1111 else
1112 return (v >> bit_sz) == 0;
1113}
1114
1115static int set_ext_value_num(struct extern_desc *ext, void *ext_val,
1116 __u64 value)
1117{
1118 if (ext->type != EXT_INT && ext->type != EXT_CHAR) {
1119 pr_warn("extern %s=%llu should be integer\n",
1120 ext->name, value);
1121 return -EINVAL;
1122 }
1123 if (!is_ext_value_in_range(ext, value)) {
1124 pr_warn("extern %s=%llu value doesn't fit in %d bytes\n",
1125 ext->name, value, ext->sz);
1126 return -ERANGE;
1127 }
1128 switch (ext->sz) {
1129 case 1: *(__u8 *)ext_val = value; break;
1130 case 2: *(__u16 *)ext_val = value; break;
1131 case 4: *(__u32 *)ext_val = value; break;
1132 case 8: *(__u64 *)ext_val = value; break;
1133 default:
1134 return -EINVAL;
1135 }
1136 ext->is_set = true;
1137 return 0;
1138}
1139
1140static int bpf_object__read_kernel_config(struct bpf_object *obj,
1141 const char *config_path,
1142 void *data)
1143{
1144 char buf[PATH_MAX], *sep, *value;
1145 struct extern_desc *ext;
1146 int len, err = 0;
1147 void *ext_val;
1148 __u64 num;
1149 gzFile file;
1150
1151 if (config_path) {
1152 file = gzopen(config_path, "r");
1153 } else {
1154 struct utsname uts;
1155
1156 uname(&uts);
1157 len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1158 if (len < 0)
1159 return -EINVAL;
1160 else if (len >= PATH_MAX)
1161 return -ENAMETOOLONG;
1162 /* gzopen also accepts uncompressed files. */
1163 file = gzopen(buf, "r");
1164 if (!file)
1165 file = gzopen("/proc/config.gz", "r");
1166 }
1167 if (!file) {
1168 pr_warn("failed to read kernel config at '%s'\n", config_path);
1169 return -ENOENT;
1170 }
1171
1172 while (gzgets(file, buf, sizeof(buf))) {
1173 if (strncmp(buf, "CONFIG_", 7))
1174 continue;
1175
1176 sep = strchr(buf, '=');
1177 if (!sep) {
1178 err = -EINVAL;
1179 pr_warn("failed to parse '%s': no separator\n", buf);
1180 goto out;
1181 }
1182 /* Trim ending '\n' */
1183 len = strlen(buf);
1184 if (buf[len - 1] == '\n')
1185 buf[len - 1] = '\0';
1186 /* Split on '=' and ensure that a value is present. */
1187 *sep = '\0';
1188 if (!sep[1]) {
1189 err = -EINVAL;
1190 *sep = '=';
1191 pr_warn("failed to parse '%s': no value\n", buf);
1192 goto out;
1193 }
1194
1195 ext = find_extern_by_name(obj, buf);
1196 if (!ext)
1197 continue;
1198 if (ext->is_set) {
1199 err = -EINVAL;
1200 pr_warn("re-defining extern '%s' not allowed\n", buf);
1201 goto out;
1202 }
1203
1204 ext_val = data + ext->data_off;
1205 value = sep + 1;
1206
1207 switch (*value) {
1208 case 'y': case 'n': case 'm':
1209 err = set_ext_value_tri(ext, ext_val, *value);
1210 break;
1211 case '"':
1212 err = set_ext_value_str(ext, ext_val, value);
1213 break;
1214 default:
1215 /* assume integer */
1216 err = parse_u64(value, &num);
1217 if (err) {
1218 pr_warn("extern %s=%s should be integer\n",
1219 ext->name, value);
1220 goto out;
1221 }
1222 err = set_ext_value_num(ext, ext_val, num);
1223 break;
1224 }
1225 if (err)
1226 goto out;
1227 pr_debug("extern %s=%s\n", ext->name, value);
1228 }
1229
1230out:
1231 gzclose(file);
1232 return err;
1233}
1234
1235static int bpf_object__init_extern_map(struct bpf_object *obj)
1236{
1237 struct extern_desc *last_ext;
1238 size_t map_sz;
1239 int err;
1240
1241 if (obj->nr_extern == 0)
1242 return 0;
1243
1244 last_ext = &obj->externs[obj->nr_extern - 1];
1245 map_sz = last_ext->data_off + last_ext->sz;
1246
1247 err = bpf_object__init_internal_map(obj, LIBBPF_MAP_EXTERN,
1248 obj->efile.symbols_shndx,
1249 NULL, map_sz);
1250 if (err)
1251 return err;
1252
1253 obj->extern_map_idx = obj->nr_maps - 1;
1254
1255 return 0;
1256}
1257
Andrii Nakryikobf829272019-06-17 12:26:53 -07001258static int bpf_object__init_user_maps(struct bpf_object *obj, bool strict)
1259{
Eric Leblond4708bbd2016-11-15 04:05:47 +00001260 Elf_Data *symbols = obj->efile.symbols;
Andrii Nakryikobf829272019-06-17 12:26:53 -07001261 int i, map_def_sz = 0, nr_maps = 0, nr_syms;
Daniel Borkmannd8599002019-04-09 23:20:13 +02001262 Elf_Data *data = NULL;
Andrii Nakryikobf829272019-06-17 12:26:53 -07001263 Elf_Scn *scn;
1264
1265 if (obj->efile.maps_shndx < 0)
1266 return 0;
Eric Leblond4708bbd2016-11-15 04:05:47 +00001267
Eric Leblond4708bbd2016-11-15 04:05:47 +00001268 if (!symbols)
1269 return -EINVAL;
1270
Andrii Nakryikobf829272019-06-17 12:26:53 -07001271 scn = elf_getscn(obj->efile.elf, obj->efile.maps_shndx);
1272 if (scn)
1273 data = elf_getdata(scn, NULL);
1274 if (!scn || !data) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001275 pr_warn("failed to get Elf_Data from map section %d\n",
1276 obj->efile.maps_shndx);
Andrii Nakryikobf829272019-06-17 12:26:53 -07001277 return -EINVAL;
Wang Nan0b3d1ef2015-07-01 02:13:58 +00001278 }
1279
Eric Leblond4708bbd2016-11-15 04:05:47 +00001280 /*
1281 * Count number of maps. Each map has a name.
1282 * Array of maps is not supported: only the first element is
1283 * considered.
1284 *
1285 * TODO: Detect array of map and report error.
1286 */
Andrii Nakryikobf829272019-06-17 12:26:53 -07001287 nr_syms = symbols->d_size / sizeof(GElf_Sym);
1288 for (i = 0; i < nr_syms; i++) {
Eric Leblond4708bbd2016-11-15 04:05:47 +00001289 GElf_Sym sym;
1290
1291 if (!gelf_getsym(symbols, i, &sym))
1292 continue;
1293 if (sym.st_shndx != obj->efile.maps_shndx)
1294 continue;
1295 nr_maps++;
1296 }
Craig Gallekb13c5c12017-10-05 10:41:57 -04001297 /* Assume equally sized map definitions */
Andrii Nakryikobf829272019-06-17 12:26:53 -07001298 pr_debug("maps in %s: %d maps in %zd bytes\n",
1299 obj->path, nr_maps, data->d_size);
Daniel Borkmann4f8827d2019-04-24 00:45:57 +02001300
Andrii Nakryiko98e527af2019-11-06 18:08:55 -08001301 if (!data->d_size || nr_maps == 0 || (data->d_size % nr_maps) != 0) {
Andrii Nakryiko8983b732019-11-20 23:07:42 -08001302 pr_warn("unable to determine map definition size section %s, %d maps in %zd bytes\n",
Kefeng Wangbe180102019-10-21 13:55:32 +08001303 obj->path, nr_maps, data->d_size);
Andrii Nakryikobf829272019-06-17 12:26:53 -07001304 return -EINVAL;
Craig Gallekb13c5c12017-10-05 10:41:57 -04001305 }
Andrii Nakryiko98e527af2019-11-06 18:08:55 -08001306 map_def_sz = data->d_size / nr_maps;
Craig Gallekb13c5c12017-10-05 10:41:57 -04001307
Andrii Nakryikobf829272019-06-17 12:26:53 -07001308 /* Fill obj->maps using data in "maps" section. */
1309 for (i = 0; i < nr_syms; i++) {
Wang Nan561bbcc2015-11-27 08:47:36 +00001310 GElf_Sym sym;
Wang Nan561bbcc2015-11-27 08:47:36 +00001311 const char *map_name;
Eric Leblond4708bbd2016-11-15 04:05:47 +00001312 struct bpf_map_def *def;
Andrii Nakryikobf829272019-06-17 12:26:53 -07001313 struct bpf_map *map;
Wang Nan561bbcc2015-11-27 08:47:36 +00001314
1315 if (!gelf_getsym(symbols, i, &sym))
1316 continue;
Wang Nan666810e2016-01-25 09:55:49 +00001317 if (sym.st_shndx != obj->efile.maps_shndx)
Wang Nan561bbcc2015-11-27 08:47:36 +00001318 continue;
1319
Andrii Nakryikobf829272019-06-17 12:26:53 -07001320 map = bpf_object__add_map(obj);
1321 if (IS_ERR(map))
1322 return PTR_ERR(map);
1323
1324 map_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
Wang Nan561bbcc2015-11-27 08:47:36 +00001325 sym.st_name);
Andrii Nakryikoc51829b2019-05-29 10:36:06 -07001326 if (!map_name) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001327 pr_warn("failed to get map #%d name sym string for obj %s\n",
1328 i, obj->path);
Andrii Nakryikoc51829b2019-05-29 10:36:06 -07001329 return -LIBBPF_ERRNO__FORMAT;
1330 }
Daniel Borkmannd8599002019-04-09 23:20:13 +02001331
Andrii Nakryikobf829272019-06-17 12:26:53 -07001332 map->libbpf_type = LIBBPF_MAP_UNSPEC;
Andrii Nakryikodb488142019-06-17 12:26:54 -07001333 map->sec_idx = sym.st_shndx;
1334 map->sec_offset = sym.st_value;
1335 pr_debug("map '%s' (legacy): at sec_idx %d, offset %zu.\n",
1336 map_name, map->sec_idx, map->sec_offset);
Craig Gallekb13c5c12017-10-05 10:41:57 -04001337 if (sym.st_value + map_def_sz > data->d_size) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001338 pr_warn("corrupted maps section in %s: last map \"%s\" too small\n",
1339 obj->path, map_name);
Eric Leblond4708bbd2016-11-15 04:05:47 +00001340 return -EINVAL;
Wang Nan561bbcc2015-11-27 08:47:36 +00001341 }
Eric Leblond4708bbd2016-11-15 04:05:47 +00001342
Andrii Nakryikobf829272019-06-17 12:26:53 -07001343 map->name = strdup(map_name);
1344 if (!map->name) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001345 pr_warn("failed to alloc map name\n");
Wang Nan973170e2015-12-08 02:25:29 +00001346 return -ENOMEM;
1347 }
Andrii Nakryikobf829272019-06-17 12:26:53 -07001348 pr_debug("map %d is \"%s\"\n", i, map->name);
Eric Leblond4708bbd2016-11-15 04:05:47 +00001349 def = (struct bpf_map_def *)(data->d_buf + sym.st_value);
Craig Gallekb13c5c12017-10-05 10:41:57 -04001350 /*
1351 * If the definition of the map in the object file fits in
1352 * bpf_map_def, copy it. Any extra fields in our version
1353 * of bpf_map_def will default to zero as a result of the
1354 * calloc above.
1355 */
1356 if (map_def_sz <= sizeof(struct bpf_map_def)) {
Andrii Nakryikobf829272019-06-17 12:26:53 -07001357 memcpy(&map->def, def, map_def_sz);
Craig Gallekb13c5c12017-10-05 10:41:57 -04001358 } else {
1359 /*
1360 * Here the map structure being read is bigger than what
1361 * we expect, truncate if the excess bits are all zero.
1362 * If they are not zero, reject this map as
1363 * incompatible.
1364 */
1365 char *b;
Andrii Nakryiko8983b732019-11-20 23:07:42 -08001366
Craig Gallekb13c5c12017-10-05 10:41:57 -04001367 for (b = ((char *)def) + sizeof(struct bpf_map_def);
1368 b < ((char *)def) + map_def_sz; b++) {
1369 if (*b != 0) {
Andrii Nakryiko8983b732019-11-20 23:07:42 -08001370 pr_warn("maps section in %s: \"%s\" has unrecognized, non-zero options\n",
Kefeng Wangbe180102019-10-21 13:55:32 +08001371 obj->path, map_name);
John Fastabendc034a172018-10-15 11:19:55 -07001372 if (strict)
1373 return -EINVAL;
Craig Gallekb13c5c12017-10-05 10:41:57 -04001374 }
1375 }
Andrii Nakryikobf829272019-06-17 12:26:53 -07001376 memcpy(&map->def, def, sizeof(struct bpf_map_def));
Craig Gallekb13c5c12017-10-05 10:41:57 -04001377 }
Wang Nan561bbcc2015-11-27 08:47:36 +00001378 }
Andrii Nakryikobf829272019-06-17 12:26:53 -07001379 return 0;
1380}
Eric Leblond4708bbd2016-11-15 04:05:47 +00001381
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07001382static const struct btf_type *
1383skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001384{
1385 const struct btf_type *t = btf__type_by_id(btf, id);
1386
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07001387 if (res_id)
1388 *res_id = id;
1389
1390 while (btf_is_mod(t) || btf_is_typedef(t)) {
1391 if (res_id)
1392 *res_id = t->type;
1393 t = btf__type_by_id(btf, t->type);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001394 }
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07001395
1396 return t;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001397}
1398
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001399/*
1400 * Fetch integer attribute of BTF map definition. Such attributes are
1401 * represented using a pointer to an array, in which dimensionality of array
1402 * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
1403 * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
1404 * type definition, while using only sizeof(void *) space in ELF data section.
1405 */
1406static bool get_map_field_int(const char *map_name, const struct btf *btf,
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001407 const struct btf_type *def,
Andrii Nakryiko8983b732019-11-20 23:07:42 -08001408 const struct btf_member *m, __u32 *res)
1409{
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07001410 const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001411 const char *name = btf__name_by_offset(btf, m->name_off);
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001412 const struct btf_array *arr_info;
1413 const struct btf_type *arr_t;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001414
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001415 if (!btf_is_ptr(t)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001416 pr_warn("map '%s': attr '%s': expected PTR, got %u.\n",
1417 map_name, name, btf_kind(t));
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001418 return false;
1419 }
Eric Leblond4708bbd2016-11-15 04:05:47 +00001420
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001421 arr_t = btf__type_by_id(btf, t->type);
1422 if (!arr_t) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001423 pr_warn("map '%s': attr '%s': type [%u] not found.\n",
1424 map_name, name, t->type);
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001425 return false;
1426 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001427 if (!btf_is_array(arr_t)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001428 pr_warn("map '%s': attr '%s': expected ARRAY, got %u.\n",
1429 map_name, name, btf_kind(arr_t));
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001430 return false;
1431 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001432 arr_info = btf_array(arr_t);
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001433 *res = arr_info->nelems;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001434 return true;
1435}
Daniel Borkmann8837fe52019-04-24 00:45:56 +02001436
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01001437static int build_map_pin_path(struct bpf_map *map, const char *path)
1438{
1439 char buf[PATH_MAX];
1440 int err, len;
1441
1442 if (!path)
1443 path = "/sys/fs/bpf";
1444
1445 len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
1446 if (len < 0)
1447 return -EINVAL;
1448 else if (len >= PATH_MAX)
1449 return -ENAMETOOLONG;
1450
1451 err = bpf_map__set_pin_path(map, buf);
1452 if (err)
1453 return err;
1454
1455 return 0;
1456}
1457
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001458static int bpf_object__init_user_btf_map(struct bpf_object *obj,
1459 const struct btf_type *sec,
1460 int var_idx, int sec_idx,
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01001461 const Elf_Data *data, bool strict,
1462 const char *pin_root_path)
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001463{
1464 const struct btf_type *var, *def, *t;
1465 const struct btf_var_secinfo *vi;
1466 const struct btf_var *var_extra;
1467 const struct btf_member *m;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001468 const char *map_name;
1469 struct bpf_map *map;
1470 int vlen, i;
1471
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001472 vi = btf_var_secinfos(sec) + var_idx;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001473 var = btf__type_by_id(obj->btf, vi->type);
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001474 var_extra = btf_var(var);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001475 map_name = btf__name_by_offset(obj->btf, var->name_off);
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001476 vlen = btf_vlen(var);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001477
1478 if (map_name == NULL || map_name[0] == '\0') {
Kefeng Wangbe180102019-10-21 13:55:32 +08001479 pr_warn("map #%d: empty name.\n", var_idx);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001480 return -EINVAL;
1481 }
1482 if ((__u64)vi->offset + vi->size > data->d_size) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001483 pr_warn("map '%s' BTF data is corrupted.\n", map_name);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001484 return -EINVAL;
1485 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001486 if (!btf_is_var(var)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001487 pr_warn("map '%s': unexpected var kind %u.\n",
1488 map_name, btf_kind(var));
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001489 return -EINVAL;
1490 }
1491 if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED &&
1492 var_extra->linkage != BTF_VAR_STATIC) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001493 pr_warn("map '%s': unsupported var linkage %u.\n",
1494 map_name, var_extra->linkage);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001495 return -EOPNOTSUPP;
1496 }
1497
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07001498 def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001499 if (!btf_is_struct(def)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001500 pr_warn("map '%s': unexpected def kind %u.\n",
1501 map_name, btf_kind(var));
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001502 return -EINVAL;
1503 }
1504 if (def->size > vi->size) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001505 pr_warn("map '%s': invalid def size.\n", map_name);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001506 return -EINVAL;
1507 }
1508
1509 map = bpf_object__add_map(obj);
1510 if (IS_ERR(map))
1511 return PTR_ERR(map);
1512 map->name = strdup(map_name);
1513 if (!map->name) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001514 pr_warn("map '%s': failed to alloc map name.\n", map_name);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001515 return -ENOMEM;
1516 }
1517 map->libbpf_type = LIBBPF_MAP_UNSPEC;
1518 map->def.type = BPF_MAP_TYPE_UNSPEC;
1519 map->sec_idx = sec_idx;
1520 map->sec_offset = vi->offset;
1521 pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
1522 map_name, map->sec_idx, map->sec_offset);
1523
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001524 vlen = btf_vlen(def);
1525 m = btf_members(def);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001526 for (i = 0; i < vlen; i++, m++) {
1527 const char *name = btf__name_by_offset(obj->btf, m->name_off);
1528
1529 if (!name) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001530 pr_warn("map '%s': invalid field #%d.\n", map_name, i);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001531 return -EINVAL;
1532 }
1533 if (strcmp(name, "type") == 0) {
1534 if (!get_map_field_int(map_name, obj->btf, def, m,
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001535 &map->def.type))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001536 return -EINVAL;
1537 pr_debug("map '%s': found type = %u.\n",
1538 map_name, map->def.type);
1539 } else if (strcmp(name, "max_entries") == 0) {
1540 if (!get_map_field_int(map_name, obj->btf, def, m,
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001541 &map->def.max_entries))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001542 return -EINVAL;
1543 pr_debug("map '%s': found max_entries = %u.\n",
1544 map_name, map->def.max_entries);
1545 } else if (strcmp(name, "map_flags") == 0) {
1546 if (!get_map_field_int(map_name, obj->btf, def, m,
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001547 &map->def.map_flags))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001548 return -EINVAL;
1549 pr_debug("map '%s': found map_flags = %u.\n",
1550 map_name, map->def.map_flags);
1551 } else if (strcmp(name, "key_size") == 0) {
1552 __u32 sz;
1553
1554 if (!get_map_field_int(map_name, obj->btf, def, m,
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001555 &sz))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001556 return -EINVAL;
1557 pr_debug("map '%s': found key_size = %u.\n",
1558 map_name, sz);
1559 if (map->def.key_size && map->def.key_size != sz) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001560 pr_warn("map '%s': conflicting key size %u != %u.\n",
1561 map_name, map->def.key_size, sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001562 return -EINVAL;
1563 }
1564 map->def.key_size = sz;
1565 } else if (strcmp(name, "key") == 0) {
1566 __s64 sz;
1567
1568 t = btf__type_by_id(obj->btf, m->type);
1569 if (!t) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001570 pr_warn("map '%s': key type [%d] not found.\n",
1571 map_name, m->type);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001572 return -EINVAL;
1573 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001574 if (!btf_is_ptr(t)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001575 pr_warn("map '%s': key spec is not PTR: %u.\n",
1576 map_name, btf_kind(t));
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001577 return -EINVAL;
1578 }
1579 sz = btf__resolve_size(obj->btf, t->type);
1580 if (sz < 0) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001581 pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
1582 map_name, t->type, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001583 return sz;
1584 }
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001585 pr_debug("map '%s': found key [%u], sz = %zd.\n",
1586 map_name, t->type, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001587 if (map->def.key_size && map->def.key_size != sz) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001588 pr_warn("map '%s': conflicting key size %u != %zd.\n",
1589 map_name, map->def.key_size, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001590 return -EINVAL;
1591 }
1592 map->def.key_size = sz;
1593 map->btf_key_type_id = t->type;
1594 } else if (strcmp(name, "value_size") == 0) {
1595 __u32 sz;
1596
1597 if (!get_map_field_int(map_name, obj->btf, def, m,
Andrii Nakryikoef99b022019-07-05 08:50:09 -07001598 &sz))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001599 return -EINVAL;
1600 pr_debug("map '%s': found value_size = %u.\n",
1601 map_name, sz);
1602 if (map->def.value_size && map->def.value_size != sz) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001603 pr_warn("map '%s': conflicting value size %u != %u.\n",
1604 map_name, map->def.value_size, sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001605 return -EINVAL;
1606 }
1607 map->def.value_size = sz;
1608 } else if (strcmp(name, "value") == 0) {
1609 __s64 sz;
1610
1611 t = btf__type_by_id(obj->btf, m->type);
1612 if (!t) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001613 pr_warn("map '%s': value type [%d] not found.\n",
1614 map_name, m->type);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001615 return -EINVAL;
1616 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001617 if (!btf_is_ptr(t)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001618 pr_warn("map '%s': value spec is not PTR: %u.\n",
1619 map_name, btf_kind(t));
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001620 return -EINVAL;
1621 }
1622 sz = btf__resolve_size(obj->btf, t->type);
1623 if (sz < 0) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001624 pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
1625 map_name, t->type, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001626 return sz;
1627 }
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001628 pr_debug("map '%s': found value [%u], sz = %zd.\n",
1629 map_name, t->type, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001630 if (map->def.value_size && map->def.value_size != sz) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08001631 pr_warn("map '%s': conflicting value size %u != %zd.\n",
1632 map_name, map->def.value_size, (ssize_t)sz);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001633 return -EINVAL;
1634 }
1635 map->def.value_size = sz;
1636 map->btf_value_type_id = t->type;
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01001637 } else if (strcmp(name, "pinning") == 0) {
1638 __u32 val;
1639 int err;
1640
1641 if (!get_map_field_int(map_name, obj->btf, def, m,
1642 &val))
1643 return -EINVAL;
1644 pr_debug("map '%s': found pinning = %u.\n",
1645 map_name, val);
1646
1647 if (val != LIBBPF_PIN_NONE &&
1648 val != LIBBPF_PIN_BY_NAME) {
1649 pr_warn("map '%s': invalid pinning value %u.\n",
1650 map_name, val);
1651 return -EINVAL;
1652 }
1653 if (val == LIBBPF_PIN_BY_NAME) {
1654 err = build_map_pin_path(map, pin_root_path);
1655 if (err) {
1656 pr_warn("map '%s': couldn't build pin path.\n",
1657 map_name);
1658 return err;
1659 }
1660 }
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001661 } else {
1662 if (strict) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001663 pr_warn("map '%s': unknown field '%s'.\n",
1664 map_name, name);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001665 return -ENOTSUP;
1666 }
1667 pr_debug("map '%s': ignoring unknown field '%s'.\n",
1668 map_name, name);
1669 }
1670 }
1671
1672 if (map->def.type == BPF_MAP_TYPE_UNSPEC) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001673 pr_warn("map '%s': map type isn't specified.\n", map_name);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001674 return -EINVAL;
1675 }
1676
1677 return 0;
1678}
1679
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01001680static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
1681 const char *pin_root_path)
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001682{
1683 const struct btf_type *sec = NULL;
1684 int nr_types, i, vlen, err;
1685 const struct btf_type *t;
1686 const char *name;
1687 Elf_Data *data;
1688 Elf_Scn *scn;
1689
1690 if (obj->efile.btf_maps_shndx < 0)
1691 return 0;
1692
1693 scn = elf_getscn(obj->efile.elf, obj->efile.btf_maps_shndx);
1694 if (scn)
1695 data = elf_getdata(scn, NULL);
1696 if (!scn || !data) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001697 pr_warn("failed to get Elf_Data from map section %d (%s)\n",
1698 obj->efile.maps_shndx, MAPS_ELF_SEC);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001699 return -EINVAL;
1700 }
1701
1702 nr_types = btf__get_nr_types(obj->btf);
1703 for (i = 1; i <= nr_types; i++) {
1704 t = btf__type_by_id(obj->btf, i);
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001705 if (!btf_is_datasec(t))
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001706 continue;
1707 name = btf__name_by_offset(obj->btf, t->name_off);
1708 if (strcmp(name, MAPS_ELF_SEC) == 0) {
1709 sec = t;
1710 break;
1711 }
1712 }
1713
1714 if (!sec) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001715 pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001716 return -ENOENT;
1717 }
1718
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001719 vlen = btf_vlen(sec);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001720 for (i = 0; i < vlen; i++) {
1721 err = bpf_object__init_user_btf_map(obj, sec, i,
1722 obj->efile.btf_maps_shndx,
Andrii Nakryiko8983b732019-11-20 23:07:42 -08001723 data, strict,
1724 pin_root_path);
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001725 if (err)
1726 return err;
1727 }
1728
1729 return 0;
1730}
1731
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08001732static int bpf_object__init_maps(struct bpf_object *obj,
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08001733 const struct bpf_object_open_opts *opts)
Andrii Nakryikobf829272019-06-17 12:26:53 -07001734{
Andrii Nakryiko166750b2019-12-13 17:47:08 -08001735 const char *pin_root_path;
1736 bool strict;
Andrii Nakryikobf829272019-06-17 12:26:53 -07001737 int err;
Eric Leblond4708bbd2016-11-15 04:05:47 +00001738
Andrii Nakryiko166750b2019-12-13 17:47:08 -08001739 strict = !OPTS_GET(opts, relaxed_maps, false);
1740 pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
1741
Andrii Nakryikobf829272019-06-17 12:26:53 -07001742 err = bpf_object__init_user_maps(obj, strict);
Andrii Nakryiko166750b2019-12-13 17:47:08 -08001743 err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
1744 err = err ?: bpf_object__init_global_data_maps(obj);
1745 err = err ?: bpf_object__init_extern_map(obj);
Andrii Nakryikobf829272019-06-17 12:26:53 -07001746 if (err)
1747 return err;
1748
1749 if (obj->nr_maps) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02001750 qsort(obj->maps, obj->nr_maps, sizeof(obj->maps[0]),
1751 compare_bpf_map);
Andrii Nakryikobf829272019-06-17 12:26:53 -07001752 }
1753 return 0;
Wang Nan561bbcc2015-11-27 08:47:36 +00001754}
1755
Jesper Dangaard Brouere3d91b02018-02-08 12:48:32 +01001756static bool section_have_execinstr(struct bpf_object *obj, int idx)
1757{
1758 Elf_Scn *scn;
1759 GElf_Shdr sh;
1760
1761 scn = elf_getscn(obj->efile.elf, idx);
1762 if (!scn)
1763 return false;
1764
1765 if (gelf_getshdr(scn, &sh) != &sh)
1766 return false;
1767
1768 if (sh.sh_flags & SHF_EXECINSTR)
1769 return true;
1770
1771 return false;
1772}
1773
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001774static void bpf_object__sanitize_btf(struct bpf_object *obj)
1775{
1776 bool has_datasec = obj->caps.btf_datasec;
1777 bool has_func = obj->caps.btf_func;
1778 struct btf *btf = obj->btf;
1779 struct btf_type *t;
1780 int i, j, vlen;
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001781
1782 if (!obj->btf || (has_func && has_datasec))
1783 return;
1784
1785 for (i = 1; i <= btf__get_nr_types(btf); i++) {
1786 t = (struct btf_type *)btf__type_by_id(btf, i);
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001787
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001788 if (!has_datasec && btf_is_var(t)) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001789 /* replace VAR with INT */
1790 t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
Andrii Nakryiko1d4126c2019-07-19 12:46:03 -07001791 /*
1792 * using size = 1 is the safest choice, 4 will be too
1793 * big and cause kernel BTF validation failure if
1794 * original variable took less than 4 bytes
1795 */
1796 t->size = 1;
Jakub Kicinski708852d2019-08-13 16:24:57 -07001797 *(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001798 } else if (!has_datasec && btf_is_datasec(t)) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001799 /* replace DATASEC with STRUCT */
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001800 const struct btf_var_secinfo *v = btf_var_secinfos(t);
1801 struct btf_member *m = btf_members(t);
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001802 struct btf_type *vt;
1803 char *name;
1804
1805 name = (char *)btf__name_by_offset(btf, t->name_off);
1806 while (*name) {
1807 if (*name == '.')
1808 *name = '_';
1809 name++;
1810 }
1811
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001812 vlen = btf_vlen(t);
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001813 t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
1814 for (j = 0; j < vlen; j++, v++, m++) {
1815 /* order of field assignments is important */
1816 m->offset = v->offset * 8;
1817 m->type = v->type;
1818 /* preserve variable name as member name */
1819 vt = (void *)btf__type_by_id(btf, v->type);
1820 m->name_off = vt->name_off;
1821 }
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001822 } else if (!has_func && btf_is_func_proto(t)) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001823 /* replace FUNC_PROTO with ENUM */
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001824 vlen = btf_vlen(t);
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001825 t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
1826 t->size = sizeof(__u32); /* kernel enforced */
Andrii Nakryikob03bc682019-08-07 14:39:49 -07001827 } else if (!has_func && btf_is_func(t)) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07001828 /* replace FUNC with TYPEDEF */
1829 t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
1830 }
1831 }
1832}
1833
1834static void bpf_object__sanitize_btf_ext(struct bpf_object *obj)
1835{
1836 if (!obj->btf_ext)
1837 return;
1838
1839 if (!obj->caps.btf_func) {
1840 btf_ext__free(obj->btf_ext);
1841 obj->btf_ext = NULL;
1842 }
1843}
1844
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001845static bool bpf_object__is_btf_mandatory(const struct bpf_object *obj)
1846{
1847 return obj->efile.btf_maps_shndx >= 0;
1848}
1849
Andrii Nakryiko063183b2019-06-17 12:26:55 -07001850static int bpf_object__init_btf(struct bpf_object *obj,
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001851 Elf_Data *btf_data,
1852 Elf_Data *btf_ext_data)
1853{
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001854 bool btf_required = bpf_object__is_btf_mandatory(obj);
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001855 int err = 0;
1856
1857 if (btf_data) {
1858 obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
1859 if (IS_ERR(obj->btf)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001860 pr_warn("Error loading ELF section %s: %d.\n",
1861 BTF_ELF_SEC, err);
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001862 goto out;
1863 }
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001864 }
1865 if (btf_ext_data) {
1866 if (!obj->btf) {
1867 pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
1868 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
1869 goto out;
1870 }
1871 obj->btf_ext = btf_ext__new(btf_ext_data->d_buf,
1872 btf_ext_data->d_size);
1873 if (IS_ERR(obj->btf_ext)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001874 pr_warn("Error loading ELF section %s: %ld. Ignored and continue.\n",
1875 BTF_EXT_ELF_SEC, PTR_ERR(obj->btf_ext));
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001876 obj->btf_ext = NULL;
1877 goto out;
1878 }
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001879 }
1880out:
1881 if (err || IS_ERR(obj->btf)) {
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001882 if (btf_required)
1883 err = err ? : PTR_ERR(obj->btf);
1884 else
1885 err = 0;
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001886 if (!IS_ERR_OR_NULL(obj->btf))
1887 btf__free(obj->btf);
1888 obj->btf = NULL;
1889 }
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001890 if (btf_required && !obj->btf) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001891 pr_warn("BTF is required, but is missing or corrupted.\n");
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001892 return err == 0 ? -ENOENT : err;
1893 }
Andrii Nakryiko9c6660d2019-06-17 12:26:51 -07001894 return 0;
1895}
1896
Andrii Nakryiko166750b2019-12-13 17:47:08 -08001897static int bpf_object__finalize_btf(struct bpf_object *obj)
1898{
1899 int err;
1900
1901 if (!obj->btf)
1902 return 0;
1903
1904 err = btf__finalize_data(obj, obj->btf);
1905 if (!err)
1906 return 0;
1907
1908 pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
1909 btf__free(obj->btf);
1910 obj->btf = NULL;
1911 btf_ext__free(obj->btf_ext);
1912 obj->btf_ext = NULL;
1913
1914 if (bpf_object__is_btf_mandatory(obj)) {
1915 pr_warn("BTF is required, but is missing or corrupted.\n");
1916 return -ENOENT;
1917 }
1918 return 0;
1919}
1920
Andrii Nakryiko063183b2019-06-17 12:26:55 -07001921static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
1922{
1923 int err = 0;
1924
1925 if (!obj->btf)
1926 return 0;
1927
1928 bpf_object__sanitize_btf(obj);
1929 bpf_object__sanitize_btf_ext(obj);
1930
1931 err = btf__load(obj->btf);
1932 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001933 pr_warn("Error loading %s into kernel: %d.\n",
1934 BTF_ELF_SEC, err);
Andrii Nakryiko063183b2019-06-17 12:26:55 -07001935 btf__free(obj->btf);
1936 obj->btf = NULL;
Andrii Nakryiko04efe592019-07-19 12:32:42 -07001937 /* btf_ext can't exist without btf, so free it as well */
1938 if (obj->btf_ext) {
1939 btf_ext__free(obj->btf_ext);
1940 obj->btf_ext = NULL;
1941 }
1942
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07001943 if (bpf_object__is_btf_mandatory(obj))
1944 return err;
Andrii Nakryiko063183b2019-06-17 12:26:55 -07001945 }
1946 return 0;
1947}
1948
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08001949static int bpf_object__elf_collect(struct bpf_object *obj)
Wang Nan29603662015-07-01 02:13:56 +00001950{
1951 Elf *elf = obj->efile.elf;
1952 GElf_Ehdr *ep = &obj->efile.ehdr;
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08001953 Elf_Data *btf_ext_data = NULL;
Daniel Borkmann1713d682019-04-09 23:20:14 +02001954 Elf_Data *btf_data = NULL;
Wang Nan29603662015-07-01 02:13:56 +00001955 Elf_Scn *scn = NULL;
Wang Nan666810e2016-01-25 09:55:49 +00001956 int idx = 0, err = 0;
Wang Nan29603662015-07-01 02:13:56 +00001957
1958 /* Elf is corrupted/truncated, avoid calling elf_strptr. */
1959 if (!elf_rawdata(elf_getscn(elf, ep->e_shstrndx), NULL)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001960 pr_warn("failed to get e_shstrndx from %s\n", obj->path);
Wang Nan6371ca3b2015-11-06 13:49:37 +00001961 return -LIBBPF_ERRNO__FORMAT;
Wang Nan29603662015-07-01 02:13:56 +00001962 }
1963
1964 while ((scn = elf_nextscn(elf, scn)) != NULL) {
1965 char *name;
1966 GElf_Shdr sh;
1967 Elf_Data *data;
1968
1969 idx++;
1970 if (gelf_getshdr(scn, &sh) != &sh) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001971 pr_warn("failed to get section(%d) header from %s\n",
1972 idx, obj->path);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07001973 return -LIBBPF_ERRNO__FORMAT;
Wang Nan29603662015-07-01 02:13:56 +00001974 }
1975
1976 name = elf_strptr(elf, ep->e_shstrndx, sh.sh_name);
1977 if (!name) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001978 pr_warn("failed to get section(%d) name from %s\n",
1979 idx, obj->path);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07001980 return -LIBBPF_ERRNO__FORMAT;
Wang Nan29603662015-07-01 02:13:56 +00001981 }
1982
1983 data = elf_getdata(scn, 0);
1984 if (!data) {
Kefeng Wangbe180102019-10-21 13:55:32 +08001985 pr_warn("failed to get section(%d) data from %s(%s)\n",
1986 idx, name, obj->path);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07001987 return -LIBBPF_ERRNO__FORMAT;
Wang Nan29603662015-07-01 02:13:56 +00001988 }
Jesper Dangaard Brouer077c0662018-02-08 12:48:17 +01001989 pr_debug("section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
1990 idx, name, (unsigned long)data->d_size,
Wang Nan29603662015-07-01 02:13:56 +00001991 (int)sh.sh_link, (unsigned long)sh.sh_flags,
1992 (int)sh.sh_type);
Wang Nancb1e5e92015-07-01 02:13:57 +00001993
Daniel Borkmann1713d682019-04-09 23:20:14 +02001994 if (strcmp(name, "license") == 0) {
Wang Nancb1e5e92015-07-01 02:13:57 +00001995 err = bpf_object__init_license(obj,
1996 data->d_buf,
1997 data->d_size);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07001998 if (err)
1999 return err;
Daniel Borkmann1713d682019-04-09 23:20:14 +02002000 } else if (strcmp(name, "version") == 0) {
John Fastabend54b86252019-10-18 07:41:26 -07002001 err = bpf_object__init_kversion(obj,
2002 data->d_buf,
2003 data->d_size);
2004 if (err)
2005 return err;
Daniel Borkmann1713d682019-04-09 23:20:14 +02002006 } else if (strcmp(name, "maps") == 0) {
Wang Nan666810e2016-01-25 09:55:49 +00002007 obj->efile.maps_shndx = idx;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002008 } else if (strcmp(name, MAPS_ELF_SEC) == 0) {
2009 obj->efile.btf_maps_shndx = idx;
Daniel Borkmann1713d682019-04-09 23:20:14 +02002010 } else if (strcmp(name, BTF_ELF_SEC) == 0) {
2011 btf_data = data;
Yonghong Song2993e052018-11-19 15:29:16 -08002012 } else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08002013 btf_ext_data = data;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002014 } else if (sh.sh_type == SHT_SYMTAB) {
Wang Nanbec7d682015-07-01 02:13:59 +00002015 if (obj->efile.symbols) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002016 pr_warn("bpf: multiple SYMTAB in %s\n",
2017 obj->path);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002018 return -LIBBPF_ERRNO__FORMAT;
Wang Nan77ba9a52015-12-08 02:25:30 +00002019 }
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002020 obj->efile.symbols = data;
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002021 obj->efile.symbols_shndx = idx;
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002022 obj->efile.strtabidx = sh.sh_link;
Joe Stringerf8c7a4d2019-04-09 23:20:12 +02002023 } else if (sh.sh_type == SHT_PROGBITS && data->d_size > 0) {
2024 if (sh.sh_flags & SHF_EXECINSTR) {
2025 if (strcmp(name, ".text") == 0)
2026 obj->efile.text_shndx = idx;
2027 err = bpf_object__add_program(obj, data->d_buf,
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002028 data->d_size,
2029 name, idx);
Joe Stringerf8c7a4d2019-04-09 23:20:12 +02002030 if (err) {
2031 char errmsg[STRERR_BUFSIZE];
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002032 char *cp;
Wang Nan6371ca3b2015-11-06 13:49:37 +00002033
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002034 cp = libbpf_strerror_r(-err, errmsg,
2035 sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08002036 pr_warn("failed to alloc program %s (%s): %s",
2037 name, obj->path, cp);
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002038 return err;
Joe Stringerf8c7a4d2019-04-09 23:20:12 +02002039 }
Andrii Nakryikoac9d1382019-12-13 17:47:07 -08002040 } else if (strcmp(name, DATA_SEC) == 0) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02002041 obj->efile.data = data;
2042 obj->efile.data_shndx = idx;
Andrii Nakryikoac9d1382019-12-13 17:47:07 -08002043 } else if (strcmp(name, RODATA_SEC) == 0) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02002044 obj->efile.rodata = data;
2045 obj->efile.rodata_shndx = idx;
2046 } else {
2047 pr_debug("skip section(%d) %s\n", idx, name);
Wang Nana5b8bd42015-07-01 02:14:00 +00002048 }
Wang Nanb62f06e2015-07-01 02:14:01 +00002049 } else if (sh.sh_type == SHT_REL) {
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002050 int nr_sects = obj->efile.nr_reloc_sects;
2051 void *sects = obj->efile.reloc_sects;
Jesper Dangaard Brouere3d91b02018-02-08 12:48:32 +01002052 int sec = sh.sh_info; /* points to other section */
2053
2054 /* Only do relo for section with exec instructions */
2055 if (!section_have_execinstr(obj, sec)) {
2056 pr_debug("skip relo %s(%d) for section(%d)\n",
2057 name, idx, sec);
2058 continue;
2059 }
Wang Nanb62f06e2015-07-01 02:14:01 +00002060
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002061 sects = reallocarray(sects, nr_sects + 1,
2062 sizeof(*obj->efile.reloc_sects));
2063 if (!sects) {
2064 pr_warn("reloc_sects realloc failed\n");
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002065 return -ENOMEM;
Wang Nanb62f06e2015-07-01 02:14:01 +00002066 }
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002067
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002068 obj->efile.reloc_sects = sects;
2069 obj->efile.nr_reloc_sects++;
Andrii Nakryiko01b29d12019-06-17 12:26:52 -07002070
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002071 obj->efile.reloc_sects[nr_sects].shdr = sh;
2072 obj->efile.reloc_sects[nr_sects].data = data;
Andrii Nakryikoac9d1382019-12-13 17:47:07 -08002073 } else if (sh.sh_type == SHT_NOBITS &&
2074 strcmp(name, BSS_SEC) == 0) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02002075 obj->efile.bss = data;
2076 obj->efile.bss_shndx = idx;
Jesper Dangaard Brouer077c0662018-02-08 12:48:17 +01002077 } else {
2078 pr_debug("skip section(%d) %s\n", idx, name);
Wang Nanbec7d682015-07-01 02:13:59 +00002079 }
Wang Nan29603662015-07-01 02:13:56 +00002080 }
Wang Nan561bbcc2015-11-27 08:47:36 +00002081
Andrii Nakryikod3a3aa02019-10-28 16:37:27 -07002082 if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002083 pr_warn("Corrupted ELF file: index of strtab invalid\n");
Andrii Nakryikof1021542019-05-29 10:36:07 -07002084 return -LIBBPF_ERRNO__FORMAT;
Wang Nan77ba9a52015-12-08 02:25:30 +00002085 }
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08002086 return bpf_object__init_btf(obj, btf_data, btf_ext_data);
Wang Nan29603662015-07-01 02:13:56 +00002087}
2088
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002089static bool sym_is_extern(const GElf_Sym *sym)
2090{
2091 int bind = GELF_ST_BIND(sym->st_info);
2092 /* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
2093 return sym->st_shndx == SHN_UNDEF &&
2094 (bind == STB_GLOBAL || bind == STB_WEAK) &&
2095 GELF_ST_TYPE(sym->st_info) == STT_NOTYPE;
2096}
2097
2098static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
2099{
2100 const struct btf_type *t;
2101 const char *var_name;
2102 int i, n;
2103
2104 if (!btf)
2105 return -ESRCH;
2106
2107 n = btf__get_nr_types(btf);
2108 for (i = 1; i <= n; i++) {
2109 t = btf__type_by_id(btf, i);
2110
2111 if (!btf_is_var(t))
2112 continue;
2113
2114 var_name = btf__name_by_offset(btf, t->name_off);
2115 if (strcmp(var_name, ext_name))
2116 continue;
2117
2118 if (btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
2119 return -EINVAL;
2120
2121 return i;
2122 }
2123
2124 return -ENOENT;
2125}
2126
2127static enum extern_type find_extern_type(const struct btf *btf, int id,
2128 bool *is_signed)
2129{
2130 const struct btf_type *t;
2131 const char *name;
2132
2133 t = skip_mods_and_typedefs(btf, id, NULL);
2134 name = btf__name_by_offset(btf, t->name_off);
2135
2136 if (is_signed)
2137 *is_signed = false;
2138 switch (btf_kind(t)) {
2139 case BTF_KIND_INT: {
2140 int enc = btf_int_encoding(t);
2141
2142 if (enc & BTF_INT_BOOL)
2143 return t->size == 1 ? EXT_BOOL : EXT_UNKNOWN;
2144 if (is_signed)
2145 *is_signed = enc & BTF_INT_SIGNED;
2146 if (t->size == 1)
2147 return EXT_CHAR;
2148 if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
2149 return EXT_UNKNOWN;
2150 return EXT_INT;
2151 }
2152 case BTF_KIND_ENUM:
2153 if (t->size != 4)
2154 return EXT_UNKNOWN;
2155 if (strcmp(name, "libbpf_tristate"))
2156 return EXT_UNKNOWN;
2157 return EXT_TRISTATE;
2158 case BTF_KIND_ARRAY:
2159 if (btf_array(t)->nelems == 0)
2160 return EXT_UNKNOWN;
2161 if (find_extern_type(btf, btf_array(t)->type, NULL) != EXT_CHAR)
2162 return EXT_UNKNOWN;
2163 return EXT_CHAR_ARR;
2164 default:
2165 return EXT_UNKNOWN;
2166 }
2167}
2168
2169static int cmp_externs(const void *_a, const void *_b)
2170{
2171 const struct extern_desc *a = _a;
2172 const struct extern_desc *b = _b;
2173
2174 /* descending order by alignment requirements */
2175 if (a->align != b->align)
2176 return a->align > b->align ? -1 : 1;
2177 /* ascending order by size, within same alignment class */
2178 if (a->sz != b->sz)
2179 return a->sz < b->sz ? -1 : 1;
2180 /* resolve ties by name */
2181 return strcmp(a->name, b->name);
2182}
2183
2184static int bpf_object__collect_externs(struct bpf_object *obj)
2185{
2186 const struct btf_type *t;
2187 struct extern_desc *ext;
2188 int i, n, off, btf_id;
2189 struct btf_type *sec;
2190 const char *ext_name;
2191 Elf_Scn *scn;
2192 GElf_Shdr sh;
2193
2194 if (!obj->efile.symbols)
2195 return 0;
2196
2197 scn = elf_getscn(obj->efile.elf, obj->efile.symbols_shndx);
2198 if (!scn)
2199 return -LIBBPF_ERRNO__FORMAT;
2200 if (gelf_getshdr(scn, &sh) != &sh)
2201 return -LIBBPF_ERRNO__FORMAT;
2202 n = sh.sh_size / sh.sh_entsize;
2203
2204 pr_debug("looking for externs among %d symbols...\n", n);
2205 for (i = 0; i < n; i++) {
2206 GElf_Sym sym;
2207
2208 if (!gelf_getsym(obj->efile.symbols, i, &sym))
2209 return -LIBBPF_ERRNO__FORMAT;
2210 if (!sym_is_extern(&sym))
2211 continue;
2212 ext_name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2213 sym.st_name);
2214 if (!ext_name || !ext_name[0])
2215 continue;
2216
2217 ext = obj->externs;
2218 ext = reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
2219 if (!ext)
2220 return -ENOMEM;
2221 obj->externs = ext;
2222 ext = &ext[obj->nr_extern];
2223 memset(ext, 0, sizeof(*ext));
2224 obj->nr_extern++;
2225
2226 ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
2227 if (ext->btf_id <= 0) {
2228 pr_warn("failed to find BTF for extern '%s': %d\n",
2229 ext_name, ext->btf_id);
2230 return ext->btf_id;
2231 }
2232 t = btf__type_by_id(obj->btf, ext->btf_id);
2233 ext->name = btf__name_by_offset(obj->btf, t->name_off);
2234 ext->sym_idx = i;
2235 ext->is_weak = GELF_ST_BIND(sym.st_info) == STB_WEAK;
2236 ext->sz = btf__resolve_size(obj->btf, t->type);
2237 if (ext->sz <= 0) {
2238 pr_warn("failed to resolve size of extern '%s': %d\n",
2239 ext_name, ext->sz);
2240 return ext->sz;
2241 }
2242 ext->align = btf__align_of(obj->btf, t->type);
2243 if (ext->align <= 0) {
2244 pr_warn("failed to determine alignment of extern '%s': %d\n",
2245 ext_name, ext->align);
2246 return -EINVAL;
2247 }
2248 ext->type = find_extern_type(obj->btf, t->type,
2249 &ext->is_signed);
2250 if (ext->type == EXT_UNKNOWN) {
2251 pr_warn("extern '%s' type is unsupported\n", ext_name);
2252 return -ENOTSUP;
2253 }
2254 }
2255 pr_debug("collected %d externs total\n", obj->nr_extern);
2256
2257 if (!obj->nr_extern)
2258 return 0;
2259
2260 /* sort externs by (alignment, size, name) and calculate their offsets
2261 * within a map */
2262 qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
2263 off = 0;
2264 for (i = 0; i < obj->nr_extern; i++) {
2265 ext = &obj->externs[i];
2266 ext->data_off = roundup(off, ext->align);
2267 off = ext->data_off + ext->sz;
2268 pr_debug("extern #%d: symbol %d, off %u, name %s\n",
2269 i, ext->sym_idx, ext->data_off, ext->name);
2270 }
2271
2272 btf_id = btf__find_by_name(obj->btf, EXTERN_SEC);
2273 if (btf_id <= 0) {
2274 pr_warn("no BTF info found for '%s' datasec\n", EXTERN_SEC);
2275 return -ESRCH;
2276 }
2277
2278 sec = (struct btf_type *)btf__type_by_id(obj->btf, btf_id);
2279 sec->size = off;
2280 n = btf_vlen(sec);
2281 for (i = 0; i < n; i++) {
2282 struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
2283
2284 t = btf__type_by_id(obj->btf, vs->type);
2285 ext_name = btf__name_by_offset(obj->btf, t->name_off);
2286 ext = find_extern_by_name(obj, ext_name);
2287 if (!ext) {
2288 pr_warn("failed to find extern definition for BTF var '%s'\n",
2289 ext_name);
2290 return -ESRCH;
2291 }
2292 vs->offset = ext->data_off;
2293 btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
2294 }
2295
2296 return 0;
2297}
2298
Wang Nan34090912015-07-01 02:14:02 +00002299static struct bpf_program *
2300bpf_object__find_prog_by_idx(struct bpf_object *obj, int idx)
2301{
2302 struct bpf_program *prog;
2303 size_t i;
2304
2305 for (i = 0; i < obj->nr_programs; i++) {
2306 prog = &obj->programs[i];
2307 if (prog->idx == idx)
2308 return prog;
2309 }
2310 return NULL;
2311}
2312
Jakub Kicinski6d4b1982018-07-26 14:32:19 -07002313struct bpf_program *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07002314bpf_object__find_program_by_title(const struct bpf_object *obj,
2315 const char *title)
Jakub Kicinski6d4b1982018-07-26 14:32:19 -07002316{
2317 struct bpf_program *pos;
2318
2319 bpf_object__for_each_program(pos, obj) {
2320 if (pos->section_name && !strcmp(pos->section_name, title))
2321 return pos;
2322 }
2323 return NULL;
2324}
2325
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08002326struct bpf_program *
2327bpf_object__find_program_by_name(const struct bpf_object *obj,
2328 const char *name)
2329{
2330 struct bpf_program *prog;
2331
2332 bpf_object__for_each_program(prog, obj) {
2333 if (!strcmp(prog->name, name))
2334 return prog;
2335 }
2336 return NULL;
2337}
2338
Daniel Borkmannd8599002019-04-09 23:20:13 +02002339static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
2340 int shndx)
2341{
2342 return shndx == obj->efile.data_shndx ||
2343 shndx == obj->efile.bss_shndx ||
2344 shndx == obj->efile.rodata_shndx;
2345}
2346
2347static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
2348 int shndx)
2349{
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002350 return shndx == obj->efile.maps_shndx ||
2351 shndx == obj->efile.btf_maps_shndx;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002352}
2353
Daniel Borkmannd8599002019-04-09 23:20:13 +02002354static enum libbpf_map_type
2355bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
2356{
2357 if (shndx == obj->efile.data_shndx)
2358 return LIBBPF_MAP_DATA;
2359 else if (shndx == obj->efile.bss_shndx)
2360 return LIBBPF_MAP_BSS;
2361 else if (shndx == obj->efile.rodata_shndx)
2362 return LIBBPF_MAP_RODATA;
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002363 else if (shndx == obj->efile.symbols_shndx)
2364 return LIBBPF_MAP_EXTERN;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002365 else
2366 return LIBBPF_MAP_UNSPEC;
2367}
2368
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002369static int bpf_program__record_reloc(struct bpf_program *prog,
2370 struct reloc_desc *reloc_desc,
2371 __u32 insn_idx, const char *name,
2372 const GElf_Sym *sym, const GElf_Rel *rel)
2373{
2374 struct bpf_insn *insn = &prog->insns[insn_idx];
2375 size_t map_idx, nr_maps = prog->obj->nr_maps;
2376 struct bpf_object *obj = prog->obj;
2377 __u32 shdr_idx = sym->st_shndx;
2378 enum libbpf_map_type type;
2379 struct bpf_map *map;
2380
2381 /* sub-program call relocation */
2382 if (insn->code == (BPF_JMP | BPF_CALL)) {
2383 if (insn->src_reg != BPF_PSEUDO_CALL) {
2384 pr_warn("incorrect bpf_call opcode\n");
2385 return -LIBBPF_ERRNO__RELOC;
2386 }
2387 /* text_shndx can be 0, if no default "main" program exists */
2388 if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
2389 pr_warn("bad call relo against section %u\n", shdr_idx);
2390 return -LIBBPF_ERRNO__RELOC;
2391 }
2392 if (sym->st_value % 8) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08002393 pr_warn("bad call relo offset: %zu\n",
2394 (size_t)sym->st_value);
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002395 return -LIBBPF_ERRNO__RELOC;
2396 }
2397 reloc_desc->type = RELO_CALL;
2398 reloc_desc->insn_idx = insn_idx;
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08002399 reloc_desc->sym_off = sym->st_value;
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002400 obj->has_pseudo_calls = true;
2401 return 0;
2402 }
2403
2404 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) {
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002405 pr_warn("invalid relo for insns[%d].code 0x%x\n",
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002406 insn_idx, insn->code);
2407 return -LIBBPF_ERRNO__RELOC;
2408 }
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002409
2410 if (sym_is_extern(sym)) {
2411 int sym_idx = GELF_R_SYM(rel->r_info);
2412 int i, n = obj->nr_extern;
2413 struct extern_desc *ext;
2414
2415 for (i = 0; i < n; i++) {
2416 ext = &obj->externs[i];
2417 if (ext->sym_idx == sym_idx)
2418 break;
2419 }
2420 if (i >= n) {
2421 pr_warn("extern relo failed to find extern for sym %d\n",
2422 sym_idx);
2423 return -LIBBPF_ERRNO__RELOC;
2424 }
2425 pr_debug("found extern #%d '%s' (sym %d, off %u) for insn %u\n",
2426 i, ext->name, ext->sym_idx, ext->data_off, insn_idx);
2427 reloc_desc->type = RELO_EXTERN;
2428 reloc_desc->insn_idx = insn_idx;
2429 reloc_desc->sym_off = ext->data_off;
2430 return 0;
2431 }
2432
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002433 if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
Andrii Nakryiko393cdfb2019-11-20 23:07:43 -08002434 pr_warn("invalid relo for \'%s\' in special section 0x%x; forgot to initialize global var?..\n",
2435 name, shdr_idx);
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002436 return -LIBBPF_ERRNO__RELOC;
2437 }
2438
2439 type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
2440
2441 /* generic map reference relocation */
2442 if (type == LIBBPF_MAP_UNSPEC) {
2443 if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
2444 pr_warn("bad map relo against section %u\n",
2445 shdr_idx);
2446 return -LIBBPF_ERRNO__RELOC;
2447 }
2448 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2449 map = &obj->maps[map_idx];
2450 if (map->libbpf_type != type ||
2451 map->sec_idx != sym->st_shndx ||
2452 map->sec_offset != sym->st_value)
2453 continue;
2454 pr_debug("found map %zd (%s, sec %d, off %zu) for insn %u\n",
2455 map_idx, map->name, map->sec_idx,
2456 map->sec_offset, insn_idx);
2457 break;
2458 }
2459 if (map_idx >= nr_maps) {
Andrii Nakryiko679152d2019-12-12 09:19:18 -08002460 pr_warn("map relo failed to find map for sec %u, off %zu\n",
2461 shdr_idx, (size_t)sym->st_value);
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002462 return -LIBBPF_ERRNO__RELOC;
2463 }
2464 reloc_desc->type = RELO_LD64;
2465 reloc_desc->insn_idx = insn_idx;
2466 reloc_desc->map_idx = map_idx;
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08002467 reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002468 return 0;
2469 }
2470
2471 /* global data map relocation */
2472 if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
2473 pr_warn("bad data relo against section %u\n", shdr_idx);
2474 return -LIBBPF_ERRNO__RELOC;
2475 }
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002476 for (map_idx = 0; map_idx < nr_maps; map_idx++) {
2477 map = &obj->maps[map_idx];
2478 if (map->libbpf_type != type)
2479 continue;
2480 pr_debug("found data map %zd (%s, sec %d, off %zu) for insn %u\n",
2481 map_idx, map->name, map->sec_idx, map->sec_offset,
2482 insn_idx);
2483 break;
2484 }
2485 if (map_idx >= nr_maps) {
2486 pr_warn("data relo failed to find map for sec %u\n",
2487 shdr_idx);
2488 return -LIBBPF_ERRNO__RELOC;
2489 }
2490
2491 reloc_desc->type = RELO_DATA;
2492 reloc_desc->insn_idx = insn_idx;
2493 reloc_desc->map_idx = map_idx;
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08002494 reloc_desc->sym_off = sym->st_value;
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002495 return 0;
2496}
2497
Wang Nan34090912015-07-01 02:14:02 +00002498static int
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08002499bpf_program__collect_reloc(struct bpf_program *prog, GElf_Shdr *shdr,
2500 Elf_Data *data, struct bpf_object *obj)
Wang Nan34090912015-07-01 02:14:02 +00002501{
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08002502 Elf_Data *symbols = obj->efile.symbols;
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002503 int err, i, nrels;
Wang Nan34090912015-07-01 02:14:02 +00002504
Andrii Nakryiko399dc652019-05-29 10:36:11 -07002505 pr_debug("collecting relocating info for: '%s'\n", prog->section_name);
Wang Nan34090912015-07-01 02:14:02 +00002506 nrels = shdr->sh_size / shdr->sh_entsize;
2507
2508 prog->reloc_desc = malloc(sizeof(*prog->reloc_desc) * nrels);
2509 if (!prog->reloc_desc) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002510 pr_warn("failed to alloc memory in relocation\n");
Wang Nan34090912015-07-01 02:14:02 +00002511 return -ENOMEM;
2512 }
2513 prog->nr_reloc = nrels;
2514
2515 for (i = 0; i < nrels; i++) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02002516 const char *name;
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002517 __u32 insn_idx;
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002518 GElf_Sym sym;
2519 GElf_Rel rel;
Wang Nan34090912015-07-01 02:14:02 +00002520
2521 if (!gelf_getrel(data, i, &rel)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002522 pr_warn("relocation: failed to get %d reloc\n", i);
Wang Nan6371ca3b2015-11-06 13:49:37 +00002523 return -LIBBPF_ERRNO__FORMAT;
Wang Nan34090912015-07-01 02:14:02 +00002524 }
Andrii Nakryiko399dc652019-05-29 10:36:11 -07002525 if (!gelf_getsym(symbols, GELF_R_SYM(rel.r_info), &sym)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002526 pr_warn("relocation: symbol %"PRIx64" not found\n",
2527 GELF_R_SYM(rel.r_info));
Wang Nan6371ca3b2015-11-06 13:49:37 +00002528 return -LIBBPF_ERRNO__FORMAT;
Wang Nan34090912015-07-01 02:14:02 +00002529 }
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002530 if (rel.r_offset % sizeof(struct bpf_insn))
2531 return -LIBBPF_ERRNO__FORMAT;
Wang Nan34090912015-07-01 02:14:02 +00002532
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002533 insn_idx = rel.r_offset / sizeof(struct bpf_insn);
Daniel Borkmannd8599002019-04-09 23:20:13 +02002534 name = elf_strptr(obj->efile.elf, obj->efile.strtabidx,
2535 sym.st_name) ? : "<?>";
2536
Andrii Nakryiko679152d2019-12-12 09:19:18 -08002537 pr_debug("relo for shdr %u, symb %zu, value %zu, type %d, bind %d, name %d (\'%s\'), insn %u\n",
2538 (__u32)sym.st_shndx, (size_t)GELF_R_SYM(rel.r_info),
2539 (size_t)sym.st_value, GELF_ST_TYPE(sym.st_info),
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002540 GELF_ST_BIND(sym.st_info), sym.st_name, name,
2541 insn_idx);
Daniel Borkmannd8599002019-04-09 23:20:13 +02002542
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08002543 err = bpf_program__record_reloc(prog, &prog->reloc_desc[i],
2544 insn_idx, name, &sym, &rel);
2545 if (err)
2546 return err;
Wang Nan34090912015-07-01 02:14:02 +00002547 }
2548 return 0;
2549}
2550
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002551static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002552{
2553 struct bpf_map_def *def = &map->def;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002554 __u32 key_type_id = 0, value_type_id = 0;
Yonghong Song96408c42019-02-04 11:00:58 -08002555 int ret;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002556
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002557 /* if it's BTF-defined map, we don't need to search for type IDs */
2558 if (map->sec_idx == obj->efile.btf_maps_shndx)
2559 return 0;
2560
Daniel Borkmannd8599002019-04-09 23:20:13 +02002561 if (!bpf_map__is_internal(map)) {
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002562 ret = btf__get_map_kv_tids(obj->btf, map->name, def->key_size,
Daniel Borkmannd8599002019-04-09 23:20:13 +02002563 def->value_size, &key_type_id,
2564 &value_type_id);
2565 } else {
2566 /*
2567 * LLVM annotates global data differently in BTF, that is,
2568 * only as '.data', '.bss' or '.rodata'.
2569 */
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002570 ret = btf__find_by_name(obj->btf,
Daniel Borkmannd8599002019-04-09 23:20:13 +02002571 libbpf_type_to_btf_name[map->libbpf_type]);
2572 }
2573 if (ret < 0)
Yonghong Song96408c42019-02-04 11:00:58 -08002574 return ret;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002575
Yonghong Song96408c42019-02-04 11:00:58 -08002576 map->btf_key_type_id = key_type_id;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002577 map->btf_value_type_id = bpf_map__is_internal(map) ?
2578 ret : value_type_id;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002579 return 0;
2580}
2581
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002582int bpf_map__reuse_fd(struct bpf_map *map, int fd)
2583{
2584 struct bpf_map_info info = {};
2585 __u32 len = sizeof(info);
2586 int new_fd, err;
2587 char *new_name;
2588
2589 err = bpf_obj_get_info_by_fd(fd, &info, &len);
2590 if (err)
2591 return err;
2592
2593 new_name = strdup(info.name);
2594 if (!new_name)
2595 return -errno;
2596
2597 new_fd = open("/", O_RDONLY | O_CLOEXEC);
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002598 if (new_fd < 0) {
2599 err = -errno;
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002600 goto err_free_new_name;
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002601 }
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002602
2603 new_fd = dup3(fd, new_fd, O_CLOEXEC);
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002604 if (new_fd < 0) {
2605 err = -errno;
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002606 goto err_close_new_fd;
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002607 }
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002608
2609 err = zclose(map->fd);
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002610 if (err) {
2611 err = -errno;
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002612 goto err_close_new_fd;
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002613 }
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002614 free(map->name);
2615
2616 map->fd = new_fd;
2617 map->name = new_name;
2618 map->def.type = info.type;
2619 map->def.key_size = info.key_size;
2620 map->def.value_size = info.value_size;
2621 map->def.max_entries = info.max_entries;
2622 map->def.map_flags = info.map_flags;
2623 map->btf_key_type_id = info.btf_key_type_id;
2624 map->btf_value_type_id = info.btf_value_type_id;
Toke Høiland-Jørgensenec6d5f472019-11-09 21:37:27 +01002625 map->reused = true;
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002626
2627 return 0;
2628
2629err_close_new_fd:
2630 close(new_fd);
2631err_free_new_name:
2632 free(new_name);
Toke Høiland-Jørgensend1b45742019-11-02 12:09:37 +01002633 return err;
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002634}
2635
Andrey Ignatov1a11a4c2019-02-14 15:01:42 -08002636int bpf_map__resize(struct bpf_map *map, __u32 max_entries)
2637{
2638 if (!map || !max_entries)
2639 return -EINVAL;
2640
2641 /* If map already created, its attributes can't be changed. */
2642 if (map->fd >= 0)
2643 return -EBUSY;
2644
2645 map->def.max_entries = max_entries;
2646
2647 return 0;
2648}
2649
Wang Nan52d33522015-07-01 02:14:04 +00002650static int
Stanislav Fomichev47eff612018-11-20 17:11:19 -08002651bpf_object__probe_name(struct bpf_object *obj)
2652{
2653 struct bpf_load_program_attr attr;
2654 char *cp, errmsg[STRERR_BUFSIZE];
2655 struct bpf_insn insns[] = {
2656 BPF_MOV64_IMM(BPF_REG_0, 0),
2657 BPF_EXIT_INSN(),
2658 };
2659 int ret;
2660
2661 /* make sure basic loading works */
2662
2663 memset(&attr, 0, sizeof(attr));
2664 attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2665 attr.insns = insns;
2666 attr.insns_cnt = ARRAY_SIZE(insns);
2667 attr.license = "GPL";
2668
2669 ret = bpf_load_program_xattr(&attr, NULL, 0);
2670 if (ret < 0) {
2671 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08002672 pr_warn("Error in %s():%s(%d). Couldn't load basic 'r0 = 0' BPF program.\n",
2673 __func__, cp, errno);
Stanislav Fomichev47eff612018-11-20 17:11:19 -08002674 return -errno;
2675 }
2676 close(ret);
2677
2678 /* now try the same program, but with the name */
2679
2680 attr.name = "test";
2681 ret = bpf_load_program_xattr(&attr, NULL, 0);
2682 if (ret >= 0) {
2683 obj->caps.name = 1;
2684 close(ret);
2685 }
2686
2687 return 0;
2688}
2689
2690static int
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002691bpf_object__probe_global_data(struct bpf_object *obj)
2692{
2693 struct bpf_load_program_attr prg_attr;
2694 struct bpf_create_map_attr map_attr;
2695 char *cp, errmsg[STRERR_BUFSIZE];
2696 struct bpf_insn insns[] = {
2697 BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
2698 BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
2699 BPF_MOV64_IMM(BPF_REG_0, 0),
2700 BPF_EXIT_INSN(),
2701 };
2702 int ret, map;
2703
2704 memset(&map_attr, 0, sizeof(map_attr));
2705 map_attr.map_type = BPF_MAP_TYPE_ARRAY;
2706 map_attr.key_size = sizeof(int);
2707 map_attr.value_size = 32;
2708 map_attr.max_entries = 1;
2709
2710 map = bpf_create_map_xattr(&map_attr);
2711 if (map < 0) {
2712 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08002713 pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
2714 __func__, cp, errno);
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002715 return -errno;
2716 }
2717
2718 insns[0].imm = map;
2719
2720 memset(&prg_attr, 0, sizeof(prg_attr));
2721 prg_attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
2722 prg_attr.insns = insns;
2723 prg_attr.insns_cnt = ARRAY_SIZE(insns);
2724 prg_attr.license = "GPL";
2725
2726 ret = bpf_load_program_xattr(&prg_attr, NULL, 0);
2727 if (ret >= 0) {
2728 obj->caps.global_data = 1;
2729 close(ret);
2730 }
2731
2732 close(map);
2733 return 0;
2734}
2735
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002736static int bpf_object__probe_btf_func(struct bpf_object *obj)
2737{
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002738 static const char strs[] = "\0int\0x\0a";
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002739 /* void x(int a) {} */
2740 __u32 types[] = {
2741 /* int */
2742 BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2743 /* FUNC_PROTO */ /* [2] */
2744 BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
2745 BTF_PARAM_ENC(7, 1),
2746 /* FUNC x */ /* [3] */
2747 BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
2748 };
Michal Rosteckicfd49212019-05-29 20:31:09 +02002749 int btf_fd;
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002750
Michal Rosteckicfd49212019-05-29 20:31:09 +02002751 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2752 strs, sizeof(strs));
2753 if (btf_fd >= 0) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002754 obj->caps.btf_func = 1;
Michal Rosteckicfd49212019-05-29 20:31:09 +02002755 close(btf_fd);
2756 return 1;
2757 }
2758
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002759 return 0;
2760}
2761
2762static int bpf_object__probe_btf_datasec(struct bpf_object *obj)
2763{
Andrii Nakryiko8983b732019-11-20 23:07:42 -08002764 static const char strs[] = "\0x\0.data";
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002765 /* static int a; */
2766 __u32 types[] = {
2767 /* int */
2768 BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4), /* [1] */
2769 /* VAR x */ /* [2] */
2770 BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
2771 BTF_VAR_STATIC,
2772 /* DATASEC val */ /* [3] */
2773 BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
2774 BTF_VAR_SECINFO_ENC(2, 0, 4),
2775 };
Michal Rosteckicfd49212019-05-29 20:31:09 +02002776 int btf_fd;
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002777
Michal Rosteckicfd49212019-05-29 20:31:09 +02002778 btf_fd = libbpf__load_raw_btf((char *)types, sizeof(types),
2779 strs, sizeof(strs));
2780 if (btf_fd >= 0) {
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002781 obj->caps.btf_datasec = 1;
Michal Rosteckicfd49212019-05-29 20:31:09 +02002782 close(btf_fd);
2783 return 1;
2784 }
2785
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002786 return 0;
2787}
2788
Andrii Nakryiko7fe74b42019-11-17 09:28:05 -08002789static int bpf_object__probe_array_mmap(struct bpf_object *obj)
2790{
2791 struct bpf_create_map_attr attr = {
2792 .map_type = BPF_MAP_TYPE_ARRAY,
2793 .map_flags = BPF_F_MMAPABLE,
2794 .key_size = sizeof(int),
2795 .value_size = sizeof(int),
2796 .max_entries = 1,
2797 };
2798 int fd;
2799
2800 fd = bpf_create_map_xattr(&attr);
2801 if (fd >= 0) {
2802 obj->caps.array_mmap = 1;
2803 close(fd);
2804 return 1;
2805 }
2806
2807 return 0;
2808}
2809
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002810static int
Stanislav Fomichev47eff612018-11-20 17:11:19 -08002811bpf_object__probe_caps(struct bpf_object *obj)
2812{
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002813 int (*probe_fn[])(struct bpf_object *obj) = {
2814 bpf_object__probe_name,
2815 bpf_object__probe_global_data,
Andrii Nakryikod7c4b392019-05-10 14:13:15 -07002816 bpf_object__probe_btf_func,
2817 bpf_object__probe_btf_datasec,
Andrii Nakryiko7fe74b42019-11-17 09:28:05 -08002818 bpf_object__probe_array_mmap,
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002819 };
2820 int i, ret;
2821
2822 for (i = 0; i < ARRAY_SIZE(probe_fn); i++) {
2823 ret = probe_fn[i](obj);
2824 if (ret < 0)
Stanislav Fomichev15ea1642019-05-14 20:38:49 -07002825 pr_debug("Probe #%d failed with %d.\n", i, ret);
Daniel Borkmann8837fe52019-04-24 00:45:56 +02002826 }
2827
2828 return 0;
Stanislav Fomichev47eff612018-11-20 17:11:19 -08002829}
2830
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01002831static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
2832{
2833 struct bpf_map_info map_info = {};
2834 char msg[STRERR_BUFSIZE];
2835 __u32 map_info_len;
2836
2837 map_info_len = sizeof(map_info);
2838
2839 if (bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len)) {
2840 pr_warn("failed to get map info for map FD %d: %s\n",
2841 map_fd, libbpf_strerror_r(errno, msg, sizeof(msg)));
2842 return false;
2843 }
2844
2845 return (map_info.type == map->def.type &&
2846 map_info.key_size == map->def.key_size &&
2847 map_info.value_size == map->def.value_size &&
2848 map_info.max_entries == map->def.max_entries &&
2849 map_info.map_flags == map->def.map_flags);
2850}
2851
2852static int
2853bpf_object__reuse_map(struct bpf_map *map)
2854{
2855 char *cp, errmsg[STRERR_BUFSIZE];
2856 int err, pin_fd;
2857
2858 pin_fd = bpf_obj_get(map->pin_path);
2859 if (pin_fd < 0) {
2860 err = -errno;
2861 if (err == -ENOENT) {
2862 pr_debug("found no pinned map to reuse at '%s'\n",
2863 map->pin_path);
2864 return 0;
2865 }
2866
2867 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
2868 pr_warn("couldn't retrieve pinned map '%s': %s\n",
2869 map->pin_path, cp);
2870 return err;
2871 }
2872
2873 if (!map_is_reuse_compat(map, pin_fd)) {
2874 pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
2875 map->pin_path);
2876 close(pin_fd);
2877 return -EINVAL;
2878 }
2879
2880 err = bpf_map__reuse_fd(map, pin_fd);
2881 if (err) {
2882 close(pin_fd);
2883 return err;
2884 }
2885 map->pinned = true;
2886 pr_debug("reused pinned map at '%s'\n", map->pin_path);
2887
2888 return 0;
2889}
2890
Stanislav Fomichev47eff612018-11-20 17:11:19 -08002891static int
Daniel Borkmannd8599002019-04-09 23:20:13 +02002892bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
2893{
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002894 enum libbpf_map_type map_type = map->libbpf_type;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002895 char *cp, errmsg[STRERR_BUFSIZE];
2896 int err, zero = 0;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002897
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002898 /* kernel already zero-initializes .bss map. */
2899 if (map_type == LIBBPF_MAP_BSS)
Daniel Borkmannd8599002019-04-09 23:20:13 +02002900 return 0;
2901
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -08002902 err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
2903 if (err) {
2904 err = -errno;
2905 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
2906 pr_warn("Error setting initial map(%s) contents: %s\n",
2907 map->name, cp);
2908 return err;
2909 }
Daniel Borkmannd8599002019-04-09 23:20:13 +02002910
Andrii Nakryiko166750b2019-12-13 17:47:08 -08002911 /* Freeze .rodata and .extern map as read-only from syscall side. */
2912 if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_EXTERN) {
Daniel Borkmannd8599002019-04-09 23:20:13 +02002913 err = bpf_map_freeze(map->fd);
2914 if (err) {
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -08002915 err = -errno;
2916 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08002917 pr_warn("Error freezing map(%s) as read-only: %s\n",
2918 map->name, cp);
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -08002919 return err;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002920 }
2921 }
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -08002922 return 0;
Daniel Borkmannd8599002019-04-09 23:20:13 +02002923}
2924
2925static int
Wang Nan52d33522015-07-01 02:14:04 +00002926bpf_object__create_maps(struct bpf_object *obj)
2927{
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002928 struct bpf_create_map_attr create_attr = {};
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07002929 int nr_cpus = 0;
Wang Nan52d33522015-07-01 02:14:04 +00002930 unsigned int i;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002931 int err;
Wang Nan52d33522015-07-01 02:14:04 +00002932
Wang Nan9d759a92015-11-27 08:47:35 +00002933 for (i = 0; i < obj->nr_maps; i++) {
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002934 struct bpf_map *map = &obj->maps[i];
2935 struct bpf_map_def *def = &map->def;
Thomas Richter1ce6a9f2018-07-30 10:53:23 +02002936 char *cp, errmsg[STRERR_BUFSIZE];
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002937 int *pfd = &map->fd;
Wang Nan52d33522015-07-01 02:14:04 +00002938
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01002939 if (map->pin_path) {
2940 err = bpf_object__reuse_map(map);
2941 if (err) {
2942 pr_warn("error reusing pinned map %s\n",
2943 map->name);
2944 return err;
2945 }
2946 }
2947
Jakub Kicinski26736eb2018-07-10 14:43:06 -07002948 if (map->fd >= 0) {
2949 pr_debug("skip map create (preset) %s: fd=%d\n",
2950 map->name, map->fd);
2951 continue;
2952 }
2953
Stanislav Fomichev94cb3102018-11-20 17:11:20 -08002954 if (obj->caps.name)
2955 create_attr.name = map->name;
David Beckettf0307a72018-05-16 14:02:49 -07002956 create_attr.map_ifindex = map->map_ifindex;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002957 create_attr.map_type = def->type;
2958 create_attr.map_flags = def->map_flags;
2959 create_attr.key_size = def->key_size;
2960 create_attr.value_size = def->value_size;
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07002961 if (def->type == BPF_MAP_TYPE_PERF_EVENT_ARRAY &&
2962 !def->max_entries) {
2963 if (!nr_cpus)
2964 nr_cpus = libbpf_num_possible_cpus();
2965 if (nr_cpus < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08002966 pr_warn("failed to determine number of system CPUs: %d\n",
2967 nr_cpus);
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07002968 err = nr_cpus;
2969 goto err_out;
2970 }
2971 pr_debug("map '%s': setting size to %d\n",
2972 map->name, nr_cpus);
2973 create_attr.max_entries = nr_cpus;
2974 } else {
2975 create_attr.max_entries = def->max_entries;
2976 }
Andrii Nakryikoe55d54f2019-06-12 22:04:57 -07002977 create_attr.btf_fd = 0;
Martin KaFai Lau61746dbe2018-05-22 15:04:24 -07002978 create_attr.btf_key_type_id = 0;
2979 create_attr.btf_value_type_id = 0;
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -08002980 if (bpf_map_type__is_map_in_map(def->type) &&
2981 map->inner_map_fd >= 0)
2982 create_attr.inner_map_fd = map->inner_map_fd;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002983
Andrii Nakryikoabd29c92019-06-17 12:26:56 -07002984 if (obj->btf && !bpf_map_find_btf_info(obj, map)) {
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002985 create_attr.btf_fd = btf__fd(obj->btf);
Martin KaFai Lau61746dbe2018-05-22 15:04:24 -07002986 create_attr.btf_key_type_id = map->btf_key_type_id;
2987 create_attr.btf_value_type_id = map->btf_value_type_id;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07002988 }
2989
2990 *pfd = bpf_create_map_xattr(&create_attr);
Andrii Nakryikoe55d54f2019-06-12 22:04:57 -07002991 if (*pfd < 0 && (create_attr.btf_key_type_id ||
2992 create_attr.btf_value_type_id)) {
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07002993 err = -errno;
2994 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08002995 pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
2996 map->name, cp, err);
Andrii Nakryikoe55d54f2019-06-12 22:04:57 -07002997 create_attr.btf_fd = 0;
Martin KaFai Lau61746dbe2018-05-22 15:04:24 -07002998 create_attr.btf_key_type_id = 0;
2999 create_attr.btf_value_type_id = 0;
3000 map->btf_key_type_id = 0;
3001 map->btf_value_type_id = 0;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07003002 *pfd = bpf_create_map_xattr(&create_attr);
3003 }
3004
Wang Nan52d33522015-07-01 02:14:04 +00003005 if (*pfd < 0) {
3006 size_t j;
Wang Nan52d33522015-07-01 02:14:04 +00003007
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07003008 err = -errno;
Daniel Borkmannd8599002019-04-09 23:20:13 +02003009err_out:
Andrii Nakryikod7ff34d2019-07-06 11:06:25 -07003010 cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08003011 pr_warn("failed to create map (name: '%s'): %s(%d)\n",
3012 map->name, cp, err);
Toke Høiland-Jørgensendc3a2d22019-12-16 19:12:04 +01003013 pr_perm_msg(err);
Wang Nan52d33522015-07-01 02:14:04 +00003014 for (j = 0; j < i; j++)
Wang Nan9d759a92015-11-27 08:47:35 +00003015 zclose(obj->maps[j].fd);
Wang Nan52d33522015-07-01 02:14:04 +00003016 return err;
3017 }
Daniel Borkmannd8599002019-04-09 23:20:13 +02003018
3019 if (bpf_map__is_internal(map)) {
3020 err = bpf_object__populate_internal_map(obj, map);
3021 if (err < 0) {
3022 zclose(*pfd);
3023 goto err_out;
3024 }
3025 }
3026
Toke Høiland-Jørgensen57a00f42019-11-02 12:09:41 +01003027 if (map->pin_path && !map->pinned) {
3028 err = bpf_map__pin(map, NULL);
3029 if (err) {
3030 pr_warn("failed to auto-pin map name '%s' at '%s'\n",
3031 map->name, map->pin_path);
3032 return err;
3033 }
3034 }
3035
Andrii Nakryiko76e10222019-05-29 10:36:10 -07003036 pr_debug("created map %s: fd=%d\n", map->name, *pfd);
Wang Nan52d33522015-07-01 02:14:04 +00003037 }
3038
Wang Nan52d33522015-07-01 02:14:04 +00003039 return 0;
3040}
3041
Wang Nan8a47a6c2015-07-01 02:14:05 +00003042static int
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003043check_btf_ext_reloc_err(struct bpf_program *prog, int err,
3044 void *btf_prog_info, const char *info_name)
3045{
3046 if (err != -ENOENT) {
Kefeng Wangbe180102019-10-21 13:55:32 +08003047 pr_warn("Error in loading %s for sec %s.\n",
3048 info_name, prog->section_name);
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003049 return err;
3050 }
3051
3052 /* err == -ENOENT (i.e. prog->section_name not found in btf_ext) */
3053
3054 if (btf_prog_info) {
3055 /*
3056 * Some info has already been found but has problem
Andrii Nakryiko399dc652019-05-29 10:36:11 -07003057 * in the last btf_ext reloc. Must have to error out.
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003058 */
Kefeng Wangbe180102019-10-21 13:55:32 +08003059 pr_warn("Error in relocating %s for sec %s.\n",
3060 info_name, prog->section_name);
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003061 return err;
3062 }
3063
Andrii Nakryiko399dc652019-05-29 10:36:11 -07003064 /* Have problem loading the very first info. Ignore the rest. */
Kefeng Wangbe180102019-10-21 13:55:32 +08003065 pr_warn("Cannot find %s for main program sec %s. Ignore all %s.\n",
3066 info_name, prog->section_name, info_name);
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003067 return 0;
3068}
3069
3070static int
3071bpf_program_reloc_btf_ext(struct bpf_program *prog, struct bpf_object *obj,
3072 const char *section_name, __u32 insn_offset)
3073{
3074 int err;
3075
3076 if (!insn_offset || prog->func_info) {
3077 /*
3078 * !insn_offset => main program
3079 *
3080 * For sub prog, the main program's func_info has to
3081 * be loaded first (i.e. prog->func_info != NULL)
3082 */
3083 err = btf_ext__reloc_func_info(obj->btf, obj->btf_ext,
3084 section_name, insn_offset,
3085 &prog->func_info,
3086 &prog->func_info_cnt);
3087 if (err)
3088 return check_btf_ext_reloc_err(prog, err,
3089 prog->func_info,
3090 "bpf_func_info");
3091
3092 prog->func_info_rec_size = btf_ext__func_info_rec_size(obj->btf_ext);
3093 }
3094
Martin KaFai Lau3d650142018-12-07 16:42:31 -08003095 if (!insn_offset || prog->line_info) {
3096 err = btf_ext__reloc_line_info(obj->btf, obj->btf_ext,
3097 section_name, insn_offset,
3098 &prog->line_info,
3099 &prog->line_info_cnt);
3100 if (err)
3101 return check_btf_ext_reloc_err(prog, err,
3102 prog->line_info,
3103 "bpf_line_info");
3104
3105 prog->line_info_rec_size = btf_ext__line_info_rec_size(obj->btf_ext);
3106 }
3107
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08003108 return 0;
3109}
3110
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003111#define BPF_CORE_SPEC_MAX_LEN 64
3112
3113/* represents BPF CO-RE field or array element accessor */
3114struct bpf_core_accessor {
3115 __u32 type_id; /* struct/union type or array element type */
3116 __u32 idx; /* field index or array index */
3117 const char *name; /* field name or NULL for array accessor */
3118};
3119
3120struct bpf_core_spec {
3121 const struct btf *btf;
3122 /* high-level spec: named fields and array indices only */
3123 struct bpf_core_accessor spec[BPF_CORE_SPEC_MAX_LEN];
3124 /* high-level spec length */
3125 int len;
3126 /* raw, low-level spec: 1-to-1 with accessor spec string */
3127 int raw_spec[BPF_CORE_SPEC_MAX_LEN];
3128 /* raw spec length */
3129 int raw_len;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003130 /* field bit offset represented by spec */
3131 __u32 bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003132};
3133
3134static bool str_is_empty(const char *s)
3135{
3136 return !s || !s[0];
3137}
3138
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003139static bool is_flex_arr(const struct btf *btf,
3140 const struct bpf_core_accessor *acc,
3141 const struct btf_array *arr)
3142{
3143 const struct btf_type *t;
3144
3145 /* not a flexible array, if not inside a struct or has non-zero size */
3146 if (!acc->name || arr->nelems > 0)
3147 return false;
3148
3149 /* has to be the last member of enclosing struct */
3150 t = btf__type_by_id(btf, acc->type_id);
3151 return acc->idx == btf_vlen(t) - 1;
3152}
3153
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003154/*
Andrii Nakryiko511bb002019-10-15 11:28:45 -07003155 * Turn bpf_field_reloc into a low- and high-level spec representation,
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003156 * validating correctness along the way, as well as calculating resulting
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003157 * field bit offset, specified by accessor string. Low-level spec captures
3158 * every single level of nestedness, including traversing anonymous
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003159 * struct/union members. High-level one only captures semantically meaningful
3160 * "turning points": named fields and array indicies.
3161 * E.g., for this case:
3162 *
3163 * struct sample {
3164 * int __unimportant;
3165 * struct {
3166 * int __1;
3167 * int __2;
3168 * int a[7];
3169 * };
3170 * };
3171 *
3172 * struct sample *s = ...;
3173 *
3174 * int x = &s->a[3]; // access string = '0:1:2:3'
3175 *
3176 * Low-level spec has 1:1 mapping with each element of access string (it's
3177 * just a parsed access string representation): [0, 1, 2, 3].
3178 *
3179 * High-level spec will capture only 3 points:
3180 * - intial zero-index access by pointer (&s->... is the same as &s[0]...);
3181 * - field 'a' access (corresponds to '2' in low-level spec);
3182 * - array element #3 access (corresponds to '3' in low-level spec).
3183 *
3184 */
3185static int bpf_core_spec_parse(const struct btf *btf,
3186 __u32 type_id,
3187 const char *spec_str,
3188 struct bpf_core_spec *spec)
3189{
3190 int access_idx, parsed_len, i;
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003191 struct bpf_core_accessor *acc;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003192 const struct btf_type *t;
3193 const char *name;
3194 __u32 id;
3195 __s64 sz;
3196
3197 if (str_is_empty(spec_str) || *spec_str == ':')
3198 return -EINVAL;
3199
3200 memset(spec, 0, sizeof(*spec));
3201 spec->btf = btf;
3202
3203 /* parse spec_str="0:1:2:3:4" into array raw_spec=[0, 1, 2, 3, 4] */
3204 while (*spec_str) {
3205 if (*spec_str == ':')
3206 ++spec_str;
3207 if (sscanf(spec_str, "%d%n", &access_idx, &parsed_len) != 1)
3208 return -EINVAL;
3209 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3210 return -E2BIG;
3211 spec_str += parsed_len;
3212 spec->raw_spec[spec->raw_len++] = access_idx;
3213 }
3214
3215 if (spec->raw_len == 0)
3216 return -EINVAL;
3217
3218 /* first spec value is always reloc type array index */
3219 t = skip_mods_and_typedefs(btf, type_id, &id);
3220 if (!t)
3221 return -EINVAL;
3222
3223 access_idx = spec->raw_spec[0];
3224 spec->spec[0].type_id = id;
3225 spec->spec[0].idx = access_idx;
3226 spec->len++;
3227
3228 sz = btf__resolve_size(btf, id);
3229 if (sz < 0)
3230 return sz;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003231 spec->bit_offset = access_idx * sz * 8;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003232
3233 for (i = 1; i < spec->raw_len; i++) {
3234 t = skip_mods_and_typedefs(btf, id, &id);
3235 if (!t)
3236 return -EINVAL;
3237
3238 access_idx = spec->raw_spec[i];
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003239 acc = &spec->spec[spec->len];
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003240
3241 if (btf_is_composite(t)) {
3242 const struct btf_member *m;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003243 __u32 bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003244
3245 if (access_idx >= btf_vlen(t))
3246 return -EINVAL;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003247
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003248 bit_offset = btf_member_bit_offset(t, access_idx);
3249 spec->bit_offset += bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003250
3251 m = btf_members(t) + access_idx;
3252 if (m->name_off) {
3253 name = btf__name_by_offset(btf, m->name_off);
3254 if (str_is_empty(name))
3255 return -EINVAL;
3256
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003257 acc->type_id = id;
3258 acc->idx = access_idx;
3259 acc->name = name;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003260 spec->len++;
3261 }
3262
3263 id = m->type;
3264 } else if (btf_is_array(t)) {
3265 const struct btf_array *a = btf_array(t);
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003266 bool flex;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003267
3268 t = skip_mods_and_typedefs(btf, a->type, &id);
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003269 if (!t)
3270 return -EINVAL;
3271
3272 flex = is_flex_arr(btf, acc - 1, a);
3273 if (!flex && access_idx >= a->nelems)
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003274 return -EINVAL;
3275
3276 spec->spec[spec->len].type_id = id;
3277 spec->spec[spec->len].idx = access_idx;
3278 spec->len++;
3279
3280 sz = btf__resolve_size(btf, id);
3281 if (sz < 0)
3282 return sz;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003283 spec->bit_offset += access_idx * sz * 8;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003284 } else {
Kefeng Wangbe180102019-10-21 13:55:32 +08003285 pr_warn("relo for [%u] %s (at idx %d) captures type [%d] of unexpected kind %d\n",
3286 type_id, spec_str, i, id, btf_kind(t));
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003287 return -EINVAL;
3288 }
3289 }
3290
3291 return 0;
3292}
3293
3294static bool bpf_core_is_flavor_sep(const char *s)
3295{
3296 /* check X___Y name pattern, where X and Y are not underscores */
3297 return s[0] != '_' && /* X */
3298 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
3299 s[4] != '_'; /* Y */
3300}
3301
3302/* Given 'some_struct_name___with_flavor' return the length of a name prefix
3303 * before last triple underscore. Struct name part after last triple
3304 * underscore is ignored by BPF CO-RE relocation during relocation matching.
3305 */
3306static size_t bpf_core_essential_name_len(const char *name)
3307{
3308 size_t n = strlen(name);
3309 int i;
3310
3311 for (i = n - 5; i >= 0; i--) {
3312 if (bpf_core_is_flavor_sep(name + i))
3313 return i + 1;
3314 }
3315 return n;
3316}
3317
3318/* dynamically sized list of type IDs */
3319struct ids_vec {
3320 __u32 *data;
3321 int len;
3322};
3323
3324static void bpf_core_free_cands(struct ids_vec *cand_ids)
3325{
3326 free(cand_ids->data);
3327 free(cand_ids);
3328}
3329
3330static struct ids_vec *bpf_core_find_cands(const struct btf *local_btf,
3331 __u32 local_type_id,
3332 const struct btf *targ_btf)
3333{
3334 size_t local_essent_len, targ_essent_len;
3335 const char *local_name, *targ_name;
3336 const struct btf_type *t;
3337 struct ids_vec *cand_ids;
3338 __u32 *new_ids;
3339 int i, err, n;
3340
3341 t = btf__type_by_id(local_btf, local_type_id);
3342 if (!t)
3343 return ERR_PTR(-EINVAL);
3344
3345 local_name = btf__name_by_offset(local_btf, t->name_off);
3346 if (str_is_empty(local_name))
3347 return ERR_PTR(-EINVAL);
3348 local_essent_len = bpf_core_essential_name_len(local_name);
3349
3350 cand_ids = calloc(1, sizeof(*cand_ids));
3351 if (!cand_ids)
3352 return ERR_PTR(-ENOMEM);
3353
3354 n = btf__get_nr_types(targ_btf);
3355 for (i = 1; i <= n; i++) {
3356 t = btf__type_by_id(targ_btf, i);
3357 targ_name = btf__name_by_offset(targ_btf, t->name_off);
3358 if (str_is_empty(targ_name))
3359 continue;
3360
3361 targ_essent_len = bpf_core_essential_name_len(targ_name);
3362 if (targ_essent_len != local_essent_len)
3363 continue;
3364
3365 if (strncmp(local_name, targ_name, local_essent_len) == 0) {
3366 pr_debug("[%d] %s: found candidate [%d] %s\n",
3367 local_type_id, local_name, i, targ_name);
3368 new_ids = realloc(cand_ids->data, cand_ids->len + 1);
3369 if (!new_ids) {
3370 err = -ENOMEM;
3371 goto err_out;
3372 }
3373 cand_ids->data = new_ids;
3374 cand_ids->data[cand_ids->len++] = i;
3375 }
3376 }
3377 return cand_ids;
3378err_out:
3379 bpf_core_free_cands(cand_ids);
3380 return ERR_PTR(err);
3381}
3382
3383/* Check two types for compatibility, skipping const/volatile/restrict and
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003384 * typedefs, to ensure we are relocating compatible entities:
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003385 * - any two STRUCTs/UNIONs are compatible and can be mixed;
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003386 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003387 * - any two PTRs are always compatible;
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003388 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
3389 * least one of enums should be anonymous;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003390 * - for ENUMs, check sizes, names are ignored;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003391 * - for INT, size and signedness are ignored;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003392 * - for ARRAY, dimensionality is ignored, element types are checked for
3393 * compatibility recursively;
3394 * - everything else shouldn't be ever a target of relocation.
3395 * These rules are not set in stone and probably will be adjusted as we get
3396 * more experience with using BPF CO-RE relocations.
3397 */
3398static int bpf_core_fields_are_compat(const struct btf *local_btf,
3399 __u32 local_id,
3400 const struct btf *targ_btf,
3401 __u32 targ_id)
3402{
3403 const struct btf_type *local_type, *targ_type;
3404
3405recur:
3406 local_type = skip_mods_and_typedefs(local_btf, local_id, &local_id);
3407 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3408 if (!local_type || !targ_type)
3409 return -EINVAL;
3410
3411 if (btf_is_composite(local_type) && btf_is_composite(targ_type))
3412 return 1;
3413 if (btf_kind(local_type) != btf_kind(targ_type))
3414 return 0;
3415
3416 switch (btf_kind(local_type)) {
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003417 case BTF_KIND_PTR:
3418 return 1;
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003419 case BTF_KIND_FWD:
3420 case BTF_KIND_ENUM: {
3421 const char *local_name, *targ_name;
3422 size_t local_len, targ_len;
3423
3424 local_name = btf__name_by_offset(local_btf,
3425 local_type->name_off);
3426 targ_name = btf__name_by_offset(targ_btf, targ_type->name_off);
3427 local_len = bpf_core_essential_name_len(local_name);
3428 targ_len = bpf_core_essential_name_len(targ_name);
3429 /* one of them is anonymous or both w/ same flavor-less names */
3430 return local_len == 0 || targ_len == 0 ||
3431 (local_len == targ_len &&
3432 strncmp(local_name, targ_name, local_len) == 0);
3433 }
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003434 case BTF_KIND_INT:
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003435 /* just reject deprecated bitfield-like integers; all other
3436 * integers are by default compatible between each other
3437 */
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003438 return btf_int_offset(local_type) == 0 &&
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003439 btf_int_offset(targ_type) == 0;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003440 case BTF_KIND_ARRAY:
3441 local_id = btf_array(local_type)->type;
3442 targ_id = btf_array(targ_type)->type;
3443 goto recur;
3444 default:
Kefeng Wangbe180102019-10-21 13:55:32 +08003445 pr_warn("unexpected kind %d relocated, local [%d], target [%d]\n",
3446 btf_kind(local_type), local_id, targ_id);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003447 return 0;
3448 }
3449}
3450
3451/*
3452 * Given single high-level named field accessor in local type, find
3453 * corresponding high-level accessor for a target type. Along the way,
3454 * maintain low-level spec for target as well. Also keep updating target
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003455 * bit offset.
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003456 *
3457 * Searching is performed through recursive exhaustive enumeration of all
3458 * fields of a struct/union. If there are any anonymous (embedded)
3459 * structs/unions, they are recursively searched as well. If field with
3460 * desired name is found, check compatibility between local and target types,
3461 * before returning result.
3462 *
3463 * 1 is returned, if field is found.
3464 * 0 is returned if no compatible field is found.
3465 * <0 is returned on error.
3466 */
3467static int bpf_core_match_member(const struct btf *local_btf,
3468 const struct bpf_core_accessor *local_acc,
3469 const struct btf *targ_btf,
3470 __u32 targ_id,
3471 struct bpf_core_spec *spec,
3472 __u32 *next_targ_id)
3473{
3474 const struct btf_type *local_type, *targ_type;
3475 const struct btf_member *local_member, *m;
3476 const char *local_name, *targ_name;
3477 __u32 local_id;
3478 int i, n, found;
3479
3480 targ_type = skip_mods_and_typedefs(targ_btf, targ_id, &targ_id);
3481 if (!targ_type)
3482 return -EINVAL;
3483 if (!btf_is_composite(targ_type))
3484 return 0;
3485
3486 local_id = local_acc->type_id;
3487 local_type = btf__type_by_id(local_btf, local_id);
3488 local_member = btf_members(local_type) + local_acc->idx;
3489 local_name = btf__name_by_offset(local_btf, local_member->name_off);
3490
3491 n = btf_vlen(targ_type);
3492 m = btf_members(targ_type);
3493 for (i = 0; i < n; i++, m++) {
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003494 __u32 bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003495
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003496 bit_offset = btf_member_bit_offset(targ_type, i);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003497
3498 /* too deep struct/union/array nesting */
3499 if (spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3500 return -E2BIG;
3501
3502 /* speculate this member will be the good one */
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003503 spec->bit_offset += bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003504 spec->raw_spec[spec->raw_len++] = i;
3505
3506 targ_name = btf__name_by_offset(targ_btf, m->name_off);
3507 if (str_is_empty(targ_name)) {
3508 /* embedded struct/union, we need to go deeper */
3509 found = bpf_core_match_member(local_btf, local_acc,
3510 targ_btf, m->type,
3511 spec, next_targ_id);
3512 if (found) /* either found or error */
3513 return found;
3514 } else if (strcmp(local_name, targ_name) == 0) {
3515 /* matching named field */
3516 struct bpf_core_accessor *targ_acc;
3517
3518 targ_acc = &spec->spec[spec->len++];
3519 targ_acc->type_id = targ_id;
3520 targ_acc->idx = i;
3521 targ_acc->name = targ_name;
3522
3523 *next_targ_id = m->type;
3524 found = bpf_core_fields_are_compat(local_btf,
3525 local_member->type,
3526 targ_btf, m->type);
3527 if (!found)
3528 spec->len--; /* pop accessor */
3529 return found;
3530 }
3531 /* member turned out not to be what we looked for */
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003532 spec->bit_offset -= bit_offset;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003533 spec->raw_len--;
3534 }
3535
3536 return 0;
3537}
3538
3539/*
3540 * Try to match local spec to a target type and, if successful, produce full
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003541 * target spec (high-level, low-level + bit offset).
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003542 */
3543static int bpf_core_spec_match(struct bpf_core_spec *local_spec,
3544 const struct btf *targ_btf, __u32 targ_id,
3545 struct bpf_core_spec *targ_spec)
3546{
3547 const struct btf_type *targ_type;
3548 const struct bpf_core_accessor *local_acc;
3549 struct bpf_core_accessor *targ_acc;
3550 int i, sz, matched;
3551
3552 memset(targ_spec, 0, sizeof(*targ_spec));
3553 targ_spec->btf = targ_btf;
3554
3555 local_acc = &local_spec->spec[0];
3556 targ_acc = &targ_spec->spec[0];
3557
3558 for (i = 0; i < local_spec->len; i++, local_acc++, targ_acc++) {
3559 targ_type = skip_mods_and_typedefs(targ_spec->btf, targ_id,
3560 &targ_id);
3561 if (!targ_type)
3562 return -EINVAL;
3563
3564 if (local_acc->name) {
3565 matched = bpf_core_match_member(local_spec->btf,
3566 local_acc,
3567 targ_btf, targ_id,
3568 targ_spec, &targ_id);
3569 if (matched <= 0)
3570 return matched;
3571 } else {
3572 /* for i=0, targ_id is already treated as array element
3573 * type (because it's the original struct), for others
3574 * we should find array element type first
3575 */
3576 if (i > 0) {
3577 const struct btf_array *a;
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003578 bool flex;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003579
3580 if (!btf_is_array(targ_type))
3581 return 0;
3582
3583 a = btf_array(targ_type);
Andrii Nakryiko1b484b32019-12-14 23:08:43 -08003584 flex = is_flex_arr(targ_btf, targ_acc - 1, a);
3585 if (!flex && local_acc->idx >= a->nelems)
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003586 return 0;
3587 if (!skip_mods_and_typedefs(targ_btf, a->type,
3588 &targ_id))
3589 return -EINVAL;
3590 }
3591
3592 /* too deep struct/union/array nesting */
3593 if (targ_spec->raw_len == BPF_CORE_SPEC_MAX_LEN)
3594 return -E2BIG;
3595
3596 targ_acc->type_id = targ_id;
3597 targ_acc->idx = local_acc->idx;
3598 targ_acc->name = NULL;
3599 targ_spec->len++;
3600 targ_spec->raw_spec[targ_spec->raw_len] = targ_acc->idx;
3601 targ_spec->raw_len++;
3602
3603 sz = btf__resolve_size(targ_btf, targ_id);
3604 if (sz < 0)
3605 return sz;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003606 targ_spec->bit_offset += local_acc->idx * sz * 8;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003607 }
3608 }
3609
3610 return 1;
3611}
3612
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003613static int bpf_core_calc_field_relo(const struct bpf_program *prog,
3614 const struct bpf_field_reloc *relo,
3615 const struct bpf_core_spec *spec,
3616 __u32 *val, bool *validate)
3617{
3618 const struct bpf_core_accessor *acc = &spec->spec[spec->len - 1];
3619 const struct btf_type *t = btf__type_by_id(spec->btf, acc->type_id);
3620 __u32 byte_off, byte_sz, bit_off, bit_sz;
3621 const struct btf_member *m;
3622 const struct btf_type *mt;
3623 bool bitfield;
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003624 __s64 sz;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003625
3626 /* a[n] accessor needs special handling */
3627 if (!acc->name) {
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003628 if (relo->kind == BPF_FIELD_BYTE_OFFSET) {
3629 *val = spec->bit_offset / 8;
3630 } else if (relo->kind == BPF_FIELD_BYTE_SIZE) {
3631 sz = btf__resolve_size(spec->btf, acc->type_id);
3632 if (sz < 0)
3633 return -EINVAL;
3634 *val = sz;
3635 } else {
3636 pr_warn("prog '%s': relo %d at insn #%d can't be applied to array access\n",
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003637 bpf_program__title(prog, false),
3638 relo->kind, relo->insn_off / 8);
3639 return -EINVAL;
3640 }
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003641 if (validate)
3642 *validate = true;
3643 return 0;
3644 }
3645
3646 m = btf_members(t) + acc->idx;
3647 mt = skip_mods_and_typedefs(spec->btf, m->type, NULL);
3648 bit_off = spec->bit_offset;
3649 bit_sz = btf_member_bitfield_size(t, acc->idx);
3650
3651 bitfield = bit_sz > 0;
3652 if (bitfield) {
3653 byte_sz = mt->size;
3654 byte_off = bit_off / 8 / byte_sz * byte_sz;
3655 /* figure out smallest int size necessary for bitfield load */
3656 while (bit_off + bit_sz - byte_off * 8 > byte_sz * 8) {
3657 if (byte_sz >= 8) {
3658 /* bitfield can't be read with 64-bit read */
3659 pr_warn("prog '%s': relo %d at insn #%d can't be satisfied for bitfield\n",
3660 bpf_program__title(prog, false),
3661 relo->kind, relo->insn_off / 8);
3662 return -E2BIG;
3663 }
3664 byte_sz *= 2;
3665 byte_off = bit_off / 8 / byte_sz * byte_sz;
3666 }
3667 } else {
Andrii Nakryiko94f060e2019-11-01 15:28:08 -07003668 sz = btf__resolve_size(spec->btf, m->type);
3669 if (sz < 0)
3670 return -EINVAL;
3671 byte_sz = sz;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003672 byte_off = spec->bit_offset / 8;
3673 bit_sz = byte_sz * 8;
3674 }
3675
3676 /* for bitfields, all the relocatable aspects are ambiguous and we
3677 * might disagree with compiler, so turn off validation of expected
3678 * value, except for signedness
3679 */
3680 if (validate)
3681 *validate = !bitfield;
3682
3683 switch (relo->kind) {
3684 case BPF_FIELD_BYTE_OFFSET:
3685 *val = byte_off;
3686 break;
3687 case BPF_FIELD_BYTE_SIZE:
3688 *val = byte_sz;
3689 break;
3690 case BPF_FIELD_SIGNED:
3691 /* enums will be assumed unsigned */
3692 *val = btf_is_enum(mt) ||
3693 (btf_int_encoding(mt) & BTF_INT_SIGNED);
3694 if (validate)
3695 *validate = true; /* signedness is never ambiguous */
3696 break;
3697 case BPF_FIELD_LSHIFT_U64:
3698#if __BYTE_ORDER == __LITTLE_ENDIAN
3699 *val = 64 - (bit_off + bit_sz - byte_off * 8);
3700#else
3701 *val = (8 - byte_sz) * 8 + (bit_off - byte_off * 8);
3702#endif
3703 break;
3704 case BPF_FIELD_RSHIFT_U64:
3705 *val = 64 - bit_sz;
3706 if (validate)
3707 *validate = true; /* right shift is never ambiguous */
3708 break;
3709 case BPF_FIELD_EXISTS:
3710 default:
3711 pr_warn("prog '%s': unknown relo %d at insn #%d\n",
3712 bpf_program__title(prog, false),
3713 relo->kind, relo->insn_off / 8);
3714 return -EINVAL;
3715 }
3716
3717 return 0;
3718}
3719
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003720/*
3721 * Patch relocatable BPF instruction.
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003722 *
3723 * Patched value is determined by relocation kind and target specification.
3724 * For field existence relocation target spec will be NULL if field is not
3725 * found.
3726 * Expected insn->imm value is determined using relocation kind and local
3727 * spec, and is checked before patching instruction. If actual insn->imm value
3728 * is wrong, bail out with error.
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003729 *
3730 * Currently three kinds of BPF instructions are supported:
3731 * 1. rX = <imm> (assignment with immediate operand);
3732 * 2. rX += <imm> (arithmetic operations with immediate operand);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003733 */
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003734static int bpf_core_reloc_insn(struct bpf_program *prog,
3735 const struct bpf_field_reloc *relo,
3736 const struct bpf_core_spec *local_spec,
3737 const struct bpf_core_spec *targ_spec)
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003738{
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003739 bool failed = false, validate = true;
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003740 __u32 orig_val, new_val;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003741 struct bpf_insn *insn;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003742 int insn_idx, err;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003743 __u8 class;
3744
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003745 if (relo->insn_off % sizeof(struct bpf_insn))
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003746 return -EINVAL;
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003747 insn_idx = relo->insn_off / sizeof(struct bpf_insn);
3748
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003749 if (relo->kind == BPF_FIELD_EXISTS) {
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003750 orig_val = 1; /* can't generate EXISTS relo w/o local field */
3751 new_val = targ_spec ? 1 : 0;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003752 } else if (!targ_spec) {
3753 failed = true;
3754 new_val = (__u32)-1;
3755 } else {
3756 err = bpf_core_calc_field_relo(prog, relo, local_spec,
3757 &orig_val, &validate);
3758 if (err)
3759 return err;
3760 err = bpf_core_calc_field_relo(prog, relo, targ_spec,
3761 &new_val, NULL);
3762 if (err)
3763 return err;
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003764 }
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003765
3766 insn = &prog->insns[insn_idx];
3767 class = BPF_CLASS(insn->code);
3768
3769 if (class == BPF_ALU || class == BPF_ALU64) {
3770 if (BPF_SRC(insn->code) != BPF_K)
3771 return -EINVAL;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003772 if (!failed && validate && insn->imm != orig_val) {
3773 pr_warn("prog '%s': unexpected insn #%d value: got %u, exp %u -> %u\n",
3774 bpf_program__title(prog, false), insn_idx,
3775 insn->imm, orig_val, new_val);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003776 return -EINVAL;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003777 }
3778 orig_val = insn->imm;
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003779 insn->imm = new_val;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003780 pr_debug("prog '%s': patched insn #%d (ALU/ALU64)%s imm %u -> %u\n",
3781 bpf_program__title(prog, false), insn_idx,
3782 failed ? " w/ failed reloc" : "", orig_val, new_val);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003783 } else {
Kefeng Wangbe180102019-10-21 13:55:32 +08003784 pr_warn("prog '%s': trying to relocate unrecognized insn #%d, code:%x, src:%x, dst:%x, off:%x, imm:%x\n",
3785 bpf_program__title(prog, false),
3786 insn_idx, insn->code, insn->src_reg, insn->dst_reg,
3787 insn->off, insn->imm);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003788 return -EINVAL;
3789 }
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07003790
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003791 return 0;
3792}
3793
Andrii Nakryikoa1916a12019-08-13 11:54:43 -07003794static struct btf *btf_load_raw(const char *path)
3795{
3796 struct btf *btf;
3797 size_t read_cnt;
3798 struct stat st;
3799 void *data;
3800 FILE *f;
3801
3802 if (stat(path, &st))
3803 return ERR_PTR(-errno);
3804
3805 data = malloc(st.st_size);
3806 if (!data)
3807 return ERR_PTR(-ENOMEM);
3808
3809 f = fopen(path, "rb");
3810 if (!f) {
3811 btf = ERR_PTR(-errno);
3812 goto cleanup;
3813 }
3814
3815 read_cnt = fread(data, 1, st.st_size, f);
3816 fclose(f);
3817 if (read_cnt < st.st_size) {
3818 btf = ERR_PTR(-EBADF);
3819 goto cleanup;
3820 }
3821
3822 btf = btf__new(data, read_cnt);
3823
3824cleanup:
3825 free(data);
3826 return btf;
3827}
3828
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003829/*
3830 * Probe few well-known locations for vmlinux kernel image and try to load BTF
3831 * data out of it to use for target BTF.
3832 */
3833static struct btf *bpf_core_find_kernel_btf(void)
3834{
Andrii Nakryikoa1916a12019-08-13 11:54:43 -07003835 struct {
3836 const char *path_fmt;
3837 bool raw_btf;
3838 } locations[] = {
3839 /* try canonical vmlinux BTF through sysfs first */
3840 { "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
3841 /* fall back to trying to find vmlinux ELF on disk otherwise */
3842 { "/boot/vmlinux-%1$s" },
3843 { "/lib/modules/%1$s/vmlinux-%1$s" },
3844 { "/lib/modules/%1$s/build/vmlinux" },
3845 { "/usr/lib/modules/%1$s/kernel/vmlinux" },
3846 { "/usr/lib/debug/boot/vmlinux-%1$s" },
3847 { "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
3848 { "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003849 };
3850 char path[PATH_MAX + 1];
3851 struct utsname buf;
3852 struct btf *btf;
3853 int i;
3854
3855 uname(&buf);
3856
3857 for (i = 0; i < ARRAY_SIZE(locations); i++) {
Andrii Nakryikoa1916a12019-08-13 11:54:43 -07003858 snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003859
3860 if (access(path, R_OK))
3861 continue;
3862
Andrii Nakryikoa1916a12019-08-13 11:54:43 -07003863 if (locations[i].raw_btf)
3864 btf = btf_load_raw(path);
3865 else
3866 btf = btf__parse_elf(path, NULL);
3867
3868 pr_debug("loading kernel BTF '%s': %ld\n",
3869 path, IS_ERR(btf) ? PTR_ERR(btf) : 0);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003870 if (IS_ERR(btf))
3871 continue;
3872
3873 return btf;
3874 }
3875
Kefeng Wangbe180102019-10-21 13:55:32 +08003876 pr_warn("failed to find valid kernel BTF\n");
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003877 return ERR_PTR(-ESRCH);
3878}
3879
3880/* Output spec definition in the format:
3881 * [<type-id>] (<type-name>) + <raw-spec> => <offset>@<spec>,
3882 * where <spec> is a C-syntax view of recorded field access, e.g.: x.a[3].b
3883 */
3884static void bpf_core_dump_spec(int level, const struct bpf_core_spec *spec)
3885{
3886 const struct btf_type *t;
3887 const char *s;
3888 __u32 type_id;
3889 int i;
3890
3891 type_id = spec->spec[0].type_id;
3892 t = btf__type_by_id(spec->btf, type_id);
3893 s = btf__name_by_offset(spec->btf, t->name_off);
3894 libbpf_print(level, "[%u] %s + ", type_id, s);
3895
3896 for (i = 0; i < spec->raw_len; i++)
3897 libbpf_print(level, "%d%s", spec->raw_spec[i],
3898 i == spec->raw_len - 1 ? " => " : ":");
3899
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07003900 libbpf_print(level, "%u.%u @ &x",
3901 spec->bit_offset / 8, spec->bit_offset % 8);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003902
3903 for (i = 0; i < spec->len; i++) {
3904 if (spec->spec[i].name)
3905 libbpf_print(level, ".%s", spec->spec[i].name);
3906 else
3907 libbpf_print(level, "[%u]", spec->spec[i].idx);
3908 }
3909
3910}
3911
3912static size_t bpf_core_hash_fn(const void *key, void *ctx)
3913{
3914 return (size_t)key;
3915}
3916
3917static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
3918{
3919 return k1 == k2;
3920}
3921
3922static void *u32_as_hash_key(__u32 x)
3923{
3924 return (void *)(uintptr_t)x;
3925}
3926
3927/*
3928 * CO-RE relocate single instruction.
3929 *
3930 * The outline and important points of the algorithm:
3931 * 1. For given local type, find corresponding candidate target types.
3932 * Candidate type is a type with the same "essential" name, ignoring
3933 * everything after last triple underscore (___). E.g., `sample`,
3934 * `sample___flavor_one`, `sample___flavor_another_one`, are all candidates
3935 * for each other. Names with triple underscore are referred to as
3936 * "flavors" and are useful, among other things, to allow to
3937 * specify/support incompatible variations of the same kernel struct, which
3938 * might differ between different kernel versions and/or build
3939 * configurations.
3940 *
3941 * N.B. Struct "flavors" could be generated by bpftool's BTF-to-C
3942 * converter, when deduplicated BTF of a kernel still contains more than
3943 * one different types with the same name. In that case, ___2, ___3, etc
3944 * are appended starting from second name conflict. But start flavors are
3945 * also useful to be defined "locally", in BPF program, to extract same
3946 * data from incompatible changes between different kernel
3947 * versions/configurations. For instance, to handle field renames between
3948 * kernel versions, one can use two flavors of the struct name with the
3949 * same common name and use conditional relocations to extract that field,
3950 * depending on target kernel version.
3951 * 2. For each candidate type, try to match local specification to this
3952 * candidate target type. Matching involves finding corresponding
3953 * high-level spec accessors, meaning that all named fields should match,
3954 * as well as all array accesses should be within the actual bounds. Also,
3955 * types should be compatible (see bpf_core_fields_are_compat for details).
3956 * 3. It is supported and expected that there might be multiple flavors
3957 * matching the spec. As long as all the specs resolve to the same set of
Andrii Nakryiko511bb002019-10-15 11:28:45 -07003958 * offsets across all candidates, there is no error. If there is any
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003959 * ambiguity, CO-RE relocation will fail. This is necessary to accomodate
3960 * imprefection of BTF deduplication, which can cause slight duplication of
3961 * the same BTF type, if some directly or indirectly referenced (by
3962 * pointer) type gets resolved to different actual types in different
3963 * object files. If such situation occurs, deduplicated BTF will end up
3964 * with two (or more) structurally identical types, which differ only in
3965 * types they refer to through pointer. This should be OK in most cases and
3966 * is not an error.
3967 * 4. Candidate types search is performed by linearly scanning through all
3968 * types in target BTF. It is anticipated that this is overall more
3969 * efficient memory-wise and not significantly worse (if not better)
3970 * CPU-wise compared to prebuilding a map from all local type names to
3971 * a list of candidate type names. It's also sped up by caching resolved
3972 * list of matching candidates per each local "root" type ID, that has at
Andrii Nakryiko511bb002019-10-15 11:28:45 -07003973 * least one bpf_field_reloc associated with it. This list is shared
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003974 * between multiple relocations for the same type ID and is updated as some
3975 * of the candidates are pruned due to structural incompatibility.
3976 */
Andrii Nakryiko511bb002019-10-15 11:28:45 -07003977static int bpf_core_reloc_field(struct bpf_program *prog,
3978 const struct bpf_field_reloc *relo,
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07003979 int relo_idx,
3980 const struct btf *local_btf,
3981 const struct btf *targ_btf,
3982 struct hashmap *cand_cache)
3983{
3984 const char *prog_name = bpf_program__title(prog, false);
3985 struct bpf_core_spec local_spec, cand_spec, targ_spec;
3986 const void *type_key = u32_as_hash_key(relo->type_id);
3987 const struct btf_type *local_type, *cand_type;
3988 const char *local_name, *cand_name;
3989 struct ids_vec *cand_ids;
3990 __u32 local_id, cand_id;
3991 const char *spec_str;
3992 int i, j, err;
3993
3994 local_id = relo->type_id;
3995 local_type = btf__type_by_id(local_btf, local_id);
3996 if (!local_type)
3997 return -EINVAL;
3998
3999 local_name = btf__name_by_offset(local_btf, local_type->name_off);
4000 if (str_is_empty(local_name))
4001 return -EINVAL;
4002
4003 spec_str = btf__name_by_offset(local_btf, relo->access_str_off);
4004 if (str_is_empty(spec_str))
4005 return -EINVAL;
4006
4007 err = bpf_core_spec_parse(local_btf, local_id, spec_str, &local_spec);
4008 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004009 pr_warn("prog '%s': relo #%d: parsing [%d] %s + %s failed: %d\n",
4010 prog_name, relo_idx, local_id, local_name, spec_str,
4011 err);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004012 return -EINVAL;
4013 }
4014
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07004015 pr_debug("prog '%s': relo #%d: kind %d, spec is ", prog_name, relo_idx,
4016 relo->kind);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004017 bpf_core_dump_spec(LIBBPF_DEBUG, &local_spec);
4018 libbpf_print(LIBBPF_DEBUG, "\n");
4019
4020 if (!hashmap__find(cand_cache, type_key, (void **)&cand_ids)) {
4021 cand_ids = bpf_core_find_cands(local_btf, local_id, targ_btf);
4022 if (IS_ERR(cand_ids)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004023 pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s: %ld",
4024 prog_name, relo_idx, local_id, local_name,
4025 PTR_ERR(cand_ids));
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004026 return PTR_ERR(cand_ids);
4027 }
4028 err = hashmap__set(cand_cache, type_key, cand_ids, NULL, NULL);
4029 if (err) {
4030 bpf_core_free_cands(cand_ids);
4031 return err;
4032 }
4033 }
4034
4035 for (i = 0, j = 0; i < cand_ids->len; i++) {
4036 cand_id = cand_ids->data[i];
4037 cand_type = btf__type_by_id(targ_btf, cand_id);
4038 cand_name = btf__name_by_offset(targ_btf, cand_type->name_off);
4039
4040 err = bpf_core_spec_match(&local_spec, targ_btf,
4041 cand_id, &cand_spec);
4042 pr_debug("prog '%s': relo #%d: matching candidate #%d %s against spec ",
4043 prog_name, relo_idx, i, cand_name);
4044 bpf_core_dump_spec(LIBBPF_DEBUG, &cand_spec);
4045 libbpf_print(LIBBPF_DEBUG, ": %d\n", err);
4046 if (err < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004047 pr_warn("prog '%s': relo #%d: matching error: %d\n",
4048 prog_name, relo_idx, err);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004049 return err;
4050 }
4051 if (err == 0)
4052 continue;
4053
4054 if (j == 0) {
4055 targ_spec = cand_spec;
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07004056 } else if (cand_spec.bit_offset != targ_spec.bit_offset) {
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004057 /* if there are many candidates, they should all
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07004058 * resolve to the same bit offset
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004059 */
Kefeng Wangbe180102019-10-21 13:55:32 +08004060 pr_warn("prog '%s': relo #%d: offset ambiguity: %u != %u\n",
Andrii Nakryikoee26dad2019-11-01 15:28:07 -07004061 prog_name, relo_idx, cand_spec.bit_offset,
4062 targ_spec.bit_offset);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004063 return -EINVAL;
4064 }
4065
4066 cand_ids->data[j++] = cand_spec.spec[0].type_id;
4067 }
4068
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07004069 /*
4070 * For BPF_FIELD_EXISTS relo or when relaxed CO-RE reloc mode is
4071 * requested, it's expected that we might not find any candidates.
4072 * In this case, if field wasn't found in any candidate, the list of
4073 * candidates shouldn't change at all, we'll just handle relocating
4074 * appropriately, depending on relo's kind.
4075 */
4076 if (j > 0)
4077 cand_ids->len = j;
4078
4079 if (j == 0 && !prog->obj->relaxed_core_relocs &&
4080 relo->kind != BPF_FIELD_EXISTS) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004081 pr_warn("prog '%s': relo #%d: no matching targets found for [%d] %s + %s\n",
4082 prog_name, relo_idx, local_id, local_name, spec_str);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004083 return -ESRCH;
4084 }
4085
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07004086 /* bpf_core_reloc_insn should know how to handle missing targ_spec */
4087 err = bpf_core_reloc_insn(prog, relo, &local_spec,
4088 j ? &targ_spec : NULL);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004089 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004090 pr_warn("prog '%s': relo #%d: failed to patch insn at offset %d: %d\n",
4091 prog_name, relo_idx, relo->insn_off, err);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004092 return -EINVAL;
4093 }
4094
4095 return 0;
4096}
4097
4098static int
Andrii Nakryiko511bb002019-10-15 11:28:45 -07004099bpf_core_reloc_fields(struct bpf_object *obj, const char *targ_btf_path)
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004100{
4101 const struct btf_ext_info_sec *sec;
Andrii Nakryiko511bb002019-10-15 11:28:45 -07004102 const struct bpf_field_reloc *rec;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004103 const struct btf_ext_info *seg;
4104 struct hashmap_entry *entry;
4105 struct hashmap *cand_cache = NULL;
4106 struct bpf_program *prog;
4107 struct btf *targ_btf;
4108 const char *sec_name;
4109 int i, err = 0;
4110
4111 if (targ_btf_path)
4112 targ_btf = btf__parse_elf(targ_btf_path, NULL);
4113 else
4114 targ_btf = bpf_core_find_kernel_btf();
4115 if (IS_ERR(targ_btf)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004116 pr_warn("failed to get target BTF: %ld\n", PTR_ERR(targ_btf));
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004117 return PTR_ERR(targ_btf);
4118 }
4119
4120 cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
4121 if (IS_ERR(cand_cache)) {
4122 err = PTR_ERR(cand_cache);
4123 goto out;
4124 }
4125
Andrii Nakryiko511bb002019-10-15 11:28:45 -07004126 seg = &obj->btf_ext->field_reloc_info;
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004127 for_each_btf_ext_sec(seg, sec) {
4128 sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
4129 if (str_is_empty(sec_name)) {
4130 err = -EINVAL;
4131 goto out;
4132 }
4133 prog = bpf_object__find_program_by_title(obj, sec_name);
4134 if (!prog) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004135 pr_warn("failed to find program '%s' for CO-RE offset relocation\n",
4136 sec_name);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004137 err = -EINVAL;
4138 goto out;
4139 }
4140
4141 pr_debug("prog '%s': performing %d CO-RE offset relocs\n",
4142 sec_name, sec->num_info);
4143
4144 for_each_btf_ext_rec(seg, sec, i, rec) {
Andrii Nakryiko511bb002019-10-15 11:28:45 -07004145 err = bpf_core_reloc_field(prog, rec, i, obj->btf,
4146 targ_btf, cand_cache);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004147 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004148 pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
4149 sec_name, i, err);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004150 goto out;
4151 }
4152 }
4153 }
4154
4155out:
4156 btf__free(targ_btf);
4157 if (!IS_ERR_OR_NULL(cand_cache)) {
4158 hashmap__for_each_entry(cand_cache, entry, i) {
4159 bpf_core_free_cands(entry->value);
4160 }
4161 hashmap__free(cand_cache);
4162 }
4163 return err;
4164}
4165
4166static int
4167bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
4168{
4169 int err = 0;
4170
Andrii Nakryiko511bb002019-10-15 11:28:45 -07004171 if (obj->btf_ext->field_reloc_info.len)
4172 err = bpf_core_reloc_fields(obj, targ_btf_path);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004173
4174 return err;
4175}
4176
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08004177static int
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004178bpf_program__reloc_text(struct bpf_program *prog, struct bpf_object *obj,
4179 struct reloc_desc *relo)
4180{
4181 struct bpf_insn *insn, *new_insn;
4182 struct bpf_program *text;
4183 size_t new_cnt;
Yonghong Song2993e052018-11-19 15:29:16 -08004184 int err;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004185
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004186 if (prog->idx == obj->efile.text_shndx) {
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08004187 pr_warn("relo in .text insn %d into off %d (insn #%d)\n",
4188 relo->insn_idx, relo->sym_off, relo->sym_off / 8);
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004189 return -LIBBPF_ERRNO__RELOC;
4190 }
4191
4192 if (prog->main_prog_cnt == 0) {
4193 text = bpf_object__find_prog_by_idx(obj, obj->efile.text_shndx);
4194 if (!text) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004195 pr_warn("no .text section found yet relo into text exist\n");
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004196 return -LIBBPF_ERRNO__RELOC;
4197 }
4198 new_cnt = prog->insns_cnt + text->insns_cnt;
Jakub Kicinski531b0142018-07-10 14:43:05 -07004199 new_insn = reallocarray(prog->insns, new_cnt, sizeof(*insn));
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004200 if (!new_insn) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004201 pr_warn("oom in prog realloc\n");
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004202 return -ENOMEM;
4203 }
Andrii Nakryiko3dc5e052019-11-06 18:08:51 -08004204 prog->insns = new_insn;
Yonghong Song2993e052018-11-19 15:29:16 -08004205
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08004206 if (obj->btf_ext) {
4207 err = bpf_program_reloc_btf_ext(prog, obj,
4208 text->section_name,
4209 prog->insns_cnt);
4210 if (err)
Yonghong Song2993e052018-11-19 15:29:16 -08004211 return err;
Yonghong Song2993e052018-11-19 15:29:16 -08004212 }
4213
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004214 memcpy(new_insn + prog->insns_cnt, text->insns,
4215 text->insns_cnt * sizeof(*insn));
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004216 prog->main_prog_cnt = prog->insns_cnt;
4217 prog->insns_cnt = new_cnt;
Jeremy Clineb1a2ce82018-02-20 01:00:07 +00004218 pr_debug("added %zd insn from %s to prog %s\n",
4219 text->insns_cnt, text->section_name,
4220 prog->section_name);
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004221 }
4222 insn = &prog->insns[relo->insn_idx];
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08004223 insn->imm += relo->sym_off / 8 + prog->main_prog_cnt - relo->insn_idx;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004224 return 0;
4225}
4226
4227static int
Wang Nan9d759a92015-11-27 08:47:35 +00004228bpf_program__relocate(struct bpf_program *prog, struct bpf_object *obj)
Wang Nan8a47a6c2015-07-01 02:14:05 +00004229{
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004230 int i, err;
Wang Nan8a47a6c2015-07-01 02:14:05 +00004231
Yonghong Song2993e052018-11-19 15:29:16 -08004232 if (!prog)
4233 return 0;
4234
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08004235 if (obj->btf_ext) {
4236 err = bpf_program_reloc_btf_ext(prog, obj,
4237 prog->section_name, 0);
4238 if (err)
Yonghong Song2993e052018-11-19 15:29:16 -08004239 return err;
Yonghong Song2993e052018-11-19 15:29:16 -08004240 }
4241
4242 if (!prog->reloc_desc)
Wang Nan8a47a6c2015-07-01 02:14:05 +00004243 return 0;
4244
4245 for (i = 0; i < prog->nr_reloc; i++) {
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08004246 struct reloc_desc *relo = &prog->reloc_desc[i];
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004247 struct bpf_insn *insn = &prog->insns[relo->insn_idx];
Wang Nan8a47a6c2015-07-01 02:14:05 +00004248
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004249 if (relo->insn_idx + 1 >= (int)prog->insns_cnt) {
4250 pr_warn("relocation out of range: '%s'\n",
4251 prog->section_name);
4252 return -LIBBPF_ERRNO__RELOC;
4253 }
Wang Nan8a47a6c2015-07-01 02:14:05 +00004254
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004255 switch (relo->type) {
4256 case RELO_LD64:
4257 insn[0].src_reg = BPF_PSEUDO_MAP_FD;
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08004258 insn[0].imm = obj->maps[relo->map_idx].fd;
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004259 break;
4260 case RELO_DATA:
4261 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4262 insn[1].imm = insn[0].imm + relo->sym_off;
4263 insn[0].imm = obj->maps[relo->map_idx].fd;
4264 break;
4265 case RELO_EXTERN:
4266 insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
4267 insn[0].imm = obj->maps[obj->extern_map_idx].fd;
4268 insn[1].imm = relo->sym_off;
4269 break;
4270 case RELO_CALL:
Andrii Nakryiko53f8dd42019-11-27 12:06:50 -08004271 err = bpf_program__reloc_text(prog, obj, relo);
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004272 if (err)
4273 return err;
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004274 break;
4275 default:
4276 pr_warn("relo #%d: bad relo type %d\n", i, relo->type);
4277 return -EINVAL;
Wang Nan8a47a6c2015-07-01 02:14:05 +00004278 }
Wang Nan8a47a6c2015-07-01 02:14:05 +00004279 }
4280
4281 zfree(&prog->reloc_desc);
4282 prog->nr_reloc = 0;
4283 return 0;
4284}
4285
Wang Nan8a47a6c2015-07-01 02:14:05 +00004286static int
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004287bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
Wang Nan8a47a6c2015-07-01 02:14:05 +00004288{
4289 struct bpf_program *prog;
4290 size_t i;
4291 int err;
4292
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004293 if (obj->btf_ext) {
4294 err = bpf_object__relocate_core(obj, targ_btf_path);
4295 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004296 pr_warn("failed to perform CO-RE relocations: %d\n",
4297 err);
Andrii Nakryikoddc7c302019-08-07 14:39:51 -07004298 return err;
4299 }
4300 }
Wang Nan8a47a6c2015-07-01 02:14:05 +00004301 for (i = 0; i < obj->nr_programs; i++) {
4302 prog = &obj->programs[i];
4303
Wang Nan9d759a92015-11-27 08:47:35 +00004304 err = bpf_program__relocate(prog, obj);
Wang Nan8a47a6c2015-07-01 02:14:05 +00004305 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004306 pr_warn("failed to relocate '%s'\n", prog->section_name);
Wang Nan8a47a6c2015-07-01 02:14:05 +00004307 return err;
4308 }
4309 }
4310 return 0;
4311}
4312
Wang Nan34090912015-07-01 02:14:02 +00004313static int bpf_object__collect_reloc(struct bpf_object *obj)
4314{
4315 int i, err;
4316
4317 if (!obj_elf_valid(obj)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004318 pr_warn("Internal error: elf object is closed\n");
Wang Nan6371ca3b2015-11-06 13:49:37 +00004319 return -LIBBPF_ERRNO__INTERNAL;
Wang Nan34090912015-07-01 02:14:02 +00004320 }
4321
Andrii Nakryiko1f8e2bc2019-11-20 23:07:41 -08004322 for (i = 0; i < obj->efile.nr_reloc_sects; i++) {
4323 GElf_Shdr *shdr = &obj->efile.reloc_sects[i].shdr;
4324 Elf_Data *data = obj->efile.reloc_sects[i].data;
Wang Nan34090912015-07-01 02:14:02 +00004325 int idx = shdr->sh_info;
4326 struct bpf_program *prog;
Wang Nan34090912015-07-01 02:14:02 +00004327
4328 if (shdr->sh_type != SHT_REL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004329 pr_warn("internal error at %d\n", __LINE__);
Wang Nan6371ca3b2015-11-06 13:49:37 +00004330 return -LIBBPF_ERRNO__INTERNAL;
Wang Nan34090912015-07-01 02:14:02 +00004331 }
4332
4333 prog = bpf_object__find_prog_by_idx(obj, idx);
4334 if (!prog) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004335 pr_warn("relocation failed: no section(%d)\n", idx);
Wang Nan6371ca3b2015-11-06 13:49:37 +00004336 return -LIBBPF_ERRNO__RELOC;
Wang Nan34090912015-07-01 02:14:02 +00004337 }
4338
Andrii Nakryiko399dc652019-05-29 10:36:11 -07004339 err = bpf_program__collect_reloc(prog, shdr, data, obj);
Wang Nan34090912015-07-01 02:14:02 +00004340 if (err)
Wang Nan6371ca3b2015-11-06 13:49:37 +00004341 return err;
Wang Nan34090912015-07-01 02:14:02 +00004342 }
4343 return 0;
4344}
4345
Wang Nan55cffde2015-07-01 02:14:07 +00004346static int
Yonghong Song2993e052018-11-19 15:29:16 -08004347load_program(struct bpf_program *prog, struct bpf_insn *insns, int insns_cnt,
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08004348 char *license, __u32 kern_version, int *pfd)
Wang Nan55cffde2015-07-01 02:14:07 +00004349{
Andrey Ignatovd7be1432018-03-30 15:08:01 -07004350 struct bpf_load_program_attr load_attr;
Thomas Richter1ce6a9f2018-07-30 10:53:23 +02004351 char *cp, errmsg[STRERR_BUFSIZE];
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004352 int log_buf_size = BPF_LOG_BUF_SIZE;
Wang Nan55cffde2015-07-01 02:14:07 +00004353 char *log_buf;
Andrii Nakryiko5d01ab72019-07-26 14:24:38 -07004354 int btf_fd, ret;
Wang Nan55cffde2015-07-01 02:14:07 +00004355
Andrii Nakryikofba01a02019-05-29 10:36:08 -07004356 if (!insns || !insns_cnt)
4357 return -EINVAL;
4358
Andrey Ignatovd7be1432018-03-30 15:08:01 -07004359 memset(&load_attr, 0, sizeof(struct bpf_load_program_attr));
Yonghong Song2993e052018-11-19 15:29:16 -08004360 load_attr.prog_type = prog->type;
4361 load_attr.expected_attach_type = prog->expected_attach_type;
Stanislav Fomichev5b32a232018-11-20 17:11:21 -08004362 if (prog->caps->name)
4363 load_attr.name = prog->name;
Andrey Ignatovd7be1432018-03-30 15:08:01 -07004364 load_attr.insns = insns;
4365 load_attr.insns_cnt = insns_cnt;
4366 load_attr.license = license;
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -08004367 if (prog->type == BPF_PROG_TYPE_TRACING) {
4368 load_attr.attach_prog_fd = prog->attach_prog_fd;
4369 load_attr.attach_btf_id = prog->attach_btf_id;
4370 } else {
4371 load_attr.kern_version = kern_version;
4372 load_attr.prog_ifindex = prog->prog_ifindex;
4373 }
Andrii Nakryiko3415ec62019-08-01 00:24:05 -07004374 /* if .BTF.ext was loaded, kernel supports associated BTF for prog */
4375 if (prog->obj->btf_ext)
4376 btf_fd = bpf_object__btf_fd(prog->obj);
4377 else
4378 btf_fd = -1;
Andrii Nakryiko5d01ab72019-07-26 14:24:38 -07004379 load_attr.prog_btf_fd = btf_fd >= 0 ? btf_fd : 0;
Yonghong Song2993e052018-11-19 15:29:16 -08004380 load_attr.func_info = prog->func_info;
4381 load_attr.func_info_rec_size = prog->func_info_rec_size;
Martin KaFai Lauf0187f02018-12-07 16:42:29 -08004382 load_attr.func_info_cnt = prog->func_info_cnt;
Martin KaFai Lau3d650142018-12-07 16:42:31 -08004383 load_attr.line_info = prog->line_info;
4384 load_attr.line_info_rec_size = prog->line_info_rec_size;
4385 load_attr.line_info_cnt = prog->line_info_cnt;
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004386 load_attr.log_level = prog->log_level;
Jiong Wang04656192019-05-24 23:25:19 +01004387 load_attr.prog_flags = prog->prog_flags;
Wang Nan55cffde2015-07-01 02:14:07 +00004388
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004389retry_load:
4390 log_buf = malloc(log_buf_size);
Wang Nan55cffde2015-07-01 02:14:07 +00004391 if (!log_buf)
Kefeng Wangbe180102019-10-21 13:55:32 +08004392 pr_warn("Alloc log buffer for bpf loader error, continue without log\n");
Wang Nan55cffde2015-07-01 02:14:07 +00004393
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004394 ret = bpf_load_program_xattr(&load_attr, log_buf, log_buf_size);
Wang Nan55cffde2015-07-01 02:14:07 +00004395
4396 if (ret >= 0) {
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004397 if (load_attr.log_level)
4398 pr_debug("verifier log:\n%s", log_buf);
Wang Nan55cffde2015-07-01 02:14:07 +00004399 *pfd = ret;
4400 ret = 0;
4401 goto out;
4402 }
4403
Alexei Starovoitovda11b412019-04-01 21:27:47 -07004404 if (errno == ENOSPC) {
4405 log_buf_size <<= 1;
4406 free(log_buf);
4407 goto retry_load;
4408 }
Toke Høiland-Jørgensen4f33ddb2019-11-09 21:37:29 +01004409 ret = -errno;
Andrey Ignatov24d6a802018-10-03 15:26:41 -07004410 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08004411 pr_warn("load bpf program failed: %s\n", cp);
Toke Høiland-Jørgensendc3a2d22019-12-16 19:12:04 +01004412 pr_perm_msg(ret);
Wang Nan55cffde2015-07-01 02:14:07 +00004413
Wang Nan6371ca3b2015-11-06 13:49:37 +00004414 if (log_buf && log_buf[0] != '\0') {
4415 ret = -LIBBPF_ERRNO__VERIFY;
Kefeng Wangbe180102019-10-21 13:55:32 +08004416 pr_warn("-- BEGIN DUMP LOG ---\n");
4417 pr_warn("\n%s\n", log_buf);
4418 pr_warn("-- END LOG --\n");
Andrey Ignatovd7be1432018-03-30 15:08:01 -07004419 } else if (load_attr.insns_cnt >= BPF_MAXINSNS) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004420 pr_warn("Program too large (%zu insns), at most %d insns\n",
4421 load_attr.insns_cnt, BPF_MAXINSNS);
Wang Nan705fa212016-07-13 10:44:02 +00004422 ret = -LIBBPF_ERRNO__PROG2BIG;
Toke Høiland-Jørgensen4f33ddb2019-11-09 21:37:29 +01004423 } else if (load_attr.prog_type != BPF_PROG_TYPE_KPROBE) {
Wang Nan705fa212016-07-13 10:44:02 +00004424 /* Wrong program type? */
Toke Høiland-Jørgensen4f33ddb2019-11-09 21:37:29 +01004425 int fd;
Wang Nan705fa212016-07-13 10:44:02 +00004426
Toke Høiland-Jørgensen4f33ddb2019-11-09 21:37:29 +01004427 load_attr.prog_type = BPF_PROG_TYPE_KPROBE;
4428 load_attr.expected_attach_type = 0;
4429 fd = bpf_load_program_xattr(&load_attr, NULL, 0);
4430 if (fd >= 0) {
4431 close(fd);
4432 ret = -LIBBPF_ERRNO__PROGTYPE;
4433 goto out;
Wang Nan6371ca3b2015-11-06 13:49:37 +00004434 }
Wang Nan55cffde2015-07-01 02:14:07 +00004435 }
4436
4437out:
4438 free(log_buf);
4439 return ret;
4440}
4441
Andrii Nakryiko13acb502019-12-13 17:43:34 -08004442static int libbpf_find_attach_btf_id(const char *name,
4443 enum bpf_attach_type attach_type,
4444 __u32 attach_prog_fd);
4445
4446int bpf_program__load(struct bpf_program *prog, char *license, __u32 kern_ver)
Wang Nan55cffde2015-07-01 02:14:07 +00004447{
Andrii Nakryiko13acb502019-12-13 17:43:34 -08004448 int err = 0, fd, i, btf_id;
4449
4450 if (prog->type == BPF_PROG_TYPE_TRACING) {
4451 btf_id = libbpf_find_attach_btf_id(prog->section_name,
4452 prog->expected_attach_type,
4453 prog->attach_prog_fd);
4454 if (btf_id <= 0)
4455 return btf_id;
4456 prog->attach_btf_id = btf_id;
4457 }
Wang Nan55cffde2015-07-01 02:14:07 +00004458
Wang Nanb5805632015-11-16 12:10:09 +00004459 if (prog->instances.nr < 0 || !prog->instances.fds) {
4460 if (prog->preprocessor) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004461 pr_warn("Internal error: can't load program '%s'\n",
4462 prog->section_name);
Wang Nanb5805632015-11-16 12:10:09 +00004463 return -LIBBPF_ERRNO__INTERNAL;
4464 }
Wang Nan55cffde2015-07-01 02:14:07 +00004465
Wang Nanb5805632015-11-16 12:10:09 +00004466 prog->instances.fds = malloc(sizeof(int));
4467 if (!prog->instances.fds) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004468 pr_warn("Not enough memory for BPF fds\n");
Wang Nanb5805632015-11-16 12:10:09 +00004469 return -ENOMEM;
4470 }
4471 prog->instances.nr = 1;
4472 prog->instances.fds[0] = -1;
4473 }
4474
4475 if (!prog->preprocessor) {
4476 if (prog->instances.nr != 1) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004477 pr_warn("Program '%s' is inconsistent: nr(%d) != 1\n",
4478 prog->section_name, prog->instances.nr);
Wang Nanb5805632015-11-16 12:10:09 +00004479 }
Yonghong Song2993e052018-11-19 15:29:16 -08004480 err = load_program(prog, prog->insns, prog->insns_cnt,
Andrii Nakryiko13acb502019-12-13 17:43:34 -08004481 license, kern_ver, &fd);
Wang Nanb5805632015-11-16 12:10:09 +00004482 if (!err)
4483 prog->instances.fds[0] = fd;
4484 goto out;
4485 }
4486
4487 for (i = 0; i < prog->instances.nr; i++) {
4488 struct bpf_prog_prep_result result;
4489 bpf_program_prep_t preprocessor = prog->preprocessor;
4490
Andrii Nakryiko1ad9cbb2019-02-13 10:25:53 -08004491 memset(&result, 0, sizeof(result));
Wang Nanb5805632015-11-16 12:10:09 +00004492 err = preprocessor(prog, i, prog->insns,
4493 prog->insns_cnt, &result);
4494 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004495 pr_warn("Preprocessing the %dth instance of program '%s' failed\n",
4496 i, prog->section_name);
Wang Nanb5805632015-11-16 12:10:09 +00004497 goto out;
4498 }
4499
4500 if (!result.new_insn_ptr || !result.new_insn_cnt) {
4501 pr_debug("Skip loading the %dth instance of program '%s'\n",
4502 i, prog->section_name);
4503 prog->instances.fds[i] = -1;
4504 if (result.pfd)
4505 *result.pfd = -1;
4506 continue;
4507 }
4508
Yonghong Song2993e052018-11-19 15:29:16 -08004509 err = load_program(prog, result.new_insn_ptr,
Andrii Nakryiko13acb502019-12-13 17:43:34 -08004510 result.new_insn_cnt, license, kern_ver, &fd);
Wang Nanb5805632015-11-16 12:10:09 +00004511 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004512 pr_warn("Loading the %dth instance of program '%s' failed\n",
4513 i, prog->section_name);
Wang Nanb5805632015-11-16 12:10:09 +00004514 goto out;
4515 }
4516
4517 if (result.pfd)
4518 *result.pfd = fd;
4519 prog->instances.fds[i] = fd;
4520 }
4521out:
Wang Nan55cffde2015-07-01 02:14:07 +00004522 if (err)
Kefeng Wangbe180102019-10-21 13:55:32 +08004523 pr_warn("failed to load program '%s'\n", prog->section_name);
Wang Nan55cffde2015-07-01 02:14:07 +00004524 zfree(&prog->insns);
4525 prog->insns_cnt = 0;
4526 return err;
4527}
4528
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07004529static bool bpf_program__is_function_storage(const struct bpf_program *prog,
4530 const struct bpf_object *obj)
Jakub Kicinski9a94f272018-06-28 14:41:38 -07004531{
4532 return prog->idx == obj->efile.text_shndx && obj->has_pseudo_calls;
4533}
4534
Wang Nan55cffde2015-07-01 02:14:07 +00004535static int
Quentin Monnet60276f92019-05-24 11:36:47 +01004536bpf_object__load_progs(struct bpf_object *obj, int log_level)
Wang Nan55cffde2015-07-01 02:14:07 +00004537{
4538 size_t i;
4539 int err;
4540
4541 for (i = 0; i < obj->nr_programs; i++) {
Jakub Kicinski9a94f272018-06-28 14:41:38 -07004542 if (bpf_program__is_function_storage(&obj->programs[i], obj))
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08004543 continue;
Quentin Monnet501b1252019-05-29 15:26:41 +01004544 obj->programs[i].log_level |= log_level;
Wang Nan55cffde2015-07-01 02:14:07 +00004545 err = bpf_program__load(&obj->programs[i],
4546 obj->license,
4547 obj->kern_version);
4548 if (err)
4549 return err;
4550 }
4551 return 0;
4552}
4553
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004554static struct bpf_object *
Andrii Nakryiko5e61f272019-10-04 15:40:34 -07004555__bpf_object__open(const char *path, const void *obj_buf, size_t obj_buf_sz,
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08004556 const struct bpf_object_open_opts *opts)
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004557{
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004558 const char *obj_name, *kconfig_path;
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07004559 struct bpf_program *prog;
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004560 struct bpf_object *obj;
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004561 char tmp_name[64];
Wang Nan6371ca3b2015-11-06 13:49:37 +00004562 int err;
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004563
4564 if (elf_version(EV_CURRENT) == EV_NONE) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004565 pr_warn("failed to init libelf for %s\n",
4566 path ? : "(mem buf)");
Wang Nan6371ca3b2015-11-06 13:49:37 +00004567 return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004568 }
4569
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004570 if (!OPTS_VALID(opts, bpf_object_open_opts))
4571 return ERR_PTR(-EINVAL);
4572
Andrii Nakryiko1aace102019-11-21 16:35:27 -08004573 obj_name = OPTS_GET(opts, object_name, NULL);
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004574 if (obj_buf) {
4575 if (!obj_name) {
4576 snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
4577 (unsigned long)obj_buf,
4578 (unsigned long)obj_buf_sz);
4579 obj_name = tmp_name;
4580 }
4581 path = obj_name;
4582 pr_debug("loading object '%s' from buffer\n", obj_name);
4583 }
4584
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004585 obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
Wang Nan6371ca3b2015-11-06 13:49:37 +00004586 if (IS_ERR(obj))
4587 return obj;
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004588
Andrii Nakryiko62561eb2019-10-15 11:28:47 -07004589 obj->relaxed_core_relocs = OPTS_GET(opts, relaxed_core_relocs, false);
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004590 kconfig_path = OPTS_GET(opts, kconfig_path, NULL);
4591 if (kconfig_path) {
4592 obj->kconfig_path = strdup(kconfig_path);
4593 if (!obj->kconfig_path)
4594 return ERR_PTR(-ENOMEM);
4595 }
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004596
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08004597 err = bpf_object__elf_init(obj);
4598 err = err ? : bpf_object__check_endianness(obj);
4599 err = err ? : bpf_object__elf_collect(obj);
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004600 err = err ? : bpf_object__collect_externs(obj);
4601 err = err ? : bpf_object__finalize_btf(obj);
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08004602 err = err ? : bpf_object__init_maps(obj, opts);
4603 err = err ? : bpf_object__init_prog_names(obj);
4604 err = err ? : bpf_object__collect_reloc(obj);
4605 if (err)
4606 goto out;
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004607 bpf_object__elf_finish(obj);
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07004608
4609 bpf_object__for_each_program(prog, obj) {
4610 enum bpf_prog_type prog_type;
4611 enum bpf_attach_type attach_type;
4612
4613 err = libbpf_prog_type_by_name(prog->section_name, &prog_type,
4614 &attach_type);
4615 if (err == -ESRCH)
4616 /* couldn't guess, but user might manually specify */
4617 continue;
4618 if (err)
4619 goto out;
4620
4621 bpf_program__set_type(prog, prog_type);
4622 bpf_program__set_expected_attach_type(prog, attach_type);
Andrii Nakryiko13acb502019-12-13 17:43:34 -08004623 if (prog_type == BPF_PROG_TYPE_TRACING)
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004624 prog->attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07004625 }
4626
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004627 return obj;
4628out:
4629 bpf_object__close(obj);
Wang Nan6371ca3b2015-11-06 13:49:37 +00004630 return ERR_PTR(err);
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004631}
4632
Andrii Nakryiko5e61f272019-10-04 15:40:34 -07004633static struct bpf_object *
4634__bpf_object__open_xattr(struct bpf_object_open_attr *attr, int flags)
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004635{
Andrii Nakryikoe00aca62019-10-22 10:21:00 -07004636 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004637 .relaxed_maps = flags & MAPS_RELAX_COMPAT,
4638 );
4639
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004640 /* param validation */
Jakub Kicinski07f2d4e2018-07-10 14:43:02 -07004641 if (!attr->file)
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004642 return NULL;
4643
Jakub Kicinski07f2d4e2018-07-10 14:43:02 -07004644 pr_debug("loading %s\n", attr->file);
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004645 return __bpf_object__open(attr->file, NULL, 0, &opts);
John Fastabendc034a172018-10-15 11:19:55 -07004646}
4647
4648struct bpf_object *bpf_object__open_xattr(struct bpf_object_open_attr *attr)
4649{
4650 return __bpf_object__open_xattr(attr, 0);
Jakub Kicinski07f2d4e2018-07-10 14:43:02 -07004651}
4652
4653struct bpf_object *bpf_object__open(const char *path)
4654{
4655 struct bpf_object_open_attr attr = {
4656 .file = path,
4657 .prog_type = BPF_PROG_TYPE_UNSPEC,
4658 };
4659
4660 return bpf_object__open_xattr(&attr);
Wang Nan6c956392015-07-01 02:13:54 +00004661}
4662
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004663struct bpf_object *
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08004664bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004665{
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004666 if (!path)
4667 return ERR_PTR(-EINVAL);
4668
4669 pr_debug("loading %s\n", path);
4670
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004671 return __bpf_object__open(path, NULL, 0, opts);
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004672}
4673
4674struct bpf_object *
4675bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08004676 const struct bpf_object_open_opts *opts)
Wang Nan6c956392015-07-01 02:13:54 +00004677{
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004678 if (!obj_buf || obj_buf_sz == 0)
4679 return ERR_PTR(-EINVAL);
Wang Nan6c956392015-07-01 02:13:54 +00004680
Andrii Nakryiko291ee022019-10-15 11:28:46 -07004681 return __bpf_object__open(NULL, obj_buf, obj_buf_sz, opts);
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004682}
4683
4684struct bpf_object *
4685bpf_object__open_buffer(const void *obj_buf, size_t obj_buf_sz,
4686 const char *name)
4687{
Andrii Nakryikoe00aca62019-10-22 10:21:00 -07004688 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts,
Andrii Nakryiko2ce84502019-10-04 15:40:35 -07004689 .object_name = name,
4690 /* wrong default, but backwards-compatible */
4691 .relaxed_maps = true,
4692 );
4693
4694 /* returning NULL is wrong, but backwards-compatible */
4695 if (!obj_buf || obj_buf_sz == 0)
4696 return NULL;
4697
4698 return bpf_object__open_mem(obj_buf, obj_buf_sz, &opts);
Wang Nan1a5e3fb2015-07-01 02:13:53 +00004699}
4700
Wang Nan52d33522015-07-01 02:14:04 +00004701int bpf_object__unload(struct bpf_object *obj)
4702{
4703 size_t i;
4704
4705 if (!obj)
4706 return -EINVAL;
4707
Wang Nan9d759a92015-11-27 08:47:35 +00004708 for (i = 0; i < obj->nr_maps; i++)
4709 zclose(obj->maps[i].fd);
Wang Nan52d33522015-07-01 02:14:04 +00004710
Wang Nan55cffde2015-07-01 02:14:07 +00004711 for (i = 0; i < obj->nr_programs; i++)
4712 bpf_program__unload(&obj->programs[i]);
4713
Wang Nan52d33522015-07-01 02:14:04 +00004714 return 0;
4715}
4716
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08004717static int bpf_object__sanitize_maps(struct bpf_object *obj)
4718{
4719 struct bpf_map *m;
4720
4721 bpf_object__for_each_map(m, obj) {
4722 if (!bpf_map__is_internal(m))
4723 continue;
4724 if (!obj->caps.global_data) {
4725 pr_warn("kernel doesn't support global data\n");
4726 return -ENOTSUP;
4727 }
4728 if (!obj->caps.array_mmap)
4729 m->def.map_flags ^= BPF_F_MMAPABLE;
4730 }
4731
4732 return 0;
4733}
4734
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004735static int bpf_object__resolve_externs(struct bpf_object *obj,
4736 const char *config_path)
4737{
4738 bool need_config = false;
4739 struct extern_desc *ext;
4740 int err, i;
4741 void *data;
4742
4743 if (obj->nr_extern == 0)
4744 return 0;
4745
4746 data = obj->maps[obj->extern_map_idx].mmaped;
4747
4748 for (i = 0; i < obj->nr_extern; i++) {
4749 ext = &obj->externs[i];
4750
4751 if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
4752 void *ext_val = data + ext->data_off;
4753 __u32 kver = get_kernel_version();
4754
4755 if (!kver) {
4756 pr_warn("failed to get kernel version\n");
4757 return -EINVAL;
4758 }
4759 err = set_ext_value_num(ext, ext_val, kver);
4760 if (err)
4761 return err;
4762 pr_debug("extern %s=0x%x\n", ext->name, kver);
4763 } else if (strncmp(ext->name, "CONFIG_", 7) == 0) {
4764 need_config = true;
4765 } else {
4766 pr_warn("unrecognized extern '%s'\n", ext->name);
4767 return -EINVAL;
4768 }
4769 }
4770 if (need_config) {
4771 err = bpf_object__read_kernel_config(obj, config_path, data);
4772 if (err)
4773 return -EINVAL;
4774 }
4775 for (i = 0; i < obj->nr_extern; i++) {
4776 ext = &obj->externs[i];
4777
4778 if (!ext->is_set && !ext->is_weak) {
4779 pr_warn("extern %s (strong) not resolved\n", ext->name);
4780 return -ESRCH;
4781 } else if (!ext->is_set) {
4782 pr_debug("extern %s (weak) not resolved, defaulting to zero\n",
4783 ext->name);
4784 }
4785 }
4786
4787 return 0;
4788}
4789
Quentin Monnet60276f92019-05-24 11:36:47 +01004790int bpf_object__load_xattr(struct bpf_object_load_attr *attr)
Wang Nan52d33522015-07-01 02:14:04 +00004791{
Quentin Monnet60276f92019-05-24 11:36:47 +01004792 struct bpf_object *obj;
Toke Høiland-Jørgensenec6d5f472019-11-09 21:37:27 +01004793 int err, i;
Wang Nan6371ca3b2015-11-06 13:49:37 +00004794
Quentin Monnet60276f92019-05-24 11:36:47 +01004795 if (!attr)
4796 return -EINVAL;
4797 obj = attr->obj;
Wang Nan52d33522015-07-01 02:14:04 +00004798 if (!obj)
4799 return -EINVAL;
4800
4801 if (obj->loaded) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004802 pr_warn("object should not be loaded twice\n");
Wang Nan52d33522015-07-01 02:14:04 +00004803 return -EINVAL;
4804 }
4805
4806 obj->loaded = true;
Wang Nan6371ca3b2015-11-06 13:49:37 +00004807
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08004808 err = bpf_object__probe_caps(obj);
Andrii Nakryiko166750b2019-12-13 17:47:08 -08004809 err = err ? : bpf_object__resolve_externs(obj, obj->kconfig_path);
Andrii Nakryiko0d13bfc2019-12-13 17:43:25 -08004810 err = err ? : bpf_object__sanitize_and_load_btf(obj);
4811 err = err ? : bpf_object__sanitize_maps(obj);
4812 err = err ? : bpf_object__create_maps(obj);
4813 err = err ? : bpf_object__relocate(obj, attr->target_btf_path);
4814 err = err ? : bpf_object__load_progs(obj, attr->log_level);
4815 if (err)
4816 goto out;
Wang Nan52d33522015-07-01 02:14:04 +00004817
4818 return 0;
4819out:
Toke Høiland-Jørgensenec6d5f472019-11-09 21:37:27 +01004820 /* unpin any maps that were auto-pinned during load */
4821 for (i = 0; i < obj->nr_maps; i++)
4822 if (obj->maps[i].pinned && !obj->maps[i].reused)
4823 bpf_map__unpin(&obj->maps[i], NULL);
4824
Wang Nan52d33522015-07-01 02:14:04 +00004825 bpf_object__unload(obj);
Kefeng Wangbe180102019-10-21 13:55:32 +08004826 pr_warn("failed to load object '%s'\n", obj->path);
Wang Nan6371ca3b2015-11-06 13:49:37 +00004827 return err;
Wang Nan52d33522015-07-01 02:14:04 +00004828}
4829
Quentin Monnet60276f92019-05-24 11:36:47 +01004830int bpf_object__load(struct bpf_object *obj)
4831{
4832 struct bpf_object_load_attr attr = {
4833 .obj = obj,
4834 };
4835
4836 return bpf_object__load_xattr(&attr);
4837}
4838
Toke Høiland-Jørgensen196f8482019-11-02 12:09:39 +01004839static int make_parent_dir(const char *path)
4840{
4841 char *cp, errmsg[STRERR_BUFSIZE];
4842 char *dname, *dir;
4843 int err = 0;
4844
4845 dname = strdup(path);
4846 if (dname == NULL)
4847 return -ENOMEM;
4848
4849 dir = dirname(dname);
4850 if (mkdir(dir, 0700) && errno != EEXIST)
4851 err = -errno;
4852
4853 free(dname);
4854 if (err) {
4855 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4856 pr_warn("failed to mkdir %s: %s\n", path, cp);
4857 }
4858 return err;
4859}
4860
Joe Stringerf3675402017-01-26 13:19:56 -08004861static int check_path(const char *path)
4862{
Thomas Richter1ce6a9f2018-07-30 10:53:23 +02004863 char *cp, errmsg[STRERR_BUFSIZE];
Joe Stringerf3675402017-01-26 13:19:56 -08004864 struct statfs st_fs;
4865 char *dname, *dir;
4866 int err = 0;
4867
4868 if (path == NULL)
4869 return -EINVAL;
4870
4871 dname = strdup(path);
4872 if (dname == NULL)
4873 return -ENOMEM;
4874
4875 dir = dirname(dname);
4876 if (statfs(dir, &st_fs)) {
Andrey Ignatov24d6a802018-10-03 15:26:41 -07004877 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08004878 pr_warn("failed to statfs %s: %s\n", dir, cp);
Joe Stringerf3675402017-01-26 13:19:56 -08004879 err = -errno;
4880 }
4881 free(dname);
4882
4883 if (!err && st_fs.f_type != BPF_FS_MAGIC) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004884 pr_warn("specified path %s is not on BPF FS\n", path);
Joe Stringerf3675402017-01-26 13:19:56 -08004885 err = -EINVAL;
4886 }
4887
4888 return err;
4889}
4890
4891int bpf_program__pin_instance(struct bpf_program *prog, const char *path,
4892 int instance)
4893{
Thomas Richter1ce6a9f2018-07-30 10:53:23 +02004894 char *cp, errmsg[STRERR_BUFSIZE];
Joe Stringerf3675402017-01-26 13:19:56 -08004895 int err;
4896
Toke Høiland-Jørgensen196f8482019-11-02 12:09:39 +01004897 err = make_parent_dir(path);
4898 if (err)
4899 return err;
4900
Joe Stringerf3675402017-01-26 13:19:56 -08004901 err = check_path(path);
4902 if (err)
4903 return err;
4904
4905 if (prog == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004906 pr_warn("invalid program pointer\n");
Joe Stringerf3675402017-01-26 13:19:56 -08004907 return -EINVAL;
4908 }
4909
4910 if (instance < 0 || instance >= prog->instances.nr) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004911 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4912 instance, prog->section_name, prog->instances.nr);
Joe Stringerf3675402017-01-26 13:19:56 -08004913 return -EINVAL;
4914 }
4915
4916 if (bpf_obj_pin(prog->instances.fds[instance], path)) {
Andrey Ignatov24d6a802018-10-03 15:26:41 -07004917 cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
Kefeng Wangbe180102019-10-21 13:55:32 +08004918 pr_warn("failed to pin program: %s\n", cp);
Joe Stringerf3675402017-01-26 13:19:56 -08004919 return -errno;
4920 }
4921 pr_debug("pinned program '%s'\n", path);
4922
4923 return 0;
4924}
4925
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08004926int bpf_program__unpin_instance(struct bpf_program *prog, const char *path,
4927 int instance)
4928{
4929 int err;
4930
4931 err = check_path(path);
4932 if (err)
4933 return err;
4934
4935 if (prog == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004936 pr_warn("invalid program pointer\n");
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08004937 return -EINVAL;
4938 }
4939
4940 if (instance < 0 || instance >= prog->instances.nr) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004941 pr_warn("invalid prog instance %d of prog %s (max %d)\n",
4942 instance, prog->section_name, prog->instances.nr);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08004943 return -EINVAL;
4944 }
4945
4946 err = unlink(path);
4947 if (err != 0)
4948 return -errno;
4949 pr_debug("unpinned program '%s'\n", path);
4950
4951 return 0;
4952}
4953
Joe Stringerf3675402017-01-26 13:19:56 -08004954int bpf_program__pin(struct bpf_program *prog, const char *path)
4955{
4956 int i, err;
4957
Toke Høiland-Jørgensen196f8482019-11-02 12:09:39 +01004958 err = make_parent_dir(path);
4959 if (err)
4960 return err;
4961
Joe Stringerf3675402017-01-26 13:19:56 -08004962 err = check_path(path);
4963 if (err)
4964 return err;
4965
4966 if (prog == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004967 pr_warn("invalid program pointer\n");
Joe Stringerf3675402017-01-26 13:19:56 -08004968 return -EINVAL;
4969 }
4970
4971 if (prog->instances.nr <= 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08004972 pr_warn("no instances of prog %s to pin\n",
Joe Stringerf3675402017-01-26 13:19:56 -08004973 prog->section_name);
4974 return -EINVAL;
4975 }
4976
Stanislav Fomichevfd734c52018-11-09 08:21:42 -08004977 if (prog->instances.nr == 1) {
4978 /* don't create subdirs when pinning single instance */
4979 return bpf_program__pin_instance(prog, path, 0);
4980 }
4981
Joe Stringerf3675402017-01-26 13:19:56 -08004982 for (i = 0; i < prog->instances.nr; i++) {
4983 char buf[PATH_MAX];
4984 int len;
4985
4986 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08004987 if (len < 0) {
4988 err = -EINVAL;
4989 goto err_unpin;
4990 } else if (len >= PATH_MAX) {
4991 err = -ENAMETOOLONG;
4992 goto err_unpin;
4993 }
4994
4995 err = bpf_program__pin_instance(prog, buf, i);
4996 if (err)
4997 goto err_unpin;
4998 }
4999
5000 return 0;
5001
5002err_unpin:
5003 for (i = i - 1; i >= 0; i--) {
5004 char buf[PATH_MAX];
5005 int len;
5006
5007 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
5008 if (len < 0)
5009 continue;
5010 else if (len >= PATH_MAX)
5011 continue;
5012
5013 bpf_program__unpin_instance(prog, buf, i);
5014 }
5015
5016 rmdir(path);
5017
5018 return err;
5019}
5020
5021int bpf_program__unpin(struct bpf_program *prog, const char *path)
5022{
5023 int i, err;
5024
5025 err = check_path(path);
5026 if (err)
5027 return err;
5028
5029 if (prog == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005030 pr_warn("invalid program pointer\n");
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005031 return -EINVAL;
5032 }
5033
5034 if (prog->instances.nr <= 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005035 pr_warn("no instances of prog %s to pin\n",
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005036 prog->section_name);
5037 return -EINVAL;
5038 }
5039
Stanislav Fomichevfd734c52018-11-09 08:21:42 -08005040 if (prog->instances.nr == 1) {
5041 /* don't create subdirs when pinning single instance */
5042 return bpf_program__unpin_instance(prog, path, 0);
5043 }
5044
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005045 for (i = 0; i < prog->instances.nr; i++) {
5046 char buf[PATH_MAX];
5047 int len;
5048
5049 len = snprintf(buf, PATH_MAX, "%s/%d", path, i);
Joe Stringerf3675402017-01-26 13:19:56 -08005050 if (len < 0)
5051 return -EINVAL;
5052 else if (len >= PATH_MAX)
5053 return -ENAMETOOLONG;
5054
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005055 err = bpf_program__unpin_instance(prog, buf, i);
Joe Stringerf3675402017-01-26 13:19:56 -08005056 if (err)
5057 return err;
5058 }
5059
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005060 err = rmdir(path);
5061 if (err)
5062 return -errno;
5063
Joe Stringerf3675402017-01-26 13:19:56 -08005064 return 0;
5065}
5066
Joe Stringerb6989f32017-01-26 13:19:57 -08005067int bpf_map__pin(struct bpf_map *map, const char *path)
5068{
Thomas Richter1ce6a9f2018-07-30 10:53:23 +02005069 char *cp, errmsg[STRERR_BUFSIZE];
Joe Stringerb6989f32017-01-26 13:19:57 -08005070 int err;
5071
Joe Stringerb6989f32017-01-26 13:19:57 -08005072 if (map == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005073 pr_warn("invalid map pointer\n");
Joe Stringerb6989f32017-01-26 13:19:57 -08005074 return -EINVAL;
5075 }
5076
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005077 if (map->pin_path) {
5078 if (path && strcmp(path, map->pin_path)) {
5079 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5080 bpf_map__name(map), map->pin_path, path);
5081 return -EINVAL;
5082 } else if (map->pinned) {
5083 pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
5084 bpf_map__name(map), map->pin_path);
5085 return 0;
5086 }
5087 } else {
5088 if (!path) {
5089 pr_warn("missing a path to pin map '%s' at\n",
5090 bpf_map__name(map));
5091 return -EINVAL;
5092 } else if (map->pinned) {
5093 pr_warn("map '%s' already pinned\n", bpf_map__name(map));
5094 return -EEXIST;
5095 }
5096
5097 map->pin_path = strdup(path);
5098 if (!map->pin_path) {
5099 err = -errno;
5100 goto out_err;
5101 }
Joe Stringerb6989f32017-01-26 13:19:57 -08005102 }
5103
Toke Høiland-Jørgensen196f8482019-11-02 12:09:39 +01005104 err = make_parent_dir(map->pin_path);
5105 if (err)
5106 return err;
5107
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005108 err = check_path(map->pin_path);
5109 if (err)
5110 return err;
5111
5112 if (bpf_obj_pin(map->fd, map->pin_path)) {
5113 err = -errno;
5114 goto out_err;
5115 }
5116
5117 map->pinned = true;
5118 pr_debug("pinned map '%s'\n", map->pin_path);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005119
Joe Stringerb6989f32017-01-26 13:19:57 -08005120 return 0;
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005121
5122out_err:
5123 cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5124 pr_warn("failed to pin map: %s\n", cp);
5125 return err;
Joe Stringerb6989f32017-01-26 13:19:57 -08005126}
5127
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005128int bpf_map__unpin(struct bpf_map *map, const char *path)
Joe Stringerd5148d82017-01-26 13:19:58 -08005129{
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005130 int err;
5131
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005132 if (map == NULL) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005133 pr_warn("invalid map pointer\n");
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005134 return -EINVAL;
5135 }
5136
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005137 if (map->pin_path) {
5138 if (path && strcmp(path, map->pin_path)) {
5139 pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
5140 bpf_map__name(map), map->pin_path, path);
5141 return -EINVAL;
5142 }
5143 path = map->pin_path;
5144 } else if (!path) {
5145 pr_warn("no path to unpin map '%s' from\n",
5146 bpf_map__name(map));
5147 return -EINVAL;
5148 }
5149
5150 err = check_path(path);
5151 if (err)
5152 return err;
5153
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005154 err = unlink(path);
5155 if (err != 0)
5156 return -errno;
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005157
5158 map->pinned = false;
5159 pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005160
5161 return 0;
5162}
5163
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005164int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
5165{
5166 char *new = NULL;
5167
5168 if (path) {
5169 new = strdup(path);
5170 if (!new)
5171 return -errno;
5172 }
5173
5174 free(map->pin_path);
5175 map->pin_path = new;
5176 return 0;
5177}
5178
5179const char *bpf_map__get_pin_path(const struct bpf_map *map)
5180{
5181 return map->pin_path;
5182}
5183
5184bool bpf_map__is_pinned(const struct bpf_map *map)
5185{
5186 return map->pinned;
5187}
5188
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005189int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
5190{
Joe Stringerd5148d82017-01-26 13:19:58 -08005191 struct bpf_map *map;
5192 int err;
5193
5194 if (!obj)
5195 return -ENOENT;
5196
5197 if (!obj->loaded) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005198 pr_warn("object not yet loaded; load it first\n");
Joe Stringerd5148d82017-01-26 13:19:58 -08005199 return -ENOENT;
5200 }
5201
Jakub Kicinskif74a53d92019-02-27 19:04:12 -08005202 bpf_object__for_each_map(map, obj) {
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005203 char *pin_path = NULL;
Joe Stringerd5148d82017-01-26 13:19:58 -08005204 char buf[PATH_MAX];
Joe Stringerd5148d82017-01-26 13:19:58 -08005205
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005206 if (path) {
5207 int len;
5208
5209 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5210 bpf_map__name(map));
5211 if (len < 0) {
5212 err = -EINVAL;
5213 goto err_unpin_maps;
5214 } else if (len >= PATH_MAX) {
5215 err = -ENAMETOOLONG;
5216 goto err_unpin_maps;
5217 }
5218 pin_path = buf;
5219 } else if (!map->pin_path) {
5220 continue;
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005221 }
5222
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005223 err = bpf_map__pin(map, pin_path);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005224 if (err)
5225 goto err_unpin_maps;
5226 }
5227
5228 return 0;
5229
5230err_unpin_maps:
5231 while ((map = bpf_map__prev(map, obj))) {
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005232 if (!map->pin_path)
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005233 continue;
5234
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005235 bpf_map__unpin(map, NULL);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005236 }
5237
5238 return err;
5239}
5240
5241int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
5242{
5243 struct bpf_map *map;
5244 int err;
5245
5246 if (!obj)
5247 return -ENOENT;
5248
Jakub Kicinskif74a53d92019-02-27 19:04:12 -08005249 bpf_object__for_each_map(map, obj) {
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005250 char *pin_path = NULL;
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005251 char buf[PATH_MAX];
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005252
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005253 if (path) {
5254 int len;
Joe Stringerd5148d82017-01-26 13:19:58 -08005255
Toke Høiland-Jørgensen4580b252019-11-02 12:09:38 +01005256 len = snprintf(buf, PATH_MAX, "%s/%s", path,
5257 bpf_map__name(map));
5258 if (len < 0)
5259 return -EINVAL;
5260 else if (len >= PATH_MAX)
5261 return -ENAMETOOLONG;
5262 pin_path = buf;
5263 } else if (!map->pin_path) {
5264 continue;
5265 }
5266
5267 err = bpf_map__unpin(map, pin_path);
Joe Stringerd5148d82017-01-26 13:19:58 -08005268 if (err)
5269 return err;
5270 }
5271
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005272 return 0;
5273}
5274
5275int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
5276{
5277 struct bpf_program *prog;
5278 int err;
5279
5280 if (!obj)
5281 return -ENOENT;
5282
5283 if (!obj->loaded) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005284 pr_warn("object not yet loaded; load it first\n");
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005285 return -ENOENT;
5286 }
5287
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005288 bpf_object__for_each_program(prog, obj) {
5289 char buf[PATH_MAX];
5290 int len;
5291
5292 len = snprintf(buf, PATH_MAX, "%s/%s", path,
Stanislav Fomichev33a2c752018-11-09 08:21:43 -08005293 prog->pin_name);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005294 if (len < 0) {
5295 err = -EINVAL;
5296 goto err_unpin_programs;
5297 } else if (len >= PATH_MAX) {
5298 err = -ENAMETOOLONG;
5299 goto err_unpin_programs;
5300 }
5301
5302 err = bpf_program__pin(prog, buf);
5303 if (err)
5304 goto err_unpin_programs;
5305 }
5306
5307 return 0;
5308
5309err_unpin_programs:
5310 while ((prog = bpf_program__prev(prog, obj))) {
5311 char buf[PATH_MAX];
5312 int len;
5313
5314 len = snprintf(buf, PATH_MAX, "%s/%s", path,
Stanislav Fomichev33a2c752018-11-09 08:21:43 -08005315 prog->pin_name);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005316 if (len < 0)
5317 continue;
5318 else if (len >= PATH_MAX)
5319 continue;
5320
5321 bpf_program__unpin(prog, buf);
5322 }
5323
5324 return err;
5325}
5326
5327int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
5328{
5329 struct bpf_program *prog;
5330 int err;
5331
5332 if (!obj)
5333 return -ENOENT;
5334
Joe Stringerd5148d82017-01-26 13:19:58 -08005335 bpf_object__for_each_program(prog, obj) {
5336 char buf[PATH_MAX];
5337 int len;
5338
5339 len = snprintf(buf, PATH_MAX, "%s/%s", path,
Stanislav Fomichev33a2c752018-11-09 08:21:43 -08005340 prog->pin_name);
Joe Stringerd5148d82017-01-26 13:19:58 -08005341 if (len < 0)
5342 return -EINVAL;
5343 else if (len >= PATH_MAX)
5344 return -ENAMETOOLONG;
5345
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005346 err = bpf_program__unpin(prog, buf);
Joe Stringerd5148d82017-01-26 13:19:58 -08005347 if (err)
5348 return err;
5349 }
5350
5351 return 0;
5352}
5353
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005354int bpf_object__pin(struct bpf_object *obj, const char *path)
5355{
5356 int err;
5357
5358 err = bpf_object__pin_maps(obj, path);
5359 if (err)
5360 return err;
5361
5362 err = bpf_object__pin_programs(obj, path);
5363 if (err) {
5364 bpf_object__unpin_maps(obj, path);
5365 return err;
5366 }
5367
5368 return 0;
5369}
5370
Wang Nan1a5e3fb2015-07-01 02:13:53 +00005371void bpf_object__close(struct bpf_object *obj)
5372{
Wang Nana5b8bd42015-07-01 02:14:00 +00005373 size_t i;
5374
Wang Nan1a5e3fb2015-07-01 02:13:53 +00005375 if (!obj)
5376 return;
5377
Wang Nan10931d22016-11-26 07:03:26 +00005378 if (obj->clear_priv)
5379 obj->clear_priv(obj, obj->priv);
5380
Wang Nan1a5e3fb2015-07-01 02:13:53 +00005381 bpf_object__elf_finish(obj);
Wang Nan52d33522015-07-01 02:14:04 +00005382 bpf_object__unload(obj);
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07005383 btf__free(obj->btf);
Yonghong Song2993e052018-11-19 15:29:16 -08005384 btf_ext__free(obj->btf_ext);
Wang Nan1a5e3fb2015-07-01 02:13:53 +00005385
Wang Nan9d759a92015-11-27 08:47:35 +00005386 for (i = 0; i < obj->nr_maps; i++) {
Andrii Nakryikoeba9c5f2019-12-13 17:43:33 -08005387 struct bpf_map *map = &obj->maps[i];
5388
5389 if (map->clear_priv)
5390 map->clear_priv(map, map->priv);
5391 map->priv = NULL;
5392 map->clear_priv = NULL;
5393
5394 if (map->mmaped) {
5395 munmap(map->mmaped, bpf_map_mmap_sz(map));
5396 map->mmaped = NULL;
5397 }
5398
5399 zfree(&map->name);
5400 zfree(&map->pin_path);
Wang Nan9d759a92015-11-27 08:47:35 +00005401 }
Daniel Borkmannd8599002019-04-09 23:20:13 +02005402
Andrii Nakryiko166750b2019-12-13 17:47:08 -08005403 zfree(&obj->kconfig_path);
5404 zfree(&obj->externs);
5405 obj->nr_extern = 0;
5406
Wang Nan9d759a92015-11-27 08:47:35 +00005407 zfree(&obj->maps);
5408 obj->nr_maps = 0;
Wang Nana5b8bd42015-07-01 02:14:00 +00005409
5410 if (obj->programs && obj->nr_programs) {
5411 for (i = 0; i < obj->nr_programs; i++)
5412 bpf_program__exit(&obj->programs[i]);
5413 }
5414 zfree(&obj->programs);
5415
Wang Nan9a208ef2015-07-01 02:14:10 +00005416 list_del(&obj->list);
Wang Nan1a5e3fb2015-07-01 02:13:53 +00005417 free(obj);
5418}
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005419
Wang Nan9a208ef2015-07-01 02:14:10 +00005420struct bpf_object *
5421bpf_object__next(struct bpf_object *prev)
5422{
5423 struct bpf_object *next;
5424
5425 if (!prev)
5426 next = list_first_entry(&bpf_objects_list,
5427 struct bpf_object,
5428 list);
5429 else
5430 next = list_next_entry(prev, list);
5431
5432 /* Empty list is noticed here so don't need checking on entry. */
5433 if (&next->list == &bpf_objects_list)
5434 return NULL;
5435
5436 return next;
5437}
5438
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005439const char *bpf_object__name(const struct bpf_object *obj)
Wang Nanacf860a2015-08-27 02:30:55 +00005440{
Andrii Nakryikoc9e4c302019-10-04 15:40:36 -07005441 return obj ? obj->name : ERR_PTR(-EINVAL);
Wang Nanacf860a2015-08-27 02:30:55 +00005442}
5443
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005444unsigned int bpf_object__kversion(const struct bpf_object *obj)
Wang Nan45825d82015-11-06 13:49:38 +00005445{
Arnaldo Carvalho de Meloa7fe0452016-06-03 12:22:51 -03005446 return obj ? obj->kern_version : 0;
Wang Nan45825d82015-11-06 13:49:38 +00005447}
5448
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005449struct btf *bpf_object__btf(const struct bpf_object *obj)
Andrey Ignatov789f6ba2019-02-14 15:01:43 -08005450{
5451 return obj ? obj->btf : NULL;
5452}
5453
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07005454int bpf_object__btf_fd(const struct bpf_object *obj)
5455{
5456 return obj->btf ? btf__fd(obj->btf) : -1;
5457}
5458
Wang Nan10931d22016-11-26 07:03:26 +00005459int bpf_object__set_priv(struct bpf_object *obj, void *priv,
5460 bpf_object_clear_priv_t clear_priv)
5461{
5462 if (obj->priv && obj->clear_priv)
5463 obj->clear_priv(obj, obj->priv);
5464
5465 obj->priv = priv;
5466 obj->clear_priv = clear_priv;
5467 return 0;
5468}
5469
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005470void *bpf_object__priv(const struct bpf_object *obj)
Wang Nan10931d22016-11-26 07:03:26 +00005471{
5472 return obj ? obj->priv : ERR_PTR(-EINVAL);
5473}
5474
Jakub Kicinskieac7d842018-06-28 14:41:39 -07005475static struct bpf_program *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005476__bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
5477 bool forward)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005478{
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005479 size_t nr_programs = obj->nr_programs;
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005480 ssize_t idx;
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005481
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005482 if (!nr_programs)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005483 return NULL;
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005484
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005485 if (!p)
5486 /* Iter from the beginning */
5487 return forward ? &obj->programs[0] :
5488 &obj->programs[nr_programs - 1];
5489
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005490 if (p->obj != obj) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005491 pr_warn("error: program handler doesn't match object\n");
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005492 return NULL;
5493 }
5494
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005495 idx = (p - obj->programs) + (forward ? 1 : -1);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005496 if (idx >= obj->nr_programs || idx < 0)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005497 return NULL;
5498 return &obj->programs[idx];
5499}
5500
Jakub Kicinskieac7d842018-06-28 14:41:39 -07005501struct bpf_program *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005502bpf_program__next(struct bpf_program *prev, const struct bpf_object *obj)
Jakub Kicinskieac7d842018-06-28 14:41:39 -07005503{
5504 struct bpf_program *prog = prev;
5505
5506 do {
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005507 prog = __bpf_program__iter(prog, obj, true);
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005508 } while (prog && bpf_program__is_function_storage(prog, obj));
5509
5510 return prog;
5511}
5512
5513struct bpf_program *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005514bpf_program__prev(struct bpf_program *next, const struct bpf_object *obj)
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005515{
5516 struct bpf_program *prog = next;
5517
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08005518 do {
Martin KaFai Laua83d6e72018-11-12 15:44:53 -08005519 prog = __bpf_program__iter(prog, obj, false);
Jakub Kicinskieac7d842018-06-28 14:41:39 -07005520 } while (prog && bpf_program__is_function_storage(prog, obj));
5521
5522 return prog;
5523}
5524
Arnaldo Carvalho de Meloedb13ed2016-06-03 12:38:21 -03005525int bpf_program__set_priv(struct bpf_program *prog, void *priv,
5526 bpf_program_clear_priv_t clear_priv)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005527{
5528 if (prog->priv && prog->clear_priv)
5529 prog->clear_priv(prog, prog->priv);
5530
5531 prog->priv = priv;
5532 prog->clear_priv = clear_priv;
5533 return 0;
5534}
5535
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005536void *bpf_program__priv(const struct bpf_program *prog)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005537{
Arnaldo Carvalho de Melobe834ff2016-06-03 12:36:39 -03005538 return prog ? prog->priv : ERR_PTR(-EINVAL);
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005539}
5540
Jakub Kicinski9aba3612018-06-28 14:41:37 -07005541void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
5542{
5543 prog->prog_ifindex = ifindex;
5544}
5545
Andrii Nakryiko01af3bf2019-12-13 17:43:32 -08005546const char *bpf_program__name(const struct bpf_program *prog)
5547{
5548 return prog->name;
5549}
5550
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005551const char *bpf_program__title(const struct bpf_program *prog, bool needs_copy)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005552{
5553 const char *title;
5554
5555 title = prog->section_name;
Namhyung Kim715f8db2015-11-03 20:21:05 +09005556 if (needs_copy) {
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005557 title = strdup(title);
5558 if (!title) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005559 pr_warn("failed to strdup program title\n");
Wang Nan6371ca3b2015-11-06 13:49:37 +00005560 return ERR_PTR(-ENOMEM);
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005561 }
5562 }
5563
5564 return title;
5565}
5566
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005567int bpf_program__fd(const struct bpf_program *prog)
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005568{
Wang Nanb5805632015-11-16 12:10:09 +00005569 return bpf_program__nth_fd(prog, 0);
5570}
5571
Toke Høiland-Jørgensen1a734ef2019-11-09 21:37:32 +01005572size_t bpf_program__size(const struct bpf_program *prog)
5573{
5574 return prog->insns_cnt * sizeof(struct bpf_insn);
5575}
5576
Wang Nanb5805632015-11-16 12:10:09 +00005577int bpf_program__set_prep(struct bpf_program *prog, int nr_instances,
5578 bpf_program_prep_t prep)
5579{
5580 int *instances_fds;
5581
5582 if (nr_instances <= 0 || !prep)
5583 return -EINVAL;
5584
5585 if (prog->instances.nr > 0 || prog->instances.fds) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005586 pr_warn("Can't set pre-processor after loading\n");
Wang Nanb5805632015-11-16 12:10:09 +00005587 return -EINVAL;
5588 }
5589
5590 instances_fds = malloc(sizeof(int) * nr_instances);
5591 if (!instances_fds) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005592 pr_warn("alloc memory failed for fds\n");
Wang Nanb5805632015-11-16 12:10:09 +00005593 return -ENOMEM;
5594 }
5595
5596 /* fill all fd with -1 */
5597 memset(instances_fds, -1, sizeof(int) * nr_instances);
5598
5599 prog->instances.nr = nr_instances;
5600 prog->instances.fds = instances_fds;
5601 prog->preprocessor = prep;
5602 return 0;
5603}
5604
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005605int bpf_program__nth_fd(const struct bpf_program *prog, int n)
Wang Nanb5805632015-11-16 12:10:09 +00005606{
5607 int fd;
5608
Jakub Kicinski1e960042018-07-26 14:32:18 -07005609 if (!prog)
5610 return -EINVAL;
5611
Wang Nanb5805632015-11-16 12:10:09 +00005612 if (n >= prog->instances.nr || n < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005613 pr_warn("Can't get the %dth fd from program %s: only %d instances\n",
5614 n, prog->section_name, prog->instances.nr);
Wang Nanb5805632015-11-16 12:10:09 +00005615 return -EINVAL;
5616 }
5617
5618 fd = prog->instances.fds[n];
5619 if (fd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08005620 pr_warn("%dth instance of program '%s' is invalid\n",
5621 n, prog->section_name);
Wang Nanb5805632015-11-16 12:10:09 +00005622 return -ENOENT;
5623 }
5624
5625 return fd;
Wang Nanaa9b1ac2015-07-01 02:14:08 +00005626}
Wang Nan9d759a92015-11-27 08:47:35 +00005627
Andrii Nakryikof1eead92019-10-20 20:38:57 -07005628enum bpf_prog_type bpf_program__get_type(struct bpf_program *prog)
5629{
5630 return prog->type;
5631}
5632
Alexei Starovoitovdd26b7f2017-03-30 21:45:40 -07005633void bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
Wang Nan5f44e4c82016-07-13 10:44:01 +00005634{
5635 prog->type = type;
5636}
5637
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005638static bool bpf_program__is_type(const struct bpf_program *prog,
Wang Nan5f44e4c82016-07-13 10:44:01 +00005639 enum bpf_prog_type type)
5640{
5641 return prog ? (prog->type == type) : false;
5642}
5643
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07005644#define BPF_PROG_TYPE_FNS(NAME, TYPE) \
5645int bpf_program__set_##NAME(struct bpf_program *prog) \
5646{ \
5647 if (!prog) \
5648 return -EINVAL; \
5649 bpf_program__set_type(prog, TYPE); \
5650 return 0; \
5651} \
5652 \
5653bool bpf_program__is_##NAME(const struct bpf_program *prog) \
5654{ \
5655 return bpf_program__is_type(prog, TYPE); \
5656} \
Wang Nan5f44e4c82016-07-13 10:44:01 +00005657
Joe Stringer7803ba72017-01-22 17:11:24 -08005658BPF_PROG_TYPE_FNS(socket_filter, BPF_PROG_TYPE_SOCKET_FILTER);
Joe Stringered794072017-01-22 17:11:23 -08005659BPF_PROG_TYPE_FNS(kprobe, BPF_PROG_TYPE_KPROBE);
Joe Stringer7803ba72017-01-22 17:11:24 -08005660BPF_PROG_TYPE_FNS(sched_cls, BPF_PROG_TYPE_SCHED_CLS);
5661BPF_PROG_TYPE_FNS(sched_act, BPF_PROG_TYPE_SCHED_ACT);
Joe Stringered794072017-01-22 17:11:23 -08005662BPF_PROG_TYPE_FNS(tracepoint, BPF_PROG_TYPE_TRACEPOINT);
Andrey Ignatove14c93fd2018-04-17 10:28:46 -07005663BPF_PROG_TYPE_FNS(raw_tracepoint, BPF_PROG_TYPE_RAW_TRACEPOINT);
Joe Stringer7803ba72017-01-22 17:11:24 -08005664BPF_PROG_TYPE_FNS(xdp, BPF_PROG_TYPE_XDP);
5665BPF_PROG_TYPE_FNS(perf_event, BPF_PROG_TYPE_PERF_EVENT);
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005666BPF_PROG_TYPE_FNS(tracing, BPF_PROG_TYPE_TRACING);
Wang Nan5f44e4c82016-07-13 10:44:01 +00005667
Andrii Nakryikof1eead92019-10-20 20:38:57 -07005668enum bpf_attach_type
5669bpf_program__get_expected_attach_type(struct bpf_program *prog)
5670{
5671 return prog->expected_attach_type;
5672}
5673
John Fastabend16962b22018-04-23 14:30:38 -07005674void bpf_program__set_expected_attach_type(struct bpf_program *prog,
5675 enum bpf_attach_type type)
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005676{
5677 prog->expected_attach_type = type;
5678}
5679
Alexei Starovoitovf75a6972019-10-15 20:24:59 -07005680#define BPF_PROG_SEC_IMPL(string, ptype, eatype, is_attachable, btf, atype) \
5681 { string, sizeof(string) - 1, ptype, eatype, is_attachable, btf, atype }
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005682
Andrey Ignatov956b6202018-09-26 15:24:53 -07005683/* Programs that can NOT be attached. */
Alexei Starovoitovf75a6972019-10-15 20:24:59 -07005684#define BPF_PROG_SEC(string, ptype) BPF_PROG_SEC_IMPL(string, ptype, 0, 0, 0, 0)
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005685
Andrey Ignatov956b6202018-09-26 15:24:53 -07005686/* Programs that can be attached. */
5687#define BPF_APROG_SEC(string, ptype, atype) \
Alexei Starovoitovf75a6972019-10-15 20:24:59 -07005688 BPF_PROG_SEC_IMPL(string, ptype, 0, 1, 0, atype)
Andrey Ignatov81efee72018-04-17 10:28:45 -07005689
Andrey Ignatov956b6202018-09-26 15:24:53 -07005690/* Programs that must specify expected attach type at load time. */
5691#define BPF_EAPROG_SEC(string, ptype, eatype) \
Alexei Starovoitovf75a6972019-10-15 20:24:59 -07005692 BPF_PROG_SEC_IMPL(string, ptype, eatype, 1, 0, eatype)
5693
5694/* Programs that use BTF to identify attach point */
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005695#define BPF_PROG_BTF(string, ptype, eatype) \
5696 BPF_PROG_SEC_IMPL(string, ptype, eatype, 0, 1, 0)
Andrey Ignatov956b6202018-09-26 15:24:53 -07005697
5698/* Programs that can be attached but attach type can't be identified by section
5699 * name. Kept for backward compatibility.
5700 */
5701#define BPF_APROG_COMPAT(string, ptype) BPF_PROG_SEC(string, ptype)
Andrey Ignatove50b0a62018-03-30 15:08:03 -07005702
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005703#define SEC_DEF(sec_pfx, ptype, ...) { \
5704 .sec = sec_pfx, \
5705 .len = sizeof(sec_pfx) - 1, \
5706 .prog_type = BPF_PROG_TYPE_##ptype, \
5707 __VA_ARGS__ \
5708}
5709
5710struct bpf_sec_def;
5711
5712typedef struct bpf_link *(*attach_fn_t)(const struct bpf_sec_def *sec,
5713 struct bpf_program *prog);
5714
5715static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
5716 struct bpf_program *prog);
5717static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
5718 struct bpf_program *prog);
5719static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
5720 struct bpf_program *prog);
5721static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
5722 struct bpf_program *prog);
5723
5724struct bpf_sec_def {
Roman Gushchin583c9002017-12-13 15:18:51 +00005725 const char *sec;
5726 size_t len;
5727 enum bpf_prog_type prog_type;
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005728 enum bpf_attach_type expected_attach_type;
Alexei Starovoitovf75a6972019-10-15 20:24:59 -07005729 bool is_attachable;
5730 bool is_attach_btf;
Andrey Ignatov956b6202018-09-26 15:24:53 -07005731 enum bpf_attach_type attach_type;
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005732 attach_fn_t attach_fn;
5733};
5734
5735static const struct bpf_sec_def section_defs[] = {
Andrey Ignatov956b6202018-09-26 15:24:53 -07005736 BPF_PROG_SEC("socket", BPF_PROG_TYPE_SOCKET_FILTER),
Jakub Sitnicki67d69cc2019-12-12 11:22:50 +01005737 BPF_PROG_SEC("sk_reuseport", BPF_PROG_TYPE_SK_REUSEPORT),
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005738 SEC_DEF("kprobe/", KPROBE,
5739 .attach_fn = attach_kprobe),
Andrii Nakryiko32dff6d2019-10-20 20:38:58 -07005740 BPF_PROG_SEC("uprobe/", BPF_PROG_TYPE_KPROBE),
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005741 SEC_DEF("kretprobe/", KPROBE,
5742 .attach_fn = attach_kprobe),
Andrii Nakryiko32dff6d2019-10-20 20:38:58 -07005743 BPF_PROG_SEC("uretprobe/", BPF_PROG_TYPE_KPROBE),
Andrey Ignatov956b6202018-09-26 15:24:53 -07005744 BPF_PROG_SEC("classifier", BPF_PROG_TYPE_SCHED_CLS),
5745 BPF_PROG_SEC("action", BPF_PROG_TYPE_SCHED_ACT),
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005746 SEC_DEF("tracepoint/", TRACEPOINT,
5747 .attach_fn = attach_tp),
5748 SEC_DEF("tp/", TRACEPOINT,
5749 .attach_fn = attach_tp),
5750 SEC_DEF("raw_tracepoint/", RAW_TRACEPOINT,
5751 .attach_fn = attach_raw_tp),
5752 SEC_DEF("raw_tp/", RAW_TRACEPOINT,
5753 .attach_fn = attach_raw_tp),
5754 SEC_DEF("tp_btf/", TRACING,
5755 .expected_attach_type = BPF_TRACE_RAW_TP,
5756 .is_attach_btf = true,
5757 .attach_fn = attach_trace),
5758 SEC_DEF("fentry/", TRACING,
5759 .expected_attach_type = BPF_TRACE_FENTRY,
5760 .is_attach_btf = true,
5761 .attach_fn = attach_trace),
5762 SEC_DEF("fexit/", TRACING,
5763 .expected_attach_type = BPF_TRACE_FEXIT,
5764 .is_attach_btf = true,
5765 .attach_fn = attach_trace),
Andrey Ignatov956b6202018-09-26 15:24:53 -07005766 BPF_PROG_SEC("xdp", BPF_PROG_TYPE_XDP),
5767 BPF_PROG_SEC("perf_event", BPF_PROG_TYPE_PERF_EVENT),
5768 BPF_PROG_SEC("lwt_in", BPF_PROG_TYPE_LWT_IN),
5769 BPF_PROG_SEC("lwt_out", BPF_PROG_TYPE_LWT_OUT),
5770 BPF_PROG_SEC("lwt_xmit", BPF_PROG_TYPE_LWT_XMIT),
5771 BPF_PROG_SEC("lwt_seg6local", BPF_PROG_TYPE_LWT_SEG6LOCAL),
Andrey Ignatovbafa7af2018-09-26 15:24:54 -07005772 BPF_APROG_SEC("cgroup_skb/ingress", BPF_PROG_TYPE_CGROUP_SKB,
5773 BPF_CGROUP_INET_INGRESS),
5774 BPF_APROG_SEC("cgroup_skb/egress", BPF_PROG_TYPE_CGROUP_SKB,
5775 BPF_CGROUP_INET_EGRESS),
Andrey Ignatov956b6202018-09-26 15:24:53 -07005776 BPF_APROG_COMPAT("cgroup/skb", BPF_PROG_TYPE_CGROUP_SKB),
5777 BPF_APROG_SEC("cgroup/sock", BPF_PROG_TYPE_CGROUP_SOCK,
5778 BPF_CGROUP_INET_SOCK_CREATE),
5779 BPF_EAPROG_SEC("cgroup/post_bind4", BPF_PROG_TYPE_CGROUP_SOCK,
5780 BPF_CGROUP_INET4_POST_BIND),
5781 BPF_EAPROG_SEC("cgroup/post_bind6", BPF_PROG_TYPE_CGROUP_SOCK,
5782 BPF_CGROUP_INET6_POST_BIND),
5783 BPF_APROG_SEC("cgroup/dev", BPF_PROG_TYPE_CGROUP_DEVICE,
5784 BPF_CGROUP_DEVICE),
5785 BPF_APROG_SEC("sockops", BPF_PROG_TYPE_SOCK_OPS,
5786 BPF_CGROUP_SOCK_OPS),
Andrey Ignatovc6f68512018-09-26 15:24:55 -07005787 BPF_APROG_SEC("sk_skb/stream_parser", BPF_PROG_TYPE_SK_SKB,
5788 BPF_SK_SKB_STREAM_PARSER),
5789 BPF_APROG_SEC("sk_skb/stream_verdict", BPF_PROG_TYPE_SK_SKB,
5790 BPF_SK_SKB_STREAM_VERDICT),
Andrey Ignatov956b6202018-09-26 15:24:53 -07005791 BPF_APROG_COMPAT("sk_skb", BPF_PROG_TYPE_SK_SKB),
5792 BPF_APROG_SEC("sk_msg", BPF_PROG_TYPE_SK_MSG,
5793 BPF_SK_MSG_VERDICT),
5794 BPF_APROG_SEC("lirc_mode2", BPF_PROG_TYPE_LIRC_MODE2,
5795 BPF_LIRC_MODE2),
5796 BPF_APROG_SEC("flow_dissector", BPF_PROG_TYPE_FLOW_DISSECTOR,
5797 BPF_FLOW_DISSECTOR),
5798 BPF_EAPROG_SEC("cgroup/bind4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5799 BPF_CGROUP_INET4_BIND),
5800 BPF_EAPROG_SEC("cgroup/bind6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5801 BPF_CGROUP_INET6_BIND),
5802 BPF_EAPROG_SEC("cgroup/connect4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5803 BPF_CGROUP_INET4_CONNECT),
5804 BPF_EAPROG_SEC("cgroup/connect6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5805 BPF_CGROUP_INET6_CONNECT),
5806 BPF_EAPROG_SEC("cgroup/sendmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5807 BPF_CGROUP_UDP4_SENDMSG),
5808 BPF_EAPROG_SEC("cgroup/sendmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5809 BPF_CGROUP_UDP6_SENDMSG),
Daniel Borkmann9bb59ac2019-06-07 01:48:59 +02005810 BPF_EAPROG_SEC("cgroup/recvmsg4", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5811 BPF_CGROUP_UDP4_RECVMSG),
5812 BPF_EAPROG_SEC("cgroup/recvmsg6", BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
5813 BPF_CGROUP_UDP6_RECVMSG),
Andrey Ignatov063cc9f2019-03-08 09:15:26 -08005814 BPF_EAPROG_SEC("cgroup/sysctl", BPF_PROG_TYPE_CGROUP_SYSCTL,
5815 BPF_CGROUP_SYSCTL),
Stanislav Fomichev4cdbfb52019-06-27 13:38:49 -07005816 BPF_EAPROG_SEC("cgroup/getsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5817 BPF_CGROUP_GETSOCKOPT),
5818 BPF_EAPROG_SEC("cgroup/setsockopt", BPF_PROG_TYPE_CGROUP_SOCKOPT,
5819 BPF_CGROUP_SETSOCKOPT),
Roman Gushchin583c9002017-12-13 15:18:51 +00005820};
Roman Gushchin583c9002017-12-13 15:18:51 +00005821
Andrey Ignatov956b6202018-09-26 15:24:53 -07005822#undef BPF_PROG_SEC_IMPL
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005823#undef BPF_PROG_SEC
Andrey Ignatov956b6202018-09-26 15:24:53 -07005824#undef BPF_APROG_SEC
5825#undef BPF_EAPROG_SEC
5826#undef BPF_APROG_COMPAT
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005827#undef SEC_DEF
Andrey Ignatovd7be1432018-03-30 15:08:01 -07005828
Taeung Songc76e4c22019-01-21 22:06:38 +09005829#define MAX_TYPE_NAME_SIZE 32
5830
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005831static const struct bpf_sec_def *find_sec_def(const char *sec_name)
5832{
5833 int i, n = ARRAY_SIZE(section_defs);
5834
5835 for (i = 0; i < n; i++) {
5836 if (strncmp(sec_name,
5837 section_defs[i].sec, section_defs[i].len))
5838 continue;
5839 return &section_defs[i];
5840 }
5841 return NULL;
5842}
5843
Taeung Songc76e4c22019-01-21 22:06:38 +09005844static char *libbpf_get_type_names(bool attach_type)
5845{
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005846 int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
Taeung Songc76e4c22019-01-21 22:06:38 +09005847 char *buf;
5848
5849 buf = malloc(len);
5850 if (!buf)
5851 return NULL;
5852
5853 buf[0] = '\0';
5854 /* Forge string buf with all available names */
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005855 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5856 if (attach_type && !section_defs[i].is_attachable)
Taeung Songc76e4c22019-01-21 22:06:38 +09005857 continue;
5858
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005859 if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
Taeung Songc76e4c22019-01-21 22:06:38 +09005860 free(buf);
5861 return NULL;
5862 }
5863 strcat(buf, " ");
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005864 strcat(buf, section_defs[i].sec);
Taeung Songc76e4c22019-01-21 22:06:38 +09005865 }
5866
5867 return buf;
5868}
5869
Jakub Kicinskib60df2a2018-07-10 14:42:59 -07005870int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
5871 enum bpf_attach_type *expected_attach_type)
Roman Gushchin583c9002017-12-13 15:18:51 +00005872{
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005873 const struct bpf_sec_def *sec_def;
Taeung Songc76e4c22019-01-21 22:06:38 +09005874 char *type_names;
Roman Gushchin583c9002017-12-13 15:18:51 +00005875
Jakub Kicinskib60df2a2018-07-10 14:42:59 -07005876 if (!name)
5877 return -EINVAL;
Roman Gushchin583c9002017-12-13 15:18:51 +00005878
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005879 sec_def = find_sec_def(name);
5880 if (sec_def) {
5881 *prog_type = sec_def->prog_type;
5882 *expected_attach_type = sec_def->expected_attach_type;
Jakub Kicinskib60df2a2018-07-10 14:42:59 -07005883 return 0;
5884 }
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005885
Andrii Nakryiko8983b732019-11-20 23:07:42 -08005886 pr_warn("failed to guess program type from ELF section '%s'\n", name);
Taeung Songc76e4c22019-01-21 22:06:38 +09005887 type_names = libbpf_get_type_names(false);
5888 if (type_names != NULL) {
Andrii Nakryiko3f519352019-12-13 17:43:35 -08005889 pr_debug("supported section(type) names are:%s\n", type_names);
Taeung Songc76e4c22019-01-21 22:06:38 +09005890 free(type_names);
5891 }
5892
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07005893 return -ESRCH;
Jakub Kicinskib60df2a2018-07-10 14:42:59 -07005894}
Roman Gushchin583c9002017-12-13 15:18:51 +00005895
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005896#define BTF_PREFIX "btf_trace_"
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005897int libbpf_find_vmlinux_btf_id(const char *name,
5898 enum bpf_attach_type attach_type)
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005899{
5900 struct btf *btf = bpf_core_find_kernel_btf();
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005901 char raw_tp_btf[128] = BTF_PREFIX;
5902 char *dst = raw_tp_btf + sizeof(BTF_PREFIX) - 1;
5903 const char *btf_name;
5904 int err = -EINVAL;
Andrii Nakryikob615e5a2019-11-25 13:29:48 -08005905 __u32 kind;
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005906
5907 if (IS_ERR(btf)) {
5908 pr_warn("vmlinux BTF is not found\n");
5909 return -EINVAL;
5910 }
5911
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005912 if (attach_type == BPF_TRACE_RAW_TP) {
5913 /* prepend "btf_trace_" prefix per kernel convention */
5914 strncat(dst, name, sizeof(raw_tp_btf) - sizeof(BTF_PREFIX));
5915 btf_name = raw_tp_btf;
5916 kind = BTF_KIND_TYPEDEF;
5917 } else {
5918 btf_name = name;
5919 kind = BTF_KIND_FUNC;
5920 }
5921 err = btf__find_by_name_kind(btf, btf_name, kind);
5922 btf__free(btf);
5923 return err;
5924}
5925
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -08005926static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
5927{
5928 struct bpf_prog_info_linear *info_linear;
5929 struct bpf_prog_info *info;
5930 struct btf *btf = NULL;
5931 int err = -EINVAL;
5932
5933 info_linear = bpf_program__get_prog_info_linear(attach_prog_fd, 0);
5934 if (IS_ERR_OR_NULL(info_linear)) {
5935 pr_warn("failed get_prog_info_linear for FD %d\n",
5936 attach_prog_fd);
5937 return -EINVAL;
5938 }
5939 info = &info_linear->info;
5940 if (!info->btf_id) {
5941 pr_warn("The target program doesn't have BTF\n");
5942 goto out;
5943 }
5944 if (btf__get_from_id(info->btf_id, &btf)) {
5945 pr_warn("Failed to get BTF of the program\n");
5946 goto out;
5947 }
5948 err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
5949 btf__free(btf);
5950 if (err <= 0) {
5951 pr_warn("%s is not found in prog's BTF\n", name);
5952 goto out;
5953 }
5954out:
5955 free(info_linear);
5956 return err;
5957}
5958
5959static int libbpf_find_attach_btf_id(const char *name,
5960 enum bpf_attach_type attach_type,
5961 __u32 attach_prog_fd)
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005962{
5963 int i, err;
5964
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005965 if (!name)
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005966 return -EINVAL;
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005967
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005968 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5969 if (!section_defs[i].is_attach_btf)
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005970 continue;
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005971 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005972 continue;
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -08005973 if (attach_prog_fd)
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005974 err = libbpf_find_prog_btf_id(name + section_defs[i].len,
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -08005975 attach_prog_fd);
5976 else
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005977 err = libbpf_find_vmlinux_btf_id(name + section_defs[i].len,
Alexei Starovoitove7bf94d2019-11-14 10:57:18 -08005978 attach_type);
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005979 if (err <= 0)
5980 pr_warn("%s is not found in vmlinux BTF\n", name);
5981 return err;
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005982 }
5983 pr_warn("failed to identify btf_id based on ELF section name '%s'\n", name);
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08005984 return -ESRCH;
Alexei Starovoitov12a86542019-10-30 15:32:12 -07005985}
5986
Andrey Ignatov956b6202018-09-26 15:24:53 -07005987int libbpf_attach_type_by_name(const char *name,
5988 enum bpf_attach_type *attach_type)
5989{
Taeung Songc76e4c22019-01-21 22:06:38 +09005990 char *type_names;
Andrey Ignatov956b6202018-09-26 15:24:53 -07005991 int i;
5992
5993 if (!name)
5994 return -EINVAL;
5995
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005996 for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
5997 if (strncmp(name, section_defs[i].sec, section_defs[i].len))
Andrey Ignatov956b6202018-09-26 15:24:53 -07005998 continue;
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08005999 if (!section_defs[i].is_attachable)
Andrey Ignatov956b6202018-09-26 15:24:53 -07006000 return -EINVAL;
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08006001 *attach_type = section_defs[i].attach_type;
Andrey Ignatov956b6202018-09-26 15:24:53 -07006002 return 0;
6003 }
Kefeng Wangbe180102019-10-21 13:55:32 +08006004 pr_warn("failed to guess attach type based on ELF section name '%s'\n", name);
Taeung Songc76e4c22019-01-21 22:06:38 +09006005 type_names = libbpf_get_type_names(true);
6006 if (type_names != NULL) {
6007 pr_info("attachable section(type) names are:%s\n", type_names);
6008 free(type_names);
6009 }
6010
Andrey Ignatov956b6202018-09-26 15:24:53 -07006011 return -EINVAL;
6012}
6013
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006014int bpf_map__fd(const struct bpf_map *map)
Wang Nan9d759a92015-11-27 08:47:35 +00006015{
Arnaldo Carvalho de Melo6e009e652016-06-03 12:15:52 -03006016 return map ? map->fd : -EINVAL;
Wang Nan9d759a92015-11-27 08:47:35 +00006017}
6018
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006019const struct bpf_map_def *bpf_map__def(const struct bpf_map *map)
Wang Nan9d759a92015-11-27 08:47:35 +00006020{
Arnaldo Carvalho de Melo53897a72016-06-02 14:21:06 -03006021 return map ? &map->def : ERR_PTR(-EINVAL);
Wang Nan9d759a92015-11-27 08:47:35 +00006022}
6023
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006024const char *bpf_map__name(const struct bpf_map *map)
Wang Nan561bbcc2015-11-27 08:47:36 +00006025{
Arnaldo Carvalho de Melo009ad5d2016-06-02 11:02:05 -03006026 return map ? map->name : NULL;
Wang Nan561bbcc2015-11-27 08:47:36 +00006027}
6028
Martin KaFai Lau5b891af2018-07-24 08:40:21 -07006029__u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07006030{
Martin KaFai Lau61746dbe2018-05-22 15:04:24 -07006031 return map ? map->btf_key_type_id : 0;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07006032}
6033
Martin KaFai Lau5b891af2018-07-24 08:40:21 -07006034__u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07006035{
Martin KaFai Lau61746dbe2018-05-22 15:04:24 -07006036 return map ? map->btf_value_type_id : 0;
Martin KaFai Lau8a138ae2018-04-18 15:56:05 -07006037}
6038
Arnaldo Carvalho de Meloedb13ed2016-06-03 12:38:21 -03006039int bpf_map__set_priv(struct bpf_map *map, void *priv,
6040 bpf_map_clear_priv_t clear_priv)
Wang Nan9d759a92015-11-27 08:47:35 +00006041{
6042 if (!map)
6043 return -EINVAL;
6044
6045 if (map->priv) {
6046 if (map->clear_priv)
6047 map->clear_priv(map, map->priv);
6048 }
6049
6050 map->priv = priv;
6051 map->clear_priv = clear_priv;
6052 return 0;
6053}
6054
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006055void *bpf_map__priv(const struct bpf_map *map)
Wang Nan9d759a92015-11-27 08:47:35 +00006056{
Arnaldo Carvalho de Melob4cbfa52016-06-02 10:51:59 -03006057 return map ? map->priv : ERR_PTR(-EINVAL);
Wang Nan9d759a92015-11-27 08:47:35 +00006058}
6059
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006060bool bpf_map__is_offload_neutral(const struct bpf_map *map)
Jakub Kicinskif83fb222018-07-10 14:43:01 -07006061{
6062 return map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
6063}
6064
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006065bool bpf_map__is_internal(const struct bpf_map *map)
Daniel Borkmannd8599002019-04-09 23:20:13 +02006066{
6067 return map->libbpf_type != LIBBPF_MAP_UNSPEC;
6068}
6069
Jakub Kicinski9aba3612018-06-28 14:41:37 -07006070void bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
6071{
6072 map->map_ifindex = ifindex;
6073}
6074
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -08006075int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
6076{
6077 if (!bpf_map_type__is_map_in_map(map->def.type)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006078 pr_warn("error: unsupported map type\n");
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -08006079 return -EINVAL;
6080 }
6081 if (map->inner_map_fd != -1) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006082 pr_warn("error: inner_map_fd already specified\n");
Nikita V. Shirokovaddb9fc2018-11-20 20:55:56 -08006083 return -EINVAL;
6084 }
6085 map->inner_map_fd = fd;
6086 return 0;
6087}
6088
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006089static struct bpf_map *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006090__bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
Wang Nan9d759a92015-11-27 08:47:35 +00006091{
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006092 ssize_t idx;
Wang Nan9d759a92015-11-27 08:47:35 +00006093 struct bpf_map *s, *e;
6094
6095 if (!obj || !obj->maps)
6096 return NULL;
6097
6098 s = obj->maps;
6099 e = obj->maps + obj->nr_maps;
6100
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006101 if ((m < s) || (m >= e)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006102 pr_warn("error in %s: map handler doesn't belong to object\n",
6103 __func__);
Wang Nan9d759a92015-11-27 08:47:35 +00006104 return NULL;
6105 }
6106
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006107 idx = (m - obj->maps) + i;
6108 if (idx >= obj->nr_maps || idx < 0)
Wang Nan9d759a92015-11-27 08:47:35 +00006109 return NULL;
6110 return &obj->maps[idx];
6111}
Wang Nan561bbcc2015-11-27 08:47:36 +00006112
6113struct bpf_map *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006114bpf_map__next(const struct bpf_map *prev, const struct bpf_object *obj)
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006115{
6116 if (prev == NULL)
6117 return obj->maps;
6118
6119 return __bpf_map__iter(prev, obj, 1);
6120}
6121
6122struct bpf_map *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006123bpf_map__prev(const struct bpf_map *next, const struct bpf_object *obj)
Stanislav Fomichev0c19a9f2018-11-09 08:21:41 -08006124{
6125 if (next == NULL) {
6126 if (!obj->nr_maps)
6127 return NULL;
6128 return obj->maps + obj->nr_maps - 1;
6129 }
6130
6131 return __bpf_map__iter(next, obj, -1);
6132}
6133
6134struct bpf_map *
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006135bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
Wang Nan561bbcc2015-11-27 08:47:36 +00006136{
6137 struct bpf_map *pos;
6138
Jakub Kicinskif74a53d92019-02-27 19:04:12 -08006139 bpf_object__for_each_map(pos, obj) {
Wang Nan973170e2015-12-08 02:25:29 +00006140 if (pos->name && !strcmp(pos->name, name))
Wang Nan561bbcc2015-11-27 08:47:36 +00006141 return pos;
6142 }
6143 return NULL;
6144}
Wang Nan5a6acad2016-11-26 07:03:27 +00006145
Maciej Fijalkowskif3cea322019-02-01 22:42:23 +01006146int
Andrii Nakryikoa324aae2019-06-17 15:48:58 -07006147bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
Maciej Fijalkowskif3cea322019-02-01 22:42:23 +01006148{
6149 return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
6150}
6151
Wang Nan5a6acad2016-11-26 07:03:27 +00006152struct bpf_map *
6153bpf_object__find_map_by_offset(struct bpf_object *obj, size_t offset)
6154{
Andrii Nakryikodb488142019-06-17 12:26:54 -07006155 return ERR_PTR(-ENOTSUP);
Wang Nan5a6acad2016-11-26 07:03:27 +00006156}
Joe Stringere28ff1a2017-01-22 17:11:25 -08006157
6158long libbpf_get_error(const void *ptr)
6159{
Hariprasad Kelamd98363b2019-05-25 14:32:57 +05306160 return PTR_ERR_OR_ZERO(ptr);
Joe Stringere28ff1a2017-01-22 17:11:25 -08006161}
John Fastabend6f6d33f2017-08-15 22:34:22 -07006162
6163int bpf_prog_load(const char *file, enum bpf_prog_type type,
6164 struct bpf_object **pobj, int *prog_fd)
6165{
Andrey Ignatovd7be1432018-03-30 15:08:01 -07006166 struct bpf_prog_load_attr attr;
6167
6168 memset(&attr, 0, sizeof(struct bpf_prog_load_attr));
6169 attr.file = file;
6170 attr.prog_type = type;
6171 attr.expected_attach_type = 0;
6172
6173 return bpf_prog_load_xattr(&attr, pobj, prog_fd);
6174}
6175
6176int bpf_prog_load_xattr(const struct bpf_prog_load_attr *attr,
6177 struct bpf_object **pobj, int *prog_fd)
6178{
Leo Yan33bae182019-07-02 18:25:31 +08006179 struct bpf_object_open_attr open_attr = {};
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006180 struct bpf_program *prog, *first_prog = NULL;
John Fastabend6f6d33f2017-08-15 22:34:22 -07006181 struct bpf_object *obj;
David Beckettf0307a72018-05-16 14:02:49 -07006182 struct bpf_map *map;
John Fastabend6f6d33f2017-08-15 22:34:22 -07006183 int err;
6184
Andrey Ignatovd7be1432018-03-30 15:08:01 -07006185 if (!attr)
6186 return -EINVAL;
Jakub Kicinski17387dd2018-05-10 10:24:42 -07006187 if (!attr->file)
6188 return -EINVAL;
Andrey Ignatovd7be1432018-03-30 15:08:01 -07006189
Leo Yan33bae182019-07-02 18:25:31 +08006190 open_attr.file = attr->file;
6191 open_attr.prog_type = attr->prog_type;
6192
Jakub Kicinski07f2d4e2018-07-10 14:43:02 -07006193 obj = bpf_object__open_xattr(&open_attr);
Jakub Kicinski35976832018-05-10 10:09:34 -07006194 if (IS_ERR_OR_NULL(obj))
John Fastabend6f6d33f2017-08-15 22:34:22 -07006195 return -ENOENT;
6196
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006197 bpf_object__for_each_program(prog, obj) {
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07006198 enum bpf_attach_type attach_type = attr->expected_attach_type;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006199 /*
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07006200 * to preserve backwards compatibility, bpf_prog_load treats
6201 * attr->prog_type, if specified, as an override to whatever
6202 * bpf_object__open guessed
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006203 */
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07006204 if (attr->prog_type != BPF_PROG_TYPE_UNSPEC) {
6205 bpf_program__set_type(prog, attr->prog_type);
6206 bpf_program__set_expected_attach_type(prog,
6207 attach_type);
6208 }
6209 if (bpf_program__get_type(prog) == BPF_PROG_TYPE_UNSPEC) {
6210 /*
6211 * we haven't guessed from section name and user
6212 * didn't provide a fallback type, too bad...
6213 */
6214 bpf_object__close(obj);
6215 return -EINVAL;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006216 }
6217
Andrii Nakryikodd4436b2019-10-20 20:38:59 -07006218 prog->prog_ifindex = attr->ifindex;
Alexei Starovoitovda11b412019-04-01 21:27:47 -07006219 prog->log_level = attr->log_level;
Jiong Wang04656192019-05-24 23:25:19 +01006220 prog->prog_flags = attr->prog_flags;
Taeung Song69495d22018-09-03 08:30:07 +09006221 if (!first_prog)
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006222 first_prog = prog;
6223 }
6224
Jakub Kicinskif74a53d92019-02-27 19:04:12 -08006225 bpf_object__for_each_map(map, obj) {
Jakub Kicinskif83fb222018-07-10 14:43:01 -07006226 if (!bpf_map__is_offload_neutral(map))
6227 map->map_ifindex = attr->ifindex;
David Beckettf0307a72018-05-16 14:02:49 -07006228 }
6229
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006230 if (!first_prog) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006231 pr_warn("object file doesn't contain bpf program\n");
John Fastabend6f6d33f2017-08-15 22:34:22 -07006232 bpf_object__close(obj);
6233 return -ENOENT;
6234 }
6235
John Fastabend6f6d33f2017-08-15 22:34:22 -07006236 err = bpf_object__load(obj);
6237 if (err) {
6238 bpf_object__close(obj);
6239 return -EINVAL;
6240 }
6241
6242 *pobj = obj;
Alexei Starovoitov48cca7e2017-12-14 17:55:10 -08006243 *prog_fd = bpf_program__fd(first_prog);
John Fastabend6f6d33f2017-08-15 22:34:22 -07006244 return 0;
6245}
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006246
Andrii Nakryiko1c2e9ef2019-07-01 16:58:56 -07006247struct bpf_link {
6248 int (*destroy)(struct bpf_link *link);
6249};
6250
6251int bpf_link__destroy(struct bpf_link *link)
6252{
6253 int err;
6254
6255 if (!link)
6256 return 0;
6257
6258 err = link->destroy(link);
6259 free(link);
6260
6261 return err;
6262}
6263
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -07006264struct bpf_link_fd {
6265 struct bpf_link link; /* has to be at the top of struct */
6266 int fd; /* hook FD */
6267};
6268
6269static int bpf_link__destroy_perf_event(struct bpf_link *link)
6270{
6271 struct bpf_link_fd *l = (void *)link;
6272 int err;
6273
6274 err = ioctl(l->fd, PERF_EVENT_IOC_DISABLE, 0);
6275 if (err)
6276 err = -errno;
6277
6278 close(l->fd);
6279 return err;
6280}
6281
6282struct bpf_link *bpf_program__attach_perf_event(struct bpf_program *prog,
6283 int pfd)
6284{
6285 char errmsg[STRERR_BUFSIZE];
6286 struct bpf_link_fd *link;
6287 int prog_fd, err;
6288
6289 if (pfd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006290 pr_warn("program '%s': invalid perf event FD %d\n",
6291 bpf_program__title(prog, false), pfd);
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -07006292 return ERR_PTR(-EINVAL);
6293 }
6294 prog_fd = bpf_program__fd(prog);
6295 if (prog_fd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006296 pr_warn("program '%s': can't attach BPF program w/o FD (did you load it?)\n",
6297 bpf_program__title(prog, false));
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -07006298 return ERR_PTR(-EINVAL);
6299 }
6300
6301 link = malloc(sizeof(*link));
6302 if (!link)
6303 return ERR_PTR(-ENOMEM);
6304 link->link.destroy = &bpf_link__destroy_perf_event;
6305 link->fd = pfd;
6306
6307 if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
6308 err = -errno;
6309 free(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006310 pr_warn("program '%s': failed to attach to pfd %d: %s\n",
6311 bpf_program__title(prog, false), pfd,
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -07006312 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6313 return ERR_PTR(err);
6314 }
6315 if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6316 err = -errno;
6317 free(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006318 pr_warn("program '%s': failed to enable pfd %d: %s\n",
6319 bpf_program__title(prog, false), pfd,
Andrii Nakryiko63f2f5e2019-07-01 16:58:57 -07006320 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
6321 return ERR_PTR(err);
6322 }
6323 return (struct bpf_link *)link;
6324}
6325
Andrii Nakryikob2650022019-07-01 16:58:58 -07006326/*
6327 * this function is expected to parse integer in the range of [0, 2^31-1] from
6328 * given file using scanf format string fmt. If actual parsed value is
6329 * negative, the result might be indistinguishable from error
6330 */
6331static int parse_uint_from_file(const char *file, const char *fmt)
6332{
6333 char buf[STRERR_BUFSIZE];
6334 int err, ret;
6335 FILE *f;
6336
6337 f = fopen(file, "r");
6338 if (!f) {
6339 err = -errno;
6340 pr_debug("failed to open '%s': %s\n", file,
6341 libbpf_strerror_r(err, buf, sizeof(buf)));
6342 return err;
6343 }
6344 err = fscanf(f, fmt, &ret);
6345 if (err != 1) {
6346 err = err == EOF ? -EIO : -errno;
6347 pr_debug("failed to parse '%s': %s\n", file,
6348 libbpf_strerror_r(err, buf, sizeof(buf)));
6349 fclose(f);
6350 return err;
6351 }
6352 fclose(f);
6353 return ret;
6354}
6355
6356static int determine_kprobe_perf_type(void)
6357{
6358 const char *file = "/sys/bus/event_source/devices/kprobe/type";
6359
6360 return parse_uint_from_file(file, "%d\n");
6361}
6362
6363static int determine_uprobe_perf_type(void)
6364{
6365 const char *file = "/sys/bus/event_source/devices/uprobe/type";
6366
6367 return parse_uint_from_file(file, "%d\n");
6368}
6369
6370static int determine_kprobe_retprobe_bit(void)
6371{
6372 const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
6373
6374 return parse_uint_from_file(file, "config:%d\n");
6375}
6376
6377static int determine_uprobe_retprobe_bit(void)
6378{
6379 const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
6380
6381 return parse_uint_from_file(file, "config:%d\n");
6382}
6383
6384static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
6385 uint64_t offset, int pid)
6386{
6387 struct perf_event_attr attr = {};
6388 char errmsg[STRERR_BUFSIZE];
6389 int type, pfd, err;
6390
6391 type = uprobe ? determine_uprobe_perf_type()
6392 : determine_kprobe_perf_type();
6393 if (type < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006394 pr_warn("failed to determine %s perf type: %s\n",
6395 uprobe ? "uprobe" : "kprobe",
6396 libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006397 return type;
6398 }
6399 if (retprobe) {
6400 int bit = uprobe ? determine_uprobe_retprobe_bit()
6401 : determine_kprobe_retprobe_bit();
6402
6403 if (bit < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006404 pr_warn("failed to determine %s retprobe bit: %s\n",
6405 uprobe ? "uprobe" : "kprobe",
6406 libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006407 return bit;
6408 }
6409 attr.config |= 1 << bit;
6410 }
6411 attr.size = sizeof(attr);
6412 attr.type = type;
Andrii Nakryiko36db2a92019-07-08 21:00:07 -07006413 attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
6414 attr.config2 = offset; /* kprobe_addr or probe_offset */
Andrii Nakryikob2650022019-07-01 16:58:58 -07006415
6416 /* pid filter is meaningful only for uprobes */
6417 pfd = syscall(__NR_perf_event_open, &attr,
6418 pid < 0 ? -1 : pid /* pid */,
6419 pid == -1 ? 0 : -1 /* cpu */,
6420 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6421 if (pfd < 0) {
6422 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006423 pr_warn("%s perf_event_open() failed: %s\n",
6424 uprobe ? "uprobe" : "kprobe",
6425 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006426 return err;
6427 }
6428 return pfd;
6429}
6430
6431struct bpf_link *bpf_program__attach_kprobe(struct bpf_program *prog,
6432 bool retprobe,
6433 const char *func_name)
6434{
6435 char errmsg[STRERR_BUFSIZE];
6436 struct bpf_link *link;
6437 int pfd, err;
6438
6439 pfd = perf_event_open_probe(false /* uprobe */, retprobe, func_name,
6440 0 /* offset */, -1 /* pid */);
6441 if (pfd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006442 pr_warn("program '%s': failed to create %s '%s' perf event: %s\n",
6443 bpf_program__title(prog, false),
6444 retprobe ? "kretprobe" : "kprobe", func_name,
6445 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006446 return ERR_PTR(pfd);
6447 }
6448 link = bpf_program__attach_perf_event(prog, pfd);
6449 if (IS_ERR(link)) {
6450 close(pfd);
6451 err = PTR_ERR(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006452 pr_warn("program '%s': failed to attach to %s '%s': %s\n",
6453 bpf_program__title(prog, false),
6454 retprobe ? "kretprobe" : "kprobe", func_name,
6455 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006456 return link;
6457 }
6458 return link;
6459}
6460
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08006461static struct bpf_link *attach_kprobe(const struct bpf_sec_def *sec,
6462 struct bpf_program *prog)
6463{
6464 const char *func_name;
6465 bool retprobe;
6466
6467 func_name = bpf_program__title(prog, false) + sec->len;
6468 retprobe = strcmp(sec->sec, "kretprobe/") == 0;
6469
6470 return bpf_program__attach_kprobe(prog, retprobe, func_name);
6471}
6472
Andrii Nakryikob2650022019-07-01 16:58:58 -07006473struct bpf_link *bpf_program__attach_uprobe(struct bpf_program *prog,
6474 bool retprobe, pid_t pid,
6475 const char *binary_path,
6476 size_t func_offset)
6477{
6478 char errmsg[STRERR_BUFSIZE];
6479 struct bpf_link *link;
6480 int pfd, err;
6481
6482 pfd = perf_event_open_probe(true /* uprobe */, retprobe,
6483 binary_path, func_offset, pid);
6484 if (pfd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006485 pr_warn("program '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
6486 bpf_program__title(prog, false),
6487 retprobe ? "uretprobe" : "uprobe",
6488 binary_path, func_offset,
6489 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006490 return ERR_PTR(pfd);
6491 }
6492 link = bpf_program__attach_perf_event(prog, pfd);
6493 if (IS_ERR(link)) {
6494 close(pfd);
6495 err = PTR_ERR(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006496 pr_warn("program '%s': failed to attach to %s '%s:0x%zx': %s\n",
6497 bpf_program__title(prog, false),
6498 retprobe ? "uretprobe" : "uprobe",
6499 binary_path, func_offset,
6500 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
Andrii Nakryikob2650022019-07-01 16:58:58 -07006501 return link;
6502 }
6503 return link;
6504}
6505
Andrii Nakryikof6de59c2019-07-01 16:58:59 -07006506static int determine_tracepoint_id(const char *tp_category,
6507 const char *tp_name)
6508{
6509 char file[PATH_MAX];
6510 int ret;
6511
6512 ret = snprintf(file, sizeof(file),
6513 "/sys/kernel/debug/tracing/events/%s/%s/id",
6514 tp_category, tp_name);
6515 if (ret < 0)
6516 return -errno;
6517 if (ret >= sizeof(file)) {
6518 pr_debug("tracepoint %s/%s path is too long\n",
6519 tp_category, tp_name);
6520 return -E2BIG;
6521 }
6522 return parse_uint_from_file(file, "%d\n");
6523}
6524
6525static int perf_event_open_tracepoint(const char *tp_category,
6526 const char *tp_name)
6527{
6528 struct perf_event_attr attr = {};
6529 char errmsg[STRERR_BUFSIZE];
6530 int tp_id, pfd, err;
6531
6532 tp_id = determine_tracepoint_id(tp_category, tp_name);
6533 if (tp_id < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006534 pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
6535 tp_category, tp_name,
6536 libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
Andrii Nakryikof6de59c2019-07-01 16:58:59 -07006537 return tp_id;
6538 }
6539
6540 attr.type = PERF_TYPE_TRACEPOINT;
6541 attr.size = sizeof(attr);
6542 attr.config = tp_id;
6543
6544 pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
6545 -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
6546 if (pfd < 0) {
6547 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006548 pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
6549 tp_category, tp_name,
6550 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
Andrii Nakryikof6de59c2019-07-01 16:58:59 -07006551 return err;
6552 }
6553 return pfd;
6554}
6555
6556struct bpf_link *bpf_program__attach_tracepoint(struct bpf_program *prog,
6557 const char *tp_category,
6558 const char *tp_name)
6559{
6560 char errmsg[STRERR_BUFSIZE];
6561 struct bpf_link *link;
6562 int pfd, err;
6563
6564 pfd = perf_event_open_tracepoint(tp_category, tp_name);
6565 if (pfd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006566 pr_warn("program '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
6567 bpf_program__title(prog, false),
6568 tp_category, tp_name,
6569 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
Andrii Nakryikof6de59c2019-07-01 16:58:59 -07006570 return ERR_PTR(pfd);
6571 }
6572 link = bpf_program__attach_perf_event(prog, pfd);
6573 if (IS_ERR(link)) {
6574 close(pfd);
6575 err = PTR_ERR(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006576 pr_warn("program '%s': failed to attach to tracepoint '%s/%s': %s\n",
6577 bpf_program__title(prog, false),
6578 tp_category, tp_name,
6579 libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
Andrii Nakryikof6de59c2019-07-01 16:58:59 -07006580 return link;
6581 }
6582 return link;
6583}
6584
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08006585static struct bpf_link *attach_tp(const struct bpf_sec_def *sec,
6586 struct bpf_program *prog)
6587{
6588 char *sec_name, *tp_cat, *tp_name;
6589 struct bpf_link *link;
6590
6591 sec_name = strdup(bpf_program__title(prog, false));
6592 if (!sec_name)
6593 return ERR_PTR(-ENOMEM);
6594
6595 /* extract "tp/<category>/<name>" */
6596 tp_cat = sec_name + sec->len;
6597 tp_name = strchr(tp_cat, '/');
6598 if (!tp_name) {
6599 link = ERR_PTR(-EINVAL);
6600 goto out;
6601 }
6602 *tp_name = '\0';
6603 tp_name++;
6604
6605 link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
6606out:
6607 free(sec_name);
6608 return link;
6609}
6610
Andrii Nakryiko84bf5e12019-07-01 16:59:00 -07006611static int bpf_link__destroy_fd(struct bpf_link *link)
6612{
6613 struct bpf_link_fd *l = (void *)link;
6614
6615 return close(l->fd);
6616}
6617
6618struct bpf_link *bpf_program__attach_raw_tracepoint(struct bpf_program *prog,
6619 const char *tp_name)
6620{
6621 char errmsg[STRERR_BUFSIZE];
6622 struct bpf_link_fd *link;
6623 int prog_fd, pfd;
6624
6625 prog_fd = bpf_program__fd(prog);
6626 if (prog_fd < 0) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006627 pr_warn("program '%s': can't attach before loaded\n",
6628 bpf_program__title(prog, false));
Andrii Nakryiko84bf5e12019-07-01 16:59:00 -07006629 return ERR_PTR(-EINVAL);
6630 }
6631
6632 link = malloc(sizeof(*link));
6633 if (!link)
6634 return ERR_PTR(-ENOMEM);
6635 link->link.destroy = &bpf_link__destroy_fd;
6636
6637 pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
6638 if (pfd < 0) {
6639 pfd = -errno;
6640 free(link);
Kefeng Wangbe180102019-10-21 13:55:32 +08006641 pr_warn("program '%s': failed to attach to raw tracepoint '%s': %s\n",
6642 bpf_program__title(prog, false), tp_name,
6643 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
Andrii Nakryiko84bf5e12019-07-01 16:59:00 -07006644 return ERR_PTR(pfd);
6645 }
6646 link->fd = pfd;
6647 return (struct bpf_link *)link;
6648}
6649
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08006650static struct bpf_link *attach_raw_tp(const struct bpf_sec_def *sec,
6651 struct bpf_program *prog)
6652{
6653 const char *tp_name = bpf_program__title(prog, false) + sec->len;
6654
6655 return bpf_program__attach_raw_tracepoint(prog, tp_name);
6656}
6657
Alexei Starovoitovb8c54ea2019-11-14 10:57:06 -08006658struct bpf_link *bpf_program__attach_trace(struct bpf_program *prog)
6659{
6660 char errmsg[STRERR_BUFSIZE];
6661 struct bpf_link_fd *link;
6662 int prog_fd, pfd;
6663
6664 prog_fd = bpf_program__fd(prog);
6665 if (prog_fd < 0) {
6666 pr_warn("program '%s': can't attach before loaded\n",
6667 bpf_program__title(prog, false));
6668 return ERR_PTR(-EINVAL);
6669 }
6670
6671 link = malloc(sizeof(*link));
6672 if (!link)
6673 return ERR_PTR(-ENOMEM);
6674 link->link.destroy = &bpf_link__destroy_fd;
6675
6676 pfd = bpf_raw_tracepoint_open(NULL, prog_fd);
6677 if (pfd < 0) {
6678 pfd = -errno;
6679 free(link);
6680 pr_warn("program '%s': failed to attach to trace: %s\n",
6681 bpf_program__title(prog, false),
6682 libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
6683 return ERR_PTR(pfd);
6684 }
6685 link->fd = pfd;
6686 return (struct bpf_link *)link;
6687}
6688
Andrii Nakryikod7a18ea2019-12-13 17:43:26 -08006689static struct bpf_link *attach_trace(const struct bpf_sec_def *sec,
6690 struct bpf_program *prog)
6691{
6692 return bpf_program__attach_trace(prog);
6693}
6694
6695struct bpf_link *bpf_program__attach(struct bpf_program *prog)
6696{
6697 const struct bpf_sec_def *sec_def;
6698
6699 sec_def = find_sec_def(bpf_program__title(prog, false));
6700 if (!sec_def || !sec_def->attach_fn)
6701 return ERR_PTR(-ESRCH);
6702
6703 return sec_def->attach_fn(sec_def, prog);
6704}
6705
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006706enum bpf_perf_event_ret
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006707bpf_perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
6708 void **copy_mem, size_t *copy_size,
6709 bpf_perf_event_print_t fn, void *private_data)
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006710{
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006711 struct perf_event_mmap_page *header = mmap_mem;
Daniel Borkmanna64af0e2018-10-19 15:51:03 +02006712 __u64 data_head = ring_buffer_read_head(header);
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006713 __u64 data_tail = header->data_tail;
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006714 void *base = ((__u8 *)header) + page_size;
6715 int ret = LIBBPF_PERF_EVENT_CONT;
6716 struct perf_event_header *ehdr;
6717 size_t ehdr_size;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006718
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006719 while (data_head != data_tail) {
6720 ehdr = base + (data_tail & (mmap_size - 1));
6721 ehdr_size = ehdr->size;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006722
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006723 if (((void *)ehdr) + ehdr_size > base + mmap_size) {
6724 void *copy_start = ehdr;
6725 size_t len_first = base + mmap_size - copy_start;
6726 size_t len_secnd = ehdr_size - len_first;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006727
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006728 if (*copy_size < ehdr_size) {
6729 free(*copy_mem);
6730 *copy_mem = malloc(ehdr_size);
6731 if (!*copy_mem) {
6732 *copy_size = 0;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006733 ret = LIBBPF_PERF_EVENT_ERROR;
6734 break;
6735 }
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006736 *copy_size = ehdr_size;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006737 }
6738
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006739 memcpy(*copy_mem, copy_start, len_first);
6740 memcpy(*copy_mem + len_first, base, len_secnd);
6741 ehdr = *copy_mem;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006742 }
6743
Daniel Borkmann3dca2112018-10-21 02:09:28 +02006744 ret = fn(ehdr, private_data);
6745 data_tail += ehdr_size;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006746 if (ret != LIBBPF_PERF_EVENT_CONT)
6747 break;
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006748 }
6749
Daniel Borkmanna64af0e2018-10-19 15:51:03 +02006750 ring_buffer_write_tail(header, data_tail);
Jakub Kicinskid0cabbb2018-05-10 10:24:40 -07006751 return ret;
6752}
Song Liu34be16462019-03-11 22:30:38 -07006753
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006754struct perf_buffer;
6755
6756struct perf_buffer_params {
6757 struct perf_event_attr *attr;
6758 /* if event_cb is specified, it takes precendence */
6759 perf_buffer_event_fn event_cb;
6760 /* sample_cb and lost_cb are higher-level common-case callbacks */
6761 perf_buffer_sample_fn sample_cb;
6762 perf_buffer_lost_fn lost_cb;
6763 void *ctx;
6764 int cpu_cnt;
6765 int *cpus;
6766 int *map_keys;
6767};
6768
6769struct perf_cpu_buf {
6770 struct perf_buffer *pb;
6771 void *base; /* mmap()'ed memory */
6772 void *buf; /* for reconstructing segmented data */
6773 size_t buf_size;
6774 int fd;
6775 int cpu;
6776 int map_key;
6777};
6778
6779struct perf_buffer {
6780 perf_buffer_event_fn event_cb;
6781 perf_buffer_sample_fn sample_cb;
6782 perf_buffer_lost_fn lost_cb;
6783 void *ctx; /* passed into callbacks */
6784
6785 size_t page_size;
6786 size_t mmap_size;
6787 struct perf_cpu_buf **cpu_bufs;
6788 struct epoll_event *events;
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08006789 int cpu_cnt; /* number of allocated CPU buffers */
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006790 int epoll_fd; /* perf event FD */
6791 int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
6792};
6793
6794static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
6795 struct perf_cpu_buf *cpu_buf)
6796{
6797 if (!cpu_buf)
6798 return;
6799 if (cpu_buf->base &&
6800 munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
Kefeng Wangbe180102019-10-21 13:55:32 +08006801 pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006802 if (cpu_buf->fd >= 0) {
6803 ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
6804 close(cpu_buf->fd);
6805 }
6806 free(cpu_buf->buf);
6807 free(cpu_buf);
6808}
6809
6810void perf_buffer__free(struct perf_buffer *pb)
6811{
6812 int i;
6813
6814 if (!pb)
6815 return;
6816 if (pb->cpu_bufs) {
6817 for (i = 0; i < pb->cpu_cnt && pb->cpu_bufs[i]; i++) {
6818 struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
6819
6820 bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
6821 perf_buffer__free_cpu_buf(pb, cpu_buf);
6822 }
6823 free(pb->cpu_bufs);
6824 }
6825 if (pb->epoll_fd >= 0)
6826 close(pb->epoll_fd);
6827 free(pb->events);
6828 free(pb);
6829}
6830
6831static struct perf_cpu_buf *
6832perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
6833 int cpu, int map_key)
6834{
6835 struct perf_cpu_buf *cpu_buf;
6836 char msg[STRERR_BUFSIZE];
6837 int err;
6838
6839 cpu_buf = calloc(1, sizeof(*cpu_buf));
6840 if (!cpu_buf)
6841 return ERR_PTR(-ENOMEM);
6842
6843 cpu_buf->pb = pb;
6844 cpu_buf->cpu = cpu;
6845 cpu_buf->map_key = map_key;
6846
6847 cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
6848 -1, PERF_FLAG_FD_CLOEXEC);
6849 if (cpu_buf->fd < 0) {
6850 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006851 pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
6852 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006853 goto error;
6854 }
6855
6856 cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
6857 PROT_READ | PROT_WRITE, MAP_SHARED,
6858 cpu_buf->fd, 0);
6859 if (cpu_buf->base == MAP_FAILED) {
6860 cpu_buf->base = NULL;
6861 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006862 pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
6863 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006864 goto error;
6865 }
6866
6867 if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
6868 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006869 pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
6870 cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006871 goto error;
6872 }
6873
6874 return cpu_buf;
6875
6876error:
6877 perf_buffer__free_cpu_buf(pb, cpu_buf);
6878 return (struct perf_cpu_buf *)ERR_PTR(err);
6879}
6880
6881static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6882 struct perf_buffer_params *p);
6883
6884struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
6885 const struct perf_buffer_opts *opts)
6886{
6887 struct perf_buffer_params p = {};
Arnaldo Carvalho de Melo4be6e052019-07-19 11:34:07 -03006888 struct perf_event_attr attr = { 0, };
6889
6890 attr.config = PERF_COUNT_SW_BPF_OUTPUT,
6891 attr.type = PERF_TYPE_SOFTWARE;
6892 attr.sample_type = PERF_SAMPLE_RAW;
6893 attr.sample_period = 1;
6894 attr.wakeup_events = 1;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006895
6896 p.attr = &attr;
6897 p.sample_cb = opts ? opts->sample_cb : NULL;
6898 p.lost_cb = opts ? opts->lost_cb : NULL;
6899 p.ctx = opts ? opts->ctx : NULL;
6900
6901 return __perf_buffer__new(map_fd, page_cnt, &p);
6902}
6903
6904struct perf_buffer *
6905perf_buffer__new_raw(int map_fd, size_t page_cnt,
6906 const struct perf_buffer_raw_opts *opts)
6907{
6908 struct perf_buffer_params p = {};
6909
6910 p.attr = opts->attr;
6911 p.event_cb = opts->event_cb;
6912 p.ctx = opts->ctx;
6913 p.cpu_cnt = opts->cpu_cnt;
6914 p.cpus = opts->cpus;
6915 p.map_keys = opts->map_keys;
6916
6917 return __perf_buffer__new(map_fd, page_cnt, &p);
6918}
6919
6920static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
6921 struct perf_buffer_params *p)
6922{
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08006923 const char *online_cpus_file = "/sys/devices/system/cpu/online";
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006924 struct bpf_map_info map = {};
6925 char msg[STRERR_BUFSIZE];
6926 struct perf_buffer *pb;
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08006927 bool *online = NULL;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006928 __u32 map_info_len;
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08006929 int err, i, j, n;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006930
6931 if (page_cnt & (page_cnt - 1)) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006932 pr_warn("page count should be power of two, but is %zu\n",
6933 page_cnt);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006934 return ERR_PTR(-EINVAL);
6935 }
6936
6937 map_info_len = sizeof(map);
6938 err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
6939 if (err) {
6940 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006941 pr_warn("failed to get map info for map FD %d: %s\n",
6942 map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006943 return ERR_PTR(err);
6944 }
6945
6946 if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
Kefeng Wangbe180102019-10-21 13:55:32 +08006947 pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
6948 map.name);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006949 return ERR_PTR(-EINVAL);
6950 }
6951
6952 pb = calloc(1, sizeof(*pb));
6953 if (!pb)
6954 return ERR_PTR(-ENOMEM);
6955
6956 pb->event_cb = p->event_cb;
6957 pb->sample_cb = p->sample_cb;
6958 pb->lost_cb = p->lost_cb;
6959 pb->ctx = p->ctx;
6960
6961 pb->page_size = getpagesize();
6962 pb->mmap_size = pb->page_size * page_cnt;
6963 pb->map_fd = map_fd;
6964
6965 pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
6966 if (pb->epoll_fd < 0) {
6967 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08006968 pr_warn("failed to create epoll instance: %s\n",
6969 libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006970 goto error;
6971 }
6972
6973 if (p->cpu_cnt > 0) {
6974 pb->cpu_cnt = p->cpu_cnt;
6975 } else {
6976 pb->cpu_cnt = libbpf_num_possible_cpus();
6977 if (pb->cpu_cnt < 0) {
6978 err = pb->cpu_cnt;
6979 goto error;
6980 }
6981 if (map.max_entries < pb->cpu_cnt)
6982 pb->cpu_cnt = map.max_entries;
6983 }
6984
6985 pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
6986 if (!pb->events) {
6987 err = -ENOMEM;
Kefeng Wangbe180102019-10-21 13:55:32 +08006988 pr_warn("failed to allocate events: out of memory\n");
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006989 goto error;
6990 }
6991 pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
6992 if (!pb->cpu_bufs) {
6993 err = -ENOMEM;
Kefeng Wangbe180102019-10-21 13:55:32 +08006994 pr_warn("failed to allocate buffers: out of memory\n");
Andrii Nakryikofb84b822019-07-06 11:06:24 -07006995 goto error;
6996 }
6997
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08006998 err = parse_cpu_mask_file(online_cpus_file, &online, &n);
6999 if (err) {
7000 pr_warn("failed to get online CPU mask: %d\n", err);
7001 goto error;
7002 }
7003
7004 for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007005 struct perf_cpu_buf *cpu_buf;
7006 int cpu, map_key;
7007
7008 cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
7009 map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
7010
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007011 /* in case user didn't explicitly requested particular CPUs to
7012 * be attached to, skip offline/not present CPUs
7013 */
7014 if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
7015 continue;
7016
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007017 cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
7018 if (IS_ERR(cpu_buf)) {
7019 err = PTR_ERR(cpu_buf);
7020 goto error;
7021 }
7022
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007023 pb->cpu_bufs[j] = cpu_buf;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007024
7025 err = bpf_map_update_elem(pb->map_fd, &map_key,
7026 &cpu_buf->fd, 0);
7027 if (err) {
7028 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08007029 pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
7030 cpu, map_key, cpu_buf->fd,
7031 libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007032 goto error;
7033 }
7034
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007035 pb->events[j].events = EPOLLIN;
7036 pb->events[j].data.ptr = cpu_buf;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007037 if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007038 &pb->events[j]) < 0) {
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007039 err = -errno;
Kefeng Wangbe180102019-10-21 13:55:32 +08007040 pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
7041 cpu, cpu_buf->fd,
7042 libbpf_strerror_r(err, msg, sizeof(msg)));
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007043 goto error;
7044 }
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007045 j++;
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007046 }
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007047 pb->cpu_cnt = j;
7048 free(online);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007049
7050 return pb;
7051
7052error:
Andrii Nakryiko783b8f02019-12-11 17:36:09 -08007053 free(online);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007054 if (pb)
7055 perf_buffer__free(pb);
7056 return ERR_PTR(err);
7057}
7058
7059struct perf_sample_raw {
7060 struct perf_event_header header;
7061 uint32_t size;
7062 char data[0];
7063};
7064
7065struct perf_sample_lost {
7066 struct perf_event_header header;
7067 uint64_t id;
7068 uint64_t lost;
7069 uint64_t sample_id;
7070};
7071
7072static enum bpf_perf_event_ret
7073perf_buffer__process_record(struct perf_event_header *e, void *ctx)
7074{
7075 struct perf_cpu_buf *cpu_buf = ctx;
7076 struct perf_buffer *pb = cpu_buf->pb;
7077 void *data = e;
7078
7079 /* user wants full control over parsing perf event */
7080 if (pb->event_cb)
7081 return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
7082
7083 switch (e->type) {
7084 case PERF_RECORD_SAMPLE: {
7085 struct perf_sample_raw *s = data;
7086
7087 if (pb->sample_cb)
7088 pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
7089 break;
7090 }
7091 case PERF_RECORD_LOST: {
7092 struct perf_sample_lost *s = data;
7093
7094 if (pb->lost_cb)
7095 pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
7096 break;
7097 }
7098 default:
Kefeng Wangbe180102019-10-21 13:55:32 +08007099 pr_warn("unknown perf sample type %d\n", e->type);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007100 return LIBBPF_PERF_EVENT_ERROR;
7101 }
7102 return LIBBPF_PERF_EVENT_CONT;
7103}
7104
7105static int perf_buffer__process_records(struct perf_buffer *pb,
7106 struct perf_cpu_buf *cpu_buf)
7107{
7108 enum bpf_perf_event_ret ret;
7109
7110 ret = bpf_perf_event_read_simple(cpu_buf->base, pb->mmap_size,
7111 pb->page_size, &cpu_buf->buf,
7112 &cpu_buf->buf_size,
7113 perf_buffer__process_record, cpu_buf);
7114 if (ret != LIBBPF_PERF_EVENT_CONT)
7115 return ret;
7116 return 0;
7117}
7118
7119int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
7120{
7121 int i, cnt, err;
7122
7123 cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
7124 for (i = 0; i < cnt; i++) {
7125 struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
7126
7127 err = perf_buffer__process_records(pb, cpu_buf);
7128 if (err) {
Kefeng Wangbe180102019-10-21 13:55:32 +08007129 pr_warn("error while processing records: %d\n", err);
Andrii Nakryikofb84b822019-07-06 11:06:24 -07007130 return err;
7131 }
7132 }
7133 return cnt < 0 ? -errno : cnt;
7134}
7135
Song Liu34be16462019-03-11 22:30:38 -07007136struct bpf_prog_info_array_desc {
7137 int array_offset; /* e.g. offset of jited_prog_insns */
7138 int count_offset; /* e.g. offset of jited_prog_len */
7139 int size_offset; /* > 0: offset of rec size,
7140 * < 0: fix size of -size_offset
7141 */
7142};
7143
7144static struct bpf_prog_info_array_desc bpf_prog_info_array_desc[] = {
7145 [BPF_PROG_INFO_JITED_INSNS] = {
7146 offsetof(struct bpf_prog_info, jited_prog_insns),
7147 offsetof(struct bpf_prog_info, jited_prog_len),
7148 -1,
7149 },
7150 [BPF_PROG_INFO_XLATED_INSNS] = {
7151 offsetof(struct bpf_prog_info, xlated_prog_insns),
7152 offsetof(struct bpf_prog_info, xlated_prog_len),
7153 -1,
7154 },
7155 [BPF_PROG_INFO_MAP_IDS] = {
7156 offsetof(struct bpf_prog_info, map_ids),
7157 offsetof(struct bpf_prog_info, nr_map_ids),
7158 -(int)sizeof(__u32),
7159 },
7160 [BPF_PROG_INFO_JITED_KSYMS] = {
7161 offsetof(struct bpf_prog_info, jited_ksyms),
7162 offsetof(struct bpf_prog_info, nr_jited_ksyms),
7163 -(int)sizeof(__u64),
7164 },
7165 [BPF_PROG_INFO_JITED_FUNC_LENS] = {
7166 offsetof(struct bpf_prog_info, jited_func_lens),
7167 offsetof(struct bpf_prog_info, nr_jited_func_lens),
7168 -(int)sizeof(__u32),
7169 },
7170 [BPF_PROG_INFO_FUNC_INFO] = {
7171 offsetof(struct bpf_prog_info, func_info),
7172 offsetof(struct bpf_prog_info, nr_func_info),
7173 offsetof(struct bpf_prog_info, func_info_rec_size),
7174 },
7175 [BPF_PROG_INFO_LINE_INFO] = {
7176 offsetof(struct bpf_prog_info, line_info),
7177 offsetof(struct bpf_prog_info, nr_line_info),
7178 offsetof(struct bpf_prog_info, line_info_rec_size),
7179 },
7180 [BPF_PROG_INFO_JITED_LINE_INFO] = {
7181 offsetof(struct bpf_prog_info, jited_line_info),
7182 offsetof(struct bpf_prog_info, nr_jited_line_info),
7183 offsetof(struct bpf_prog_info, jited_line_info_rec_size),
7184 },
7185 [BPF_PROG_INFO_PROG_TAGS] = {
7186 offsetof(struct bpf_prog_info, prog_tags),
7187 offsetof(struct bpf_prog_info, nr_prog_tags),
7188 -(int)sizeof(__u8) * BPF_TAG_SIZE,
7189 },
7190
7191};
7192
Andrii Nakryiko8983b732019-11-20 23:07:42 -08007193static __u32 bpf_prog_info_read_offset_u32(struct bpf_prog_info *info,
7194 int offset)
Song Liu34be16462019-03-11 22:30:38 -07007195{
7196 __u32 *array = (__u32 *)info;
7197
7198 if (offset >= 0)
7199 return array[offset / sizeof(__u32)];
7200 return -(int)offset;
7201}
7202
Andrii Nakryiko8983b732019-11-20 23:07:42 -08007203static __u64 bpf_prog_info_read_offset_u64(struct bpf_prog_info *info,
7204 int offset)
Song Liu34be16462019-03-11 22:30:38 -07007205{
7206 __u64 *array = (__u64 *)info;
7207
7208 if (offset >= 0)
7209 return array[offset / sizeof(__u64)];
7210 return -(int)offset;
7211}
7212
7213static void bpf_prog_info_set_offset_u32(struct bpf_prog_info *info, int offset,
7214 __u32 val)
7215{
7216 __u32 *array = (__u32 *)info;
7217
7218 if (offset >= 0)
7219 array[offset / sizeof(__u32)] = val;
7220}
7221
7222static void bpf_prog_info_set_offset_u64(struct bpf_prog_info *info, int offset,
7223 __u64 val)
7224{
7225 __u64 *array = (__u64 *)info;
7226
7227 if (offset >= 0)
7228 array[offset / sizeof(__u64)] = val;
7229}
7230
7231struct bpf_prog_info_linear *
7232bpf_program__get_prog_info_linear(int fd, __u64 arrays)
7233{
7234 struct bpf_prog_info_linear *info_linear;
7235 struct bpf_prog_info info = {};
7236 __u32 info_len = sizeof(info);
7237 __u32 data_len = 0;
7238 int i, err;
7239 void *ptr;
7240
7241 if (arrays >> BPF_PROG_INFO_LAST_ARRAY)
7242 return ERR_PTR(-EINVAL);
7243
7244 /* step 1: get array dimensions */
7245 err = bpf_obj_get_info_by_fd(fd, &info, &info_len);
7246 if (err) {
7247 pr_debug("can't get prog info: %s", strerror(errno));
7248 return ERR_PTR(-EFAULT);
7249 }
7250
7251 /* step 2: calculate total size of all arrays */
7252 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7253 bool include_array = (arrays & (1UL << i)) > 0;
7254 struct bpf_prog_info_array_desc *desc;
7255 __u32 count, size;
7256
7257 desc = bpf_prog_info_array_desc + i;
7258
7259 /* kernel is too old to support this field */
7260 if (info_len < desc->array_offset + sizeof(__u32) ||
7261 info_len < desc->count_offset + sizeof(__u32) ||
7262 (desc->size_offset > 0 && info_len < desc->size_offset))
7263 include_array = false;
7264
7265 if (!include_array) {
7266 arrays &= ~(1UL << i); /* clear the bit */
7267 continue;
7268 }
7269
7270 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7271 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7272
7273 data_len += count * size;
7274 }
7275
7276 /* step 3: allocate continuous memory */
7277 data_len = roundup(data_len, sizeof(__u64));
7278 info_linear = malloc(sizeof(struct bpf_prog_info_linear) + data_len);
7279 if (!info_linear)
7280 return ERR_PTR(-ENOMEM);
7281
7282 /* step 4: fill data to info_linear->info */
7283 info_linear->arrays = arrays;
7284 memset(&info_linear->info, 0, sizeof(info));
7285 ptr = info_linear->data;
7286
7287 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7288 struct bpf_prog_info_array_desc *desc;
7289 __u32 count, size;
7290
7291 if ((arrays & (1UL << i)) == 0)
7292 continue;
7293
7294 desc = bpf_prog_info_array_desc + i;
7295 count = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7296 size = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7297 bpf_prog_info_set_offset_u32(&info_linear->info,
7298 desc->count_offset, count);
7299 bpf_prog_info_set_offset_u32(&info_linear->info,
7300 desc->size_offset, size);
7301 bpf_prog_info_set_offset_u64(&info_linear->info,
7302 desc->array_offset,
7303 ptr_to_u64(ptr));
7304 ptr += count * size;
7305 }
7306
7307 /* step 5: call syscall again to get required arrays */
7308 err = bpf_obj_get_info_by_fd(fd, &info_linear->info, &info_len);
7309 if (err) {
7310 pr_debug("can't get prog info: %s", strerror(errno));
7311 free(info_linear);
7312 return ERR_PTR(-EFAULT);
7313 }
7314
7315 /* step 6: verify the data */
7316 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7317 struct bpf_prog_info_array_desc *desc;
7318 __u32 v1, v2;
7319
7320 if ((arrays & (1UL << i)) == 0)
7321 continue;
7322
7323 desc = bpf_prog_info_array_desc + i;
7324 v1 = bpf_prog_info_read_offset_u32(&info, desc->count_offset);
7325 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7326 desc->count_offset);
7327 if (v1 != v2)
Kefeng Wangbe180102019-10-21 13:55:32 +08007328 pr_warn("%s: mismatch in element count\n", __func__);
Song Liu34be16462019-03-11 22:30:38 -07007329
7330 v1 = bpf_prog_info_read_offset_u32(&info, desc->size_offset);
7331 v2 = bpf_prog_info_read_offset_u32(&info_linear->info,
7332 desc->size_offset);
7333 if (v1 != v2)
Kefeng Wangbe180102019-10-21 13:55:32 +08007334 pr_warn("%s: mismatch in rec size\n", __func__);
Song Liu34be16462019-03-11 22:30:38 -07007335 }
7336
7337 /* step 7: update info_len and data_len */
7338 info_linear->info_len = sizeof(struct bpf_prog_info);
7339 info_linear->data_len = data_len;
7340
7341 return info_linear;
7342}
7343
7344void bpf_program__bpil_addr_to_offs(struct bpf_prog_info_linear *info_linear)
7345{
7346 int i;
7347
7348 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7349 struct bpf_prog_info_array_desc *desc;
7350 __u64 addr, offs;
7351
7352 if ((info_linear->arrays & (1UL << i)) == 0)
7353 continue;
7354
7355 desc = bpf_prog_info_array_desc + i;
7356 addr = bpf_prog_info_read_offset_u64(&info_linear->info,
7357 desc->array_offset);
7358 offs = addr - ptr_to_u64(info_linear->data);
7359 bpf_prog_info_set_offset_u64(&info_linear->info,
7360 desc->array_offset, offs);
7361 }
7362}
7363
7364void bpf_program__bpil_offs_to_addr(struct bpf_prog_info_linear *info_linear)
7365{
7366 int i;
7367
7368 for (i = BPF_PROG_INFO_FIRST_ARRAY; i < BPF_PROG_INFO_LAST_ARRAY; ++i) {
7369 struct bpf_prog_info_array_desc *desc;
7370 __u64 addr, offs;
7371
7372 if ((info_linear->arrays & (1UL << i)) == 0)
7373 continue;
7374
7375 desc = bpf_prog_info_array_desc + i;
7376 offs = bpf_prog_info_read_offset_u64(&info_linear->info,
7377 desc->array_offset);
7378 addr = offs + ptr_to_u64(info_linear->data);
7379 bpf_prog_info_set_offset_u64(&info_linear->info,
7380 desc->array_offset, addr);
7381 }
7382}
Hechao Li6446b312019-06-10 17:56:50 -07007383
Andrii Nakryiko6803ee22019-12-11 17:35:48 -08007384int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
7385{
7386 int err = 0, n, len, start, end = -1;
7387 bool *tmp;
7388
7389 *mask = NULL;
7390 *mask_sz = 0;
7391
7392 /* Each sub string separated by ',' has format \d+-\d+ or \d+ */
7393 while (*s) {
7394 if (*s == ',' || *s == '\n') {
7395 s++;
7396 continue;
7397 }
7398 n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
7399 if (n <= 0 || n > 2) {
7400 pr_warn("Failed to get CPU range %s: %d\n", s, n);
7401 err = -EINVAL;
7402 goto cleanup;
7403 } else if (n == 1) {
7404 end = start;
7405 }
7406 if (start < 0 || start > end) {
7407 pr_warn("Invalid CPU range [%d,%d] in %s\n",
7408 start, end, s);
7409 err = -EINVAL;
7410 goto cleanup;
7411 }
7412 tmp = realloc(*mask, end + 1);
7413 if (!tmp) {
7414 err = -ENOMEM;
7415 goto cleanup;
7416 }
7417 *mask = tmp;
7418 memset(tmp + *mask_sz, 0, start - *mask_sz);
7419 memset(tmp + start, 1, end - start + 1);
7420 *mask_sz = end + 1;
7421 s += len;
7422 }
7423 if (!*mask_sz) {
7424 pr_warn("Empty CPU range\n");
7425 return -EINVAL;
7426 }
7427 return 0;
7428cleanup:
7429 free(*mask);
7430 *mask = NULL;
7431 return err;
7432}
7433
7434int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
7435{
7436 int fd, err = 0, len;
7437 char buf[128];
7438
7439 fd = open(fcpu, O_RDONLY);
7440 if (fd < 0) {
7441 err = -errno;
7442 pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
7443 return err;
7444 }
7445 len = read(fd, buf, sizeof(buf));
7446 close(fd);
7447 if (len <= 0) {
7448 err = len ? -errno : -EINVAL;
7449 pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
7450 return err;
7451 }
7452 if (len >= sizeof(buf)) {
7453 pr_warn("CPU mask is too big in file %s\n", fcpu);
7454 return -E2BIG;
7455 }
7456 buf[len] = '\0';
7457
7458 return parse_cpu_mask_str(buf, mask, mask_sz);
7459}
7460
Hechao Li6446b312019-06-10 17:56:50 -07007461int libbpf_num_possible_cpus(void)
7462{
7463 static const char *fcpu = "/sys/devices/system/cpu/possible";
Hechao Li6446b312019-06-10 17:56:50 -07007464 static int cpus;
Andrii Nakryiko6803ee22019-12-11 17:35:48 -08007465 int err, n, i, tmp_cpus;
7466 bool *mask;
Hechao Li6446b312019-06-10 17:56:50 -07007467
Takshak Chahande56fbc242019-07-31 15:10:55 -07007468 tmp_cpus = READ_ONCE(cpus);
7469 if (tmp_cpus > 0)
7470 return tmp_cpus;
Hechao Li6446b312019-06-10 17:56:50 -07007471
Andrii Nakryiko6803ee22019-12-11 17:35:48 -08007472 err = parse_cpu_mask_file(fcpu, &mask, &n);
7473 if (err)
7474 return err;
Hechao Li6446b312019-06-10 17:56:50 -07007475
Andrii Nakryiko6803ee22019-12-11 17:35:48 -08007476 tmp_cpus = 0;
7477 for (i = 0; i < n; i++) {
7478 if (mask[i])
7479 tmp_cpus++;
Hechao Li6446b312019-06-10 17:56:50 -07007480 }
Andrii Nakryiko6803ee22019-12-11 17:35:48 -08007481 free(mask);
Takshak Chahande56fbc242019-07-31 15:10:55 -07007482
7483 WRITE_ONCE(cpus, tmp_cpus);
7484 return tmp_cpus;
Hechao Li6446b312019-06-10 17:56:50 -07007485}
Andrii Nakryikod66562f2019-12-13 17:43:36 -08007486
7487int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
7488 const struct bpf_object_open_opts *opts)
7489{
7490 DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
7491 .object_name = s->name,
7492 );
7493 struct bpf_object *obj;
7494 int i;
7495
7496 /* Attempt to preserve opts->object_name, unless overriden by user
7497 * explicitly. Overwriting object name for skeletons is discouraged,
7498 * as it breaks global data maps, because they contain object name
7499 * prefix as their own map name prefix. When skeleton is generated,
7500 * bpftool is making an assumption that this name will stay the same.
7501 */
7502 if (opts) {
7503 memcpy(&skel_opts, opts, sizeof(*opts));
7504 if (!opts->object_name)
7505 skel_opts.object_name = s->name;
7506 }
7507
7508 obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
7509 if (IS_ERR(obj)) {
7510 pr_warn("failed to initialize skeleton BPF object '%s': %ld\n",
7511 s->name, PTR_ERR(obj));
7512 return PTR_ERR(obj);
7513 }
7514
7515 *s->obj = obj;
7516
7517 for (i = 0; i < s->map_cnt; i++) {
7518 struct bpf_map **map = s->maps[i].map;
7519 const char *name = s->maps[i].name;
7520 void **mmaped = s->maps[i].mmaped;
7521
7522 *map = bpf_object__find_map_by_name(obj, name);
7523 if (!*map) {
7524 pr_warn("failed to find skeleton map '%s'\n", name);
7525 return -ESRCH;
7526 }
7527
Andrii Nakryiko2ad97d42019-12-13 17:47:09 -08007528 /* externs shouldn't be pre-setup from user code */
7529 if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_EXTERN)
Andrii Nakryikod66562f2019-12-13 17:43:36 -08007530 *mmaped = (*map)->mmaped;
7531 }
7532
7533 for (i = 0; i < s->prog_cnt; i++) {
7534 struct bpf_program **prog = s->progs[i].prog;
7535 const char *name = s->progs[i].name;
7536
7537 *prog = bpf_object__find_program_by_name(obj, name);
7538 if (!*prog) {
7539 pr_warn("failed to find skeleton program '%s'\n", name);
7540 return -ESRCH;
7541 }
7542 }
7543
7544 return 0;
7545}
7546
7547int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
7548{
7549 int i, err;
7550
7551 err = bpf_object__load(*s->obj);
7552 if (err) {
7553 pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
7554 return err;
7555 }
7556
7557 for (i = 0; i < s->map_cnt; i++) {
7558 struct bpf_map *map = *s->maps[i].map;
7559 size_t mmap_sz = bpf_map_mmap_sz(map);
7560 int prot, map_fd = bpf_map__fd(map);
7561 void **mmaped = s->maps[i].mmaped;
Andrii Nakryikod66562f2019-12-13 17:43:36 -08007562
7563 if (!mmaped)
7564 continue;
7565
7566 if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
7567 *mmaped = NULL;
7568 continue;
7569 }
7570
7571 if (map->def.map_flags & BPF_F_RDONLY_PROG)
7572 prot = PROT_READ;
7573 else
7574 prot = PROT_READ | PROT_WRITE;
7575
7576 /* Remap anonymous mmap()-ed "map initialization image" as
7577 * a BPF map-backed mmap()-ed memory, but preserving the same
7578 * memory address. This will cause kernel to change process'
7579 * page table to point to a different piece of kernel memory,
7580 * but from userspace point of view memory address (and its
7581 * contents, being identical at this point) will stay the
7582 * same. This mapping will be released by bpf_object__close()
7583 * as per normal clean up procedure, so we don't need to worry
7584 * about it from skeleton's clean up perspective.
7585 */
Andrii Nakryiko2ad97d42019-12-13 17:47:09 -08007586 *mmaped = mmap(map->mmaped, mmap_sz, prot,
7587 MAP_SHARED | MAP_FIXED, map_fd, 0);
7588 if (*mmaped == MAP_FAILED) {
Andrii Nakryikod66562f2019-12-13 17:43:36 -08007589 err = -errno;
7590 *mmaped = NULL;
7591 pr_warn("failed to re-mmap() map '%s': %d\n",
7592 bpf_map__name(map), err);
7593 return err;
7594 }
7595 }
7596
7597 return 0;
7598}
7599
7600int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
7601{
7602 int i;
7603
7604 for (i = 0; i < s->prog_cnt; i++) {
7605 struct bpf_program *prog = *s->progs[i].prog;
7606 struct bpf_link **link = s->progs[i].link;
7607 const struct bpf_sec_def *sec_def;
7608 const char *sec_name = bpf_program__title(prog, false);
7609
7610 sec_def = find_sec_def(sec_name);
7611 if (!sec_def || !sec_def->attach_fn)
7612 continue;
7613
7614 *link = sec_def->attach_fn(sec_def, prog);
7615 if (IS_ERR(*link)) {
7616 pr_warn("failed to auto-attach program '%s': %ld\n",
7617 bpf_program__name(prog), PTR_ERR(*link));
7618 return PTR_ERR(*link);
7619 }
7620 }
7621
7622 return 0;
7623}
7624
7625void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
7626{
7627 int i;
7628
7629 for (i = 0; i < s->prog_cnt; i++) {
7630 struct bpf_link **link = s->progs[i].link;
7631
7632 if (!IS_ERR_OR_NULL(*link))
7633 bpf_link__destroy(*link);
7634 *link = NULL;
7635 }
7636}
7637
7638void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
7639{
7640 if (s->progs)
7641 bpf_object__detach_skeleton(s);
7642 if (s->obj)
7643 bpf_object__close(*s->obj);
7644 free(s->maps);
7645 free(s->progs);
7646 free(s);
7647}