xref: /linux/tools/lib/bpf/libbpf_internal.h (revision 110d3047a3ec033de00322b1a8068b1215efa97a)
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 <fcntl.h>
17 #include <unistd.h>
18 #include <sys/syscall.h>
19 #include <libelf.h>
20 #include "relo_core.h"
21 
22 /* make sure libbpf doesn't use kernel-only integer typedefs */
23 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
24 
25 /* prevent accidental re-addition of reallocarray() */
26 #pragma GCC poison reallocarray
27 
28 #include "libbpf.h"
29 #include "btf.h"
30 
31 #ifndef EM_BPF
32 #define EM_BPF 247
33 #endif
34 
35 #ifndef R_BPF_64_64
36 #define R_BPF_64_64 1
37 #endif
38 #ifndef R_BPF_64_ABS64
39 #define R_BPF_64_ABS64 2
40 #endif
41 #ifndef R_BPF_64_ABS32
42 #define R_BPF_64_ABS32 3
43 #endif
44 #ifndef R_BPF_64_32
45 #define R_BPF_64_32 10
46 #endif
47 
48 #ifndef SHT_LLVM_ADDRSIG
49 #define SHT_LLVM_ADDRSIG 0x6FFF4C03
50 #endif
51 
52 /* if libelf is old and doesn't support mmap(), fall back to read() */
53 #ifndef ELF_C_READ_MMAP
54 #define ELF_C_READ_MMAP ELF_C_READ
55 #endif
56 
57 /* Older libelf all end up in this expression, for both 32 and 64 bit */
58 #ifndef ELF64_ST_VISIBILITY
59 #define ELF64_ST_VISIBILITY(o) ((o) & 0x03)
60 #endif
61 
62 #define BTF_INFO_ENC(kind, kind_flag, vlen) \
63 	((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
64 #define BTF_TYPE_ENC(name, info, size_or_type) (name), (info), (size_or_type)
65 #define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
66 	((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
67 #define BTF_TYPE_INT_ENC(name, encoding, bits_offset, bits, sz) \
68 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_INT, 0, 0), sz), \
69 	BTF_INT_ENC(encoding, bits_offset, bits)
70 #define BTF_MEMBER_ENC(name, type, bits_offset) (name), (type), (bits_offset)
71 #define BTF_PARAM_ENC(name, type) (name), (type)
72 #define BTF_VAR_SECINFO_ENC(type, offset, size) (type), (offset), (size)
73 #define BTF_TYPE_FLOAT_ENC(name, sz) \
74 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_FLOAT, 0, 0), sz)
75 #define BTF_TYPE_DECL_TAG_ENC(value, type, component_idx) \
76 	BTF_TYPE_ENC(value, BTF_INFO_ENC(BTF_KIND_DECL_TAG, 0, 0), type), (component_idx)
77 #define BTF_TYPE_TYPE_TAG_ENC(value, type) \
78 	BTF_TYPE_ENC(value, BTF_INFO_ENC(BTF_KIND_TYPE_TAG, 0, 0), type)
79 
80 #ifndef likely
81 #define likely(x) __builtin_expect(!!(x), 1)
82 #endif
83 #ifndef unlikely
84 #define unlikely(x) __builtin_expect(!!(x), 0)
85 #endif
86 #ifndef min
87 # define min(x, y) ((x) < (y) ? (x) : (y))
88 #endif
89 #ifndef max
90 # define max(x, y) ((x) < (y) ? (y) : (x))
91 #endif
92 #ifndef offsetofend
93 # define offsetofend(TYPE, FIELD) \
94 	(offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
95 #endif
96 #ifndef __alias
97 #define __alias(symbol) __attribute__((alias(#symbol)))
98 #endif
99 
100 /* Check whether a string `str` has prefix `pfx`, regardless if `pfx` is
101  * a string literal known at compilation time or char * pointer known only at
102  * runtime.
103  */
104 #define str_has_pfx(str, pfx) \
105 	(strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
106 
107 /* suffix check */
108 static inline bool str_has_sfx(const char *str, const char *sfx)
109 {
110 	size_t str_len = strlen(str);
111 	size_t sfx_len = strlen(sfx);
112 
113 	if (sfx_len > str_len)
114 		return false;
115 	return strcmp(str + str_len - sfx_len, sfx) == 0;
116 }
117 
118 /* Symbol versioning is different between static and shared library.
119  * Properly versioned symbols are needed for shared library, but
120  * only the symbol of the new version is needed for static library.
121  * Starting with GNU C 10, use symver attribute instead of .symver assembler
122  * directive, which works better with GCC LTO builds.
123  */
124 #if defined(SHARED) && defined(__GNUC__) && __GNUC__ >= 10
125 
126 #define DEFAULT_VERSION(internal_name, api_name, version) \
127 	__attribute__((symver(#api_name "@@" #version)))
128 #define COMPAT_VERSION(internal_name, api_name, version) \
129 	__attribute__((symver(#api_name "@" #version)))
130 
131 #elif defined(SHARED)
132 
133 #define COMPAT_VERSION(internal_name, api_name, version) \
134 	asm(".symver " #internal_name "," #api_name "@" #version);
135 #define DEFAULT_VERSION(internal_name, api_name, version) \
136 	asm(".symver " #internal_name "," #api_name "@@" #version);
137 
138 #else /* !SHARED */
139 
140 #define COMPAT_VERSION(internal_name, api_name, version)
141 #define DEFAULT_VERSION(internal_name, api_name, version) \
142 	extern typeof(internal_name) api_name \
143 	__attribute__((alias(#internal_name)));
144 
145 #endif
146 
147 extern void libbpf_print(enum libbpf_print_level level,
148 			 const char *format, ...)
149 	__attribute__((format(printf, 2, 3)));
150 
151 #define __pr(level, fmt, ...)	\
152 do {				\
153 	libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__);	\
154 } while (0)
155 
156 #define pr_warn(fmt, ...)	__pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
157 #define pr_info(fmt, ...)	__pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
158 #define pr_debug(fmt, ...)	__pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
159 
160 #ifndef __has_builtin
161 #define __has_builtin(x) 0
162 #endif
163 
164 struct bpf_link {
165 	int (*detach)(struct bpf_link *link);
166 	void (*dealloc)(struct bpf_link *link);
167 	char *pin_path;		/* NULL, if not pinned */
168 	int fd;			/* hook FD, -1 if not applicable */
169 	bool disconnected;
170 };
171 
172 /*
173  * Re-implement glibc's reallocarray() for libbpf internal-only use.
174  * reallocarray(), unfortunately, is not available in all versions of glibc,
175  * so requires extra feature detection and using reallocarray() stub from
176  * <tools/libc_compat.h> and COMPAT_NEED_REALLOCARRAY. All this complicates
177  * build of libbpf unnecessarily and is just a maintenance burden. Instead,
178  * it's trivial to implement libbpf-specific internal version and use it
179  * throughout libbpf.
180  */
181 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
182 {
183 	size_t total;
184 
185 #if __has_builtin(__builtin_mul_overflow)
186 	if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
187 		return NULL;
188 #else
189 	if (size == 0 || nmemb > ULONG_MAX / size)
190 		return NULL;
191 	total = nmemb * size;
192 #endif
193 	return realloc(ptr, total);
194 }
195 
196 /* Copy up to sz - 1 bytes from zero-terminated src string and ensure that dst
197  * is zero-terminated string no matter what (unless sz == 0, in which case
198  * it's a no-op). It's conceptually close to FreeBSD's strlcpy(), but differs
199  * in what is returned. Given this is internal helper, it's trivial to extend
200  * this, when necessary. Use this instead of strncpy inside libbpf source code.
201  */
202 static inline void libbpf_strlcpy(char *dst, const char *src, size_t sz)
203 {
204 	size_t i;
205 
206 	if (sz == 0)
207 		return;
208 
209 	sz--;
210 	for (i = 0; i < sz && src[i]; i++)
211 		dst[i] = src[i];
212 	dst[i] = '\0';
213 }
214 
215 __u32 get_kernel_version(void);
216 
217 struct btf;
218 struct btf_type;
219 
220 struct btf_type *btf_type_by_id(const struct btf *btf, __u32 type_id);
221 const char *btf_kind_str(const struct btf_type *t);
222 const struct btf_type *skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
223 
224 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
225 {
226 	return (enum btf_func_linkage)(int)btf_vlen(t);
227 }
228 
229 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
230 {
231 	return (kflag << 31) | (kind << 24) | vlen;
232 }
233 
234 enum map_def_parts {
235 	MAP_DEF_MAP_TYPE	= 0x001,
236 	MAP_DEF_KEY_TYPE	= 0x002,
237 	MAP_DEF_KEY_SIZE	= 0x004,
238 	MAP_DEF_VALUE_TYPE	= 0x008,
239 	MAP_DEF_VALUE_SIZE	= 0x010,
240 	MAP_DEF_MAX_ENTRIES	= 0x020,
241 	MAP_DEF_MAP_FLAGS	= 0x040,
242 	MAP_DEF_NUMA_NODE	= 0x080,
243 	MAP_DEF_PINNING		= 0x100,
244 	MAP_DEF_INNER_MAP	= 0x200,
245 	MAP_DEF_MAP_EXTRA	= 0x400,
246 
247 	MAP_DEF_ALL		= 0x7ff, /* combination of all above */
248 };
249 
250 struct btf_map_def {
251 	enum map_def_parts parts;
252 	__u32 map_type;
253 	__u32 key_type_id;
254 	__u32 key_size;
255 	__u32 value_type_id;
256 	__u32 value_size;
257 	__u32 max_entries;
258 	__u32 map_flags;
259 	__u32 numa_node;
260 	__u32 pinning;
261 	__u64 map_extra;
262 };
263 
264 int parse_btf_map_def(const char *map_name, struct btf *btf,
265 		      const struct btf_type *def_t, bool strict,
266 		      struct btf_map_def *map_def, struct btf_map_def *inner_def);
267 
268 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
269 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt);
270 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt);
271 
272 static inline bool libbpf_is_mem_zeroed(const char *p, ssize_t len)
273 {
274 	while (len > 0) {
275 		if (*p)
276 			return false;
277 		p++;
278 		len--;
279 	}
280 	return true;
281 }
282 
283 static inline bool libbpf_validate_opts(const char *opts,
284 					size_t opts_sz, size_t user_sz,
285 					const char *type_name)
286 {
287 	if (user_sz < sizeof(size_t)) {
288 		pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
289 		return false;
290 	}
291 	if (!libbpf_is_mem_zeroed(opts + opts_sz, (ssize_t)user_sz - opts_sz)) {
292 		pr_warn("%s has non-zero extra bytes\n", type_name);
293 		return false;
294 	}
295 	return true;
296 }
297 
298 #define OPTS_VALID(opts, type)						      \
299 	(!(opts) || libbpf_validate_opts((const char *)opts,		      \
300 					 offsetofend(struct type,	      \
301 						     type##__last_field),     \
302 					 (opts)->sz, #type))
303 #define OPTS_HAS(opts, field) \
304 	((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
305 #define OPTS_GET(opts, field, fallback_value) \
306 	(OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
307 #define OPTS_SET(opts, field, value)		\
308 	do {					\
309 		if (OPTS_HAS(opts, field))	\
310 			(opts)->field = value;	\
311 	} while (0)
312 
313 #define OPTS_ZEROED(opts, last_nonzero_field)				      \
314 ({									      \
315 	ssize_t __off = offsetofend(typeof(*(opts)), last_nonzero_field);     \
316 	!(opts) || libbpf_is_mem_zeroed((const void *)opts + __off,	      \
317 					(opts)->sz - __off);		      \
318 })
319 
320 enum kern_feature_id {
321 	/* v4.14: kernel support for program & map names. */
322 	FEAT_PROG_NAME,
323 	/* v5.2: kernel support for global data sections. */
324 	FEAT_GLOBAL_DATA,
325 	/* BTF support */
326 	FEAT_BTF,
327 	/* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
328 	FEAT_BTF_FUNC,
329 	/* BTF_KIND_VAR and BTF_KIND_DATASEC support */
330 	FEAT_BTF_DATASEC,
331 	/* BTF_FUNC_GLOBAL is supported */
332 	FEAT_BTF_GLOBAL_FUNC,
333 	/* BPF_F_MMAPABLE is supported for arrays */
334 	FEAT_ARRAY_MMAP,
335 	/* kernel support for expected_attach_type in BPF_PROG_LOAD */
336 	FEAT_EXP_ATTACH_TYPE,
337 	/* bpf_probe_read_{kernel,user}[_str] helpers */
338 	FEAT_PROBE_READ_KERN,
339 	/* BPF_PROG_BIND_MAP is supported */
340 	FEAT_PROG_BIND_MAP,
341 	/* Kernel support for module BTFs */
342 	FEAT_MODULE_BTF,
343 	/* BTF_KIND_FLOAT support */
344 	FEAT_BTF_FLOAT,
345 	/* BPF perf link support */
346 	FEAT_PERF_LINK,
347 	/* BTF_KIND_DECL_TAG support */
348 	FEAT_BTF_DECL_TAG,
349 	/* BTF_KIND_TYPE_TAG support */
350 	FEAT_BTF_TYPE_TAG,
351 	/* memcg-based accounting for BPF maps and progs */
352 	FEAT_MEMCG_ACCOUNT,
353 	/* BPF cookie (bpf_get_attach_cookie() BPF helper) support */
354 	FEAT_BPF_COOKIE,
355 	/* BTF_KIND_ENUM64 support and BTF_KIND_ENUM kflag support */
356 	FEAT_BTF_ENUM64,
357 	/* Kernel uses syscall wrapper (CONFIG_ARCH_HAS_SYSCALL_WRAPPER) */
358 	FEAT_SYSCALL_WRAPPER,
359 	/* BPF multi-uprobe link support */
360 	FEAT_UPROBE_MULTI_LINK,
361 	__FEAT_CNT,
362 };
363 
364 enum kern_feature_result {
365 	FEAT_UNKNOWN = 0,
366 	FEAT_SUPPORTED = 1,
367 	FEAT_MISSING = 2,
368 };
369 
370 struct kern_feature_cache {
371 	enum kern_feature_result res[__FEAT_CNT];
372 	int token_fd;
373 };
374 
375 bool feat_supported(struct kern_feature_cache *cache, enum kern_feature_id feat_id);
376 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
377 
378 int probe_kern_syscall_wrapper(int token_fd);
379 int probe_memcg_account(int token_fd);
380 int bump_rlimit_memlock(void);
381 
382 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
383 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
384 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
385 			 const char *str_sec, size_t str_len,
386 			 int token_fd);
387 int btf_load_into_kernel(struct btf *btf,
388 			 char *log_buf, size_t log_sz, __u32 log_level,
389 			 int token_fd);
390 
391 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf);
392 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
393 				const char **prefix, int *kind);
394 
395 struct btf_ext_info {
396 	/*
397 	 * info points to the individual info section (e.g. func_info and
398 	 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
399 	 */
400 	void *info;
401 	__u32 rec_size;
402 	__u32 len;
403 	/* optional (maintained internally by libbpf) mapping between .BTF.ext
404 	 * section and corresponding ELF section. This is used to join
405 	 * information like CO-RE relocation records with corresponding BPF
406 	 * programs defined in ELF sections
407 	 */
408 	__u32 *sec_idxs;
409 	int sec_cnt;
410 };
411 
412 #define for_each_btf_ext_sec(seg, sec)					\
413 	for (sec = (seg)->info;						\
414 	     (void *)sec < (seg)->info + (seg)->len;			\
415 	     sec = (void *)sec + sizeof(struct btf_ext_info_sec) +	\
416 		   (seg)->rec_size * sec->num_info)
417 
418 #define for_each_btf_ext_rec(seg, sec, i, rec)				\
419 	for (i = 0, rec = (void *)&(sec)->data;				\
420 	     i < (sec)->num_info;					\
421 	     i++, rec = (void *)rec + (seg)->rec_size)
422 
423 /*
424  * The .BTF.ext ELF section layout defined as
425  *   struct btf_ext_header
426  *   func_info subsection
427  *
428  * The func_info subsection layout:
429  *   record size for struct bpf_func_info in the func_info subsection
430  *   struct btf_sec_func_info for section #1
431  *   a list of bpf_func_info records for section #1
432  *     where struct bpf_func_info mimics one in include/uapi/linux/bpf.h
433  *     but may not be identical
434  *   struct btf_sec_func_info for section #2
435  *   a list of bpf_func_info records for section #2
436  *   ......
437  *
438  * Note that the bpf_func_info record size in .BTF.ext may not
439  * be the same as the one defined in include/uapi/linux/bpf.h.
440  * The loader should ensure that record_size meets minimum
441  * requirement and pass the record as is to the kernel. The
442  * kernel will handle the func_info properly based on its contents.
443  */
444 struct btf_ext_header {
445 	__u16	magic;
446 	__u8	version;
447 	__u8	flags;
448 	__u32	hdr_len;
449 
450 	/* All offsets are in bytes relative to the end of this header */
451 	__u32	func_info_off;
452 	__u32	func_info_len;
453 	__u32	line_info_off;
454 	__u32	line_info_len;
455 
456 	/* optional part of .BTF.ext header */
457 	__u32	core_relo_off;
458 	__u32	core_relo_len;
459 };
460 
461 struct btf_ext {
462 	union {
463 		struct btf_ext_header *hdr;
464 		void *data;
465 	};
466 	struct btf_ext_info func_info;
467 	struct btf_ext_info line_info;
468 	struct btf_ext_info core_relo_info;
469 	__u32 data_size;
470 };
471 
472 struct btf_ext_info_sec {
473 	__u32	sec_name_off;
474 	__u32	num_info;
475 	/* Followed by num_info * record_size number of bytes */
476 	__u8	data[];
477 };
478 
479 /* The minimum bpf_func_info checked by the loader */
480 struct bpf_func_info_min {
481 	__u32   insn_off;
482 	__u32   type_id;
483 };
484 
485 /* The minimum bpf_line_info checked by the loader */
486 struct bpf_line_info_min {
487 	__u32	insn_off;
488 	__u32	file_name_off;
489 	__u32	line_off;
490 	__u32	line_col;
491 };
492 
493 
494 typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
495 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
496 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx);
497 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx);
498 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
499 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
500 __s32 btf__find_by_name_kind_own(const struct btf *btf, const char *type_name,
501 				 __u32 kind);
502 
503 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
504 			     const char *sym_name, void *ctx);
505 
506 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *arg);
507 
508 /* handle direct returned errors */
509 static inline int libbpf_err(int ret)
510 {
511 	if (ret < 0)
512 		errno = -ret;
513 	return ret;
514 }
515 
516 /* handle errno-based (e.g., syscall or libc) errors according to libbpf's
517  * strict mode settings
518  */
519 static inline int libbpf_err_errno(int ret)
520 {
521 	/* errno is already assumed to be set on error */
522 	return ret < 0 ? -errno : ret;
523 }
524 
525 /* handle error for pointer-returning APIs, err is assumed to be < 0 always */
526 static inline void *libbpf_err_ptr(int err)
527 {
528 	/* set errno on error, this doesn't break anything */
529 	errno = -err;
530 	return NULL;
531 }
532 
533 /* handle pointer-returning APIs' error handling */
534 static inline void *libbpf_ptr(void *ret)
535 {
536 	/* set errno on error, this doesn't break anything */
537 	if (IS_ERR(ret))
538 		errno = -PTR_ERR(ret);
539 
540 	return IS_ERR(ret) ? NULL : ret;
541 }
542 
543 static inline bool str_is_empty(const char *s)
544 {
545 	return !s || !s[0];
546 }
547 
548 static inline bool is_ldimm64_insn(struct bpf_insn *insn)
549 {
550 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
551 }
552 
553 /* Unconditionally dup FD, ensuring it doesn't use [0, 2] range.
554  * Original FD is not closed or altered in any other way.
555  * Preserves original FD value, if it's invalid (negative).
556  */
557 static inline int dup_good_fd(int fd)
558 {
559 	if (fd < 0)
560 		return fd;
561 	return fcntl(fd, F_DUPFD_CLOEXEC, 3);
562 }
563 
564 /* if fd is stdin, stdout, or stderr, dup to a fd greater than 2
565  * Takes ownership of the fd passed in, and closes it if calling
566  * fcntl(fd, F_DUPFD_CLOEXEC, 3).
567  */
568 static inline int ensure_good_fd(int fd)
569 {
570 	int old_fd = fd, saved_errno;
571 
572 	if (fd < 0)
573 		return fd;
574 	if (fd < 3) {
575 		fd = dup_good_fd(fd);
576 		saved_errno = errno;
577 		close(old_fd);
578 		errno = saved_errno;
579 		if (fd < 0) {
580 			pr_warn("failed to dup FD %d to FD > 2: %d\n", old_fd, -saved_errno);
581 			errno = saved_errno;
582 		}
583 	}
584 	return fd;
585 }
586 
587 static inline int sys_dup2(int oldfd, int newfd)
588 {
589 #ifdef __NR_dup2
590 	return syscall(__NR_dup2, oldfd, newfd);
591 #else
592 	return syscall(__NR_dup3, oldfd, newfd, 0);
593 #endif
594 }
595 
596 /* Point *fixed_fd* to the same file that *tmp_fd* points to.
597  * Regardless of success, *tmp_fd* is closed.
598  * Whatever *fixed_fd* pointed to is closed silently.
599  */
600 static inline int reuse_fd(int fixed_fd, int tmp_fd)
601 {
602 	int err;
603 
604 	err = sys_dup2(tmp_fd, fixed_fd);
605 	err = err < 0 ? -errno : 0;
606 	close(tmp_fd); /* clean up temporary FD */
607 	return err;
608 }
609 
610 /* The following two functions are exposed to bpftool */
611 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
612 		       size_t local_essent_len,
613 		       const struct btf *targ_btf,
614 		       const char *targ_btf_name,
615 		       int targ_start_id,
616 		       struct bpf_core_cand_list *cands);
617 void bpf_core_free_cands(struct bpf_core_cand_list *cands);
618 
619 struct usdt_manager *usdt_manager_new(struct bpf_object *obj);
620 void usdt_manager_free(struct usdt_manager *man);
621 struct bpf_link * usdt_manager_attach_usdt(struct usdt_manager *man,
622 					   const struct bpf_program *prog,
623 					   pid_t pid, const char *path,
624 					   const char *usdt_provider, const char *usdt_name,
625 					   __u64 usdt_cookie);
626 
627 static inline bool is_pow_of_2(size_t x)
628 {
629 	return x && (x & (x - 1)) == 0;
630 }
631 
632 #define PROG_LOAD_ATTEMPTS 5
633 int sys_bpf_prog_load(union bpf_attr *attr, unsigned int size, int attempts);
634 
635 bool glob_match(const char *str, const char *pat);
636 
637 long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name);
638 long elf_find_func_offset_from_file(const char *binary_path, const char *name);
639 
640 struct elf_fd {
641 	Elf *elf;
642 	int fd;
643 };
644 
645 int elf_open(const char *binary_path, struct elf_fd *elf_fd);
646 void elf_close(struct elf_fd *elf_fd);
647 
648 int elf_resolve_syms_offsets(const char *binary_path, int cnt,
649 			     const char **syms, unsigned long **poffsets,
650 			     int st_type);
651 int elf_resolve_pattern_offsets(const char *binary_path, const char *pattern,
652 				 unsigned long **poffsets, size_t *pcnt);
653 
654 int probe_fd(int fd);
655 
656 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
657