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