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