xref: /openbmc/linux/tools/lib/bpf/bpf_core_read.h (revision 0bf49ffb)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 #ifndef __BPF_CORE_READ_H__
3 #define __BPF_CORE_READ_H__
4 
5 /*
6  * enum bpf_field_info_kind is passed as a second argument into
7  * __builtin_preserve_field_info() built-in to get a specific aspect of
8  * a field, captured as a first argument. __builtin_preserve_field_info(field,
9  * info_kind) returns __u32 integer and produces BTF field relocation, which
10  * is understood and processed by libbpf during BPF object loading. See
11  * selftests/bpf for examples.
12  */
13 enum bpf_field_info_kind {
14 	BPF_FIELD_BYTE_OFFSET = 0,	/* field byte offset */
15 	BPF_FIELD_BYTE_SIZE = 1,
16 	BPF_FIELD_EXISTS = 2,		/* field existence in target kernel */
17 	BPF_FIELD_SIGNED = 3,
18 	BPF_FIELD_LSHIFT_U64 = 4,
19 	BPF_FIELD_RSHIFT_U64 = 5,
20 };
21 
22 /* second argument to __builtin_btf_type_id() built-in */
23 enum bpf_type_id_kind {
24 	BPF_TYPE_ID_LOCAL = 0,		/* BTF type ID in local program */
25 	BPF_TYPE_ID_TARGET = 1,		/* BTF type ID in target kernel */
26 };
27 
28 /* second argument to __builtin_preserve_type_info() built-in */
29 enum bpf_type_info_kind {
30 	BPF_TYPE_EXISTS = 0,		/* type existence in target kernel */
31 	BPF_TYPE_SIZE = 1,		/* type size in target kernel */
32 };
33 
34 /* second argument to __builtin_preserve_enum_value() built-in */
35 enum bpf_enum_value_kind {
36 	BPF_ENUMVAL_EXISTS = 0,		/* enum value existence in kernel */
37 	BPF_ENUMVAL_VALUE = 1,		/* enum value value relocation */
38 };
39 
40 #define __CORE_RELO(src, field, info)					      \
41 	__builtin_preserve_field_info((src)->field, BPF_FIELD_##info)
42 
43 #if __BYTE_ORDER == __LITTLE_ENDIAN
44 #define __CORE_BITFIELD_PROBE_READ(dst, src, fld)			      \
45 	bpf_probe_read_kernel(						      \
46 			(void *)dst,				      \
47 			__CORE_RELO(src, fld, BYTE_SIZE),		      \
48 			(const void *)src + __CORE_RELO(src, fld, BYTE_OFFSET))
49 #else
50 /* semantics of LSHIFT_64 assumes loading values into low-ordered bytes, so
51  * for big-endian we need to adjust destination pointer accordingly, based on
52  * field byte size
53  */
54 #define __CORE_BITFIELD_PROBE_READ(dst, src, fld)			      \
55 	bpf_probe_read_kernel(						      \
56 			(void *)dst + (8 - __CORE_RELO(src, fld, BYTE_SIZE)), \
57 			__CORE_RELO(src, fld, BYTE_SIZE),		      \
58 			(const void *)src + __CORE_RELO(src, fld, BYTE_OFFSET))
59 #endif
60 
61 /*
62  * Extract bitfield, identified by s->field, and return its value as u64.
63  * All this is done in relocatable manner, so bitfield changes such as
64  * signedness, bit size, offset changes, this will be handled automatically.
65  * This version of macro is using bpf_probe_read_kernel() to read underlying
66  * integer storage. Macro functions as an expression and its return type is
67  * bpf_probe_read_kernel()'s return value: 0, on success, <0 on error.
68  */
69 #define BPF_CORE_READ_BITFIELD_PROBED(s, field) ({			      \
70 	unsigned long long val = 0;					      \
71 									      \
72 	__CORE_BITFIELD_PROBE_READ(&val, s, field);			      \
73 	val <<= __CORE_RELO(s, field, LSHIFT_U64);			      \
74 	if (__CORE_RELO(s, field, SIGNED))				      \
75 		val = ((long long)val) >> __CORE_RELO(s, field, RSHIFT_U64);  \
76 	else								      \
77 		val = val >> __CORE_RELO(s, field, RSHIFT_U64);		      \
78 	val;								      \
79 })
80 
81 /*
82  * Extract bitfield, identified by s->field, and return its value as u64.
83  * This version of macro is using direct memory reads and should be used from
84  * BPF program types that support such functionality (e.g., typed raw
85  * tracepoints).
86  */
87 #define BPF_CORE_READ_BITFIELD(s, field) ({				      \
88 	const void *p = (const void *)s + __CORE_RELO(s, field, BYTE_OFFSET); \
89 	unsigned long long val;						      \
90 									      \
91 	switch (__CORE_RELO(s, field, BYTE_SIZE)) {			      \
92 	case 1: val = *(const unsigned char *)p;			      \
93 	case 2: val = *(const unsigned short *)p;			      \
94 	case 4: val = *(const unsigned int *)p;				      \
95 	case 8: val = *(const unsigned long long *)p;			      \
96 	}								      \
97 	val <<= __CORE_RELO(s, field, LSHIFT_U64);			      \
98 	if (__CORE_RELO(s, field, SIGNED))				      \
99 		val = ((long long)val) >> __CORE_RELO(s, field, RSHIFT_U64);  \
100 	else								      \
101 		val = val >> __CORE_RELO(s, field, RSHIFT_U64);		      \
102 	val;								      \
103 })
104 
105 /*
106  * Convenience macro to check that field actually exists in target kernel's.
107  * Returns:
108  *    1, if matching field is present in target kernel;
109  *    0, if no matching field found.
110  */
111 #define bpf_core_field_exists(field)					    \
112 	__builtin_preserve_field_info(field, BPF_FIELD_EXISTS)
113 
114 /*
115  * Convenience macro to get the byte size of a field. Works for integers,
116  * struct/unions, pointers, arrays, and enums.
117  */
118 #define bpf_core_field_size(field)					    \
119 	__builtin_preserve_field_info(field, BPF_FIELD_BYTE_SIZE)
120 
121 /*
122  * Convenience macro to get BTF type ID of a specified type, using a local BTF
123  * information. Return 32-bit unsigned integer with type ID from program's own
124  * BTF. Always succeeds.
125  */
126 #define bpf_core_type_id_local(type)					    \
127 	__builtin_btf_type_id(*(typeof(type) *)0, BPF_TYPE_ID_LOCAL)
128 
129 /*
130  * Convenience macro to get BTF type ID of a target kernel's type that matches
131  * specified local type.
132  * Returns:
133  *    - valid 32-bit unsigned type ID in kernel BTF;
134  *    - 0, if no matching type was found in a target kernel BTF.
135  */
136 #define bpf_core_type_id_kernel(type)					    \
137 	__builtin_btf_type_id(*(typeof(type) *)0, BPF_TYPE_ID_TARGET)
138 
139 /*
140  * Convenience macro to check that provided named type
141  * (struct/union/enum/typedef) exists in a target kernel.
142  * Returns:
143  *    1, if such type is present in target kernel's BTF;
144  *    0, if no matching type is found.
145  */
146 #define bpf_core_type_exists(type)					    \
147 	__builtin_preserve_type_info(*(typeof(type) *)0, BPF_TYPE_EXISTS)
148 
149 /*
150  * Convenience macro to get the byte size of a provided named type
151  * (struct/union/enum/typedef) in a target kernel.
152  * Returns:
153  *    >= 0 size (in bytes), if type is present in target kernel's BTF;
154  *    0, if no matching type is found.
155  */
156 #define bpf_core_type_size(type)					    \
157 	__builtin_preserve_type_info(*(typeof(type) *)0, BPF_TYPE_SIZE)
158 
159 /*
160  * Convenience macro to check that provided enumerator value is defined in
161  * a target kernel.
162  * Returns:
163  *    1, if specified enum type and its enumerator value are present in target
164  *    kernel's BTF;
165  *    0, if no matching enum and/or enum value within that enum is found.
166  */
167 #define bpf_core_enum_value_exists(enum_type, enum_value)		    \
168 	__builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, BPF_ENUMVAL_EXISTS)
169 
170 /*
171  * Convenience macro to get the integer value of an enumerator value in
172  * a target kernel.
173  * Returns:
174  *    64-bit value, if specified enum type and its enumerator value are
175  *    present in target kernel's BTF;
176  *    0, if no matching enum and/or enum value within that enum is found.
177  */
178 #define bpf_core_enum_value(enum_type, enum_value)			    \
179 	__builtin_preserve_enum_value(*(typeof(enum_type) *)enum_value, BPF_ENUMVAL_VALUE)
180 
181 /*
182  * bpf_core_read() abstracts away bpf_probe_read_kernel() call and captures
183  * offset relocation for source address using __builtin_preserve_access_index()
184  * built-in, provided by Clang.
185  *
186  * __builtin_preserve_access_index() takes as an argument an expression of
187  * taking an address of a field within struct/union. It makes compiler emit
188  * a relocation, which records BTF type ID describing root struct/union and an
189  * accessor string which describes exact embedded field that was used to take
190  * an address. See detailed description of this relocation format and
191  * semantics in comments to struct bpf_field_reloc in libbpf_internal.h.
192  *
193  * This relocation allows libbpf to adjust BPF instruction to use correct
194  * actual field offset, based on target kernel BTF type that matches original
195  * (local) BTF, used to record relocation.
196  */
197 #define bpf_core_read(dst, sz, src)					    \
198 	bpf_probe_read_kernel(dst, sz, (const void *)__builtin_preserve_access_index(src))
199 
200 /* NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. */
201 #define bpf_core_read_user(dst, sz, src)				    \
202 	bpf_probe_read_user(dst, sz, (const void *)__builtin_preserve_access_index(src))
203 /*
204  * bpf_core_read_str() is a thin wrapper around bpf_probe_read_str()
205  * additionally emitting BPF CO-RE field relocation for specified source
206  * argument.
207  */
208 #define bpf_core_read_str(dst, sz, src)					    \
209 	bpf_probe_read_kernel_str(dst, sz, (const void *)__builtin_preserve_access_index(src))
210 
211 /* NOTE: see comments for BPF_CORE_READ_USER() about the proper types use. */
212 #define bpf_core_read_user_str(dst, sz, src)				    \
213 	bpf_probe_read_user_str(dst, sz, (const void *)__builtin_preserve_access_index(src))
214 
215 #define ___concat(a, b) a ## b
216 #define ___apply(fn, n) ___concat(fn, n)
217 #define ___nth(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, __11, N, ...) N
218 
219 /*
220  * return number of provided arguments; used for switch-based variadic macro
221  * definitions (see ___last, ___arrow, etc below)
222  */
223 #define ___narg(...) ___nth(_, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
224 /*
225  * return 0 if no arguments are passed, N - otherwise; used for
226  * recursively-defined macros to specify termination (0) case, and generic
227  * (N) case (e.g., ___read_ptrs, ___core_read)
228  */
229 #define ___empty(...) ___nth(_, ##__VA_ARGS__, N, N, N, N, N, N, N, N, N, N, 0)
230 
231 #define ___last1(x) x
232 #define ___last2(a, x) x
233 #define ___last3(a, b, x) x
234 #define ___last4(a, b, c, x) x
235 #define ___last5(a, b, c, d, x) x
236 #define ___last6(a, b, c, d, e, x) x
237 #define ___last7(a, b, c, d, e, f, x) x
238 #define ___last8(a, b, c, d, e, f, g, x) x
239 #define ___last9(a, b, c, d, e, f, g, h, x) x
240 #define ___last10(a, b, c, d, e, f, g, h, i, x) x
241 #define ___last(...) ___apply(___last, ___narg(__VA_ARGS__))(__VA_ARGS__)
242 
243 #define ___nolast2(a, _) a
244 #define ___nolast3(a, b, _) a, b
245 #define ___nolast4(a, b, c, _) a, b, c
246 #define ___nolast5(a, b, c, d, _) a, b, c, d
247 #define ___nolast6(a, b, c, d, e, _) a, b, c, d, e
248 #define ___nolast7(a, b, c, d, e, f, _) a, b, c, d, e, f
249 #define ___nolast8(a, b, c, d, e, f, g, _) a, b, c, d, e, f, g
250 #define ___nolast9(a, b, c, d, e, f, g, h, _) a, b, c, d, e, f, g, h
251 #define ___nolast10(a, b, c, d, e, f, g, h, i, _) a, b, c, d, e, f, g, h, i
252 #define ___nolast(...) ___apply(___nolast, ___narg(__VA_ARGS__))(__VA_ARGS__)
253 
254 #define ___arrow1(a) a
255 #define ___arrow2(a, b) a->b
256 #define ___arrow3(a, b, c) a->b->c
257 #define ___arrow4(a, b, c, d) a->b->c->d
258 #define ___arrow5(a, b, c, d, e) a->b->c->d->e
259 #define ___arrow6(a, b, c, d, e, f) a->b->c->d->e->f
260 #define ___arrow7(a, b, c, d, e, f, g) a->b->c->d->e->f->g
261 #define ___arrow8(a, b, c, d, e, f, g, h) a->b->c->d->e->f->g->h
262 #define ___arrow9(a, b, c, d, e, f, g, h, i) a->b->c->d->e->f->g->h->i
263 #define ___arrow10(a, b, c, d, e, f, g, h, i, j) a->b->c->d->e->f->g->h->i->j
264 #define ___arrow(...) ___apply(___arrow, ___narg(__VA_ARGS__))(__VA_ARGS__)
265 
266 #define ___type(...) typeof(___arrow(__VA_ARGS__))
267 
268 #define ___read(read_fn, dst, src_type, src, accessor)			    \
269 	read_fn((void *)(dst), sizeof(*(dst)), &((src_type)(src))->accessor)
270 
271 /* "recursively" read a sequence of inner pointers using local __t var */
272 #define ___rd_first(fn, src, a) ___read(fn, &__t, ___type(src), src, a);
273 #define ___rd_last(fn, ...)						    \
274 	___read(fn, &__t, ___type(___nolast(__VA_ARGS__)), __t, ___last(__VA_ARGS__));
275 #define ___rd_p1(fn, ...) const void *__t; ___rd_first(fn, __VA_ARGS__)
276 #define ___rd_p2(fn, ...) ___rd_p1(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
277 #define ___rd_p3(fn, ...) ___rd_p2(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
278 #define ___rd_p4(fn, ...) ___rd_p3(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
279 #define ___rd_p5(fn, ...) ___rd_p4(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
280 #define ___rd_p6(fn, ...) ___rd_p5(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
281 #define ___rd_p7(fn, ...) ___rd_p6(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
282 #define ___rd_p8(fn, ...) ___rd_p7(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
283 #define ___rd_p9(fn, ...) ___rd_p8(fn, ___nolast(__VA_ARGS__)) ___rd_last(fn, __VA_ARGS__)
284 #define ___read_ptrs(fn, src, ...)					    \
285 	___apply(___rd_p, ___narg(__VA_ARGS__))(fn, src, __VA_ARGS__)
286 
287 #define ___core_read0(fn, fn_ptr, dst, src, a)				    \
288 	___read(fn, dst, ___type(src), src, a);
289 #define ___core_readN(fn, fn_ptr, dst, src, ...)			    \
290 	___read_ptrs(fn_ptr, src, ___nolast(__VA_ARGS__))		    \
291 	___read(fn, dst, ___type(src, ___nolast(__VA_ARGS__)), __t,	    \
292 		___last(__VA_ARGS__));
293 #define ___core_read(fn, fn_ptr, dst, src, a, ...)			    \
294 	___apply(___core_read, ___empty(__VA_ARGS__))(fn, fn_ptr, dst,	    \
295 						      src, a, ##__VA_ARGS__)
296 
297 /*
298  * BPF_CORE_READ_INTO() is a more performance-conscious variant of
299  * BPF_CORE_READ(), in which final field is read into user-provided storage.
300  * See BPF_CORE_READ() below for more details on general usage.
301  */
302 #define BPF_CORE_READ_INTO(dst, src, a, ...) ({				    \
303 	___core_read(bpf_core_read, bpf_core_read,			    \
304 		     dst, (src), a, ##__VA_ARGS__)			    \
305 })
306 
307 /*
308  * Variant of BPF_CORE_READ_INTO() for reading from user-space memory.
309  *
310  * NOTE: see comments for BPF_CORE_READ_USER() about the proper types use.
311  */
312 #define BPF_CORE_READ_USER_INTO(dst, src, a, ...) ({			    \
313 	___core_read(bpf_core_read_user, bpf_core_read_user,		    \
314 		     dst, (src), a, ##__VA_ARGS__)			    \
315 })
316 
317 /* Non-CO-RE variant of BPF_CORE_READ_INTO() */
318 #define BPF_PROBE_READ_INTO(dst, src, a, ...) ({			    \
319 	___core_read(bpf_probe_read, bpf_probe_read,			    \
320 		     dst, (src), a, ##__VA_ARGS__)			    \
321 })
322 
323 /* Non-CO-RE variant of BPF_CORE_READ_USER_INTO().
324  *
325  * As no CO-RE relocations are emitted, source types can be arbitrary and are
326  * not restricted to kernel types only.
327  */
328 #define BPF_PROBE_READ_USER_INTO(dst, src, a, ...) ({			    \
329 	___core_read(bpf_probe_read_user, bpf_probe_read_user,		    \
330 		     dst, (src), a, ##__VA_ARGS__)			    \
331 })
332 
333 /*
334  * BPF_CORE_READ_STR_INTO() does same "pointer chasing" as
335  * BPF_CORE_READ() for intermediate pointers, but then executes (and returns
336  * corresponding error code) bpf_core_read_str() for final string read.
337  */
338 #define BPF_CORE_READ_STR_INTO(dst, src, a, ...) ({			    \
339 	___core_read(bpf_core_read_str, bpf_core_read,			    \
340 		     dst, (src), a, ##__VA_ARGS__)			    \
341 })
342 
343 /*
344  * Variant of BPF_CORE_READ_STR_INTO() for reading from user-space memory.
345  *
346  * NOTE: see comments for BPF_CORE_READ_USER() about the proper types use.
347  */
348 #define BPF_CORE_READ_USER_STR_INTO(dst, src, a, ...) ({		    \
349 	___core_read(bpf_core_read_user_str, bpf_core_read_user,	    \
350 		     dst, (src), a, ##__VA_ARGS__)			    \
351 })
352 
353 /* Non-CO-RE variant of BPF_CORE_READ_STR_INTO() */
354 #define BPF_PROBE_READ_STR_INTO(dst, src, a, ...) ({			    \
355 	___core_read(bpf_probe_read_str, bpf_probe_read,		    \
356 		     dst, (src), a, ##__VA_ARGS__)			    \
357 })
358 
359 /*
360  * Non-CO-RE variant of BPF_CORE_READ_USER_STR_INTO().
361  *
362  * As no CO-RE relocations are emitted, source types can be arbitrary and are
363  * not restricted to kernel types only.
364  */
365 #define BPF_PROBE_READ_USER_STR_INTO(dst, src, a, ...) ({		    \
366 	___core_read(bpf_probe_read_user_str, bpf_probe_read_user,	    \
367 		     dst, (src), a, ##__VA_ARGS__)			    \
368 })
369 
370 /*
371  * BPF_CORE_READ() is used to simplify BPF CO-RE relocatable read, especially
372  * when there are few pointer chasing steps.
373  * E.g., what in non-BPF world (or in BPF w/ BCC) would be something like:
374  *	int x = s->a.b.c->d.e->f->g;
375  * can be succinctly achieved using BPF_CORE_READ as:
376  *	int x = BPF_CORE_READ(s, a.b.c, d.e, f, g);
377  *
378  * BPF_CORE_READ will decompose above statement into 4 bpf_core_read (BPF
379  * CO-RE relocatable bpf_probe_read_kernel() wrapper) calls, logically
380  * equivalent to:
381  * 1. const void *__t = s->a.b.c;
382  * 2. __t = __t->d.e;
383  * 3. __t = __t->f;
384  * 4. return __t->g;
385  *
386  * Equivalence is logical, because there is a heavy type casting/preservation
387  * involved, as well as all the reads are happening through
388  * bpf_probe_read_kernel() calls using __builtin_preserve_access_index() to
389  * emit CO-RE relocations.
390  *
391  * N.B. Only up to 9 "field accessors" are supported, which should be more
392  * than enough for any practical purpose.
393  */
394 #define BPF_CORE_READ(src, a, ...) ({					    \
395 	___type((src), a, ##__VA_ARGS__) __r;				    \
396 	BPF_CORE_READ_INTO(&__r, (src), a, ##__VA_ARGS__);		    \
397 	__r;								    \
398 })
399 
400 /*
401  * Variant of BPF_CORE_READ() for reading from user-space memory.
402  *
403  * NOTE: all the source types involved are still *kernel types* and need to
404  * exist in kernel (or kernel module) BTF, otherwise CO-RE relocation will
405  * fail. Custom user types are not relocatable with CO-RE.
406  * The typical situation in which BPF_CORE_READ_USER() might be used is to
407  * read kernel UAPI types from the user-space memory passed in as a syscall
408  * input argument.
409  */
410 #define BPF_CORE_READ_USER(src, a, ...) ({				    \
411 	___type((src), a, ##__VA_ARGS__) __r;				    \
412 	BPF_CORE_READ_USER_INTO(&__r, (src), a, ##__VA_ARGS__);		    \
413 	__r;								    \
414 })
415 
416 /* Non-CO-RE variant of BPF_CORE_READ() */
417 #define BPF_PROBE_READ(src, a, ...) ({					    \
418 	___type((src), a, ##__VA_ARGS__) __r;				    \
419 	BPF_PROBE_READ_INTO(&__r, (src), a, ##__VA_ARGS__);		    \
420 	__r;								    \
421 })
422 
423 /*
424  * Non-CO-RE variant of BPF_CORE_READ_USER().
425  *
426  * As no CO-RE relocations are emitted, source types can be arbitrary and are
427  * not restricted to kernel types only.
428  */
429 #define BPF_PROBE_READ_USER(src, a, ...) ({				    \
430 	___type((src), a, ##__VA_ARGS__) __r;				    \
431 	BPF_PROBE_READ_USER_INTO(&__r, (src), a, ##__VA_ARGS__);	    \
432 	__r;								    \
433 })
434 
435 #endif
436 
437