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