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>
19 #include "relo_core.h"
21 /* Android's libc doesn't support AT_EACCESS in faccessat() implementation
22 * ([0]), and just returns -EINVAL even if file exists and is accessible.
23 * See [1] for issues caused by this.
25 * So just redefine it to 0 on Android.
27 * [0] https://android.googlesource.com/platform/bionic/+/refs/heads/android13-release/libc/bionic/faccessat.cpp#50
28 * [1] https://github.com/libbpf/libbpf-bootstrap/issues/250#issuecomment-1911324250
35 /* make sure libbpf doesn't use kernel-only integer typedefs */
36 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
38 /* prevent accidental re-addition of reallocarray() */
39 #pragma GCC poison reallocarray
51 #ifndef R_BPF_64_ABS64
52 #define R_BPF_64_ABS64 2
54 #ifndef R_BPF_64_ABS32
55 #define R_BPF_64_ABS32 3
58 #define R_BPF_64_32 10
61 #ifndef SHT_LLVM_ADDRSIG
62 #define SHT_LLVM_ADDRSIG 0x6FFF4C03
65 /* if libelf is old and doesn't support mmap(), fall back to read() */
66 #ifndef ELF_C_READ_MMAP
67 #define ELF_C_READ_MMAP ELF_C_READ
70 /* Older libelf all end up in this expression, for both 32 and 64 bit */
71 #ifndef ELF64_ST_VISIBILITY
72 #define ELF64_ST_VISIBILITY(o) ((o) & 0x03)
75 #define BTF_INFO_ENC(kind, kind_flag, vlen) \
76 ((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
77 #define BTF_TYPE_ENC(name, info, size_or_type) (name), (info), (size_or_type)
78 #define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
79 ((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
80 #define BTF_TYPE_INT_ENC(name, encoding, bits_offset, bits, sz) \
81 BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_INT, 0, 0), sz), \
82 BTF_INT_ENC(encoding, bits_offset, bits)
83 #define BTF_MEMBER_ENC(name, type, bits_offset) (name), (type), (bits_offset)
84 #define BTF_PARAM_ENC(name, type) (name), (type)
85 #define BTF_VAR_SECINFO_ENC(type, offset, size) (type), (offset), (size)
86 #define BTF_TYPE_FLOAT_ENC(name, sz) \
87 BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_FLOAT, 0, 0), sz)
88 #define BTF_TYPE_DECL_TAG_ENC(value, type, component_idx) \
89 BTF_TYPE_ENC(value, BTF_INFO_ENC(BTF_KIND_DECL_TAG, 0, 0), type), (component_idx)
90 #define BTF_TYPE_TYPE_TAG_ENC(value, type) \
91 BTF_TYPE_ENC(value, BTF_INFO_ENC(BTF_KIND_TYPE_TAG, 0, 0), type)
94 #define likely(x) __builtin_expect(!!(x), 1)
97 #define unlikely(x) __builtin_expect(!!(x), 0)
100 # define min(x, y) ((x) < (y) ? (x) : (y))
103 # define max(x, y) ((x) < (y) ? (y) : (x))
106 # define offsetofend(TYPE, FIELD) \
107 (offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
110 #define __alias(symbol) __attribute__((alias(#symbol)))
113 /* Check whether a string `str` has prefix `pfx`, regardless if `pfx` is
114 * a string literal known at compilation time or char * pointer known only at
117 #define str_has_pfx(str, pfx) \
118 (strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
121 static inline bool str_has_sfx(const char *str, const char *sfx)
123 size_t str_len = strlen(str);
124 size_t sfx_len = strlen(sfx);
126 if (sfx_len > str_len)
128 return strcmp(str + str_len - sfx_len, sfx) == 0;
131 /* Symbol versioning is different between static and shared library.
132 * Properly versioned symbols are needed for shared library, but
133 * only the symbol of the new version is needed for static library.
134 * Starting with GNU C 10, use symver attribute instead of .symver assembler
135 * directive, which works better with GCC LTO builds.
137 #if defined(SHARED) && defined(__GNUC__) && __GNUC__ >= 10
139 #define DEFAULT_VERSION(internal_name, api_name, version) \
140 __attribute__((symver(#api_name "@@" #version)))
141 #define COMPAT_VERSION(internal_name, api_name, version) \
142 __attribute__((symver(#api_name "@" #version)))
144 #elif defined(SHARED)
146 #define COMPAT_VERSION(internal_name, api_name, version) \
147 asm(".symver " #internal_name "," #api_name "@" #version);
148 #define DEFAULT_VERSION(internal_name, api_name, version) \
149 asm(".symver " #internal_name "," #api_name "@@" #version);
153 #define COMPAT_VERSION(internal_name, api_name, version)
154 #define DEFAULT_VERSION(internal_name, api_name, version) \
155 extern typeof(internal_name) api_name \
156 __attribute__((alias(#internal_name)));
160 extern void libbpf_print(enum libbpf_print_level level,
161 const char *format, ...)
162 __attribute__((format(printf, 2, 3)));
164 #define __pr(level, fmt, ...) \
166 libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__); \
169 #define pr_warn(fmt, ...) __pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
170 #define pr_info(fmt, ...) __pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
171 #define pr_debug(fmt, ...) __pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
173 #ifndef __has_builtin
174 #define __has_builtin(x) 0
178 int (*detach)(struct bpf_link *link);
179 void (*dealloc)(struct bpf_link *link);
180 char *pin_path; /* NULL, if not pinned */
181 int fd; /* hook FD, -1 if not applicable */
186 * Re-implement glibc's reallocarray() for libbpf internal-only use.
187 * reallocarray(), unfortunately, is not available in all versions of glibc,
188 * so requires extra feature detection and using reallocarray() stub from
189 * <tools/libc_compat.h> and COMPAT_NEED_REALLOCARRAY. All this complicates
190 * build of libbpf unnecessarily and is just a maintenance burden. Instead,
191 * it's trivial to implement libbpf-specific internal version and use it
194 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
198 #if __has_builtin(__builtin_mul_overflow)
199 if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
202 if (size == 0 || nmemb > ULONG_MAX / size)
204 total = nmemb * size;
206 return realloc(ptr, total);
209 /* Copy up to sz - 1 bytes from zero-terminated src string and ensure that dst
210 * is zero-terminated string no matter what (unless sz == 0, in which case
211 * it's a no-op). It's conceptually close to FreeBSD's strlcpy(), but differs
212 * in what is returned. Given this is internal helper, it's trivial to extend
213 * this, when necessary. Use this instead of strncpy inside libbpf source code.
215 static inline void libbpf_strlcpy(char *dst, const char *src, size_t sz)
223 for (i = 0; i < sz && src[i]; i++)
228 __u32 get_kernel_version(void);
233 struct btf_type *btf_type_by_id(const struct btf *btf, __u32 type_id);
234 const char *btf_kind_str(const struct btf_type *t);
235 const struct btf_type *skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
237 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
239 return (enum btf_func_linkage)(int)btf_vlen(t);
242 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
244 return (kflag << 31) | (kind << 24) | vlen;
248 MAP_DEF_MAP_TYPE = 0x001,
249 MAP_DEF_KEY_TYPE = 0x002,
250 MAP_DEF_KEY_SIZE = 0x004,
251 MAP_DEF_VALUE_TYPE = 0x008,
252 MAP_DEF_VALUE_SIZE = 0x010,
253 MAP_DEF_MAX_ENTRIES = 0x020,
254 MAP_DEF_MAP_FLAGS = 0x040,
255 MAP_DEF_NUMA_NODE = 0x080,
256 MAP_DEF_PINNING = 0x100,
257 MAP_DEF_INNER_MAP = 0x200,
258 MAP_DEF_MAP_EXTRA = 0x400,
260 MAP_DEF_ALL = 0x7ff, /* combination of all above */
264 enum map_def_parts parts;
277 int parse_btf_map_def(const char *map_name, struct btf *btf,
278 const struct btf_type *def_t, bool strict,
279 struct btf_map_def *map_def, struct btf_map_def *inner_def);
281 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
282 size_t cur_cnt, size_t max_cnt, size_t add_cnt);
283 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt);
285 static inline bool libbpf_is_mem_zeroed(const char *p, ssize_t len)
296 static inline bool libbpf_validate_opts(const char *opts,
297 size_t opts_sz, size_t user_sz,
298 const char *type_name)
300 if (user_sz < sizeof(size_t)) {
301 pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
304 if (!libbpf_is_mem_zeroed(opts + opts_sz, (ssize_t)user_sz - opts_sz)) {
305 pr_warn("%s has non-zero extra bytes\n", type_name);
311 #define OPTS_VALID(opts, type) \
312 (!(opts) || libbpf_validate_opts((const char *)opts, \
313 offsetofend(struct type, \
314 type##__last_field), \
316 #define OPTS_HAS(opts, field) \
317 ((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
318 #define OPTS_GET(opts, field, fallback_value) \
319 (OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
320 #define OPTS_SET(opts, field, value) \
322 if (OPTS_HAS(opts, field)) \
323 (opts)->field = value; \
326 #define OPTS_ZEROED(opts, last_nonzero_field) \
328 ssize_t __off = offsetofend(typeof(*(opts)), last_nonzero_field); \
329 !(opts) || libbpf_is_mem_zeroed((const void *)opts + __off, \
330 (opts)->sz - __off); \
333 enum kern_feature_id {
334 /* v4.14: kernel support for program & map names. */
336 /* v5.2: kernel support for global data sections. */
340 /* BTF_KIND_FUNC and BTF_KIND_FUNC_PROTO support */
342 /* BTF_KIND_VAR and BTF_KIND_DATASEC support */
344 /* BTF_FUNC_GLOBAL is supported */
345 FEAT_BTF_GLOBAL_FUNC,
346 /* BPF_F_MMAPABLE is supported for arrays */
348 /* kernel support for expected_attach_type in BPF_PROG_LOAD */
349 FEAT_EXP_ATTACH_TYPE,
350 /* bpf_probe_read_{kernel,user}[_str] helpers */
351 FEAT_PROBE_READ_KERN,
352 /* BPF_PROG_BIND_MAP is supported */
354 /* Kernel support for module BTFs */
356 /* BTF_KIND_FLOAT support */
358 /* BPF perf link support */
360 /* BTF_KIND_DECL_TAG support */
362 /* BTF_KIND_TYPE_TAG support */
364 /* memcg-based accounting for BPF maps and progs */
366 /* BPF cookie (bpf_get_attach_cookie() BPF helper) support */
368 /* BTF_KIND_ENUM64 support and BTF_KIND_ENUM kflag support */
370 /* Kernel uses syscall wrapper (CONFIG_ARCH_HAS_SYSCALL_WRAPPER) */
371 FEAT_SYSCALL_WRAPPER,
372 /* BPF multi-uprobe link support */
373 FEAT_UPROBE_MULTI_LINK,
377 int probe_memcg_account(void);
378 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id);
379 int bump_rlimit_memlock(void);
381 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
382 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
383 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
384 const char *str_sec, size_t str_len);
385 int btf_load_into_kernel(struct btf *btf, char *log_buf, size_t log_sz, __u32 log_level);
387 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf);
388 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
389 const char **prefix, int *kind);
391 struct btf_ext_info {
393 * info points to the individual info section (e.g. func_info and
394 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
399 /* optional (maintained internally by libbpf) mapping between .BTF.ext
400 * section and corresponding ELF section. This is used to join
401 * information like CO-RE relocation records with corresponding BPF
402 * programs defined in ELF sections
408 #define for_each_btf_ext_sec(seg, sec) \
409 for (sec = (seg)->info; \
410 (void *)sec < (seg)->info + (seg)->len; \
411 sec = (void *)sec + sizeof(struct btf_ext_info_sec) + \
412 (seg)->rec_size * sec->num_info)
414 #define for_each_btf_ext_rec(seg, sec, i, rec) \
415 for (i = 0, rec = (void *)&(sec)->data; \
416 i < (sec)->num_info; \
417 i++, rec = (void *)rec + (seg)->rec_size)
420 * The .BTF.ext ELF section layout defined as
421 * struct btf_ext_header
422 * func_info subsection
424 * The func_info subsection layout:
425 * record size for struct bpf_func_info in the func_info subsection
426 * struct btf_sec_func_info for section #1
427 * a list of bpf_func_info records for section #1
428 * where struct bpf_func_info mimics one in include/uapi/linux/bpf.h
429 * but may not be identical
430 * struct btf_sec_func_info for section #2
431 * a list of bpf_func_info records for section #2
434 * Note that the bpf_func_info record size in .BTF.ext may not
435 * be the same as the one defined in include/uapi/linux/bpf.h.
436 * The loader should ensure that record_size meets minimum
437 * requirement and pass the record as is to the kernel. The
438 * kernel will handle the func_info properly based on its contents.
440 struct btf_ext_header {
446 /* All offsets are in bytes relative to the end of this header */
452 /* optional part of .BTF.ext header */
459 struct btf_ext_header *hdr;
462 struct btf_ext_info func_info;
463 struct btf_ext_info line_info;
464 struct btf_ext_info core_relo_info;
468 struct btf_ext_info_sec {
471 /* Followed by num_info * record_size number of bytes */
475 /* The minimum bpf_func_info checked by the loader */
476 struct bpf_func_info_min {
481 /* The minimum bpf_line_info checked by the loader */
482 struct bpf_line_info_min {
490 typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
491 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
492 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx);
493 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx);
494 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
495 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
496 __s32 btf__find_by_name_kind_own(const struct btf *btf, const char *type_name,
499 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
500 const char *sym_name, void *ctx);
502 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *arg);
504 /* handle direct returned errors */
505 static inline int libbpf_err(int ret)
512 /* handle errno-based (e.g., syscall or libc) errors according to libbpf's
513 * strict mode settings
515 static inline int libbpf_err_errno(int ret)
517 /* errno is already assumed to be set on error */
518 return ret < 0 ? -errno : ret;
521 /* handle error for pointer-returning APIs, err is assumed to be < 0 always */
522 static inline void *libbpf_err_ptr(int err)
524 /* set errno on error, this doesn't break anything */
529 /* handle pointer-returning APIs' error handling */
530 static inline void *libbpf_ptr(void *ret)
532 /* set errno on error, this doesn't break anything */
534 errno = -PTR_ERR(ret);
536 return IS_ERR(ret) ? NULL : ret;
539 static inline bool str_is_empty(const char *s)
544 static inline bool is_ldimm64_insn(struct bpf_insn *insn)
546 return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
549 /* if fd is stdin, stdout, or stderr, dup to a fd greater than 2
550 * Takes ownership of the fd passed in, and closes it if calling
551 * fcntl(fd, F_DUPFD_CLOEXEC, 3).
553 static inline int ensure_good_fd(int fd)
555 int old_fd = fd, saved_errno;
560 fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
565 pr_warn("failed to dup FD %d to FD > 2: %d\n", old_fd, -saved_errno);
572 /* Point *fixed_fd* to the same file that *tmp_fd* points to.
573 * Regardless of success, *tmp_fd* is closed.
574 * Whatever *fixed_fd* pointed to is closed silently.
576 static inline int reuse_fd(int fixed_fd, int tmp_fd)
580 err = dup2(tmp_fd, fixed_fd);
581 err = err < 0 ? -errno : 0;
582 close(tmp_fd); /* clean up temporary FD */
586 /* The following two functions are exposed to bpftool */
587 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
588 size_t local_essent_len,
589 const struct btf *targ_btf,
590 const char *targ_btf_name,
592 struct bpf_core_cand_list *cands);
593 void bpf_core_free_cands(struct bpf_core_cand_list *cands);
595 struct usdt_manager *usdt_manager_new(struct bpf_object *obj);
596 void usdt_manager_free(struct usdt_manager *man);
597 struct bpf_link * usdt_manager_attach_usdt(struct usdt_manager *man,
598 const struct bpf_program *prog,
599 pid_t pid, const char *path,
600 const char *usdt_provider, const char *usdt_name,
603 static inline bool is_pow_of_2(size_t x)
605 return x && (x & (x - 1)) == 0;
608 #define PROG_LOAD_ATTEMPTS 5
609 int sys_bpf_prog_load(union bpf_attr *attr, unsigned int size, int attempts);
611 bool glob_match(const char *str, const char *pat);
613 long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name);
614 long elf_find_func_offset_from_file(const char *binary_path, const char *name);
621 int elf_open(const char *binary_path, struct elf_fd *elf_fd);
622 void elf_close(struct elf_fd *elf_fd);
624 int elf_resolve_syms_offsets(const char *binary_path, int cnt,
625 const char **syms, unsigned long **poffsets,
627 int elf_resolve_pattern_offsets(const char *binary_path, const char *pattern,
628 unsigned long **poffsets, size_t *pcnt);
630 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */