xref: /openbmc/linux/tools/lib/bpf/libbpf_internal.h (revision e330fb14)
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 #define BTF_TYPE_TAG_ENC(value, type, component_idx) \
73 	BTF_TYPE_ENC(value, BTF_INFO_ENC(BTF_KIND_TAG, 0, 0), type), (component_idx)
74 
75 #ifndef likely
76 #define likely(x) __builtin_expect(!!(x), 1)
77 #endif
78 #ifndef unlikely
79 #define unlikely(x) __builtin_expect(!!(x), 0)
80 #endif
81 #ifndef min
82 # define min(x, y) ((x) < (y) ? (x) : (y))
83 #endif
84 #ifndef max
85 # define max(x, y) ((x) < (y) ? (y) : (x))
86 #endif
87 #ifndef offsetofend
88 # define offsetofend(TYPE, FIELD) \
89 	(offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
90 #endif
91 
92 /* Check whether a string `str` has prefix `pfx`, regardless if `pfx` is
93  * a string literal known at compilation time or char * pointer known only at
94  * runtime.
95  */
96 #define str_has_pfx(str, pfx) \
97 	(strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
98 
99 /* Symbol versioning is different between static and shared library.
100  * Properly versioned symbols are needed for shared library, but
101  * only the symbol of the new version is needed for static library.
102  * Starting with GNU C 10, use symver attribute instead of .symver assembler
103  * directive, which works better with GCC LTO builds.
104  */
105 #if defined(SHARED) && defined(__GNUC__) && __GNUC__ >= 10
106 
107 #define DEFAULT_VERSION(internal_name, api_name, version) \
108 	__attribute__((symver(#api_name "@@" #version)))
109 #define COMPAT_VERSION(internal_name, api_name, version) \
110 	__attribute__((symver(#api_name "@" #version)))
111 
112 #elif defined(SHARED)
113 
114 #define COMPAT_VERSION(internal_name, api_name, version) \
115 	asm(".symver " #internal_name "," #api_name "@" #version);
116 #define DEFAULT_VERSION(internal_name, api_name, version) \
117 	asm(".symver " #internal_name "," #api_name "@@" #version);
118 
119 #else /* !SHARED */
120 
121 #define COMPAT_VERSION(internal_name, api_name, version)
122 #define DEFAULT_VERSION(internal_name, api_name, version) \
123 	extern typeof(internal_name) api_name \
124 	__attribute__((alias(#internal_name)));
125 
126 #endif
127 
128 extern void libbpf_print(enum libbpf_print_level level,
129 			 const char *format, ...)
130 	__attribute__((format(printf, 2, 3)));
131 
132 #define __pr(level, fmt, ...)	\
133 do {				\
134 	libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__);	\
135 } while (0)
136 
137 #define pr_warn(fmt, ...)	__pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
138 #define pr_info(fmt, ...)	__pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
139 #define pr_debug(fmt, ...)	__pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
140 
141 #ifndef __has_builtin
142 #define __has_builtin(x) 0
143 #endif
144 /*
145  * Re-implement glibc's reallocarray() for libbpf internal-only use.
146  * reallocarray(), unfortunately, is not available in all versions of glibc,
147  * so requires extra feature detection and using reallocarray() stub from
148  * <tools/libc_compat.h> and COMPAT_NEED_REALLOCARRAY. All this complicates
149  * build of libbpf unnecessarily and is just a maintenance burden. Instead,
150  * it's trivial to implement libbpf-specific internal version and use it
151  * throughout libbpf.
152  */
153 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
154 {
155 	size_t total;
156 
157 #if __has_builtin(__builtin_mul_overflow)
158 	if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
159 		return NULL;
160 #else
161 	if (size == 0 || nmemb > ULONG_MAX / size)
162 		return NULL;
163 	total = nmemb * size;
164 #endif
165 	return realloc(ptr, total);
166 }
167 
168 struct btf;
169 struct btf_type;
170 
171 struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id);
172 const char *btf_kind_str(const struct btf_type *t);
173 const struct btf_type *skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
174 
175 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
176 {
177 	return (enum btf_func_linkage)(int)btf_vlen(t);
178 }
179 
180 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
181 {
182 	return (kflag << 31) | (kind << 24) | vlen;
183 }
184 
185 enum map_def_parts {
186 	MAP_DEF_MAP_TYPE	= 0x001,
187 	MAP_DEF_KEY_TYPE	= 0x002,
188 	MAP_DEF_KEY_SIZE	= 0x004,
189 	MAP_DEF_VALUE_TYPE	= 0x008,
190 	MAP_DEF_VALUE_SIZE	= 0x010,
191 	MAP_DEF_MAX_ENTRIES	= 0x020,
192 	MAP_DEF_MAP_FLAGS	= 0x040,
193 	MAP_DEF_NUMA_NODE	= 0x080,
194 	MAP_DEF_PINNING		= 0x100,
195 	MAP_DEF_INNER_MAP	= 0x200,
196 
197 	MAP_DEF_ALL		= 0x3ff, /* combination of all above */
198 };
199 
200 struct btf_map_def {
201 	enum map_def_parts parts;
202 	__u32 map_type;
203 	__u32 key_type_id;
204 	__u32 key_size;
205 	__u32 value_type_id;
206 	__u32 value_size;
207 	__u32 max_entries;
208 	__u32 map_flags;
209 	__u32 numa_node;
210 	__u32 pinning;
211 };
212 
213 int parse_btf_map_def(const char *map_name, struct btf *btf,
214 		      const struct btf_type *def_t, bool strict,
215 		      struct btf_map_def *map_def, struct btf_map_def *inner_def);
216 
217 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
218 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt);
219 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt);
220 
221 static inline bool libbpf_is_mem_zeroed(const char *p, ssize_t len)
222 {
223 	while (len > 0) {
224 		if (*p)
225 			return false;
226 		p++;
227 		len--;
228 	}
229 	return true;
230 }
231 
232 static inline bool libbpf_validate_opts(const char *opts,
233 					size_t opts_sz, size_t user_sz,
234 					const char *type_name)
235 {
236 	if (user_sz < sizeof(size_t)) {
237 		pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
238 		return false;
239 	}
240 	if (!libbpf_is_mem_zeroed(opts + opts_sz, (ssize_t)user_sz - opts_sz)) {
241 		pr_warn("%s has non-zero extra bytes\n", type_name);
242 		return false;
243 	}
244 	return true;
245 }
246 
247 #define OPTS_VALID(opts, type)						      \
248 	(!(opts) || libbpf_validate_opts((const char *)opts,		      \
249 					 offsetofend(struct type,	      \
250 						     type##__last_field),     \
251 					 (opts)->sz, #type))
252 #define OPTS_HAS(opts, field) \
253 	((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
254 #define OPTS_GET(opts, field, fallback_value) \
255 	(OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
256 #define OPTS_SET(opts, field, value)		\
257 	do {					\
258 		if (OPTS_HAS(opts, field))	\
259 			(opts)->field = value;	\
260 	} while (0)
261 
262 #define OPTS_ZEROED(opts, last_nonzero_field)				      \
263 ({									      \
264 	ssize_t __off = offsetofend(typeof(*(opts)), last_nonzero_field);     \
265 	!(opts) || libbpf_is_mem_zeroed((const void *)opts + __off,	      \
266 					(opts)->sz - __off);		      \
267 })
268 
269 
270 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
271 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
272 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
273 			 const char *str_sec, size_t str_len);
274 
275 struct bpf_prog_load_params {
276 	enum bpf_prog_type prog_type;
277 	enum bpf_attach_type expected_attach_type;
278 	const char *name;
279 	const struct bpf_insn *insns;
280 	size_t insn_cnt;
281 	const char *license;
282 	__u32 kern_version;
283 	__u32 attach_prog_fd;
284 	__u32 attach_btf_obj_fd;
285 	__u32 attach_btf_id;
286 	__u32 prog_ifindex;
287 	__u32 prog_btf_fd;
288 	__u32 prog_flags;
289 
290 	__u32 func_info_rec_size;
291 	const void *func_info;
292 	__u32 func_info_cnt;
293 
294 	__u32 line_info_rec_size;
295 	const void *line_info;
296 	__u32 line_info_cnt;
297 
298 	__u32 log_level;
299 	char *log_buf;
300 	size_t log_buf_sz;
301 };
302 
303 int libbpf__bpf_prog_load(const struct bpf_prog_load_params *load_attr);
304 
305 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
306 			     __u32 *size);
307 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
308 				__u32 *off);
309 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf);
310 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
311 				const char **prefix, int *kind);
312 
313 struct btf_ext_info {
314 	/*
315 	 * info points to the individual info section (e.g. func_info and
316 	 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
317 	 */
318 	void *info;
319 	__u32 rec_size;
320 	__u32 len;
321 };
322 
323 #define for_each_btf_ext_sec(seg, sec)					\
324 	for (sec = (seg)->info;						\
325 	     (void *)sec < (seg)->info + (seg)->len;			\
326 	     sec = (void *)sec + sizeof(struct btf_ext_info_sec) +	\
327 		   (seg)->rec_size * sec->num_info)
328 
329 #define for_each_btf_ext_rec(seg, sec, i, rec)				\
330 	for (i = 0, rec = (void *)&(sec)->data;				\
331 	     i < (sec)->num_info;					\
332 	     i++, rec = (void *)rec + (seg)->rec_size)
333 
334 /*
335  * The .BTF.ext ELF section layout defined as
336  *   struct btf_ext_header
337  *   func_info subsection
338  *
339  * The func_info subsection layout:
340  *   record size for struct bpf_func_info in the func_info subsection
341  *   struct btf_sec_func_info for section #1
342  *   a list of bpf_func_info records for section #1
343  *     where struct bpf_func_info mimics one in include/uapi/linux/bpf.h
344  *     but may not be identical
345  *   struct btf_sec_func_info for section #2
346  *   a list of bpf_func_info records for section #2
347  *   ......
348  *
349  * Note that the bpf_func_info record size in .BTF.ext may not
350  * be the same as the one defined in include/uapi/linux/bpf.h.
351  * The loader should ensure that record_size meets minimum
352  * requirement and pass the record as is to the kernel. The
353  * kernel will handle the func_info properly based on its contents.
354  */
355 struct btf_ext_header {
356 	__u16	magic;
357 	__u8	version;
358 	__u8	flags;
359 	__u32	hdr_len;
360 
361 	/* All offsets are in bytes relative to the end of this header */
362 	__u32	func_info_off;
363 	__u32	func_info_len;
364 	__u32	line_info_off;
365 	__u32	line_info_len;
366 
367 	/* optional part of .BTF.ext header */
368 	__u32	core_relo_off;
369 	__u32	core_relo_len;
370 };
371 
372 struct btf_ext {
373 	union {
374 		struct btf_ext_header *hdr;
375 		void *data;
376 	};
377 	struct btf_ext_info func_info;
378 	struct btf_ext_info line_info;
379 	struct btf_ext_info core_relo_info;
380 	__u32 data_size;
381 };
382 
383 struct btf_ext_info_sec {
384 	__u32	sec_name_off;
385 	__u32	num_info;
386 	/* Followed by num_info * record_size number of bytes */
387 	__u8	data[];
388 };
389 
390 /* The minimum bpf_func_info checked by the loader */
391 struct bpf_func_info_min {
392 	__u32   insn_off;
393 	__u32   type_id;
394 };
395 
396 /* The minimum bpf_line_info checked by the loader */
397 struct bpf_line_info_min {
398 	__u32	insn_off;
399 	__u32	file_name_off;
400 	__u32	line_off;
401 	__u32	line_col;
402 };
403 
404 
405 typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
406 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
407 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx);
408 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx);
409 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
410 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
411 
412 extern enum libbpf_strict_mode libbpf_mode;
413 
414 /* handle direct returned errors */
415 static inline int libbpf_err(int ret)
416 {
417 	if (ret < 0)
418 		errno = -ret;
419 	return ret;
420 }
421 
422 /* handle errno-based (e.g., syscall or libc) errors according to libbpf's
423  * strict mode settings
424  */
425 static inline int libbpf_err_errno(int ret)
426 {
427 	if (libbpf_mode & LIBBPF_STRICT_DIRECT_ERRS)
428 		/* errno is already assumed to be set on error */
429 		return ret < 0 ? -errno : ret;
430 
431 	/* legacy: on error return -1 directly and don't touch errno */
432 	return ret;
433 }
434 
435 /* handle error for pointer-returning APIs, err is assumed to be < 0 always */
436 static inline void *libbpf_err_ptr(int err)
437 {
438 	/* set errno on error, this doesn't break anything */
439 	errno = -err;
440 
441 	if (libbpf_mode & LIBBPF_STRICT_CLEAN_PTRS)
442 		return NULL;
443 
444 	/* legacy: encode err as ptr */
445 	return ERR_PTR(err);
446 }
447 
448 /* handle pointer-returning APIs' error handling */
449 static inline void *libbpf_ptr(void *ret)
450 {
451 	/* set errno on error, this doesn't break anything */
452 	if (IS_ERR(ret))
453 		errno = -PTR_ERR(ret);
454 
455 	if (libbpf_mode & LIBBPF_STRICT_CLEAN_PTRS)
456 		return IS_ERR(ret) ? NULL : ret;
457 
458 	/* legacy: pass-through original pointer */
459 	return ret;
460 }
461 
462 static inline bool str_is_empty(const char *s)
463 {
464 	return !s || !s[0];
465 }
466 
467 static inline bool is_ldimm64_insn(struct bpf_insn *insn)
468 {
469 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
470 }
471 
472 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
473