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