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