libbpf_internal.h 20 KB

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