1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
4 * Internal libbpf helpers.
6 * Copyright (c) 2019 Facebook
9 #ifndef __LIBBPF_LIBBPF_INTERNAL_H
10 #define __LIBBPF_LIBBPF_INTERNAL_H
15 #include <linux/err.h>
18 #include <sys/syscall.h>
20 #include "relo_core.h"
22 /* make sure libbpf doesn't use kernel-only integer typedefs */
23 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
25 /* prevent accidental re-addition of reallocarray() */
26 #pragma GCC poison reallocarray
38 #ifndef R_BPF_64_ABS64
39 #define R_BPF_64_ABS64 2
41 #ifndef R_BPF_64_ABS32
42 #define R_BPF_64_ABS32 3
45 #define R_BPF_64_32 10
48 #ifndef SHT_LLVM_ADDRSIG
49 #define SHT_LLVM_ADDRSIG 0x6FFF4C03
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
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)
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)
81 #define likely(x) __builtin_expect(!!(x), 1)
84 #define unlikely(x) __builtin_expect(!!(x), 0)
87 # define min(x, y) ((x) < (y) ? (x) : (y))
90 # define max(x, y) ((x) < (y) ? (y) : (x))
93 # define offsetofend(TYPE, FIELD) \
94 (offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
97 #define __alias(symbol) __attribute__((alias(#symbol)))
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
104 #define str_has_pfx(str, pfx) \
105 (strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
108 static inline bool str_has_sfx(const char *str, const char *sfx)
110 size_t str_len = strlen(str);
111 size_t sfx_len = strlen(sfx);
113 if (sfx_len > str_len)
115 return strcmp(str + str_len - sfx_len, sfx) == 0;
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.
124 #if defined(SHARED) && defined(__GNUC__) && __GNUC__ >= 10
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)))
131 #elif defined(SHARED)
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);
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)));
147 extern void libbpf_print(enum libbpf_print_level level,
148 const char *format, ...)
149 __attribute__((format(printf, 2, 3)));
151 #define __pr(level, fmt, ...) \
153 libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__); \
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__)
160 #ifndef __has_builtin
161 #define __has_builtin(x) 0
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 */
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
181 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
185 #if __has_builtin(__builtin_mul_overflow)
186 if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
189 if (size == 0 || nmemb > ULONG_MAX / size)
191 total = nmemb * size;
193 return realloc(ptr, total);
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.
202 static inline void libbpf_strlcpy(char *dst, const char *src, size_t sz)
210 for (i = 0; i < sz && src[i]; i++)
215 __u32 get_kernel_version(void);
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);
224 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
226 return (enum btf_func_linkage)(int)btf_vlen(t);
229 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
231 return (kflag << 31) | (kind << 24) | vlen;
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,
247 MAP_DEF_ALL = 0x7ff, /* combination of all above */
251 enum map_def_parts parts;
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);
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);
272 static inline bool libbpf_is_mem_zeroed(const char *p, ssize_t len)
283 static inline bool libbpf_validate_opts(const char *opts,
284 size_t opts_sz, size_t user_sz,
285 const char *type_name)
287 if (user_sz < sizeof(size_t)) {
288 pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
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);
298 #define OPTS_VALID(opts, type) \
299 (!(opts) || libbpf_validate_opts((const char *)opts, \
300 offsetofend(struct type, \
301 type##__last_field), \
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) \
309 if (OPTS_HAS(opts, field)) \
310 (opts)->field = value; \
313 #define OPTS_ZEROED(opts, last_nonzero_field) \
315 ssize_t __off = offsetofend(typeof(*(opts)), last_nonzero_field); \
316 !(opts) || libbpf_is_mem_zeroed((const void *)opts + __off, \
317 (opts)->sz - __off); \
320 enum kern_feature_id {
321 /* v4.14: kernel support for program & map names. */
323 /* v5.2: kernel support for global data sections. */
327 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
329 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
331 /* BTF_FUNC_GLOBAL is supported */
332 FEAT_BTF_GLOBAL_FUNC,
333 /* BPF_F_MMAPABLE is supported for arrays */
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 */
341 /* Kernel support for module BTFs */
343 /* BTF_KIND_FLOAT support */
345 /* BPF perf link support */
347 /* BTF_KIND_DECL_TAG support */
349 /* BTF_KIND_TYPE_TAG support */
351 /* memcg-based accounting for BPF maps and progs */
353 /* BPF cookie (bpf_get_attach_cookie() BPF helper) support */
355 /* BTF_KIND_ENUM64 support and BTF_KIND_ENUM kflag support */
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,
364 enum kern_feature_result {
370 struct kern_feature_cache {
371 enum kern_feature_result res[__FEAT_CNT];
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);
378 int probe_kern_syscall_wrapper(int token_fd);
379 int probe_memcg_account(int token_fd);
380 int bump_rlimit_memlock(void);
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,
387 int btf_load_into_kernel(struct btf *btf,
388 char *log_buf, size_t log_sz, __u32 log_level,
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);
395 struct btf_ext_info {
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.
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
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)
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)
424 * The .BTF.ext ELF section layout defined as
425 * struct btf_ext_header
426 * func_info subsection
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
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.
444 struct btf_ext_header {
450 /* All offsets are in bytes relative to the end of this header */
456 /* optional part of .BTF.ext header */
463 struct btf_ext_header *hdr;
466 struct btf_ext_info func_info;
467 struct btf_ext_info line_info;
468 struct btf_ext_info core_relo_info;
472 struct btf_ext_info_sec {
475 /* Followed by num_info * record_size number of bytes */
479 /* The minimum bpf_func_info checked by the loader */
480 struct bpf_func_info_min {
485 /* The minimum bpf_line_info checked by the loader */
486 struct bpf_line_info_min {
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,
503 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
504 const char *sym_name, void *ctx);
506 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *arg);
508 /* handle direct returned errors */
509 static inline int libbpf_err(int ret)
516 /* handle errno-based (e.g., syscall or libc) errors according to libbpf's
517 * strict mode settings
519 static inline int libbpf_err_errno(int ret)
521 /* errno is already assumed to be set on error */
522 return ret < 0 ? -errno : ret;
525 /* handle error for pointer-returning APIs, err is assumed to be < 0 always */
526 static inline void *libbpf_err_ptr(int err)
528 /* set errno on error, this doesn't break anything */
533 /* handle pointer-returning APIs' error handling */
534 static inline void *libbpf_ptr(void *ret)
536 /* set errno on error, this doesn't break anything */
538 errno = -PTR_ERR(ret);
540 return IS_ERR(ret) ? NULL : ret;
543 static inline bool str_is_empty(const char *s)
548 static inline bool is_ldimm64_insn(struct bpf_insn *insn)
550 return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
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).
557 static inline int dup_good_fd(int fd)
561 return fcntl(fd, F_DUPFD_CLOEXEC, 3);
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).
568 static inline int ensure_good_fd(int fd)
570 int old_fd = fd, saved_errno;
575 fd = dup_good_fd(fd);
580 pr_warn("failed to dup FD %d to FD > 2: %d\n", old_fd, -saved_errno);
587 static inline int sys_dup2(int oldfd, int newfd)
590 return syscall(__NR_dup2, oldfd, newfd);
592 return syscall(__NR_dup3, oldfd, newfd, 0);
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.
600 static inline int reuse_fd(int fixed_fd, int tmp_fd)
604 err = sys_dup2(tmp_fd, fixed_fd);
605 err = err < 0 ? -errno : 0;
606 close(tmp_fd); /* clean up temporary FD */
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,
616 struct bpf_core_cand_list *cands);
617 void bpf_core_free_cands(struct bpf_core_cand_list *cands);
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,
627 static inline bool is_pow_of_2(size_t x)
629 return x && (x & (x - 1)) == 0;
632 #define PROG_LOAD_ATTEMPTS 5
633 int sys_bpf_prog_load(union bpf_attr *attr, unsigned int size, int attempts);
635 bool glob_match(const char *str, const char *pat);
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);
645 int elf_open(const char *binary_path, struct elf_fd *elf_fd);
646 void elf_close(struct elf_fd *elf_fd);
648 int elf_resolve_syms_offsets(const char *binary_path, int cnt,
649 const char **syms, unsigned long **poffsets,
651 int elf_resolve_pattern_offsets(const char *binary_path, const char *pattern,
652 unsigned long **poffsets, size_t *pcnt);
654 int probe_fd(int fd);
656 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */