xref: /openbmc/linux/tools/lib/bpf/libbpf_internal.h (revision 413d6ed3)
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 
15 /* make sure libbpf doesn't use kernel-only integer typedefs */
16 #pragma GCC poison u8 u16 u32 u64 s8 s16 s32 s64
17 
18 /* prevent accidental re-addition of reallocarray() */
19 #pragma GCC poison reallocarray
20 
21 #include "libbpf.h"
22 #include "btf.h"
23 
24 #ifndef EM_BPF
25 #define EM_BPF 247
26 #endif
27 
28 #ifndef R_BPF_64_64
29 #define R_BPF_64_64 1
30 #endif
31 #ifndef R_BPF_64_32
32 #define R_BPF_64_32 10
33 #endif
34 
35 #ifndef SHT_LLVM_ADDRSIG
36 #define SHT_LLVM_ADDRSIG 0x6FFF4C03
37 #endif
38 
39 /* if libelf is old and doesn't support mmap(), fall back to read() */
40 #ifndef ELF_C_READ_MMAP
41 #define ELF_C_READ_MMAP ELF_C_READ
42 #endif
43 
44 #define BTF_INFO_ENC(kind, kind_flag, vlen) \
45 	((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
46 #define BTF_TYPE_ENC(name, info, size_or_type) (name), (info), (size_or_type)
47 #define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
48 	((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
49 #define BTF_TYPE_INT_ENC(name, encoding, bits_offset, bits, sz) \
50 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_INT, 0, 0), sz), \
51 	BTF_INT_ENC(encoding, bits_offset, bits)
52 #define BTF_MEMBER_ENC(name, type, bits_offset) (name), (type), (bits_offset)
53 #define BTF_PARAM_ENC(name, type) (name), (type)
54 #define BTF_VAR_SECINFO_ENC(type, offset, size) (type), (offset), (size)
55 #define BTF_TYPE_FLOAT_ENC(name, sz) \
56 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_FLOAT, 0, 0), sz)
57 
58 #ifndef likely
59 #define likely(x) __builtin_expect(!!(x), 1)
60 #endif
61 #ifndef unlikely
62 #define unlikely(x) __builtin_expect(!!(x), 0)
63 #endif
64 #ifndef min
65 # define min(x, y) ((x) < (y) ? (x) : (y))
66 #endif
67 #ifndef max
68 # define max(x, y) ((x) < (y) ? (y) : (x))
69 #endif
70 #ifndef offsetofend
71 # define offsetofend(TYPE, FIELD) \
72 	(offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
73 #endif
74 
75 /* Symbol versioning is different between static and shared library.
76  * Properly versioned symbols are needed for shared library, but
77  * only the symbol of the new version is needed for static library.
78  */
79 #ifdef SHARED
80 # define COMPAT_VERSION(internal_name, api_name, version) \
81 	asm(".symver " #internal_name "," #api_name "@" #version);
82 # define DEFAULT_VERSION(internal_name, api_name, version) \
83 	asm(".symver " #internal_name "," #api_name "@@" #version);
84 #else
85 # define COMPAT_VERSION(internal_name, api_name, version)
86 # define DEFAULT_VERSION(internal_name, api_name, version) \
87 	extern typeof(internal_name) api_name \
88 	__attribute__((alias(#internal_name)));
89 #endif
90 
91 extern void libbpf_print(enum libbpf_print_level level,
92 			 const char *format, ...)
93 	__attribute__((format(printf, 2, 3)));
94 
95 #define __pr(level, fmt, ...)	\
96 do {				\
97 	libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__);	\
98 } while (0)
99 
100 #define pr_warn(fmt, ...)	__pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
101 #define pr_info(fmt, ...)	__pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
102 #define pr_debug(fmt, ...)	__pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
103 
104 #ifndef __has_builtin
105 #define __has_builtin(x) 0
106 #endif
107 /*
108  * Re-implement glibc's reallocarray() for libbpf internal-only use.
109  * reallocarray(), unfortunately, is not available in all versions of glibc,
110  * so requires extra feature detection and using reallocarray() stub from
111  * <tools/libc_compat.h> and COMPAT_NEED_REALLOCARRAY. All this complicates
112  * build of libbpf unnecessarily and is just a maintenance burden. Instead,
113  * it's trivial to implement libbpf-specific internal version and use it
114  * throughout libbpf.
115  */
116 static inline void *libbpf_reallocarray(void *ptr, size_t nmemb, size_t size)
117 {
118 	size_t total;
119 
120 #if __has_builtin(__builtin_mul_overflow)
121 	if (unlikely(__builtin_mul_overflow(nmemb, size, &total)))
122 		return NULL;
123 #else
124 	if (size == 0 || nmemb > ULONG_MAX / size)
125 		return NULL;
126 	total = nmemb * size;
127 #endif
128 	return realloc(ptr, total);
129 }
130 
131 struct btf;
132 struct btf_type;
133 
134 struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id);
135 const char *btf_kind_str(const struct btf_type *t);
136 const struct btf_type *skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id);
137 
138 static inline enum btf_func_linkage btf_func_linkage(const struct btf_type *t)
139 {
140 	return (enum btf_func_linkage)(int)btf_vlen(t);
141 }
142 
143 static inline __u32 btf_type_info(int kind, int vlen, int kflag)
144 {
145 	return (kflag << 31) | (kind << 24) | vlen;
146 }
147 
148 enum map_def_parts {
149 	MAP_DEF_MAP_TYPE	= 0x001,
150 	MAP_DEF_KEY_TYPE	= 0x002,
151 	MAP_DEF_KEY_SIZE	= 0x004,
152 	MAP_DEF_VALUE_TYPE	= 0x008,
153 	MAP_DEF_VALUE_SIZE	= 0x010,
154 	MAP_DEF_MAX_ENTRIES	= 0x020,
155 	MAP_DEF_MAP_FLAGS	= 0x040,
156 	MAP_DEF_NUMA_NODE	= 0x080,
157 	MAP_DEF_PINNING		= 0x100,
158 	MAP_DEF_INNER_MAP	= 0x200,
159 
160 	MAP_DEF_ALL		= 0x3ff, /* combination of all above */
161 };
162 
163 struct btf_map_def {
164 	enum map_def_parts parts;
165 	__u32 map_type;
166 	__u32 key_type_id;
167 	__u32 key_size;
168 	__u32 value_type_id;
169 	__u32 value_size;
170 	__u32 max_entries;
171 	__u32 map_flags;
172 	__u32 numa_node;
173 	__u32 pinning;
174 };
175 
176 int parse_btf_map_def(const char *map_name, struct btf *btf,
177 		      const struct btf_type *def_t, bool strict,
178 		      struct btf_map_def *map_def, struct btf_map_def *inner_def);
179 
180 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
181 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt);
182 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt);
183 
184 static inline bool libbpf_validate_opts(const char *opts,
185 					size_t opts_sz, size_t user_sz,
186 					const char *type_name)
187 {
188 	if (user_sz < sizeof(size_t)) {
189 		pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
190 		return false;
191 	}
192 	if (user_sz > opts_sz) {
193 		size_t i;
194 
195 		for (i = opts_sz; i < user_sz; i++) {
196 			if (opts[i]) {
197 				pr_warn("%s has non-zero extra bytes\n",
198 					type_name);
199 				return false;
200 			}
201 		}
202 	}
203 	return true;
204 }
205 
206 #define OPTS_VALID(opts, type)						      \
207 	(!(opts) || libbpf_validate_opts((const char *)opts,		      \
208 					 offsetofend(struct type,	      \
209 						     type##__last_field),     \
210 					 (opts)->sz, #type))
211 #define OPTS_HAS(opts, field) \
212 	((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
213 #define OPTS_GET(opts, field, fallback_value) \
214 	(OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
215 #define OPTS_SET(opts, field, value)		\
216 	do {					\
217 		if (OPTS_HAS(opts, field))	\
218 			(opts)->field = value;	\
219 	} while (0)
220 
221 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
222 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
223 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
224 			 const char *str_sec, size_t str_len);
225 
226 struct bpf_prog_load_params {
227 	enum bpf_prog_type prog_type;
228 	enum bpf_attach_type expected_attach_type;
229 	const char *name;
230 	const struct bpf_insn *insns;
231 	size_t insn_cnt;
232 	const char *license;
233 	__u32 kern_version;
234 	__u32 attach_prog_fd;
235 	__u32 attach_btf_obj_fd;
236 	__u32 attach_btf_id;
237 	__u32 prog_ifindex;
238 	__u32 prog_btf_fd;
239 	__u32 prog_flags;
240 
241 	__u32 func_info_rec_size;
242 	const void *func_info;
243 	__u32 func_info_cnt;
244 
245 	__u32 line_info_rec_size;
246 	const void *line_info;
247 	__u32 line_info_cnt;
248 
249 	__u32 log_level;
250 	char *log_buf;
251 	size_t log_buf_sz;
252 };
253 
254 int libbpf__bpf_prog_load(const struct bpf_prog_load_params *load_attr);
255 
256 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
257 			     __u32 *size);
258 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
259 				__u32 *off);
260 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf);
261 
262 struct btf_ext_info {
263 	/*
264 	 * info points to the individual info section (e.g. func_info and
265 	 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
266 	 */
267 	void *info;
268 	__u32 rec_size;
269 	__u32 len;
270 };
271 
272 #define for_each_btf_ext_sec(seg, sec)					\
273 	for (sec = (seg)->info;						\
274 	     (void *)sec < (seg)->info + (seg)->len;			\
275 	     sec = (void *)sec + sizeof(struct btf_ext_info_sec) +	\
276 		   (seg)->rec_size * sec->num_info)
277 
278 #define for_each_btf_ext_rec(seg, sec, i, rec)				\
279 	for (i = 0, rec = (void *)&(sec)->data;				\
280 	     i < (sec)->num_info;					\
281 	     i++, rec = (void *)rec + (seg)->rec_size)
282 
283 /*
284  * The .BTF.ext ELF section layout defined as
285  *   struct btf_ext_header
286  *   func_info subsection
287  *
288  * The func_info subsection layout:
289  *   record size for struct bpf_func_info in the func_info subsection
290  *   struct btf_sec_func_info for section #1
291  *   a list of bpf_func_info records for section #1
292  *     where struct bpf_func_info mimics one in include/uapi/linux/bpf.h
293  *     but may not be identical
294  *   struct btf_sec_func_info for section #2
295  *   a list of bpf_func_info records for section #2
296  *   ......
297  *
298  * Note that the bpf_func_info record size in .BTF.ext may not
299  * be the same as the one defined in include/uapi/linux/bpf.h.
300  * The loader should ensure that record_size meets minimum
301  * requirement and pass the record as is to the kernel. The
302  * kernel will handle the func_info properly based on its contents.
303  */
304 struct btf_ext_header {
305 	__u16	magic;
306 	__u8	version;
307 	__u8	flags;
308 	__u32	hdr_len;
309 
310 	/* All offsets are in bytes relative to the end of this header */
311 	__u32	func_info_off;
312 	__u32	func_info_len;
313 	__u32	line_info_off;
314 	__u32	line_info_len;
315 
316 	/* optional part of .BTF.ext header */
317 	__u32	core_relo_off;
318 	__u32	core_relo_len;
319 };
320 
321 struct btf_ext {
322 	union {
323 		struct btf_ext_header *hdr;
324 		void *data;
325 	};
326 	struct btf_ext_info func_info;
327 	struct btf_ext_info line_info;
328 	struct btf_ext_info core_relo_info;
329 	__u32 data_size;
330 };
331 
332 struct btf_ext_info_sec {
333 	__u32	sec_name_off;
334 	__u32	num_info;
335 	/* Followed by num_info * record_size number of bytes */
336 	__u8	data[];
337 };
338 
339 /* The minimum bpf_func_info checked by the loader */
340 struct bpf_func_info_min {
341 	__u32   insn_off;
342 	__u32   type_id;
343 };
344 
345 /* The minimum bpf_line_info checked by the loader */
346 struct bpf_line_info_min {
347 	__u32	insn_off;
348 	__u32	file_name_off;
349 	__u32	line_off;
350 	__u32	line_col;
351 };
352 
353 /* bpf_core_relo_kind encodes which aspect of captured field/type/enum value
354  * has to be adjusted by relocations.
355  */
356 enum bpf_core_relo_kind {
357 	BPF_FIELD_BYTE_OFFSET = 0,	/* field byte offset */
358 	BPF_FIELD_BYTE_SIZE = 1,	/* field size in bytes */
359 	BPF_FIELD_EXISTS = 2,		/* field existence in target kernel */
360 	BPF_FIELD_SIGNED = 3,		/* field signedness (0 - unsigned, 1 - signed) */
361 	BPF_FIELD_LSHIFT_U64 = 4,	/* bitfield-specific left bitshift */
362 	BPF_FIELD_RSHIFT_U64 = 5,	/* bitfield-specific right bitshift */
363 	BPF_TYPE_ID_LOCAL = 6,		/* type ID in local BPF object */
364 	BPF_TYPE_ID_TARGET = 7,		/* type ID in target kernel */
365 	BPF_TYPE_EXISTS = 8,		/* type existence in target kernel */
366 	BPF_TYPE_SIZE = 9,		/* type size in bytes */
367 	BPF_ENUMVAL_EXISTS = 10,	/* enum value existence in target kernel */
368 	BPF_ENUMVAL_VALUE = 11,		/* enum value integer value */
369 };
370 
371 /* The minimum bpf_core_relo checked by the loader
372  *
373  * CO-RE relocation captures the following data:
374  * - insn_off - instruction offset (in bytes) within a BPF program that needs
375  *   its insn->imm field to be relocated with actual field info;
376  * - type_id - BTF type ID of the "root" (containing) entity of a relocatable
377  *   type or field;
378  * - access_str_off - offset into corresponding .BTF string section. String
379  *   interpretation depends on specific relocation kind:
380  *     - for field-based relocations, string encodes an accessed field using
381  *     a sequence of field and array indices, separated by colon (:). It's
382  *     conceptually very close to LLVM's getelementptr ([0]) instruction's
383  *     arguments for identifying offset to a field.
384  *     - for type-based relocations, strings is expected to be just "0";
385  *     - for enum value-based relocations, string contains an index of enum
386  *     value within its enum type;
387  *
388  * Example to provide a better feel.
389  *
390  *   struct sample {
391  *       int a;
392  *       struct {
393  *           int b[10];
394  *       };
395  *   };
396  *
397  *   struct sample *s = ...;
398  *   int x = &s->a;     // encoded as "0:0" (a is field #0)
399  *   int y = &s->b[5];  // encoded as "0:1:0:5" (anon struct is field #1,
400  *                      // b is field #0 inside anon struct, accessing elem #5)
401  *   int z = &s[10]->b; // encoded as "10:1" (ptr is used as an array)
402  *
403  * type_id for all relocs in this example  will capture BTF type id of
404  * `struct sample`.
405  *
406  * Such relocation is emitted when using __builtin_preserve_access_index()
407  * Clang built-in, passing expression that captures field address, e.g.:
408  *
409  * bpf_probe_read(&dst, sizeof(dst),
410  *		  __builtin_preserve_access_index(&src->a.b.c));
411  *
412  * In this case Clang will emit field relocation recording necessary data to
413  * be able to find offset of embedded `a.b.c` field within `src` struct.
414  *
415  *   [0] https://llvm.org/docs/LangRef.html#getelementptr-instruction
416  */
417 struct bpf_core_relo {
418 	__u32   insn_off;
419 	__u32   type_id;
420 	__u32   access_str_off;
421 	enum bpf_core_relo_kind kind;
422 };
423 
424 typedef int (*type_id_visit_fn)(__u32 *type_id, void *ctx);
425 typedef int (*str_off_visit_fn)(__u32 *str_off, void *ctx);
426 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx);
427 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx);
428 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx);
429 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx);
430 
431 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
432