1
0

libbpf_internal.h 22 KB

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