xref: /openbmc/linux/tools/lib/bpf/libbpf_internal.h (revision ee7da21a)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * Internal libbpf helpers.
5  *
6  * Copyright (c) 2019 Facebook
7  */
8 
9 #ifndef __LIBBPF_LIBBPF_INTERNAL_H
10 #define __LIBBPF_LIBBPF_INTERNAL_H
11 
12 #include <stdlib.h>
13 #include <limits.h>
14 #include <errno.h>
15 #include <linux/err.h>
16 #include "libbpf_legacy.h"
17 #include "relo_core.h"
18 
19 /* make sure libbpf doesn't use kernel-only integer typedefs */
20 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
21 
22 /* prevent accidental re-addition of reallocarray() */
23 #pragma GCC poison reallocarray
24 
25 #include "libbpf.h"
26 #include "btf.h"
27 
28 #ifndef EM_BPF
29 #define EM_BPF 247
30 #endif
31 
32 #ifndef R_BPF_64_64
33 #define R_BPF_64_64 1
34 #endif
35 #ifndef R_BPF_64_ABS64
36 #define R_BPF_64_ABS64 2
37 #endif
38 #ifndef R_BPF_64_ABS32
39 #define R_BPF_64_ABS32 3
40 #endif
41 #ifndef R_BPF_64_32
42 #define R_BPF_64_32 10
43 #endif
44 
45 #ifndef SHT_LLVM_ADDRSIG
46 #define SHT_LLVM_ADDRSIG 0x6FFF4C03
47 #endif
48 
49 /* if libelf is old and doesn't support mmap(), fall back to read() */
50 #ifndef ELF_C_READ_MMAP
51 #define ELF_C_READ_MMAP ELF_C_READ
52 #endif
53 
54 /* Older libelf all end up in this expression, for both 32 and 64 bit */
55 #ifndef GELF_ST_VISIBILITY
56 #define GELF_ST_VISIBILITY(o) ((o) & 0x03)
57 #endif
58 
59 #define BTF_INFO_ENC(kind, kind_flag, vlen) \
60 	((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
61 #define BTF_TYPE_ENC(name, info, size_or_type) (name), (info), (size_or_type)
62 #define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
63 	((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
64 #define BTF_TYPE_INT_ENC(name, encoding, bits_offset, bits, sz) \
65 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_INT, 0, 0), sz), \
66 	BTF_INT_ENC(encoding, bits_offset, bits)
67 #define BTF_MEMBER_ENC(name, type, bits_offset) (name), (type), (bits_offset)
68 #define BTF_PARAM_ENC(name, type) (name), (type)
69 #define BTF_VAR_SECINFO_ENC(type, offset, size) (type), (offset), (size)
70 #define BTF_TYPE_FLOAT_ENC(name, sz) \
71 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_FLOAT, 0, 0), sz)
72 
73 #ifndef likely
74 #define likely(x) __builtin_expect(!!(x), 1)
75 #endif
76 #ifndef unlikely
77 #define unlikely(x) __builtin_expect(!!(x), 0)
78 #endif
79 #ifndef min
80 # define min(x, y) ((x) < (y) ? (x) : (y))
81 #endif
82 #ifndef max
83 # define max(x, y) ((x) < (y) ? (y) : (x))
84 #endif
85 #ifndef offsetofend
86 # define offsetofend(TYPE, FIELD) \
87 	(offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
88 #endif
89 
90 /* Symbol versioning is different between static and shared library.
91  * Properly versioned symbols are needed for shared library, but
92  * only the symbol of the new version is needed for static library.
93  */
94 #ifdef SHARED
95 # define COMPAT_VERSION(internal_name, api_name, version) \
96 	asm(".symver " #internal_name "," #api_name "@" #version);
97 # define DEFAULT_VERSION(internal_name, api_name, version) \
98 	asm(".symver " #internal_name "," #api_name "@@" #version);
99 #else
100 # define COMPAT_VERSION(internal_name, api_name, version)
101 # define DEFAULT_VERSION(internal_name, api_name, version) \
102 	extern typeof(internal_name) api_name \
103 	__attribute__((alias(#internal_name)));
104 #endif
105 
106 extern void libbpf_print(enum libbpf_print_level level,
107 			 const char *format, ...)
108 	__attribute__((format(printf, 2, 3)));
109 
110 #define __pr(level, fmt, ...)	\
111 do {				\
112 	libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__);	\
113 } while (0)
114 
115 #define pr_warn(fmt, ...)	__pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
116 #define pr_info(fmt, ...)	__pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
117 #define pr_debug(fmt, ...)	__pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
118 
119 #ifndef __has_builtin
120 #define __has_builtin(x) 0
121 #endif
122 /*
123  * Re-implement glibc's reallocarray() for libbpf internal-only use.
124  * reallocarray(), unfortunately, is not available in all versions of glibc,
125  * so requires extra feature detection and using reallocarray() stub from
126  * <tools/libc_compat.h> and COMPAT_NEED_REALLOCARRAY. All this complicates
127  * build of libbpf unnecessarily and is just a maintenance burden. Instead,
128  * it's trivial to implement libbpf-specific internal version and use it
129  * throughout libbpf.
130  */
131 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
132 {
133 	size_t total;
134 
135 #if __has_builtin(__builtin_mul_overflow)
136 	if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
137 		return NULL;
138 #else
139 	if (size == 0 || nmemb > ULONG_MAX / size)
140 		return NULL;
141 	total = nmemb * size;
142 #endif
143 	return realloc(ptr, total);
144 }
145 
146 struct btf;
147 struct btf_type;
148 
149 struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id);
150 const char *btf_kind_str(const struct btf_type *t);
151 const struct btf_type *skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
152 
153 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
154 {
155 	return (enum btf_func_linkage)(int)btf_vlen(t);
156 }
157 
158 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
159 {
160 	return (kflag << 31) | (kind << 24) | vlen;
161 }
162 
163 enum map_def_parts {
164 	MAP_DEF_MAP_TYPE	= 0x001,
165 	MAP_DEF_KEY_TYPE	= 0x002,
166 	MAP_DEF_KEY_SIZE	= 0x004,
167 	MAP_DEF_VALUE_TYPE	= 0x008,
168 	MAP_DEF_VALUE_SIZE	= 0x010,
169 	MAP_DEF_MAX_ENTRIES	= 0x020,
170 	MAP_DEF_MAP_FLAGS	= 0x040,
171 	MAP_DEF_NUMA_NODE	= 0x080,
172 	MAP_DEF_PINNING		= 0x100,
173 	MAP_DEF_INNER_MAP	= 0x200,
174 
175 	MAP_DEF_ALL		= 0x3ff, /* combination of all above */
176 };
177 
178 struct btf_map_def {
179 	enum map_def_parts parts;
180 	__u32 map_type;
181 	__u32 key_type_id;
182 	__u32 key_size;
183 	__u32 value_type_id;
184 	__u32 value_size;
185 	__u32 max_entries;
186 	__u32 map_flags;
187 	__u32 numa_node;
188 	__u32 pinning;
189 };
190 
191 int parse_btf_map_def(const char *map_name, struct btf *btf,
192 		      const struct btf_type *def_t, bool strict,
193 		      struct btf_map_def *map_def, struct btf_map_def *inner_def);
194 
195 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
196 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt);
197 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt);
198 
199 static inline bool libbpf_validate_opts(const char *opts,
200 					size_t opts_sz, size_t user_sz,
201 					const char *type_name)
202 {
203 	if (user_sz < sizeof(size_t)) {
204 		pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
205 		return false;
206 	}
207 	if (user_sz > opts_sz) {
208 		size_t i;
209 
210 		for (i = opts_sz; i < user_sz; i++) {
211 			if (opts[i]) {
212 				pr_warn("%s has non-zero extra bytes\n",
213 					type_name);
214 				return false;
215 			}
216 		}
217 	}
218 	return true;
219 }
220 
221 #define OPTS_VALID(opts, type)						      \
222 	(!(opts) || libbpf_validate_opts((const char *)opts,		      \
223 					 offsetofend(struct type,	      \
224 						     type##__last_field),     \
225 					 (opts)->sz, #type))
226 #define OPTS_HAS(opts, field) \
227 	((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
228 #define OPTS_GET(opts, field, fallback_value) \
229 	(OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
230 #define OPTS_SET(opts, field, value)		\
231 	do {					\
232 		if (OPTS_HAS(opts, field))	\
233 			(opts)->field = value;	\
234 	} while (0)
235 
236 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
237 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
238 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
239 			 const char *str_sec, size_t str_len);
240 
241 struct bpf_prog_load_params {
242 	enum bpf_prog_type prog_type;
243 	enum bpf_attach_type expected_attach_type;
244 	const char *name;
245 	const struct bpf_insn *insns;
246 	size_t insn_cnt;
247 	const char *license;
248 	__u32 kern_version;
249 	__u32 attach_prog_fd;
250 	__u32 attach_btf_obj_fd;
251 	__u32 attach_btf_id;
252 	__u32 prog_ifindex;
253 	__u32 prog_btf_fd;
254 	__u32 prog_flags;
255 
256 	__u32 func_info_rec_size;
257 	const void *func_info;
258 	__u32 func_info_cnt;
259 
260 	__u32 line_info_rec_size;
261 	const void *line_info;
262 	__u32 line_info_cnt;
263 
264 	__u32 log_level;
265 	char *log_buf;
266 	size_t log_buf_sz;
267 };
268 
269 int libbpf__bpf_prog_load(const struct bpf_prog_load_params *load_attr);
270 
271 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
272 			     __u32 *size);
273 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
274 				__u32 *off);
275 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf);
276 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
277 				const char **prefix, int *kind);
278 
279 struct btf_ext_info {
280 	/*
281 	 * info points to the individual info section (e.g. func_info and
282 	 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
283 	 */
284 	void *info;
285 	__u32 rec_size;
286 	__u32 len;
287 };
288 
289 #define for_each_btf_ext_sec(seg, sec)					\
290 	for (sec = (seg)->info;						\
291 	     (void *)sec < (seg)->info + (seg)->len;			\
292 	     sec = (void *)sec + sizeof(struct btf_ext_info_sec) +	\
293 		   (seg)->rec_size * sec->num_info)
294 
295 #define for_each_btf_ext_rec(seg, sec, i, rec)				\
296 	for (i = 0, rec = (void *)&(sec)->data;				\
297 	     i < (sec)->num_info;					\
298 	     i++, rec = (void *)rec + (seg)->rec_size)
299 
300 /*
301  * The .BTF.ext ELF section layout defined as
302  *   struct btf_ext_header
303  *   func_info subsection
304  *
305  * The func_info subsection layout:
306  *   record size for struct bpf_func_info in the func_info subsection
307  *   struct btf_sec_func_info for section #1
308  *   a list of bpf_func_info records for section #1
309  *     where struct bpf_func_info mimics one in include/uapi/linux/bpf.h
310  *     but may not be identical
311  *   struct btf_sec_func_info for section #2
312  *   a list of bpf_func_info records for section #2
313  *   ......
314  *
315  * Note that the bpf_func_info record size in .BTF.ext may not
316  * be the same as the one defined in include/uapi/linux/bpf.h.
317  * The loader should ensure that record_size meets minimum
318  * requirement and pass the record as is to the kernel. The
319  * kernel will handle the func_info properly based on its contents.
320  */
321 struct btf_ext_header {
322 	__u16	magic;
323 	__u8	version;
324 	__u8	flags;
325 	__u32	hdr_len;
326 
327 	/* All offsets are in bytes relative to the end of this header */
328 	__u32	func_info_off;
329 	__u32	func_info_len;
330 	__u32	line_info_off;
331 	__u32	line_info_len;
332 
333 	/* optional part of .BTF.ext header */
334 	__u32	core_relo_off;
335 	__u32	core_relo_len;
336 };
337 
338 struct btf_ext {
339 	union {
340 		struct btf_ext_header *hdr;
341 		void *data;
342 	};
343 	struct btf_ext_info func_info;
344 	struct btf_ext_info line_info;
345 	struct btf_ext_info core_relo_info;
346 	__u32 data_size;
347 };
348 
349 struct btf_ext_info_sec {
350 	__u32	sec_name_off;
351 	__u32	num_info;
352 	/* Followed by num_info * record_size number of bytes */
353 	__u8	data[];
354 };
355 
356 /* The minimum bpf_func_info checked by the loader */
357 struct bpf_func_info_min {
358 	__u32   insn_off;
359 	__u32   type_id;
360 };
361 
362 /* The minimum bpf_line_info checked by the loader */
363 struct bpf_line_info_min {
364 	__u32	insn_off;
365 	__u32	file_name_off;
366 	__u32	line_off;
367 	__u32	line_col;
368 };
369 
370 
371 typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
372 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
373 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx);
374 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx);
375 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
376 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
377 
378 extern enum libbpf_strict_mode libbpf_mode;
379 
380 /* handle direct returned errors */
381 static inline int libbpf_err(int ret)
382 {
383 	if (ret < 0)
384 		errno = -ret;
385 	return ret;
386 }
387 
388 /* handle errno-based (e.g., syscall or libc) errors according to libbpf's
389  * strict mode settings
390  */
391 static inline int libbpf_err_errno(int ret)
392 {
393 	if (libbpf_mode & LIBBPF_STRICT_DIRECT_ERRS)
394 		/* errno is already assumed to be set on error */
395 		return ret < 0 ? -errno : ret;
396 
397 	/* legacy: on error return -1 directly and don't touch errno */
398 	return ret;
399 }
400 
401 /* handle error for pointer-returning APIs, err is assumed to be < 0 always */
402 static inline void *libbpf_err_ptr(int err)
403 {
404 	/* set errno on error, this doesn't break anything */
405 	errno = -err;
406 
407 	if (libbpf_mode & LIBBPF_STRICT_CLEAN_PTRS)
408 		return NULL;
409 
410 	/* legacy: encode err as ptr */
411 	return ERR_PTR(err);
412 }
413 
414 /* handle pointer-returning APIs' error handling */
415 static inline void *libbpf_ptr(void *ret)
416 {
417 	/* set errno on error, this doesn't break anything */
418 	if (IS_ERR(ret))
419 		errno = -PTR_ERR(ret);
420 
421 	if (libbpf_mode & LIBBPF_STRICT_CLEAN_PTRS)
422 		return IS_ERR(ret) ? NULL : ret;
423 
424 	/* legacy: pass-through original pointer */
425 	return ret;
426 }
427 
428 static inline bool str_is_empty(const char *s)
429 {
430 	return !s || !s[0];
431 }
432 
433 static inline bool is_ldimm64_insn(struct bpf_insn *insn)
434 {
435 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
436 }
437 
438 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
439