xref: /linux/kernel/bpf/btf.c (revision d5273fd3ca0bf0b59fff49fb59237440998fbec8)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018 Facebook */
3 
4 #include <uapi/linux/btf.h>
5 #include <uapi/linux/bpf.h>
6 #include <uapi/linux/bpf_perf_event.h>
7 #include <uapi/linux/types.h>
8 #include <linux/seq_file.h>
9 #include <linux/compiler.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/file.h>
15 #include <linux/uaccess.h>
16 #include <linux/kernel.h>
17 #include <linux/idr.h>
18 #include <linux/sort.h>
19 #include <linux/bpf_verifier.h>
20 #include <linux/btf.h>
21 #include <linux/btf_ids.h>
22 #include <linux/bpf.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/skmsg.h>
25 #include <linux/perf_event.h>
26 #include <linux/bsearch.h>
27 #include <linux/kobject.h>
28 #include <linux/string.h>
29 #include <linux/sysfs.h>
30 #include <linux/overflow.h>
31 
32 #include <net/netfilter/nf_bpf_link.h>
33 
34 #include <net/sock.h>
35 #include <net/xdp.h>
36 #include "../tools/lib/bpf/relo_core.h"
37 
38 /* BTF (BPF Type Format) is the meta data format which describes
39  * the data types of BPF program/map.  Hence, it basically focus
40  * on the C programming language which the modern BPF is primary
41  * using.
42  *
43  * ELF Section:
44  * ~~~~~~~~~~~
45  * The BTF data is stored under the ".BTF" ELF section
46  *
47  * struct btf_type:
48  * ~~~~~~~~~~~~~~~
49  * Each 'struct btf_type' object describes a C data type.
50  * Depending on the type it is describing, a 'struct btf_type'
51  * object may be followed by more data.  F.e.
52  * To describe an array, 'struct btf_type' is followed by
53  * 'struct btf_array'.
54  *
55  * 'struct btf_type' and any extra data following it are
56  * 4 bytes aligned.
57  *
58  * Type section:
59  * ~~~~~~~~~~~~~
60  * The BTF type section contains a list of 'struct btf_type' objects.
61  * Each one describes a C type.  Recall from the above section
62  * that a 'struct btf_type' object could be immediately followed by extra
63  * data in order to describe some particular C types.
64  *
65  * type_id:
66  * ~~~~~~~
67  * Each btf_type object is identified by a type_id.  The type_id
68  * is implicitly implied by the location of the btf_type object in
69  * the BTF type section.  The first one has type_id 1.  The second
70  * one has type_id 2...etc.  Hence, an earlier btf_type has
71  * a smaller type_id.
72  *
73  * A btf_type object may refer to another btf_type object by using
74  * type_id (i.e. the "type" in the "struct btf_type").
75  *
76  * NOTE that we cannot assume any reference-order.
77  * A btf_type object can refer to an earlier btf_type object
78  * but it can also refer to a later btf_type object.
79  *
80  * For example, to describe "const void *".  A btf_type
81  * object describing "const" may refer to another btf_type
82  * object describing "void *".  This type-reference is done
83  * by specifying type_id:
84  *
85  * [1] CONST (anon) type_id=2
86  * [2] PTR (anon) type_id=0
87  *
88  * The above is the btf_verifier debug log:
89  *   - Each line started with "[?]" is a btf_type object
90  *   - [?] is the type_id of the btf_type object.
91  *   - CONST/PTR is the BTF_KIND_XXX
92  *   - "(anon)" is the name of the type.  It just
93  *     happens that CONST and PTR has no name.
94  *   - type_id=XXX is the 'u32 type' in btf_type
95  *
96  * NOTE: "void" has type_id 0
97  *
98  * String section:
99  * ~~~~~~~~~~~~~~
100  * The BTF string section contains the names used by the type section.
101  * Each string is referred by an "offset" from the beginning of the
102  * string section.
103  *
104  * Each string is '\0' terminated.
105  *
106  * The first character in the string section must be '\0'
107  * which is used to mean 'anonymous'. Some btf_type may not
108  * have a name.
109  */
110 
111 /* BTF verification:
112  *
113  * To verify BTF data, two passes are needed.
114  *
115  * Pass #1
116  * ~~~~~~~
117  * The first pass is to collect all btf_type objects to
118  * an array: "btf->types".
119  *
120  * Depending on the C type that a btf_type is describing,
121  * a btf_type may be followed by extra data.  We don't know
122  * how many btf_type is there, and more importantly we don't
123  * know where each btf_type is located in the type section.
124  *
125  * Without knowing the location of each type_id, most verifications
126  * cannot be done.  e.g. an earlier btf_type may refer to a later
127  * btf_type (recall the "const void *" above), so we cannot
128  * check this type-reference in the first pass.
129  *
130  * In the first pass, it still does some verifications (e.g.
131  * checking the name is a valid offset to the string section).
132  *
133  * Pass #2
134  * ~~~~~~~
135  * The main focus is to resolve a btf_type that is referring
136  * to another type.
137  *
138  * We have to ensure the referring type:
139  * 1) does exist in the BTF (i.e. in btf->types[])
140  * 2) does not cause a loop:
141  *	struct A {
142  *		struct B b;
143  *	};
144  *
145  *	struct B {
146  *		struct A a;
147  *	};
148  *
149  * btf_type_needs_resolve() decides if a btf_type needs
150  * to be resolved.
151  *
152  * The needs_resolve type implements the "resolve()" ops which
153  * essentially does a DFS and detects backedge.
154  *
155  * During resolve (or DFS), different C types have different
156  * "RESOLVED" conditions.
157  *
158  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
159  * members because a member is always referring to another
160  * type.  A struct's member can be treated as "RESOLVED" if
161  * it is referring to a BTF_KIND_PTR.  Otherwise, the
162  * following valid C struct would be rejected:
163  *
164  *	struct A {
165  *		int m;
166  *		struct A *a;
167  *	};
168  *
169  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
170  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
171  * detect a pointer loop, e.g.:
172  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
173  *                        ^                                         |
174  *                        +-----------------------------------------+
175  *
176  */
177 
178 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
179 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
180 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
181 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
182 #define BITS_ROUNDUP_BYTES(bits) \
183 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
184 
185 #define BTF_INFO_MASK 0x9f00ffff
186 #define BTF_INT_MASK 0x0fffffff
187 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
188 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
189 
190 /* 16MB for 64k structs and each has 16 members and
191  * a few MB spaces for the string section.
192  * The hard limit is S32_MAX.
193  */
194 #define BTF_MAX_SIZE (16 * 1024 * 1024)
195 
196 #define for_each_member_from(i, from, struct_type, member)		\
197 	for (i = from, member = btf_type_member(struct_type) + from;	\
198 	     i < btf_type_vlen(struct_type);				\
199 	     i++, member++)
200 
201 #define for_each_vsi_from(i, from, struct_type, member)				\
202 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
203 	     i < btf_type_vlen(struct_type);					\
204 	     i++, member++)
205 
206 DEFINE_IDR(btf_idr);
207 DEFINE_SPINLOCK(btf_idr_lock);
208 
209 enum btf_kfunc_hook {
210 	BTF_KFUNC_HOOK_COMMON,
211 	BTF_KFUNC_HOOK_XDP,
212 	BTF_KFUNC_HOOK_TC,
213 	BTF_KFUNC_HOOK_STRUCT_OPS,
214 	BTF_KFUNC_HOOK_TRACING,
215 	BTF_KFUNC_HOOK_SYSCALL,
216 	BTF_KFUNC_HOOK_FMODRET,
217 	BTF_KFUNC_HOOK_CGROUP,
218 	BTF_KFUNC_HOOK_SCHED_ACT,
219 	BTF_KFUNC_HOOK_SK_SKB,
220 	BTF_KFUNC_HOOK_SOCKET_FILTER,
221 	BTF_KFUNC_HOOK_LWT,
222 	BTF_KFUNC_HOOK_NETFILTER,
223 	BTF_KFUNC_HOOK_KPROBE,
224 	BTF_KFUNC_HOOK_MAX,
225 };
226 
227 enum {
228 	BTF_KFUNC_SET_MAX_CNT = 256,
229 	BTF_DTOR_KFUNC_MAX_CNT = 256,
230 	BTF_KFUNC_FILTER_MAX_CNT = 16,
231 };
232 
233 struct btf_kfunc_hook_filter {
234 	btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
235 	u32 nr_filters;
236 };
237 
238 struct btf_kfunc_set_tab {
239 	struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
240 	struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
241 };
242 
243 struct btf_id_dtor_kfunc_tab {
244 	u32 cnt;
245 	struct btf_id_dtor_kfunc dtors[];
246 };
247 
248 struct btf_struct_ops_tab {
249 	u32 cnt;
250 	u32 capacity;
251 	struct bpf_struct_ops_desc ops[];
252 };
253 
254 struct btf {
255 	void *data;
256 	struct btf_type **types;
257 	u32 *resolved_ids;
258 	u32 *resolved_sizes;
259 	const char *strings;
260 	void *nohdr_data;
261 	struct btf_header hdr;
262 	u32 nr_types; /* includes VOID for base BTF */
263 	u32 named_start_id;
264 	u32 types_size;
265 	u32 data_size;
266 	refcount_t refcnt;
267 	u32 id;
268 	struct rcu_head rcu;
269 	struct btf_kfunc_set_tab *kfunc_set_tab;
270 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
271 	struct btf_struct_metas *struct_meta_tab;
272 	struct btf_struct_ops_tab *struct_ops_tab;
273 
274 	/* split BTF support */
275 	struct btf *base_btf;
276 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
277 	u32 start_str_off; /* first string offset (0 for base BTF) */
278 	char name[MODULE_NAME_LEN];
279 	bool kernel_btf;
280 	__u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
281 };
282 
283 enum verifier_phase {
284 	CHECK_META,
285 	CHECK_TYPE,
286 };
287 
288 struct resolve_vertex {
289 	const struct btf_type *t;
290 	u32 type_id;
291 	u16 next_member;
292 };
293 
294 enum visit_state {
295 	NOT_VISITED,
296 	VISITED,
297 	RESOLVED,
298 };
299 
300 enum resolve_mode {
301 	RESOLVE_TBD,	/* To Be Determined */
302 	RESOLVE_PTR,	/* Resolving for Pointer */
303 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
304 					 * or array
305 					 */
306 };
307 
308 #define MAX_RESOLVE_DEPTH 32
309 
310 struct btf_sec_info {
311 	u32 off;
312 	u32 len;
313 };
314 
315 struct btf_verifier_env {
316 	struct btf *btf;
317 	u8 *visit_states;
318 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
319 	struct bpf_verifier_log log;
320 	u32 log_type_id;
321 	u32 top_stack;
322 	enum verifier_phase phase;
323 	enum resolve_mode resolve_mode;
324 };
325 
326 static const char * const btf_kind_str[NR_BTF_KINDS] = {
327 	[BTF_KIND_UNKN]		= "UNKNOWN",
328 	[BTF_KIND_INT]		= "INT",
329 	[BTF_KIND_PTR]		= "PTR",
330 	[BTF_KIND_ARRAY]	= "ARRAY",
331 	[BTF_KIND_STRUCT]	= "STRUCT",
332 	[BTF_KIND_UNION]	= "UNION",
333 	[BTF_KIND_ENUM]		= "ENUM",
334 	[BTF_KIND_FWD]		= "FWD",
335 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
336 	[BTF_KIND_VOLATILE]	= "VOLATILE",
337 	[BTF_KIND_CONST]	= "CONST",
338 	[BTF_KIND_RESTRICT]	= "RESTRICT",
339 	[BTF_KIND_FUNC]		= "FUNC",
340 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
341 	[BTF_KIND_VAR]		= "VAR",
342 	[BTF_KIND_DATASEC]	= "DATASEC",
343 	[BTF_KIND_FLOAT]	= "FLOAT",
344 	[BTF_KIND_DECL_TAG]	= "DECL_TAG",
345 	[BTF_KIND_TYPE_TAG]	= "TYPE_TAG",
346 	[BTF_KIND_ENUM64]	= "ENUM64",
347 };
348 
btf_type_str(const struct btf_type * t)349 const char *btf_type_str(const struct btf_type *t)
350 {
351 	return btf_kind_str[BTF_INFO_KIND(t->info)];
352 }
353 
354 /* Chunk size we use in safe copy of data to be shown. */
355 #define BTF_SHOW_OBJ_SAFE_SIZE		32
356 
357 /*
358  * This is the maximum size of a base type value (equivalent to a
359  * 128-bit int); if we are at the end of our safe buffer and have
360  * less than 16 bytes space we can't be assured of being able
361  * to copy the next type safely, so in such cases we will initiate
362  * a new copy.
363  */
364 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
365 
366 /* Type name size */
367 #define BTF_SHOW_NAME_SIZE		80
368 
369 /*
370  * The suffix of a type that indicates it cannot alias another type when
371  * comparing BTF IDs for kfunc invocations.
372  */
373 #define NOCAST_ALIAS_SUFFIX		"___init"
374 
375 /*
376  * Common data to all BTF show operations. Private show functions can add
377  * their own data to a structure containing a struct btf_show and consult it
378  * in the show callback.  See btf_type_show() below.
379  *
380  * One challenge with showing nested data is we want to skip 0-valued
381  * data, but in order to figure out whether a nested object is all zeros
382  * we need to walk through it.  As a result, we need to make two passes
383  * when handling structs, unions and arrays; the first path simply looks
384  * for nonzero data, while the second actually does the display.  The first
385  * pass is signalled by show->state.depth_check being set, and if we
386  * encounter a non-zero value we set show->state.depth_to_show to
387  * the depth at which we encountered it.  When we have completed the
388  * first pass, we will know if anything needs to be displayed if
389  * depth_to_show > depth.  See btf_[struct,array]_show() for the
390  * implementation of this.
391  *
392  * Another problem is we want to ensure the data for display is safe to
393  * access.  To support this, the anonymous "struct {} obj" tracks the data
394  * object and our safe copy of it.  We copy portions of the data needed
395  * to the object "copy" buffer, but because its size is limited to
396  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
397  * traverse larger objects for display.
398  *
399  * The various data type show functions all start with a call to
400  * btf_show_start_type() which returns a pointer to the safe copy
401  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
402  * raw data itself).  btf_show_obj_safe() is responsible for
403  * using copy_from_kernel_nofault() to update the safe data if necessary
404  * as we traverse the object's data.  skbuff-like semantics are
405  * used:
406  *
407  * - obj.head points to the start of the toplevel object for display
408  * - obj.size is the size of the toplevel object
409  * - obj.data points to the current point in the original data at
410  *   which our safe data starts.  obj.data will advance as we copy
411  *   portions of the data.
412  *
413  * In most cases a single copy will suffice, but larger data structures
414  * such as "struct task_struct" will require many copies.  The logic in
415  * btf_show_obj_safe() handles the logic that determines if a new
416  * copy_from_kernel_nofault() is needed.
417  */
418 struct btf_show {
419 	u64 flags;
420 	void *target;	/* target of show operation (seq file, buffer) */
421 	__printf(2, 0) void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
422 	const struct btf *btf;
423 	/* below are used during iteration */
424 	struct {
425 		u8 depth;
426 		u8 depth_to_show;
427 		u8 depth_check;
428 		u8 array_member:1,
429 		   array_terminated:1;
430 		u16 array_encoding;
431 		u32 type_id;
432 		int status;			/* non-zero for error */
433 		const struct btf_type *type;
434 		const struct btf_member *member;
435 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
436 	} state;
437 	struct {
438 		u32 size;
439 		void *head;
440 		void *data;
441 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
442 	} obj;
443 };
444 
445 struct btf_kind_operations {
446 	s32 (*check_meta)(struct btf_verifier_env *env,
447 			  const struct btf_type *t,
448 			  u32 meta_left);
449 	int (*resolve)(struct btf_verifier_env *env,
450 		       const struct resolve_vertex *v);
451 	int (*check_member)(struct btf_verifier_env *env,
452 			    const struct btf_type *struct_type,
453 			    const struct btf_member *member,
454 			    const struct btf_type *member_type);
455 	int (*check_kflag_member)(struct btf_verifier_env *env,
456 				  const struct btf_type *struct_type,
457 				  const struct btf_member *member,
458 				  const struct btf_type *member_type);
459 	void (*log_details)(struct btf_verifier_env *env,
460 			    const struct btf_type *t);
461 	void (*show)(const struct btf *btf, const struct btf_type *t,
462 			 u32 type_id, void *data, u8 bits_offsets,
463 			 struct btf_show *show);
464 };
465 
466 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
467 static struct btf_type btf_void;
468 
469 static int btf_resolve(struct btf_verifier_env *env,
470 		       const struct btf_type *t, u32 type_id);
471 
472 static int btf_func_check(struct btf_verifier_env *env,
473 			  const struct btf_type *t);
474 
btf_type_is_modifier(const struct btf_type * t)475 static bool btf_type_is_modifier(const struct btf_type *t)
476 {
477 	/* Some of them is not strictly a C modifier
478 	 * but they are grouped into the same bucket
479 	 * for BTF concern:
480 	 *   A type (t) that refers to another
481 	 *   type through t->type AND its size cannot
482 	 *   be determined without following the t->type.
483 	 *
484 	 * ptr does not fall into this bucket
485 	 * because its size is always sizeof(void *).
486 	 */
487 	switch (BTF_INFO_KIND(t->info)) {
488 	case BTF_KIND_TYPEDEF:
489 	case BTF_KIND_VOLATILE:
490 	case BTF_KIND_CONST:
491 	case BTF_KIND_RESTRICT:
492 	case BTF_KIND_TYPE_TAG:
493 		return true;
494 	}
495 
496 	return false;
497 }
498 
btf_start_id(const struct btf * btf)499 static int btf_start_id(const struct btf *btf)
500 {
501 	return btf->start_id + (btf->base_btf ? 0 : 1);
502 }
503 
btf_type_is_void(const struct btf_type * t)504 bool btf_type_is_void(const struct btf_type *t)
505 {
506 	return t == &btf_void;
507 }
508 
btf_type_is_datasec(const struct btf_type * t)509 static bool btf_type_is_datasec(const struct btf_type *t)
510 {
511 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
512 }
513 
btf_type_is_decl_tag(const struct btf_type * t)514 static bool btf_type_is_decl_tag(const struct btf_type *t)
515 {
516 	return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
517 }
518 
btf_type_nosize(const struct btf_type * t)519 static bool btf_type_nosize(const struct btf_type *t)
520 {
521 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
522 	       btf_type_is_func(t) || btf_type_is_func_proto(t) ||
523 	       btf_type_is_decl_tag(t);
524 }
525 
btf_type_nosize_or_null(const struct btf_type * t)526 static bool btf_type_nosize_or_null(const struct btf_type *t)
527 {
528 	return !t || btf_type_nosize(t);
529 }
530 
btf_type_is_decl_tag_target(const struct btf_type * t)531 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
532 {
533 	return btf_type_is_func(t) || btf_type_is_struct(t) ||
534 	       btf_type_is_var(t) || btf_type_is_typedef(t);
535 }
536 
btf_is_vmlinux(const struct btf * btf)537 bool btf_is_vmlinux(const struct btf *btf)
538 {
539 	return btf->kernel_btf && !btf->base_btf;
540 }
541 
btf_nr_types(const struct btf * btf)542 u32 btf_nr_types(const struct btf *btf)
543 {
544 	u32 total = 0;
545 
546 	while (btf) {
547 		total += btf->nr_types;
548 		btf = btf->base_btf;
549 	}
550 
551 	return total;
552 }
553 
554 /*
555  * Note that vmlinux and kernel module BTFs are always sorted
556  * during the building phase.
557  */
btf_check_sorted(struct btf * btf)558 static void btf_check_sorted(struct btf *btf)
559 {
560 	u32 i, n, named_start_id = 0;
561 
562 	n = btf_nr_types(btf);
563 	if (btf_is_vmlinux(btf)) {
564 		for (i = btf_start_id(btf); i < n; i++) {
565 			const struct btf_type *t = btf_type_by_id(btf, i);
566 			const char *n = btf_name_by_offset(btf, t->name_off);
567 
568 			if (n[0] != '\0') {
569 				btf->named_start_id = i;
570 				return;
571 			}
572 		}
573 		return;
574 	}
575 
576 	for (i = btf_start_id(btf) + 1; i < n; i++) {
577 		const struct btf_type *ta = btf_type_by_id(btf, i - 1);
578 		const struct btf_type *tb = btf_type_by_id(btf, i);
579 		const char *na = btf_name_by_offset(btf, ta->name_off);
580 		const char *nb = btf_name_by_offset(btf, tb->name_off);
581 
582 		if (strcmp(na, nb) > 0)
583 			return;
584 
585 		if (named_start_id == 0 && na[0] != '\0')
586 			named_start_id = i - 1;
587 		if (named_start_id == 0 && nb[0] != '\0')
588 			named_start_id = i;
589 	}
590 
591 	if (named_start_id)
592 		btf->named_start_id = named_start_id;
593 }
594 
595 /*
596  * btf_named_start_id - Get the named starting ID for the BTF
597  * @btf: Pointer to the target BTF object
598  * @own: Flag indicating whether to query only the current BTF (true = current BTF only,
599  *       false = recursively traverse the base BTF chain)
600  *
601  * Return value rules:
602  * 1. For a sorted btf, return its named_start_id
603  * 2. Else for a split BTF, return its start_id
604  * 3. Else for a base BTF, return 1
605  */
btf_named_start_id(const struct btf * btf,bool own)606 u32 btf_named_start_id(const struct btf *btf, bool own)
607 {
608 	const struct btf *base_btf = btf;
609 
610 	while (!own && base_btf->base_btf)
611 		base_btf = base_btf->base_btf;
612 
613 	return base_btf->named_start_id ?: (base_btf->start_id ?: 1);
614 }
615 
btf_find_by_name_kind_bsearch(const struct btf * btf,const char * name)616 static s32 btf_find_by_name_kind_bsearch(const struct btf *btf, const char *name)
617 {
618 	const struct btf_type *t;
619 	const char *tname;
620 	s32 l, r, m;
621 
622 	l = btf_named_start_id(btf, true);
623 	r = btf_nr_types(btf) - 1;
624 	while (l <= r) {
625 		m = l + (r - l) / 2;
626 		t = btf_type_by_id(btf, m);
627 		tname = btf_name_by_offset(btf, t->name_off);
628 		if (strcmp(tname, name) >= 0) {
629 			if (l == r)
630 				return r;
631 			r = m;
632 		} else {
633 			l = m + 1;
634 		}
635 	}
636 
637 	return btf_nr_types(btf);
638 }
639 
btf_find_by_name_kind(const struct btf * btf,const char * name,u8 kind)640 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
641 {
642 	const struct btf *base_btf = btf_base_btf(btf);
643 	const struct btf_type *t;
644 	const char *tname;
645 	s32 id, total;
646 
647 	if (base_btf) {
648 		id = btf_find_by_name_kind(base_btf, name, kind);
649 		if (id > 0)
650 			return id;
651 	}
652 
653 	total = btf_nr_types(btf);
654 	if (btf->named_start_id > 0 && name[0]) {
655 		id = btf_find_by_name_kind_bsearch(btf, name);
656 		for (; id < total; id++) {
657 			t = btf_type_by_id(btf, id);
658 			tname = btf_name_by_offset(btf, t->name_off);
659 			if (strcmp(tname, name) != 0)
660 				return -ENOENT;
661 			if (BTF_INFO_KIND(t->info) == kind)
662 				return id;
663 		}
664 	} else {
665 		for (id = btf_start_id(btf); id < total; id++) {
666 			t = btf_type_by_id(btf, id);
667 			if (BTF_INFO_KIND(t->info) != kind)
668 				continue;
669 			tname = btf_name_by_offset(btf, t->name_off);
670 			if (strcmp(tname, name) == 0)
671 				return id;
672 		}
673 	}
674 
675 	return -ENOENT;
676 }
677 
bpf_find_btf_id(const char * name,u32 kind,struct btf ** btf_p)678 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
679 {
680 	struct btf *btf;
681 	s32 ret;
682 	int id;
683 
684 	btf = bpf_get_btf_vmlinux();
685 	if (IS_ERR(btf))
686 		return PTR_ERR(btf);
687 	if (!btf)
688 		return -EINVAL;
689 
690 	ret = btf_find_by_name_kind(btf, name, kind);
691 	/* ret is never zero, since btf_find_by_name_kind returns
692 	 * positive btf_id or negative error.
693 	 */
694 	if (ret > 0) {
695 		btf_get(btf);
696 		*btf_p = btf;
697 		return ret;
698 	}
699 
700 	/* If name is not found in vmlinux's BTF then search in module's BTFs */
701 	spin_lock_bh(&btf_idr_lock);
702 	idr_for_each_entry(&btf_idr, btf, id) {
703 		if (!btf_is_module(btf))
704 			continue;
705 		/* linear search could be slow hence unlock/lock
706 		 * the IDR to avoiding holding it for too long
707 		 */
708 		btf_get(btf);
709 		spin_unlock_bh(&btf_idr_lock);
710 		ret = btf_find_by_name_kind(btf, name, kind);
711 		if (ret > 0) {
712 			*btf_p = btf;
713 			return ret;
714 		}
715 		btf_put(btf);
716 		spin_lock_bh(&btf_idr_lock);
717 	}
718 	spin_unlock_bh(&btf_idr_lock);
719 	return ret;
720 }
721 EXPORT_SYMBOL_GPL(bpf_find_btf_id);
722 
btf_type_skip_modifiers(const struct btf * btf,u32 id,u32 * res_id)723 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
724 					       u32 id, u32 *res_id)
725 {
726 	const struct btf_type *t = btf_type_by_id(btf, id);
727 
728 	while (btf_type_is_modifier(t)) {
729 		id = t->type;
730 		t = btf_type_by_id(btf, t->type);
731 	}
732 
733 	if (res_id)
734 		*res_id = id;
735 
736 	return t;
737 }
738 
btf_type_resolve_ptr(const struct btf * btf,u32 id,u32 * res_id)739 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
740 					    u32 id, u32 *res_id)
741 {
742 	const struct btf_type *t;
743 
744 	t = btf_type_skip_modifiers(btf, id, NULL);
745 	if (!btf_type_is_ptr(t))
746 		return NULL;
747 
748 	return btf_type_skip_modifiers(btf, t->type, res_id);
749 }
750 
btf_type_resolve_func_ptr(const struct btf * btf,u32 id,u32 * res_id)751 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
752 						 u32 id, u32 *res_id)
753 {
754 	const struct btf_type *ptype;
755 
756 	ptype = btf_type_resolve_ptr(btf, id, res_id);
757 	if (ptype && btf_type_is_func_proto(ptype))
758 		return ptype;
759 
760 	return NULL;
761 }
762 
763 /* Types that act only as a source, not sink or intermediate
764  * type when resolving.
765  */
btf_type_is_resolve_source_only(const struct btf_type * t)766 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
767 {
768 	return btf_type_is_var(t) ||
769 	       btf_type_is_decl_tag(t) ||
770 	       btf_type_is_datasec(t);
771 }
772 
773 /* What types need to be resolved?
774  *
775  * btf_type_is_modifier() is an obvious one.
776  *
777  * btf_type_is_struct() because its member refers to
778  * another type (through member->type).
779  *
780  * btf_type_is_var() because the variable refers to
781  * another type. btf_type_is_datasec() holds multiple
782  * btf_type_is_var() types that need resolving.
783  *
784  * btf_type_is_array() because its element (array->type)
785  * refers to another type.  Array can be thought of a
786  * special case of struct while array just has the same
787  * member-type repeated by array->nelems of times.
788  */
btf_type_needs_resolve(const struct btf_type * t)789 static bool btf_type_needs_resolve(const struct btf_type *t)
790 {
791 	return btf_type_is_modifier(t) ||
792 	       btf_type_is_ptr(t) ||
793 	       btf_type_is_struct(t) ||
794 	       btf_type_is_array(t) ||
795 	       btf_type_is_var(t) ||
796 	       btf_type_is_func(t) ||
797 	       btf_type_is_decl_tag(t) ||
798 	       btf_type_is_datasec(t);
799 }
800 
801 /* t->size can be used */
btf_type_has_size(const struct btf_type * t)802 static bool btf_type_has_size(const struct btf_type *t)
803 {
804 	switch (BTF_INFO_KIND(t->info)) {
805 	case BTF_KIND_INT:
806 	case BTF_KIND_STRUCT:
807 	case BTF_KIND_UNION:
808 	case BTF_KIND_ENUM:
809 	case BTF_KIND_DATASEC:
810 	case BTF_KIND_FLOAT:
811 	case BTF_KIND_ENUM64:
812 		return true;
813 	}
814 
815 	return false;
816 }
817 
btf_int_encoding_str(u8 encoding)818 static const char *btf_int_encoding_str(u8 encoding)
819 {
820 	if (encoding == 0)
821 		return "(none)";
822 	else if (encoding == BTF_INT_SIGNED)
823 		return "SIGNED";
824 	else if (encoding == BTF_INT_CHAR)
825 		return "CHAR";
826 	else if (encoding == BTF_INT_BOOL)
827 		return "BOOL";
828 	else
829 		return "UNKN";
830 }
831 
btf_type_int(const struct btf_type * t)832 static u32 btf_type_int(const struct btf_type *t)
833 {
834 	return *(u32 *)(t + 1);
835 }
836 
btf_type_array(const struct btf_type * t)837 static const struct btf_array *btf_type_array(const struct btf_type *t)
838 {
839 	return (const struct btf_array *)(t + 1);
840 }
841 
btf_type_enum(const struct btf_type * t)842 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
843 {
844 	return (const struct btf_enum *)(t + 1);
845 }
846 
btf_type_var(const struct btf_type * t)847 static const struct btf_var *btf_type_var(const struct btf_type *t)
848 {
849 	return (const struct btf_var *)(t + 1);
850 }
851 
btf_type_decl_tag(const struct btf_type * t)852 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
853 {
854 	return (const struct btf_decl_tag *)(t + 1);
855 }
856 
btf_type_enum64(const struct btf_type * t)857 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
858 {
859 	return (const struct btf_enum64 *)(t + 1);
860 }
861 
btf_type_ops(const struct btf_type * t)862 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
863 {
864 	return kind_ops[BTF_INFO_KIND(t->info)];
865 }
866 
btf_name_offset_valid(const struct btf * btf,u32 offset)867 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
868 {
869 	if (!BTF_STR_OFFSET_VALID(offset))
870 		return false;
871 
872 	while (offset < btf->start_str_off)
873 		btf = btf->base_btf;
874 
875 	offset -= btf->start_str_off;
876 	return offset < btf->hdr.str_len;
877 }
878 
__btf_name_char_ok(char c,bool first)879 static bool __btf_name_char_ok(char c, bool first)
880 {
881 	if ((first ? !isalpha(c) :
882 		     !isalnum(c)) &&
883 	    c != '_' &&
884 	    c != '.')
885 		return false;
886 	return true;
887 }
888 
btf_str_by_offset(const struct btf * btf,u32 offset)889 const char *btf_str_by_offset(const struct btf *btf, u32 offset)
890 {
891 	while (offset < btf->start_str_off)
892 		btf = btf->base_btf;
893 
894 	offset -= btf->start_str_off;
895 	if (offset < btf->hdr.str_len)
896 		return &btf->strings[offset];
897 
898 	return NULL;
899 }
900 
btf_name_valid_identifier(const struct btf * btf,u32 offset)901 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
902 {
903 	/* offset must be valid */
904 	const char *src = btf_str_by_offset(btf, offset);
905 	const char *src_limit;
906 
907 	if (!__btf_name_char_ok(*src, true))
908 		return false;
909 
910 	/* set a limit on identifier length */
911 	src_limit = src + KSYM_NAME_LEN;
912 	src++;
913 	while (*src && src < src_limit) {
914 		if (!__btf_name_char_ok(*src, false))
915 			return false;
916 		src++;
917 	}
918 
919 	return !*src;
920 }
921 
922 /* Allow any printable character in DATASEC names */
btf_name_valid_section(const struct btf * btf,u32 offset)923 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
924 {
925 	/* offset must be valid */
926 	const char *src = btf_str_by_offset(btf, offset);
927 	const char *src_limit;
928 
929 	if (!*src)
930 		return false;
931 
932 	/* set a limit on identifier length */
933 	src_limit = src + KSYM_NAME_LEN;
934 	while (*src && src < src_limit) {
935 		if (!isprint(*src))
936 			return false;
937 		src++;
938 	}
939 
940 	return !*src;
941 }
942 
__btf_name_by_offset(const struct btf * btf,u32 offset)943 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
944 {
945 	const char *name;
946 
947 	if (!offset)
948 		return "(anon)";
949 
950 	name = btf_str_by_offset(btf, offset);
951 	return name ?: "(invalid-name-offset)";
952 }
953 
btf_name_by_offset(const struct btf * btf,u32 offset)954 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
955 {
956 	return btf_str_by_offset(btf, offset);
957 }
958 
btf_type_by_id(const struct btf * btf,u32 type_id)959 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
960 {
961 	while (type_id < btf->start_id)
962 		btf = btf->base_btf;
963 
964 	type_id -= btf->start_id;
965 	if (type_id >= btf->nr_types)
966 		return NULL;
967 	return btf->types[type_id];
968 }
969 EXPORT_SYMBOL_GPL(btf_type_by_id);
970 
971 /*
972  * Check that the type @t is a regular int. This means that @t is not
973  * a bit field and it has the same size as either of u8/u16/u32/u64
974  * or __int128. If @expected_size is not zero, then size of @t should
975  * be the same. A caller should already have checked that the type @t
976  * is an integer.
977  */
__btf_type_int_is_regular(const struct btf_type * t,size_t expected_size)978 static bool __btf_type_int_is_regular(const struct btf_type *t, size_t expected_size)
979 {
980 	u32 int_data = btf_type_int(t);
981 	u8 nr_bits = BTF_INT_BITS(int_data);
982 	u8 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
983 
984 	return BITS_PER_BYTE_MASKED(nr_bits) == 0 &&
985 	       BTF_INT_OFFSET(int_data) == 0 &&
986 	       (nr_bytes <= 16 && is_power_of_2(nr_bytes)) &&
987 	       (expected_size == 0 || nr_bytes == expected_size);
988 }
989 
btf_type_int_is_regular(const struct btf_type * t)990 static bool btf_type_int_is_regular(const struct btf_type *t)
991 {
992 	return __btf_type_int_is_regular(t, 0);
993 }
994 
btf_type_is_i32(const struct btf_type * t)995 bool btf_type_is_i32(const struct btf_type *t)
996 {
997 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 4);
998 }
999 
btf_type_is_i64(const struct btf_type * t)1000 bool btf_type_is_i64(const struct btf_type *t)
1001 {
1002 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 8);
1003 }
1004 
btf_type_is_primitive(const struct btf_type * t)1005 bool btf_type_is_primitive(const struct btf_type *t)
1006 {
1007 	return (btf_type_is_int(t) && btf_type_int_is_regular(t)) ||
1008 	       btf_is_any_enum(t);
1009 }
1010 
1011 /*
1012  * Check that given struct member is a regular int with expected
1013  * offset and size.
1014  */
btf_member_is_reg_int(const struct btf * btf,const struct btf_type * s,const struct btf_member * m,u32 expected_offset,u32 expected_size)1015 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
1016 			   const struct btf_member *m,
1017 			   u32 expected_offset, u32 expected_size)
1018 {
1019 	const struct btf_type *t;
1020 	u32 id, int_data;
1021 	u8 nr_bits;
1022 
1023 	id = m->type;
1024 	t = btf_type_id_size(btf, &id, NULL);
1025 	if (!t || !btf_type_is_int(t))
1026 		return false;
1027 
1028 	int_data = btf_type_int(t);
1029 	nr_bits = BTF_INT_BITS(int_data);
1030 	if (btf_type_kflag(s)) {
1031 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
1032 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
1033 
1034 		/* if kflag set, int should be a regular int and
1035 		 * bit offset should be at byte boundary.
1036 		 */
1037 		return !bitfield_size &&
1038 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
1039 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
1040 	}
1041 
1042 	if (BTF_INT_OFFSET(int_data) ||
1043 	    BITS_PER_BYTE_MASKED(m->offset) ||
1044 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
1045 	    BITS_PER_BYTE_MASKED(nr_bits) ||
1046 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
1047 		return false;
1048 
1049 	return true;
1050 }
1051 
1052 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
btf_type_skip_qualifiers(const struct btf * btf,u32 id)1053 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
1054 						       u32 id)
1055 {
1056 	const struct btf_type *t = btf_type_by_id(btf, id);
1057 
1058 	while (btf_type_is_modifier(t) &&
1059 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
1060 		t = btf_type_by_id(btf, t->type);
1061 	}
1062 
1063 	return t;
1064 }
1065 
1066 #define BTF_SHOW_MAX_ITER	10
1067 
1068 #define BTF_KIND_BIT(kind)	(1ULL << kind)
1069 
1070 /*
1071  * Populate show->state.name with type name information.
1072  * Format of type name is
1073  *
1074  * [.member_name = ] (type_name)
1075  */
btf_show_name(struct btf_show * show)1076 static const char *btf_show_name(struct btf_show *show)
1077 {
1078 	/* BTF_MAX_ITER array suffixes "[]" */
1079 	const char *array_suffixes = "[][][][][][][][][][]";
1080 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
1081 	/* BTF_MAX_ITER pointer suffixes "*" */
1082 	const char *ptr_suffixes = "**********";
1083 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
1084 	const char *name = NULL, *prefix = "", *parens = "";
1085 	const struct btf_member *m = show->state.member;
1086 	const struct btf_type *t;
1087 	const struct btf_array *array;
1088 	u32 id = show->state.type_id;
1089 	const char *member = NULL;
1090 	bool show_member = false;
1091 	u64 kinds = 0;
1092 	int i;
1093 
1094 	show->state.name[0] = '\0';
1095 
1096 	/*
1097 	 * Don't show type name if we're showing an array member;
1098 	 * in that case we show the array type so don't need to repeat
1099 	 * ourselves for each member.
1100 	 */
1101 	if (show->state.array_member)
1102 		return "";
1103 
1104 	/* Retrieve member name, if any. */
1105 	if (m) {
1106 		member = btf_name_by_offset(show->btf, m->name_off);
1107 		show_member = strlen(member) > 0;
1108 		id = m->type;
1109 	}
1110 
1111 	/*
1112 	 * Start with type_id, as we have resolved the struct btf_type *
1113 	 * via btf_modifier_show() past the parent typedef to the child
1114 	 * struct, int etc it is defined as.  In such cases, the type_id
1115 	 * still represents the starting type while the struct btf_type *
1116 	 * in our show->state points at the resolved type of the typedef.
1117 	 */
1118 	t = btf_type_by_id(show->btf, id);
1119 	if (!t)
1120 		return "";
1121 
1122 	/*
1123 	 * The goal here is to build up the right number of pointer and
1124 	 * array suffixes while ensuring the type name for a typedef
1125 	 * is represented.  Along the way we accumulate a list of
1126 	 * BTF kinds we have encountered, since these will inform later
1127 	 * display; for example, pointer types will not require an
1128 	 * opening "{" for struct, we will just display the pointer value.
1129 	 *
1130 	 * We also want to accumulate the right number of pointer or array
1131 	 * indices in the format string while iterating until we get to
1132 	 * the typedef/pointee/array member target type.
1133 	 *
1134 	 * We start by pointing at the end of pointer and array suffix
1135 	 * strings; as we accumulate pointers and arrays we move the pointer
1136 	 * or array string backwards so it will show the expected number of
1137 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
1138 	 * and/or arrays and typedefs are supported as a precaution.
1139 	 *
1140 	 * We also want to get typedef name while proceeding to resolve
1141 	 * type it points to so that we can add parentheses if it is a
1142 	 * "typedef struct" etc.
1143 	 */
1144 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1145 
1146 		switch (BTF_INFO_KIND(t->info)) {
1147 		case BTF_KIND_TYPEDEF:
1148 			if (!name)
1149 				name = btf_name_by_offset(show->btf,
1150 							       t->name_off);
1151 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1152 			id = t->type;
1153 			break;
1154 		case BTF_KIND_ARRAY:
1155 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1156 			parens = "[";
1157 			if (!t)
1158 				return "";
1159 			array = btf_type_array(t);
1160 			if (array_suffix > array_suffixes)
1161 				array_suffix -= 2;
1162 			id = array->type;
1163 			break;
1164 		case BTF_KIND_PTR:
1165 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1166 			if (ptr_suffix > ptr_suffixes)
1167 				ptr_suffix -= 1;
1168 			id = t->type;
1169 			break;
1170 		default:
1171 			id = 0;
1172 			break;
1173 		}
1174 		if (!id)
1175 			break;
1176 		t = btf_type_skip_qualifiers(show->btf, id);
1177 	}
1178 	/* We may not be able to represent this type; bail to be safe */
1179 	if (i == BTF_SHOW_MAX_ITER)
1180 		return "";
1181 
1182 	if (!name)
1183 		name = btf_name_by_offset(show->btf, t->name_off);
1184 
1185 	switch (BTF_INFO_KIND(t->info)) {
1186 	case BTF_KIND_STRUCT:
1187 	case BTF_KIND_UNION:
1188 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1189 			 "struct" : "union";
1190 		/* if it's an array of struct/union, parens is already set */
1191 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1192 			parens = "{";
1193 		break;
1194 	case BTF_KIND_ENUM:
1195 	case BTF_KIND_ENUM64:
1196 		prefix = "enum";
1197 		break;
1198 	default:
1199 		break;
1200 	}
1201 
1202 	/* pointer does not require parens */
1203 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1204 		parens = "";
1205 	/* typedef does not require struct/union/enum prefix */
1206 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1207 		prefix = "";
1208 
1209 	if (!name)
1210 		name = "";
1211 
1212 	/* Even if we don't want type name info, we want parentheses etc */
1213 	if (show->flags & BTF_SHOW_NONAME)
1214 		snprintf(show->state.name, sizeof(show->state.name), "%s",
1215 			 parens);
1216 	else
1217 		snprintf(show->state.name, sizeof(show->state.name),
1218 			 "%s%s%s(%s%s%s%s%s%s)%s",
1219 			 /* first 3 strings comprise ".member = " */
1220 			 show_member ? "." : "",
1221 			 show_member ? member : "",
1222 			 show_member ? " = " : "",
1223 			 /* ...next is our prefix (struct, enum, etc) */
1224 			 prefix,
1225 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1226 			 /* ...this is the type name itself */
1227 			 name,
1228 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
1229 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1230 			 array_suffix, parens);
1231 
1232 	return show->state.name;
1233 }
1234 
__btf_show_indent(struct btf_show * show)1235 static const char *__btf_show_indent(struct btf_show *show)
1236 {
1237 	const char *indents = "                                ";
1238 	const char *indent = &indents[strlen(indents)];
1239 
1240 	if ((indent - show->state.depth) >= indents)
1241 		return indent - show->state.depth;
1242 	return indents;
1243 }
1244 
btf_show_indent(struct btf_show * show)1245 static const char *btf_show_indent(struct btf_show *show)
1246 {
1247 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1248 }
1249 
btf_show_newline(struct btf_show * show)1250 static const char *btf_show_newline(struct btf_show *show)
1251 {
1252 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1253 }
1254 
btf_show_delim(struct btf_show * show)1255 static const char *btf_show_delim(struct btf_show *show)
1256 {
1257 	if (show->state.depth == 0)
1258 		return "";
1259 
1260 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1261 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1262 		return "|";
1263 
1264 	return ",";
1265 }
1266 
btf_show(struct btf_show * show,const char * fmt,...)1267 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1268 {
1269 	va_list args;
1270 
1271 	if (!show->state.depth_check) {
1272 		va_start(args, fmt);
1273 		show->showfn(show, fmt, args);
1274 		va_end(args);
1275 	}
1276 }
1277 
1278 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1279  * format specifiers to the format specifier passed in; these do the work of
1280  * adding indentation, delimiters etc while the caller simply has to specify
1281  * the type value(s) in the format specifier + value(s).
1282  */
1283 #define btf_show_type_value(show, fmt, value)				       \
1284 	do {								       \
1285 		if ((value) != (__typeof__(value))0 ||			       \
1286 		    (show->flags & BTF_SHOW_ZERO) ||			       \
1287 		    show->state.depth == 0) {				       \
1288 			btf_show(show, "%s%s" fmt "%s%s",		       \
1289 				 btf_show_indent(show),			       \
1290 				 btf_show_name(show),			       \
1291 				 value, btf_show_delim(show),		       \
1292 				 btf_show_newline(show));		       \
1293 			if (show->state.depth > show->state.depth_to_show)     \
1294 				show->state.depth_to_show = show->state.depth; \
1295 		}							       \
1296 	} while (0)
1297 
1298 #define btf_show_type_values(show, fmt, ...)				       \
1299 	do {								       \
1300 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1301 			 btf_show_name(show),				       \
1302 			 __VA_ARGS__, btf_show_delim(show),		       \
1303 			 btf_show_newline(show));			       \
1304 		if (show->state.depth > show->state.depth_to_show)	       \
1305 			show->state.depth_to_show = show->state.depth;	       \
1306 	} while (0)
1307 
1308 /* How much is left to copy to safe buffer after @data? */
btf_show_obj_size_left(struct btf_show * show,void * data)1309 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1310 {
1311 	return show->obj.head + show->obj.size - data;
1312 }
1313 
1314 /* Is object pointed to by @data of @size already copied to our safe buffer? */
btf_show_obj_is_safe(struct btf_show * show,void * data,int size)1315 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1316 {
1317 	return data >= show->obj.data &&
1318 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1319 }
1320 
1321 /*
1322  * If object pointed to by @data of @size falls within our safe buffer, return
1323  * the equivalent pointer to the same safe data.  Assumes
1324  * copy_from_kernel_nofault() has already happened and our safe buffer is
1325  * populated.
1326  */
__btf_show_obj_safe(struct btf_show * show,void * data,int size)1327 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1328 {
1329 	if (btf_show_obj_is_safe(show, data, size))
1330 		return show->obj.safe + (data - show->obj.data);
1331 	return NULL;
1332 }
1333 
1334 /*
1335  * Return a safe-to-access version of data pointed to by @data.
1336  * We do this by copying the relevant amount of information
1337  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1338  *
1339  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1340  * safe copy is needed.
1341  *
1342  * Otherwise we need to determine if we have the required amount
1343  * of data (determined by the @data pointer and the size of the
1344  * largest base type we can encounter (represented by
1345  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1346  * that we will be able to print some of the current object,
1347  * and if more is needed a copy will be triggered.
1348  * Some objects such as structs will not fit into the buffer;
1349  * in such cases additional copies when we iterate over their
1350  * members may be needed.
1351  *
1352  * btf_show_obj_safe() is used to return a safe buffer for
1353  * btf_show_start_type(); this ensures that as we recurse into
1354  * nested types we always have safe data for the given type.
1355  * This approach is somewhat wasteful; it's possible for example
1356  * that when iterating over a large union we'll end up copying the
1357  * same data repeatedly, but the goal is safety not performance.
1358  * We use stack data as opposed to per-CPU buffers because the
1359  * iteration over a type can take some time, and preemption handling
1360  * would greatly complicate use of the safe buffer.
1361  */
btf_show_obj_safe(struct btf_show * show,const struct btf_type * t,void * data)1362 static void *btf_show_obj_safe(struct btf_show *show,
1363 			       const struct btf_type *t,
1364 			       void *data)
1365 {
1366 	const struct btf_type *rt;
1367 	int size_left, size;
1368 	void *safe = NULL;
1369 
1370 	if (show->flags & BTF_SHOW_UNSAFE)
1371 		return data;
1372 
1373 	rt = btf_resolve_size(show->btf, t, &size);
1374 	if (IS_ERR(rt)) {
1375 		show->state.status = PTR_ERR(rt);
1376 		return NULL;
1377 	}
1378 
1379 	/*
1380 	 * Is this toplevel object? If so, set total object size and
1381 	 * initialize pointers.  Otherwise check if we still fall within
1382 	 * our safe object data.
1383 	 */
1384 	if (show->state.depth == 0) {
1385 		show->obj.size = size;
1386 		show->obj.head = data;
1387 	} else {
1388 		/*
1389 		 * If the size of the current object is > our remaining
1390 		 * safe buffer we _may_ need to do a new copy.  However
1391 		 * consider the case of a nested struct; it's size pushes
1392 		 * us over the safe buffer limit, but showing any individual
1393 		 * struct members does not.  In such cases, we don't need
1394 		 * to initiate a fresh copy yet; however we definitely need
1395 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1396 		 * in our buffer, regardless of the current object size.
1397 		 * The logic here is that as we resolve types we will
1398 		 * hit a base type at some point, and we need to be sure
1399 		 * the next chunk of data is safely available to display
1400 		 * that type info safely.  We cannot rely on the size of
1401 		 * the current object here because it may be much larger
1402 		 * than our current buffer (e.g. task_struct is 8k).
1403 		 * All we want to do here is ensure that we can print the
1404 		 * next basic type, which we can if either
1405 		 * - the current type size is within the safe buffer; or
1406 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1407 		 *   the safe buffer.
1408 		 */
1409 		safe = __btf_show_obj_safe(show, data,
1410 					   min(size,
1411 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1412 	}
1413 
1414 	/*
1415 	 * We need a new copy to our safe object, either because we haven't
1416 	 * yet copied and are initializing safe data, or because the data
1417 	 * we want falls outside the boundaries of the safe object.
1418 	 */
1419 	if (!safe) {
1420 		size_left = btf_show_obj_size_left(show, data);
1421 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1422 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1423 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1424 							      data, size_left);
1425 		if (!show->state.status) {
1426 			show->obj.data = data;
1427 			safe = show->obj.safe;
1428 		}
1429 	}
1430 
1431 	return safe;
1432 }
1433 
1434 /*
1435  * Set the type we are starting to show and return a safe data pointer
1436  * to be used for showing the associated data.
1437  */
btf_show_start_type(struct btf_show * show,const struct btf_type * t,u32 type_id,void * data)1438 static void *btf_show_start_type(struct btf_show *show,
1439 				 const struct btf_type *t,
1440 				 u32 type_id, void *data)
1441 {
1442 	show->state.type = t;
1443 	show->state.type_id = type_id;
1444 	show->state.name[0] = '\0';
1445 
1446 	return btf_show_obj_safe(show, t, data);
1447 }
1448 
btf_show_end_type(struct btf_show * show)1449 static void btf_show_end_type(struct btf_show *show)
1450 {
1451 	show->state.type = NULL;
1452 	show->state.type_id = 0;
1453 	show->state.name[0] = '\0';
1454 }
1455 
btf_show_start_aggr_type(struct btf_show * show,const struct btf_type * t,u32 type_id,void * data)1456 static void *btf_show_start_aggr_type(struct btf_show *show,
1457 				      const struct btf_type *t,
1458 				      u32 type_id, void *data)
1459 {
1460 	void *safe_data = btf_show_start_type(show, t, type_id, data);
1461 
1462 	if (!safe_data)
1463 		return safe_data;
1464 
1465 	btf_show(show, "%s%s%s", btf_show_indent(show),
1466 		 btf_show_name(show),
1467 		 btf_show_newline(show));
1468 	show->state.depth++;
1469 	return safe_data;
1470 }
1471 
btf_show_end_aggr_type(struct btf_show * show,const char * suffix)1472 static void btf_show_end_aggr_type(struct btf_show *show,
1473 				   const char *suffix)
1474 {
1475 	show->state.depth--;
1476 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1477 		 btf_show_delim(show), btf_show_newline(show));
1478 	btf_show_end_type(show);
1479 }
1480 
btf_show_start_member(struct btf_show * show,const struct btf_member * m)1481 static void btf_show_start_member(struct btf_show *show,
1482 				  const struct btf_member *m)
1483 {
1484 	show->state.member = m;
1485 }
1486 
btf_show_start_array_member(struct btf_show * show)1487 static void btf_show_start_array_member(struct btf_show *show)
1488 {
1489 	show->state.array_member = 1;
1490 	btf_show_start_member(show, NULL);
1491 }
1492 
btf_show_end_member(struct btf_show * show)1493 static void btf_show_end_member(struct btf_show *show)
1494 {
1495 	show->state.member = NULL;
1496 }
1497 
btf_show_end_array_member(struct btf_show * show)1498 static void btf_show_end_array_member(struct btf_show *show)
1499 {
1500 	show->state.array_member = 0;
1501 	btf_show_end_member(show);
1502 }
1503 
btf_show_start_array_type(struct btf_show * show,const struct btf_type * t,u32 type_id,u16 array_encoding,void * data)1504 static void *btf_show_start_array_type(struct btf_show *show,
1505 				       const struct btf_type *t,
1506 				       u32 type_id,
1507 				       u16 array_encoding,
1508 				       void *data)
1509 {
1510 	show->state.array_encoding = array_encoding;
1511 	show->state.array_terminated = 0;
1512 	return btf_show_start_aggr_type(show, t, type_id, data);
1513 }
1514 
btf_show_end_array_type(struct btf_show * show)1515 static void btf_show_end_array_type(struct btf_show *show)
1516 {
1517 	show->state.array_encoding = 0;
1518 	show->state.array_terminated = 0;
1519 	btf_show_end_aggr_type(show, "]");
1520 }
1521 
btf_show_start_struct_type(struct btf_show * show,const struct btf_type * t,u32 type_id,void * data)1522 static void *btf_show_start_struct_type(struct btf_show *show,
1523 					const struct btf_type *t,
1524 					u32 type_id,
1525 					void *data)
1526 {
1527 	return btf_show_start_aggr_type(show, t, type_id, data);
1528 }
1529 
btf_show_end_struct_type(struct btf_show * show)1530 static void btf_show_end_struct_type(struct btf_show *show)
1531 {
1532 	btf_show_end_aggr_type(show, "}");
1533 }
1534 
__btf_verifier_log(struct bpf_verifier_log * log,const char * fmt,...)1535 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1536 					      const char *fmt, ...)
1537 {
1538 	va_list args;
1539 
1540 	va_start(args, fmt);
1541 	bpf_verifier_vlog(log, fmt, args);
1542 	va_end(args);
1543 }
1544 
btf_verifier_log(struct btf_verifier_env * env,const char * fmt,...)1545 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1546 					    const char *fmt, ...)
1547 {
1548 	struct bpf_verifier_log *log = &env->log;
1549 	va_list args;
1550 
1551 	if (!bpf_verifier_log_needed(log))
1552 		return;
1553 
1554 	va_start(args, fmt);
1555 	bpf_verifier_vlog(log, fmt, args);
1556 	va_end(args);
1557 }
1558 
__btf_verifier_log_type(struct btf_verifier_env * env,const struct btf_type * t,bool log_details,const char * fmt,...)1559 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1560 						   const struct btf_type *t,
1561 						   bool log_details,
1562 						   const char *fmt, ...)
1563 {
1564 	struct bpf_verifier_log *log = &env->log;
1565 	struct btf *btf = env->btf;
1566 	va_list args;
1567 
1568 	if (!bpf_verifier_log_needed(log))
1569 		return;
1570 
1571 	if (log->level == BPF_LOG_KERNEL) {
1572 		/* btf verifier prints all types it is processing via
1573 		 * btf_verifier_log_type(..., fmt = NULL).
1574 		 * Skip those prints for in-kernel BTF verification.
1575 		 */
1576 		if (!fmt)
1577 			return;
1578 
1579 		/* Skip logging when loading module BTF with mismatches permitted */
1580 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1581 			return;
1582 	}
1583 
1584 	__btf_verifier_log(log, "[%u] %s %s%s",
1585 			   env->log_type_id,
1586 			   btf_type_str(t),
1587 			   __btf_name_by_offset(btf, t->name_off),
1588 			   log_details ? " " : "");
1589 
1590 	if (log_details)
1591 		btf_type_ops(t)->log_details(env, t);
1592 
1593 	if (fmt && *fmt) {
1594 		__btf_verifier_log(log, " ");
1595 		va_start(args, fmt);
1596 		bpf_verifier_vlog(log, fmt, args);
1597 		va_end(args);
1598 	}
1599 
1600 	__btf_verifier_log(log, "\n");
1601 }
1602 
1603 #define btf_verifier_log_type(env, t, ...) \
1604 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1605 #define btf_verifier_log_basic(env, t, ...) \
1606 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1607 
1608 __printf(4, 5)
btf_verifier_log_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const char * fmt,...)1609 static void btf_verifier_log_member(struct btf_verifier_env *env,
1610 				    const struct btf_type *struct_type,
1611 				    const struct btf_member *member,
1612 				    const char *fmt, ...)
1613 {
1614 	struct bpf_verifier_log *log = &env->log;
1615 	struct btf *btf = env->btf;
1616 	va_list args;
1617 
1618 	if (!bpf_verifier_log_needed(log))
1619 		return;
1620 
1621 	if (log->level == BPF_LOG_KERNEL) {
1622 		if (!fmt)
1623 			return;
1624 
1625 		/* Skip logging when loading module BTF with mismatches permitted */
1626 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1627 			return;
1628 	}
1629 
1630 	/* The CHECK_META phase already did a btf dump.
1631 	 *
1632 	 * If member is logged again, it must hit an error in
1633 	 * parsing this member.  It is useful to print out which
1634 	 * struct this member belongs to.
1635 	 */
1636 	if (env->phase != CHECK_META)
1637 		btf_verifier_log_type(env, struct_type, NULL);
1638 
1639 	if (btf_type_kflag(struct_type))
1640 		__btf_verifier_log(log,
1641 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1642 				   __btf_name_by_offset(btf, member->name_off),
1643 				   member->type,
1644 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1645 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1646 	else
1647 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1648 				   __btf_name_by_offset(btf, member->name_off),
1649 				   member->type, member->offset);
1650 
1651 	if (fmt && *fmt) {
1652 		__btf_verifier_log(log, " ");
1653 		va_start(args, fmt);
1654 		bpf_verifier_vlog(log, fmt, args);
1655 		va_end(args);
1656 	}
1657 
1658 	__btf_verifier_log(log, "\n");
1659 }
1660 
1661 __printf(4, 5)
btf_verifier_log_vsi(struct btf_verifier_env * env,const struct btf_type * datasec_type,const struct btf_var_secinfo * vsi,const char * fmt,...)1662 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1663 				 const struct btf_type *datasec_type,
1664 				 const struct btf_var_secinfo *vsi,
1665 				 const char *fmt, ...)
1666 {
1667 	struct bpf_verifier_log *log = &env->log;
1668 	va_list args;
1669 
1670 	if (!bpf_verifier_log_needed(log))
1671 		return;
1672 	if (log->level == BPF_LOG_KERNEL && !fmt)
1673 		return;
1674 	if (env->phase != CHECK_META)
1675 		btf_verifier_log_type(env, datasec_type, NULL);
1676 
1677 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1678 			   vsi->type, vsi->offset, vsi->size);
1679 	if (fmt && *fmt) {
1680 		__btf_verifier_log(log, " ");
1681 		va_start(args, fmt);
1682 		bpf_verifier_vlog(log, fmt, args);
1683 		va_end(args);
1684 	}
1685 
1686 	__btf_verifier_log(log, "\n");
1687 }
1688 
btf_verifier_log_hdr(struct btf_verifier_env * env,u32 btf_data_size)1689 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1690 				 u32 btf_data_size)
1691 {
1692 	struct bpf_verifier_log *log = &env->log;
1693 	const struct btf *btf = env->btf;
1694 	const struct btf_header *hdr;
1695 
1696 	if (!bpf_verifier_log_needed(log))
1697 		return;
1698 
1699 	if (log->level == BPF_LOG_KERNEL)
1700 		return;
1701 	hdr = &btf->hdr;
1702 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1703 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1704 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1705 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1706 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1707 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1708 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1709 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1710 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1711 }
1712 
btf_add_type(struct btf_verifier_env * env,struct btf_type * t)1713 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1714 {
1715 	struct btf *btf = env->btf;
1716 
1717 	if (btf->types_size == btf->nr_types) {
1718 		/* Expand 'types' array */
1719 
1720 		struct btf_type **new_types;
1721 		u32 expand_by, new_size;
1722 
1723 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1724 			btf_verifier_log(env, "Exceeded max num of types");
1725 			return -E2BIG;
1726 		}
1727 
1728 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1729 		new_size = min_t(u32, BTF_MAX_TYPE,
1730 				 btf->types_size + expand_by);
1731 
1732 		new_types = kvzalloc_objs(*new_types, new_size,
1733 					  GFP_KERNEL | __GFP_NOWARN);
1734 		if (!new_types)
1735 			return -ENOMEM;
1736 
1737 		if (btf->nr_types == 0) {
1738 			if (!btf->base_btf) {
1739 				/* lazily init VOID type */
1740 				new_types[0] = &btf_void;
1741 				btf->nr_types++;
1742 			}
1743 		} else {
1744 			memcpy(new_types, btf->types,
1745 			       sizeof(*btf->types) * btf->nr_types);
1746 		}
1747 
1748 		kvfree(btf->types);
1749 		btf->types = new_types;
1750 		btf->types_size = new_size;
1751 	}
1752 
1753 	btf->types[btf->nr_types++] = t;
1754 
1755 	return 0;
1756 }
1757 
btf_alloc_id(struct btf * btf)1758 static int btf_alloc_id(struct btf *btf)
1759 {
1760 	int id;
1761 
1762 	idr_preload(GFP_KERNEL);
1763 	spin_lock_bh(&btf_idr_lock);
1764 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1765 	if (id > 0)
1766 		btf->id = id;
1767 	spin_unlock_bh(&btf_idr_lock);
1768 	idr_preload_end();
1769 
1770 	if (WARN_ON_ONCE(!id))
1771 		return -ENOSPC;
1772 
1773 	return id > 0 ? 0 : id;
1774 }
1775 
btf_free_id(struct btf * btf)1776 static void btf_free_id(struct btf *btf)
1777 {
1778 	unsigned long flags;
1779 
1780 	/*
1781 	 * In map-in-map, calling map_delete_elem() on outer
1782 	 * map will call bpf_map_put on the inner map.
1783 	 * It will then eventually call btf_free_id()
1784 	 * on the inner map.  Some of the map_delete_elem()
1785 	 * implementation may have irq disabled, so
1786 	 * we need to use the _irqsave() version instead
1787 	 * of the _bh() version.
1788 	 */
1789 	spin_lock_irqsave(&btf_idr_lock, flags);
1790 	if (btf->id) {
1791 		idr_remove(&btf_idr, btf->id);
1792 		/*
1793 		 * Clear the id here to make this function idempotent, since it will get
1794 		 * called a couple of times for module BTFs: on module unload, and then
1795 		 * the final btf_put(). btf_alloc_id() starts IDs with 1, so we can use
1796 		 * 0 as sentinel value.
1797 		 */
1798 		WRITE_ONCE(btf->id, 0);
1799 	}
1800 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1801 }
1802 
btf_free_kfunc_set_tab(struct btf * btf)1803 static void btf_free_kfunc_set_tab(struct btf *btf)
1804 {
1805 	struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1806 	int hook;
1807 
1808 	if (!tab)
1809 		return;
1810 	for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1811 		kfree(tab->sets[hook]);
1812 	kfree(tab);
1813 	btf->kfunc_set_tab = NULL;
1814 }
1815 
btf_free_dtor_kfunc_tab(struct btf * btf)1816 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1817 {
1818 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1819 
1820 	if (!tab)
1821 		return;
1822 	kfree(tab);
1823 	btf->dtor_kfunc_tab = NULL;
1824 }
1825 
btf_struct_metas_free(struct btf_struct_metas * tab)1826 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1827 {
1828 	int i;
1829 
1830 	if (!tab)
1831 		return;
1832 	for (i = 0; i < tab->cnt; i++)
1833 		btf_record_free(tab->types[i].record);
1834 	kfree(tab);
1835 }
1836 
btf_free_struct_meta_tab(struct btf * btf)1837 static void btf_free_struct_meta_tab(struct btf *btf)
1838 {
1839 	struct btf_struct_metas *tab = btf->struct_meta_tab;
1840 
1841 	btf_struct_metas_free(tab);
1842 	btf->struct_meta_tab = NULL;
1843 }
1844 
btf_free_struct_ops_tab(struct btf * btf)1845 static void btf_free_struct_ops_tab(struct btf *btf)
1846 {
1847 	struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1848 	u32 i;
1849 
1850 	if (!tab)
1851 		return;
1852 
1853 	for (i = 0; i < tab->cnt; i++)
1854 		bpf_struct_ops_desc_release(&tab->ops[i]);
1855 
1856 	kfree(tab);
1857 	btf->struct_ops_tab = NULL;
1858 }
1859 
btf_free(struct btf * btf)1860 static void btf_free(struct btf *btf)
1861 {
1862 	btf_free_struct_meta_tab(btf);
1863 	btf_free_dtor_kfunc_tab(btf);
1864 	btf_free_kfunc_set_tab(btf);
1865 	btf_free_struct_ops_tab(btf);
1866 	kvfree(btf->types);
1867 	kvfree(btf->resolved_sizes);
1868 	kvfree(btf->resolved_ids);
1869 	/* vmlinux does not allocate btf->data, it simply points it at
1870 	 * __start_BTF.
1871 	 */
1872 	if (!btf_is_vmlinux(btf))
1873 		kvfree(btf->data);
1874 	kvfree(btf->base_id_map);
1875 	kfree(btf);
1876 }
1877 
btf_free_rcu(struct rcu_head * rcu)1878 static void btf_free_rcu(struct rcu_head *rcu)
1879 {
1880 	struct btf *btf = container_of(rcu, struct btf, rcu);
1881 
1882 	btf_free(btf);
1883 }
1884 
btf_get_name(const struct btf * btf)1885 const char *btf_get_name(const struct btf *btf)
1886 {
1887 	return btf->name;
1888 }
1889 
btf_get(struct btf * btf)1890 void btf_get(struct btf *btf)
1891 {
1892 	refcount_inc(&btf->refcnt);
1893 }
1894 
btf_put(struct btf * btf)1895 void btf_put(struct btf *btf)
1896 {
1897 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1898 		btf_free_id(btf);
1899 		call_rcu(&btf->rcu, btf_free_rcu);
1900 	}
1901 }
1902 
btf_base_btf(const struct btf * btf)1903 struct btf *btf_base_btf(const struct btf *btf)
1904 {
1905 	return btf->base_btf;
1906 }
1907 
btf_header(const struct btf * btf)1908 const struct btf_header *btf_header(const struct btf *btf)
1909 {
1910 	return &btf->hdr;
1911 }
1912 
btf_set_base_btf(struct btf * btf,const struct btf * base_btf)1913 void btf_set_base_btf(struct btf *btf, const struct btf *base_btf)
1914 {
1915 	btf->base_btf = (struct btf *)base_btf;
1916 	btf->start_id = btf_nr_types(base_btf);
1917 	btf->start_str_off = base_btf->hdr.str_len;
1918 }
1919 
env_resolve_init(struct btf_verifier_env * env)1920 static int env_resolve_init(struct btf_verifier_env *env)
1921 {
1922 	struct btf *btf = env->btf;
1923 	u32 nr_types = btf->nr_types;
1924 	u32 *resolved_sizes = NULL;
1925 	u32 *resolved_ids = NULL;
1926 	u8 *visit_states = NULL;
1927 
1928 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1929 				  GFP_KERNEL | __GFP_NOWARN);
1930 	if (!resolved_sizes)
1931 		goto nomem;
1932 
1933 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1934 				GFP_KERNEL | __GFP_NOWARN);
1935 	if (!resolved_ids)
1936 		goto nomem;
1937 
1938 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1939 				GFP_KERNEL | __GFP_NOWARN);
1940 	if (!visit_states)
1941 		goto nomem;
1942 
1943 	btf->resolved_sizes = resolved_sizes;
1944 	btf->resolved_ids = resolved_ids;
1945 	env->visit_states = visit_states;
1946 
1947 	return 0;
1948 
1949 nomem:
1950 	kvfree(resolved_sizes);
1951 	kvfree(resolved_ids);
1952 	kvfree(visit_states);
1953 	return -ENOMEM;
1954 }
1955 
btf_verifier_env_free(struct btf_verifier_env * env)1956 static void btf_verifier_env_free(struct btf_verifier_env *env)
1957 {
1958 	kvfree(env->visit_states);
1959 	kfree(env);
1960 }
1961 
env_type_is_resolve_sink(const struct btf_verifier_env * env,const struct btf_type * next_type)1962 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1963 				     const struct btf_type *next_type)
1964 {
1965 	switch (env->resolve_mode) {
1966 	case RESOLVE_TBD:
1967 		/* int, enum or void is a sink */
1968 		return !btf_type_needs_resolve(next_type);
1969 	case RESOLVE_PTR:
1970 		/* int, enum, void, struct, array, func or func_proto is a sink
1971 		 * for ptr
1972 		 */
1973 		return !btf_type_is_modifier(next_type) &&
1974 			!btf_type_is_ptr(next_type);
1975 	case RESOLVE_STRUCT_OR_ARRAY:
1976 		/* int, enum, void, ptr, func or func_proto is a sink
1977 		 * for struct and array
1978 		 */
1979 		return !btf_type_is_modifier(next_type) &&
1980 			!btf_type_is_array(next_type) &&
1981 			!btf_type_is_struct(next_type);
1982 	default:
1983 		BUG();
1984 	}
1985 }
1986 
env_type_is_resolved(const struct btf_verifier_env * env,u32 type_id)1987 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1988 				 u32 type_id)
1989 {
1990 	/* base BTF types should be resolved by now */
1991 	if (type_id < env->btf->start_id)
1992 		return true;
1993 
1994 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1995 }
1996 
env_stack_push(struct btf_verifier_env * env,const struct btf_type * t,u32 type_id)1997 static int env_stack_push(struct btf_verifier_env *env,
1998 			  const struct btf_type *t, u32 type_id)
1999 {
2000 	const struct btf *btf = env->btf;
2001 	struct resolve_vertex *v;
2002 
2003 	if (env->top_stack == MAX_RESOLVE_DEPTH)
2004 		return -E2BIG;
2005 
2006 	if (type_id < btf->start_id
2007 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
2008 		return -EEXIST;
2009 
2010 	env->visit_states[type_id - btf->start_id] = VISITED;
2011 
2012 	v = &env->stack[env->top_stack++];
2013 	v->t = t;
2014 	v->type_id = type_id;
2015 	v->next_member = 0;
2016 
2017 	if (env->resolve_mode == RESOLVE_TBD) {
2018 		if (btf_type_is_ptr(t))
2019 			env->resolve_mode = RESOLVE_PTR;
2020 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
2021 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
2022 	}
2023 
2024 	return 0;
2025 }
2026 
env_stack_set_next_member(struct btf_verifier_env * env,u16 next_member)2027 static void env_stack_set_next_member(struct btf_verifier_env *env,
2028 				      u16 next_member)
2029 {
2030 	env->stack[env->top_stack - 1].next_member = next_member;
2031 }
2032 
env_stack_pop_resolved(struct btf_verifier_env * env,u32 resolved_type_id,u32 resolved_size)2033 static void env_stack_pop_resolved(struct btf_verifier_env *env,
2034 				   u32 resolved_type_id,
2035 				   u32 resolved_size)
2036 {
2037 	u32 type_id = env->stack[--(env->top_stack)].type_id;
2038 	struct btf *btf = env->btf;
2039 
2040 	type_id -= btf->start_id; /* adjust to local type id */
2041 	btf->resolved_sizes[type_id] = resolved_size;
2042 	btf->resolved_ids[type_id] = resolved_type_id;
2043 	env->visit_states[type_id] = RESOLVED;
2044 }
2045 
env_stack_peak(struct btf_verifier_env * env)2046 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
2047 {
2048 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
2049 }
2050 
2051 /* Resolve the size of a passed-in "type"
2052  *
2053  * type: is an array (e.g. u32 array[x][y])
2054  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
2055  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
2056  *             corresponds to the return type.
2057  * *elem_type: u32
2058  * *elem_id: id of u32
2059  * *total_nelems: (x * y).  Hence, individual elem size is
2060  *                (*type_size / *total_nelems)
2061  * *type_id: id of type if it's changed within the function, 0 if not
2062  *
2063  * type: is not an array (e.g. const struct X)
2064  * return type: type "struct X"
2065  * *type_size: sizeof(struct X)
2066  * *elem_type: same as return type ("struct X")
2067  * *elem_id: 0
2068  * *total_nelems: 1
2069  * *type_id: id of type if it's changed within the function, 0 if not
2070  */
2071 static const struct btf_type *
__btf_resolve_size(const struct btf * btf,const struct btf_type * type,u32 * type_size,const struct btf_type ** elem_type,u32 * elem_id,u32 * total_nelems,u32 * type_id)2072 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2073 		   u32 *type_size, const struct btf_type **elem_type,
2074 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
2075 {
2076 	const struct btf_type *array_type = NULL;
2077 	const struct btf_array *array = NULL;
2078 	u32 i, size, nelems = 1, id = 0;
2079 
2080 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
2081 		switch (BTF_INFO_KIND(type->info)) {
2082 		/* type->size can be used */
2083 		case BTF_KIND_INT:
2084 		case BTF_KIND_STRUCT:
2085 		case BTF_KIND_UNION:
2086 		case BTF_KIND_ENUM:
2087 		case BTF_KIND_FLOAT:
2088 		case BTF_KIND_ENUM64:
2089 			size = type->size;
2090 			goto resolved;
2091 
2092 		case BTF_KIND_PTR:
2093 			size = sizeof(void *);
2094 			goto resolved;
2095 
2096 		/* Modifiers */
2097 		case BTF_KIND_TYPEDEF:
2098 		case BTF_KIND_VOLATILE:
2099 		case BTF_KIND_CONST:
2100 		case BTF_KIND_RESTRICT:
2101 		case BTF_KIND_TYPE_TAG:
2102 			id = type->type;
2103 			type = btf_type_by_id(btf, type->type);
2104 			break;
2105 
2106 		case BTF_KIND_ARRAY:
2107 			if (!array_type)
2108 				array_type = type;
2109 			array = btf_type_array(type);
2110 			if (nelems && array->nelems > U32_MAX / nelems)
2111 				return ERR_PTR(-EINVAL);
2112 			nelems *= array->nelems;
2113 			type = btf_type_by_id(btf, array->type);
2114 			break;
2115 
2116 		/* type without size */
2117 		default:
2118 			return ERR_PTR(-EINVAL);
2119 		}
2120 	}
2121 
2122 	return ERR_PTR(-EINVAL);
2123 
2124 resolved:
2125 	if (nelems && size > U32_MAX / nelems)
2126 		return ERR_PTR(-EINVAL);
2127 
2128 	*type_size = nelems * size;
2129 	if (total_nelems)
2130 		*total_nelems = nelems;
2131 	if (elem_type)
2132 		*elem_type = type;
2133 	if (elem_id)
2134 		*elem_id = array ? array->type : 0;
2135 	if (type_id && id)
2136 		*type_id = id;
2137 
2138 	return array_type ? : type;
2139 }
2140 
2141 const struct btf_type *
btf_resolve_size(const struct btf * btf,const struct btf_type * type,u32 * type_size)2142 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2143 		 u32 *type_size)
2144 {
2145 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
2146 }
2147 
btf_resolved_type_id(const struct btf * btf,u32 type_id)2148 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
2149 {
2150 	while (type_id < btf->start_id)
2151 		btf = btf->base_btf;
2152 
2153 	return btf->resolved_ids[type_id - btf->start_id];
2154 }
2155 
2156 /* The input param "type_id" must point to a needs_resolve type */
btf_type_id_resolve(const struct btf * btf,u32 * type_id)2157 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
2158 						  u32 *type_id)
2159 {
2160 	*type_id = btf_resolved_type_id(btf, *type_id);
2161 	return btf_type_by_id(btf, *type_id);
2162 }
2163 
btf_resolved_type_size(const struct btf * btf,u32 type_id)2164 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2165 {
2166 	while (type_id < btf->start_id)
2167 		btf = btf->base_btf;
2168 
2169 	return btf->resolved_sizes[type_id - btf->start_id];
2170 }
2171 
btf_type_id_size(const struct btf * btf,u32 * type_id,u32 * ret_size)2172 const struct btf_type *btf_type_id_size(const struct btf *btf,
2173 					u32 *type_id, u32 *ret_size)
2174 {
2175 	const struct btf_type *size_type;
2176 	u32 size_type_id = *type_id;
2177 	u32 size = 0;
2178 
2179 	size_type = btf_type_by_id(btf, size_type_id);
2180 	if (btf_type_nosize_or_null(size_type))
2181 		return NULL;
2182 
2183 	if (btf_type_has_size(size_type)) {
2184 		size = size_type->size;
2185 	} else if (btf_type_is_array(size_type)) {
2186 		size = btf_resolved_type_size(btf, size_type_id);
2187 	} else if (btf_type_is_ptr(size_type)) {
2188 		size = sizeof(void *);
2189 	} else {
2190 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2191 				 !btf_type_is_var(size_type)))
2192 			return NULL;
2193 
2194 		size_type_id = btf_resolved_type_id(btf, size_type_id);
2195 		size_type = btf_type_by_id(btf, size_type_id);
2196 		if (btf_type_nosize_or_null(size_type))
2197 			return NULL;
2198 		else if (btf_type_has_size(size_type))
2199 			size = size_type->size;
2200 		else if (btf_type_is_array(size_type))
2201 			size = btf_resolved_type_size(btf, size_type_id);
2202 		else if (btf_type_is_ptr(size_type))
2203 			size = sizeof(void *);
2204 		else
2205 			return NULL;
2206 	}
2207 
2208 	*type_id = size_type_id;
2209 	if (ret_size)
2210 		*ret_size = size;
2211 
2212 	return size_type;
2213 }
2214 
btf_df_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2215 static int btf_df_check_member(struct btf_verifier_env *env,
2216 			       const struct btf_type *struct_type,
2217 			       const struct btf_member *member,
2218 			       const struct btf_type *member_type)
2219 {
2220 	btf_verifier_log_basic(env, struct_type,
2221 			       "Unsupported check_member");
2222 	return -EINVAL;
2223 }
2224 
btf_df_check_kflag_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2225 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2226 				     const struct btf_type *struct_type,
2227 				     const struct btf_member *member,
2228 				     const struct btf_type *member_type)
2229 {
2230 	btf_verifier_log_basic(env, struct_type,
2231 			       "Unsupported check_kflag_member");
2232 	return -EINVAL;
2233 }
2234 
2235 /* Used for ptr, array struct/union and float type members.
2236  * int, enum and modifier types have their specific callback functions.
2237  */
btf_generic_check_kflag_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2238 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2239 					  const struct btf_type *struct_type,
2240 					  const struct btf_member *member,
2241 					  const struct btf_type *member_type)
2242 {
2243 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2244 		btf_verifier_log_member(env, struct_type, member,
2245 					"Invalid member bitfield_size");
2246 		return -EINVAL;
2247 	}
2248 
2249 	/* bitfield size is 0, so member->offset represents bit offset only.
2250 	 * It is safe to call non kflag check_member variants.
2251 	 */
2252 	return btf_type_ops(member_type)->check_member(env, struct_type,
2253 						       member,
2254 						       member_type);
2255 }
2256 
btf_df_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)2257 static int btf_df_resolve(struct btf_verifier_env *env,
2258 			  const struct resolve_vertex *v)
2259 {
2260 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2261 	return -EINVAL;
2262 }
2263 
btf_df_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offsets,struct btf_show * show)2264 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2265 			u32 type_id, void *data, u8 bits_offsets,
2266 			struct btf_show *show)
2267 {
2268 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2269 }
2270 
btf_int_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2271 static int btf_int_check_member(struct btf_verifier_env *env,
2272 				const struct btf_type *struct_type,
2273 				const struct btf_member *member,
2274 				const struct btf_type *member_type)
2275 {
2276 	u32 int_data = btf_type_int(member_type);
2277 	u32 struct_bits_off = member->offset;
2278 	u32 struct_size = struct_type->size;
2279 	u32 nr_copy_bits;
2280 	u32 bytes_offset;
2281 
2282 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2283 		btf_verifier_log_member(env, struct_type, member,
2284 					"bits_offset exceeds U32_MAX");
2285 		return -EINVAL;
2286 	}
2287 
2288 	struct_bits_off += BTF_INT_OFFSET(int_data);
2289 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2290 	nr_copy_bits = BTF_INT_BITS(int_data) +
2291 		BITS_PER_BYTE_MASKED(struct_bits_off);
2292 
2293 	if (nr_copy_bits > BITS_PER_U128) {
2294 		btf_verifier_log_member(env, struct_type, member,
2295 					"nr_copy_bits exceeds 128");
2296 		return -EINVAL;
2297 	}
2298 
2299 	if (struct_size < bytes_offset ||
2300 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2301 		btf_verifier_log_member(env, struct_type, member,
2302 					"Member exceeds struct_size");
2303 		return -EINVAL;
2304 	}
2305 
2306 	return 0;
2307 }
2308 
btf_int_check_kflag_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2309 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2310 				      const struct btf_type *struct_type,
2311 				      const struct btf_member *member,
2312 				      const struct btf_type *member_type)
2313 {
2314 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2315 	u32 int_data = btf_type_int(member_type);
2316 	u32 struct_size = struct_type->size;
2317 	u32 nr_copy_bits;
2318 
2319 	/* a regular int type is required for the kflag int member */
2320 	if (!btf_type_int_is_regular(member_type)) {
2321 		btf_verifier_log_member(env, struct_type, member,
2322 					"Invalid member base type");
2323 		return -EINVAL;
2324 	}
2325 
2326 	/* check sanity of bitfield size */
2327 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2328 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2329 	nr_int_data_bits = BTF_INT_BITS(int_data);
2330 	if (!nr_bits) {
2331 		/* Not a bitfield member, member offset must be at byte
2332 		 * boundary.
2333 		 */
2334 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2335 			btf_verifier_log_member(env, struct_type, member,
2336 						"Invalid member offset");
2337 			return -EINVAL;
2338 		}
2339 
2340 		nr_bits = nr_int_data_bits;
2341 	} else if (nr_bits > nr_int_data_bits) {
2342 		btf_verifier_log_member(env, struct_type, member,
2343 					"Invalid member bitfield_size");
2344 		return -EINVAL;
2345 	}
2346 
2347 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2348 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2349 	if (nr_copy_bits > BITS_PER_U128) {
2350 		btf_verifier_log_member(env, struct_type, member,
2351 					"nr_copy_bits exceeds 128");
2352 		return -EINVAL;
2353 	}
2354 
2355 	if (struct_size < bytes_offset ||
2356 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2357 		btf_verifier_log_member(env, struct_type, member,
2358 					"Member exceeds struct_size");
2359 		return -EINVAL;
2360 	}
2361 
2362 	return 0;
2363 }
2364 
btf_int_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)2365 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2366 			      const struct btf_type *t,
2367 			      u32 meta_left)
2368 {
2369 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2370 	u16 encoding;
2371 
2372 	if (meta_left < meta_needed) {
2373 		btf_verifier_log_basic(env, t,
2374 				       "meta_left:%u meta_needed:%u",
2375 				       meta_left, meta_needed);
2376 		return -EINVAL;
2377 	}
2378 
2379 	if (btf_type_vlen(t)) {
2380 		btf_verifier_log_type(env, t, "vlen != 0");
2381 		return -EINVAL;
2382 	}
2383 
2384 	if (btf_type_kflag(t)) {
2385 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2386 		return -EINVAL;
2387 	}
2388 
2389 	int_data = btf_type_int(t);
2390 	if (int_data & ~BTF_INT_MASK) {
2391 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2392 				       int_data);
2393 		return -EINVAL;
2394 	}
2395 
2396 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2397 
2398 	if (nr_bits > BITS_PER_U128) {
2399 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2400 				      BITS_PER_U128);
2401 		return -EINVAL;
2402 	}
2403 
2404 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2405 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2406 		return -EINVAL;
2407 	}
2408 
2409 	/*
2410 	 * Only one of the encoding bits is allowed and it
2411 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2412 	 * Multiple bits can be allowed later if it is found
2413 	 * to be insufficient.
2414 	 */
2415 	encoding = BTF_INT_ENCODING(int_data);
2416 	if (encoding &&
2417 	    encoding != BTF_INT_SIGNED &&
2418 	    encoding != BTF_INT_CHAR &&
2419 	    encoding != BTF_INT_BOOL) {
2420 		btf_verifier_log_type(env, t, "Unsupported encoding");
2421 		return -ENOTSUPP;
2422 	}
2423 
2424 	btf_verifier_log_type(env, t, NULL);
2425 
2426 	return meta_needed;
2427 }
2428 
btf_int_log(struct btf_verifier_env * env,const struct btf_type * t)2429 static void btf_int_log(struct btf_verifier_env *env,
2430 			const struct btf_type *t)
2431 {
2432 	int int_data = btf_type_int(t);
2433 
2434 	btf_verifier_log(env,
2435 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2436 			 t->size, BTF_INT_OFFSET(int_data),
2437 			 BTF_INT_BITS(int_data),
2438 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2439 }
2440 
btf_int128_print(struct btf_show * show,void * data)2441 static void btf_int128_print(struct btf_show *show, void *data)
2442 {
2443 	/* data points to a __int128 number.
2444 	 * Suppose
2445 	 *     int128_num = *(__int128 *)data;
2446 	 * The below formulas shows what upper_num and lower_num represents:
2447 	 *     upper_num = int128_num >> 64;
2448 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2449 	 */
2450 	u64 upper_num, lower_num;
2451 
2452 #ifdef __BIG_ENDIAN_BITFIELD
2453 	upper_num = *(u64 *)data;
2454 	lower_num = *(u64 *)(data + 8);
2455 #else
2456 	upper_num = *(u64 *)(data + 8);
2457 	lower_num = *(u64 *)data;
2458 #endif
2459 	if (upper_num == 0)
2460 		btf_show_type_value(show, "0x%llx", lower_num);
2461 	else
2462 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2463 				     lower_num);
2464 }
2465 
btf_int128_shift(u64 * print_num,u16 left_shift_bits,u16 right_shift_bits)2466 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2467 			     u16 right_shift_bits)
2468 {
2469 	u64 upper_num, lower_num;
2470 
2471 #ifdef __BIG_ENDIAN_BITFIELD
2472 	upper_num = print_num[0];
2473 	lower_num = print_num[1];
2474 #else
2475 	upper_num = print_num[1];
2476 	lower_num = print_num[0];
2477 #endif
2478 
2479 	/* shake out un-needed bits by shift/or operations */
2480 	if (left_shift_bits >= 64) {
2481 		upper_num = lower_num << (left_shift_bits - 64);
2482 		lower_num = 0;
2483 	} else {
2484 		upper_num = (upper_num << left_shift_bits) |
2485 			    (lower_num >> (64 - left_shift_bits));
2486 		lower_num = lower_num << left_shift_bits;
2487 	}
2488 
2489 	if (right_shift_bits >= 64) {
2490 		lower_num = upper_num >> (right_shift_bits - 64);
2491 		upper_num = 0;
2492 	} else {
2493 		lower_num = (lower_num >> right_shift_bits) |
2494 			    (upper_num << (64 - right_shift_bits));
2495 		upper_num = upper_num >> right_shift_bits;
2496 	}
2497 
2498 #ifdef __BIG_ENDIAN_BITFIELD
2499 	print_num[0] = upper_num;
2500 	print_num[1] = lower_num;
2501 #else
2502 	print_num[0] = lower_num;
2503 	print_num[1] = upper_num;
2504 #endif
2505 }
2506 
btf_bitfield_show(void * data,u8 bits_offset,u8 nr_bits,struct btf_show * show)2507 static void btf_bitfield_show(void *data, u8 bits_offset,
2508 			      u8 nr_bits, struct btf_show *show)
2509 {
2510 	u16 left_shift_bits, right_shift_bits;
2511 	u8 nr_copy_bytes;
2512 	u8 nr_copy_bits;
2513 	u64 print_num[2] = {};
2514 
2515 	nr_copy_bits = nr_bits + bits_offset;
2516 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2517 
2518 	memcpy(print_num, data, nr_copy_bytes);
2519 
2520 #ifdef __BIG_ENDIAN_BITFIELD
2521 	left_shift_bits = bits_offset;
2522 #else
2523 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2524 #endif
2525 	right_shift_bits = BITS_PER_U128 - nr_bits;
2526 
2527 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2528 	btf_int128_print(show, print_num);
2529 }
2530 
2531 
btf_int_bits_show(const struct btf * btf,const struct btf_type * t,void * data,u8 bits_offset,struct btf_show * show)2532 static void btf_int_bits_show(const struct btf *btf,
2533 			      const struct btf_type *t,
2534 			      void *data, u8 bits_offset,
2535 			      struct btf_show *show)
2536 {
2537 	u32 int_data = btf_type_int(t);
2538 	u8 nr_bits = BTF_INT_BITS(int_data);
2539 	u8 total_bits_offset;
2540 
2541 	/*
2542 	 * bits_offset is at most 7.
2543 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2544 	 */
2545 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2546 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2547 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2548 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2549 }
2550 
btf_int_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)2551 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2552 			 u32 type_id, void *data, u8 bits_offset,
2553 			 struct btf_show *show)
2554 {
2555 	u32 int_data = btf_type_int(t);
2556 	u8 encoding = BTF_INT_ENCODING(int_data);
2557 	bool sign = encoding & BTF_INT_SIGNED;
2558 	u8 nr_bits = BTF_INT_BITS(int_data);
2559 	void *safe_data;
2560 
2561 	safe_data = btf_show_start_type(show, t, type_id, data);
2562 	if (!safe_data)
2563 		return;
2564 
2565 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2566 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2567 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2568 		goto out;
2569 	}
2570 
2571 	switch (nr_bits) {
2572 	case 128:
2573 		btf_int128_print(show, safe_data);
2574 		break;
2575 	case 64:
2576 		if (sign)
2577 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2578 		else
2579 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2580 		break;
2581 	case 32:
2582 		if (sign)
2583 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2584 		else
2585 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2586 		break;
2587 	case 16:
2588 		if (sign)
2589 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2590 		else
2591 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2592 		break;
2593 	case 8:
2594 		if (show->state.array_encoding == BTF_INT_CHAR) {
2595 			/* check for null terminator */
2596 			if (show->state.array_terminated)
2597 				break;
2598 			if (*(char *)data == '\0') {
2599 				show->state.array_terminated = 1;
2600 				break;
2601 			}
2602 			if (isprint(*(char *)data)) {
2603 				btf_show_type_value(show, "'%c'",
2604 						    *(char *)safe_data);
2605 				break;
2606 			}
2607 		}
2608 		if (sign)
2609 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2610 		else
2611 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2612 		break;
2613 	default:
2614 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2615 		break;
2616 	}
2617 out:
2618 	btf_show_end_type(show);
2619 }
2620 
2621 static const struct btf_kind_operations int_ops = {
2622 	.check_meta = btf_int_check_meta,
2623 	.resolve = btf_df_resolve,
2624 	.check_member = btf_int_check_member,
2625 	.check_kflag_member = btf_int_check_kflag_member,
2626 	.log_details = btf_int_log,
2627 	.show = btf_int_show,
2628 };
2629 
btf_modifier_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2630 static int btf_modifier_check_member(struct btf_verifier_env *env,
2631 				     const struct btf_type *struct_type,
2632 				     const struct btf_member *member,
2633 				     const struct btf_type *member_type)
2634 {
2635 	const struct btf_type *resolved_type;
2636 	u32 resolved_type_id = member->type;
2637 	struct btf_member resolved_member;
2638 	struct btf *btf = env->btf;
2639 
2640 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2641 	if (!resolved_type) {
2642 		btf_verifier_log_member(env, struct_type, member,
2643 					"Invalid member");
2644 		return -EINVAL;
2645 	}
2646 
2647 	resolved_member = *member;
2648 	resolved_member.type = resolved_type_id;
2649 
2650 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2651 							 &resolved_member,
2652 							 resolved_type);
2653 }
2654 
btf_modifier_check_kflag_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2655 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2656 					   const struct btf_type *struct_type,
2657 					   const struct btf_member *member,
2658 					   const struct btf_type *member_type)
2659 {
2660 	const struct btf_type *resolved_type;
2661 	u32 resolved_type_id = member->type;
2662 	struct btf_member resolved_member;
2663 	struct btf *btf = env->btf;
2664 
2665 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2666 	if (!resolved_type) {
2667 		btf_verifier_log_member(env, struct_type, member,
2668 					"Invalid member");
2669 		return -EINVAL;
2670 	}
2671 
2672 	resolved_member = *member;
2673 	resolved_member.type = resolved_type_id;
2674 
2675 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2676 							       &resolved_member,
2677 							       resolved_type);
2678 }
2679 
btf_ptr_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)2680 static int btf_ptr_check_member(struct btf_verifier_env *env,
2681 				const struct btf_type *struct_type,
2682 				const struct btf_member *member,
2683 				const struct btf_type *member_type)
2684 {
2685 	u32 struct_size, struct_bits_off, bytes_offset;
2686 
2687 	struct_size = struct_type->size;
2688 	struct_bits_off = member->offset;
2689 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2690 
2691 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2692 		btf_verifier_log_member(env, struct_type, member,
2693 					"Member is not byte aligned");
2694 		return -EINVAL;
2695 	}
2696 
2697 	if (struct_size - bytes_offset < sizeof(void *)) {
2698 		btf_verifier_log_member(env, struct_type, member,
2699 					"Member exceeds struct_size");
2700 		return -EINVAL;
2701 	}
2702 
2703 	return 0;
2704 }
2705 
btf_ref_type_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)2706 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2707 				   const struct btf_type *t,
2708 				   u32 meta_left)
2709 {
2710 	const char *value;
2711 
2712 	if (btf_type_vlen(t)) {
2713 		btf_verifier_log_type(env, t, "vlen != 0");
2714 		return -EINVAL;
2715 	}
2716 
2717 	if (btf_type_kflag(t) && !btf_type_is_type_tag(t)) {
2718 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2719 		return -EINVAL;
2720 	}
2721 
2722 	if (!BTF_TYPE_ID_VALID(t->type)) {
2723 		btf_verifier_log_type(env, t, "Invalid type_id");
2724 		return -EINVAL;
2725 	}
2726 
2727 	/* typedef/type_tag type must have a valid name, and other ref types,
2728 	 * volatile, const, restrict, should have a null name.
2729 	 */
2730 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2731 		if (!t->name_off ||
2732 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2733 			btf_verifier_log_type(env, t, "Invalid name");
2734 			return -EINVAL;
2735 		}
2736 	} else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2737 		value = btf_name_by_offset(env->btf, t->name_off);
2738 		if (!value || !value[0]) {
2739 			btf_verifier_log_type(env, t, "Invalid name");
2740 			return -EINVAL;
2741 		}
2742 	} else {
2743 		if (t->name_off) {
2744 			btf_verifier_log_type(env, t, "Invalid name");
2745 			return -EINVAL;
2746 		}
2747 	}
2748 
2749 	btf_verifier_log_type(env, t, NULL);
2750 
2751 	return 0;
2752 }
2753 
btf_modifier_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)2754 static int btf_modifier_resolve(struct btf_verifier_env *env,
2755 				const struct resolve_vertex *v)
2756 {
2757 	const struct btf_type *t = v->t;
2758 	const struct btf_type *next_type;
2759 	u32 next_type_id = t->type;
2760 	struct btf *btf = env->btf;
2761 
2762 	next_type = btf_type_by_id(btf, next_type_id);
2763 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2764 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2765 		return -EINVAL;
2766 	}
2767 
2768 	if (!env_type_is_resolve_sink(env, next_type) &&
2769 	    !env_type_is_resolved(env, next_type_id))
2770 		return env_stack_push(env, next_type, next_type_id);
2771 
2772 	/* Figure out the resolved next_type_id with size.
2773 	 * They will be stored in the current modifier's
2774 	 * resolved_ids and resolved_sizes such that it can
2775 	 * save us a few type-following when we use it later (e.g. in
2776 	 * pretty print).
2777 	 */
2778 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2779 		if (env_type_is_resolved(env, next_type_id))
2780 			next_type = btf_type_id_resolve(btf, &next_type_id);
2781 
2782 		/* "typedef void new_void", "const void"...etc */
2783 		if (!btf_type_is_void(next_type) &&
2784 		    !btf_type_is_fwd(next_type) &&
2785 		    !btf_type_is_func_proto(next_type)) {
2786 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2787 			return -EINVAL;
2788 		}
2789 	}
2790 
2791 	env_stack_pop_resolved(env, next_type_id, 0);
2792 
2793 	return 0;
2794 }
2795 
btf_var_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)2796 static int btf_var_resolve(struct btf_verifier_env *env,
2797 			   const struct resolve_vertex *v)
2798 {
2799 	const struct btf_type *next_type;
2800 	const struct btf_type *t = v->t;
2801 	u32 next_type_id = t->type;
2802 	struct btf *btf = env->btf;
2803 
2804 	next_type = btf_type_by_id(btf, next_type_id);
2805 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2806 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2807 		return -EINVAL;
2808 	}
2809 
2810 	if (!env_type_is_resolve_sink(env, next_type) &&
2811 	    !env_type_is_resolved(env, next_type_id))
2812 		return env_stack_push(env, next_type, next_type_id);
2813 
2814 	if (btf_type_is_modifier(next_type)) {
2815 		const struct btf_type *resolved_type;
2816 		u32 resolved_type_id;
2817 
2818 		resolved_type_id = next_type_id;
2819 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2820 
2821 		if (btf_type_is_ptr(resolved_type) &&
2822 		    !env_type_is_resolve_sink(env, resolved_type) &&
2823 		    !env_type_is_resolved(env, resolved_type_id))
2824 			return env_stack_push(env, resolved_type,
2825 					      resolved_type_id);
2826 	}
2827 
2828 	/* We must resolve to something concrete at this point, no
2829 	 * forward types or similar that would resolve to size of
2830 	 * zero is allowed.
2831 	 */
2832 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2833 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2834 		return -EINVAL;
2835 	}
2836 
2837 	env_stack_pop_resolved(env, next_type_id, 0);
2838 
2839 	return 0;
2840 }
2841 
btf_ptr_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)2842 static int btf_ptr_resolve(struct btf_verifier_env *env,
2843 			   const struct resolve_vertex *v)
2844 {
2845 	const struct btf_type *next_type;
2846 	const struct btf_type *t = v->t;
2847 	u32 next_type_id = t->type;
2848 	struct btf *btf = env->btf;
2849 
2850 	next_type = btf_type_by_id(btf, next_type_id);
2851 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2852 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2853 		return -EINVAL;
2854 	}
2855 
2856 	if (!env_type_is_resolve_sink(env, next_type) &&
2857 	    !env_type_is_resolved(env, next_type_id))
2858 		return env_stack_push(env, next_type, next_type_id);
2859 
2860 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2861 	 * the modifier may have stopped resolving when it was resolved
2862 	 * to a ptr (last-resolved-ptr).
2863 	 *
2864 	 * We now need to continue from the last-resolved-ptr to
2865 	 * ensure the last-resolved-ptr will not referring back to
2866 	 * the current ptr (t).
2867 	 */
2868 	if (btf_type_is_modifier(next_type)) {
2869 		const struct btf_type *resolved_type;
2870 		u32 resolved_type_id;
2871 
2872 		resolved_type_id = next_type_id;
2873 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2874 
2875 		if (btf_type_is_ptr(resolved_type) &&
2876 		    !env_type_is_resolve_sink(env, resolved_type) &&
2877 		    !env_type_is_resolved(env, resolved_type_id))
2878 			return env_stack_push(env, resolved_type,
2879 					      resolved_type_id);
2880 	}
2881 
2882 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2883 		if (env_type_is_resolved(env, next_type_id))
2884 			next_type = btf_type_id_resolve(btf, &next_type_id);
2885 
2886 		if (!btf_type_is_void(next_type) &&
2887 		    !btf_type_is_fwd(next_type) &&
2888 		    !btf_type_is_func_proto(next_type)) {
2889 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2890 			return -EINVAL;
2891 		}
2892 	}
2893 
2894 	env_stack_pop_resolved(env, next_type_id, 0);
2895 
2896 	return 0;
2897 }
2898 
btf_modifier_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)2899 static void btf_modifier_show(const struct btf *btf,
2900 			      const struct btf_type *t,
2901 			      u32 type_id, void *data,
2902 			      u8 bits_offset, struct btf_show *show)
2903 {
2904 	if (btf->resolved_ids)
2905 		t = btf_type_id_resolve(btf, &type_id);
2906 	else
2907 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2908 
2909 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2910 }
2911 
btf_var_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)2912 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2913 			 u32 type_id, void *data, u8 bits_offset,
2914 			 struct btf_show *show)
2915 {
2916 	t = btf_type_id_resolve(btf, &type_id);
2917 
2918 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2919 }
2920 
btf_ptr_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)2921 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2922 			 u32 type_id, void *data, u8 bits_offset,
2923 			 struct btf_show *show)
2924 {
2925 	void *safe_data;
2926 
2927 	safe_data = btf_show_start_type(show, t, type_id, data);
2928 	if (!safe_data)
2929 		return;
2930 
2931 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2932 	if (show->flags & BTF_SHOW_PTR_RAW)
2933 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2934 	else
2935 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2936 	btf_show_end_type(show);
2937 }
2938 
btf_ref_type_log(struct btf_verifier_env * env,const struct btf_type * t)2939 static void btf_ref_type_log(struct btf_verifier_env *env,
2940 			     const struct btf_type *t)
2941 {
2942 	btf_verifier_log(env, "type_id=%u", t->type);
2943 }
2944 
2945 static const struct btf_kind_operations modifier_ops = {
2946 	.check_meta = btf_ref_type_check_meta,
2947 	.resolve = btf_modifier_resolve,
2948 	.check_member = btf_modifier_check_member,
2949 	.check_kflag_member = btf_modifier_check_kflag_member,
2950 	.log_details = btf_ref_type_log,
2951 	.show = btf_modifier_show,
2952 };
2953 
2954 static const struct btf_kind_operations ptr_ops = {
2955 	.check_meta = btf_ref_type_check_meta,
2956 	.resolve = btf_ptr_resolve,
2957 	.check_member = btf_ptr_check_member,
2958 	.check_kflag_member = btf_generic_check_kflag_member,
2959 	.log_details = btf_ref_type_log,
2960 	.show = btf_ptr_show,
2961 };
2962 
btf_fwd_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)2963 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2964 			      const struct btf_type *t,
2965 			      u32 meta_left)
2966 {
2967 	if (btf_type_vlen(t)) {
2968 		btf_verifier_log_type(env, t, "vlen != 0");
2969 		return -EINVAL;
2970 	}
2971 
2972 	if (t->type) {
2973 		btf_verifier_log_type(env, t, "type != 0");
2974 		return -EINVAL;
2975 	}
2976 
2977 	/* fwd type must have a valid name */
2978 	if (!t->name_off ||
2979 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2980 		btf_verifier_log_type(env, t, "Invalid name");
2981 		return -EINVAL;
2982 	}
2983 
2984 	btf_verifier_log_type(env, t, NULL);
2985 
2986 	return 0;
2987 }
2988 
btf_fwd_type_log(struct btf_verifier_env * env,const struct btf_type * t)2989 static void btf_fwd_type_log(struct btf_verifier_env *env,
2990 			     const struct btf_type *t)
2991 {
2992 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2993 }
2994 
2995 static const struct btf_kind_operations fwd_ops = {
2996 	.check_meta = btf_fwd_check_meta,
2997 	.resolve = btf_df_resolve,
2998 	.check_member = btf_df_check_member,
2999 	.check_kflag_member = btf_df_check_kflag_member,
3000 	.log_details = btf_fwd_type_log,
3001 	.show = btf_df_show,
3002 };
3003 
btf_array_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)3004 static int btf_array_check_member(struct btf_verifier_env *env,
3005 				  const struct btf_type *struct_type,
3006 				  const struct btf_member *member,
3007 				  const struct btf_type *member_type)
3008 {
3009 	u32 struct_bits_off = member->offset;
3010 	u32 struct_size, bytes_offset;
3011 	u32 array_type_id, array_size;
3012 	struct btf *btf = env->btf;
3013 
3014 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3015 		btf_verifier_log_member(env, struct_type, member,
3016 					"Member is not byte aligned");
3017 		return -EINVAL;
3018 	}
3019 
3020 	array_type_id = member->type;
3021 	btf_type_id_size(btf, &array_type_id, &array_size);
3022 	struct_size = struct_type->size;
3023 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3024 	if (struct_size - bytes_offset < array_size) {
3025 		btf_verifier_log_member(env, struct_type, member,
3026 					"Member exceeds struct_size");
3027 		return -EINVAL;
3028 	}
3029 
3030 	return 0;
3031 }
3032 
btf_array_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)3033 static s32 btf_array_check_meta(struct btf_verifier_env *env,
3034 				const struct btf_type *t,
3035 				u32 meta_left)
3036 {
3037 	const struct btf_array *array = btf_type_array(t);
3038 	u32 meta_needed = sizeof(*array);
3039 
3040 	if (meta_left < meta_needed) {
3041 		btf_verifier_log_basic(env, t,
3042 				       "meta_left:%u meta_needed:%u",
3043 				       meta_left, meta_needed);
3044 		return -EINVAL;
3045 	}
3046 
3047 	/* array type should not have a name */
3048 	if (t->name_off) {
3049 		btf_verifier_log_type(env, t, "Invalid name");
3050 		return -EINVAL;
3051 	}
3052 
3053 	if (btf_type_vlen(t)) {
3054 		btf_verifier_log_type(env, t, "vlen != 0");
3055 		return -EINVAL;
3056 	}
3057 
3058 	if (btf_type_kflag(t)) {
3059 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3060 		return -EINVAL;
3061 	}
3062 
3063 	if (t->size) {
3064 		btf_verifier_log_type(env, t, "size != 0");
3065 		return -EINVAL;
3066 	}
3067 
3068 	/* Array elem type and index type cannot be in type void,
3069 	 * so !array->type and !array->index_type are not allowed.
3070 	 */
3071 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
3072 		btf_verifier_log_type(env, t, "Invalid elem");
3073 		return -EINVAL;
3074 	}
3075 
3076 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
3077 		btf_verifier_log_type(env, t, "Invalid index");
3078 		return -EINVAL;
3079 	}
3080 
3081 	btf_verifier_log_type(env, t, NULL);
3082 
3083 	return meta_needed;
3084 }
3085 
btf_array_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)3086 static int btf_array_resolve(struct btf_verifier_env *env,
3087 			     const struct resolve_vertex *v)
3088 {
3089 	const struct btf_array *array = btf_type_array(v->t);
3090 	const struct btf_type *elem_type, *index_type;
3091 	u32 elem_type_id, index_type_id;
3092 	struct btf *btf = env->btf;
3093 	u32 elem_size;
3094 
3095 	/* Check array->index_type */
3096 	index_type_id = array->index_type;
3097 	index_type = btf_type_by_id(btf, index_type_id);
3098 	if (btf_type_nosize_or_null(index_type) ||
3099 	    btf_type_is_resolve_source_only(index_type)) {
3100 		btf_verifier_log_type(env, v->t, "Invalid index");
3101 		return -EINVAL;
3102 	}
3103 
3104 	if (!env_type_is_resolve_sink(env, index_type) &&
3105 	    !env_type_is_resolved(env, index_type_id))
3106 		return env_stack_push(env, index_type, index_type_id);
3107 
3108 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
3109 	if (!index_type || !btf_type_is_int(index_type) ||
3110 	    !btf_type_int_is_regular(index_type)) {
3111 		btf_verifier_log_type(env, v->t, "Invalid index");
3112 		return -EINVAL;
3113 	}
3114 
3115 	/* Check array->type */
3116 	elem_type_id = array->type;
3117 	elem_type = btf_type_by_id(btf, elem_type_id);
3118 	if (btf_type_nosize_or_null(elem_type) ||
3119 	    btf_type_is_resolve_source_only(elem_type)) {
3120 		btf_verifier_log_type(env, v->t,
3121 				      "Invalid elem");
3122 		return -EINVAL;
3123 	}
3124 
3125 	if (!env_type_is_resolve_sink(env, elem_type) &&
3126 	    !env_type_is_resolved(env, elem_type_id))
3127 		return env_stack_push(env, elem_type, elem_type_id);
3128 
3129 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3130 	if (!elem_type) {
3131 		btf_verifier_log_type(env, v->t, "Invalid elem");
3132 		return -EINVAL;
3133 	}
3134 
3135 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
3136 		btf_verifier_log_type(env, v->t, "Invalid array of int");
3137 		return -EINVAL;
3138 	}
3139 
3140 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
3141 		btf_verifier_log_type(env, v->t,
3142 				      "Array size overflows U32_MAX");
3143 		return -EINVAL;
3144 	}
3145 
3146 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
3147 
3148 	return 0;
3149 }
3150 
btf_array_log(struct btf_verifier_env * env,const struct btf_type * t)3151 static void btf_array_log(struct btf_verifier_env *env,
3152 			  const struct btf_type *t)
3153 {
3154 	const struct btf_array *array = btf_type_array(t);
3155 
3156 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3157 			 array->type, array->index_type, array->nelems);
3158 }
3159 
__btf_array_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)3160 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
3161 			     u32 type_id, void *data, u8 bits_offset,
3162 			     struct btf_show *show)
3163 {
3164 	const struct btf_array *array = btf_type_array(t);
3165 	const struct btf_kind_operations *elem_ops;
3166 	const struct btf_type *elem_type;
3167 	u32 i, elem_size = 0, elem_type_id;
3168 	u16 encoding = 0;
3169 
3170 	elem_type_id = array->type;
3171 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
3172 	if (elem_type && btf_type_has_size(elem_type))
3173 		elem_size = elem_type->size;
3174 
3175 	if (elem_type && btf_type_is_int(elem_type)) {
3176 		u32 int_type = btf_type_int(elem_type);
3177 
3178 		encoding = BTF_INT_ENCODING(int_type);
3179 
3180 		/*
3181 		 * BTF_INT_CHAR encoding never seems to be set for
3182 		 * char arrays, so if size is 1 and element is
3183 		 * printable as a char, we'll do that.
3184 		 */
3185 		if (elem_size == 1)
3186 			encoding = BTF_INT_CHAR;
3187 	}
3188 
3189 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3190 		return;
3191 
3192 	if (!elem_type)
3193 		goto out;
3194 	elem_ops = btf_type_ops(elem_type);
3195 
3196 	for (i = 0; i < array->nelems; i++) {
3197 
3198 		btf_show_start_array_member(show);
3199 
3200 		elem_ops->show(btf, elem_type, elem_type_id, data,
3201 			       bits_offset, show);
3202 		data += elem_size;
3203 
3204 		btf_show_end_array_member(show);
3205 
3206 		if (show->state.array_terminated)
3207 			break;
3208 	}
3209 out:
3210 	btf_show_end_array_type(show);
3211 }
3212 
btf_array_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)3213 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3214 			   u32 type_id, void *data, u8 bits_offset,
3215 			   struct btf_show *show)
3216 {
3217 	const struct btf_member *m = show->state.member;
3218 
3219 	/*
3220 	 * First check if any members would be shown (are non-zero).
3221 	 * See comments above "struct btf_show" definition for more
3222 	 * details on how this works at a high-level.
3223 	 */
3224 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3225 		if (!show->state.depth_check) {
3226 			show->state.depth_check = show->state.depth + 1;
3227 			show->state.depth_to_show = 0;
3228 		}
3229 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
3230 		show->state.member = m;
3231 
3232 		if (show->state.depth_check != show->state.depth + 1)
3233 			return;
3234 		show->state.depth_check = 0;
3235 
3236 		if (show->state.depth_to_show <= show->state.depth)
3237 			return;
3238 		/*
3239 		 * Reaching here indicates we have recursed and found
3240 		 * non-zero array member(s).
3241 		 */
3242 	}
3243 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
3244 }
3245 
3246 static const struct btf_kind_operations array_ops = {
3247 	.check_meta = btf_array_check_meta,
3248 	.resolve = btf_array_resolve,
3249 	.check_member = btf_array_check_member,
3250 	.check_kflag_member = btf_generic_check_kflag_member,
3251 	.log_details = btf_array_log,
3252 	.show = btf_array_show,
3253 };
3254 
btf_struct_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)3255 static int btf_struct_check_member(struct btf_verifier_env *env,
3256 				   const struct btf_type *struct_type,
3257 				   const struct btf_member *member,
3258 				   const struct btf_type *member_type)
3259 {
3260 	u32 struct_bits_off = member->offset;
3261 	u32 struct_size, bytes_offset;
3262 
3263 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3264 		btf_verifier_log_member(env, struct_type, member,
3265 					"Member is not byte aligned");
3266 		return -EINVAL;
3267 	}
3268 
3269 	struct_size = struct_type->size;
3270 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3271 	if (struct_size - bytes_offset < member_type->size) {
3272 		btf_verifier_log_member(env, struct_type, member,
3273 					"Member exceeds struct_size");
3274 		return -EINVAL;
3275 	}
3276 
3277 	return 0;
3278 }
3279 
btf_struct_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)3280 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3281 				 const struct btf_type *t,
3282 				 u32 meta_left)
3283 {
3284 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3285 	const struct btf_member *member;
3286 	u32 meta_needed, last_offset;
3287 	struct btf *btf = env->btf;
3288 	u32 struct_size = t->size;
3289 	u32 offset;
3290 	u16 i;
3291 
3292 	meta_needed = btf_type_vlen(t) * sizeof(*member);
3293 	if (meta_left < meta_needed) {
3294 		btf_verifier_log_basic(env, t,
3295 				       "meta_left:%u meta_needed:%u",
3296 				       meta_left, meta_needed);
3297 		return -EINVAL;
3298 	}
3299 
3300 	/* struct type either no name or a valid one */
3301 	if (t->name_off &&
3302 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3303 		btf_verifier_log_type(env, t, "Invalid name");
3304 		return -EINVAL;
3305 	}
3306 
3307 	btf_verifier_log_type(env, t, NULL);
3308 
3309 	last_offset = 0;
3310 	for_each_member(i, t, member) {
3311 		if (!btf_name_offset_valid(btf, member->name_off)) {
3312 			btf_verifier_log_member(env, t, member,
3313 						"Invalid member name_offset:%u",
3314 						member->name_off);
3315 			return -EINVAL;
3316 		}
3317 
3318 		/* struct member either no name or a valid one */
3319 		if (member->name_off &&
3320 		    !btf_name_valid_identifier(btf, member->name_off)) {
3321 			btf_verifier_log_member(env, t, member, "Invalid name");
3322 			return -EINVAL;
3323 		}
3324 		/* A member cannot be in type void */
3325 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3326 			btf_verifier_log_member(env, t, member,
3327 						"Invalid type_id");
3328 			return -EINVAL;
3329 		}
3330 
3331 		offset = __btf_member_bit_offset(t, member);
3332 		if (is_union && offset) {
3333 			btf_verifier_log_member(env, t, member,
3334 						"Invalid member bits_offset");
3335 			return -EINVAL;
3336 		}
3337 
3338 		/*
3339 		 * ">" instead of ">=" because the last member could be
3340 		 * "char a[0];"
3341 		 */
3342 		if (last_offset > offset) {
3343 			btf_verifier_log_member(env, t, member,
3344 						"Invalid member bits_offset");
3345 			return -EINVAL;
3346 		}
3347 
3348 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3349 			btf_verifier_log_member(env, t, member,
3350 						"Member bits_offset exceeds its struct size");
3351 			return -EINVAL;
3352 		}
3353 
3354 		btf_verifier_log_member(env, t, member, NULL);
3355 		last_offset = offset;
3356 	}
3357 
3358 	return meta_needed;
3359 }
3360 
btf_struct_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)3361 static int btf_struct_resolve(struct btf_verifier_env *env,
3362 			      const struct resolve_vertex *v)
3363 {
3364 	const struct btf_member *member;
3365 	int err;
3366 	u16 i;
3367 
3368 	/* Before continue resolving the next_member,
3369 	 * ensure the last member is indeed resolved to a
3370 	 * type with size info.
3371 	 */
3372 	if (v->next_member) {
3373 		const struct btf_type *last_member_type;
3374 		const struct btf_member *last_member;
3375 		u32 last_member_type_id;
3376 
3377 		last_member = btf_type_member(v->t) + v->next_member - 1;
3378 		last_member_type_id = last_member->type;
3379 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
3380 						       last_member_type_id)))
3381 			return -EINVAL;
3382 
3383 		last_member_type = btf_type_by_id(env->btf,
3384 						  last_member_type_id);
3385 		if (btf_type_kflag(v->t))
3386 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3387 								last_member,
3388 								last_member_type);
3389 		else
3390 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3391 								last_member,
3392 								last_member_type);
3393 		if (err)
3394 			return err;
3395 	}
3396 
3397 	for_each_member_from(i, v->next_member, v->t, member) {
3398 		u32 member_type_id = member->type;
3399 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3400 								member_type_id);
3401 
3402 		if (btf_type_nosize_or_null(member_type) ||
3403 		    btf_type_is_resolve_source_only(member_type)) {
3404 			btf_verifier_log_member(env, v->t, member,
3405 						"Invalid member");
3406 			return -EINVAL;
3407 		}
3408 
3409 		if (!env_type_is_resolve_sink(env, member_type) &&
3410 		    !env_type_is_resolved(env, member_type_id)) {
3411 			env_stack_set_next_member(env, i + 1);
3412 			return env_stack_push(env, member_type, member_type_id);
3413 		}
3414 
3415 		if (btf_type_kflag(v->t))
3416 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3417 									    member,
3418 									    member_type);
3419 		else
3420 			err = btf_type_ops(member_type)->check_member(env, v->t,
3421 								      member,
3422 								      member_type);
3423 		if (err)
3424 			return err;
3425 	}
3426 
3427 	env_stack_pop_resolved(env, 0, 0);
3428 
3429 	return 0;
3430 }
3431 
btf_struct_log(struct btf_verifier_env * env,const struct btf_type * t)3432 static void btf_struct_log(struct btf_verifier_env *env,
3433 			   const struct btf_type *t)
3434 {
3435 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3436 }
3437 
3438 enum {
3439 	BTF_FIELD_IGNORE = 0,
3440 	BTF_FIELD_FOUND  = 1,
3441 };
3442 
3443 struct btf_field_info {
3444 	enum btf_field_type type;
3445 	u32 off;
3446 	union {
3447 		struct {
3448 			u32 type_id;
3449 		} kptr;
3450 		struct {
3451 			const char *node_name;
3452 			u32 value_btf_id;
3453 		} graph_root;
3454 	};
3455 };
3456 
btf_find_struct(const struct btf * btf,const struct btf_type * t,u32 off,int sz,enum btf_field_type field_type,struct btf_field_info * info)3457 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3458 			   u32 off, int sz, enum btf_field_type field_type,
3459 			   struct btf_field_info *info)
3460 {
3461 	if (!__btf_type_is_struct(t))
3462 		return BTF_FIELD_IGNORE;
3463 	if (t->size != sz)
3464 		return BTF_FIELD_IGNORE;
3465 	info->type = field_type;
3466 	info->off = off;
3467 	return BTF_FIELD_FOUND;
3468 }
3469 
btf_find_kptr(const struct btf * btf,const struct btf_type * t,u32 off,int sz,struct btf_field_info * info,u32 field_mask)3470 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3471 			 u32 off, int sz, struct btf_field_info *info, u32 field_mask)
3472 {
3473 	enum btf_field_type type;
3474 	const char *tag_value;
3475 	bool is_type_tag;
3476 	u32 res_id;
3477 
3478 	/* Permit modifiers on the pointer itself */
3479 	if (btf_type_is_volatile(t))
3480 		t = btf_type_by_id(btf, t->type);
3481 	/* For PTR, sz is always == 8 */
3482 	if (!btf_type_is_ptr(t))
3483 		return BTF_FIELD_IGNORE;
3484 	t = btf_type_by_id(btf, t->type);
3485 	is_type_tag = btf_type_is_type_tag(t) && !btf_type_kflag(t);
3486 	if (!is_type_tag)
3487 		return BTF_FIELD_IGNORE;
3488 	/* Reject extra tags */
3489 	if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3490 		return -EINVAL;
3491 	tag_value = __btf_name_by_offset(btf, t->name_off);
3492 	if (!strcmp("kptr_untrusted", tag_value))
3493 		type = BPF_KPTR_UNREF;
3494 	else if (!strcmp("kptr", tag_value))
3495 		type = BPF_KPTR_REF;
3496 	else if (!strcmp("percpu_kptr", tag_value))
3497 		type = BPF_KPTR_PERCPU;
3498 	else if (!strcmp("uptr", tag_value))
3499 		type = BPF_UPTR;
3500 	else
3501 		return -EINVAL;
3502 
3503 	if (!(type & field_mask))
3504 		return BTF_FIELD_IGNORE;
3505 
3506 	/* Get the base type */
3507 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
3508 	/* Only pointer to struct is allowed */
3509 	if (!__btf_type_is_struct(t))
3510 		return -EINVAL;
3511 
3512 	info->type = type;
3513 	info->off = off;
3514 	info->kptr.type_id = res_id;
3515 	return BTF_FIELD_FOUND;
3516 }
3517 
btf_find_next_decl_tag(const struct btf * btf,const struct btf_type * pt,int comp_idx,const char * tag_key,int last_id)3518 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3519 			   int comp_idx, const char *tag_key, int last_id)
3520 {
3521 	int len = strlen(tag_key);
3522 	int i, n;
3523 
3524 	for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
3525 		const struct btf_type *t = btf_type_by_id(btf, i);
3526 
3527 		if (!btf_type_is_decl_tag(t))
3528 			continue;
3529 		if (pt != btf_type_by_id(btf, t->type))
3530 			continue;
3531 		if (btf_type_decl_tag(t)->component_idx != comp_idx)
3532 			continue;
3533 		if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3534 			continue;
3535 		return i;
3536 	}
3537 	return -ENOENT;
3538 }
3539 
btf_find_decl_tag_value(const struct btf * btf,const struct btf_type * pt,int comp_idx,const char * tag_key)3540 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3541 				    int comp_idx, const char *tag_key)
3542 {
3543 	const char *value = NULL;
3544 	const struct btf_type *t;
3545 	int len, id;
3546 
3547 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key,
3548 				    btf_named_start_id(btf, false) - 1);
3549 	if (id < 0)
3550 		return ERR_PTR(id);
3551 
3552 	t = btf_type_by_id(btf, id);
3553 	len = strlen(tag_key);
3554 	value = __btf_name_by_offset(btf, t->name_off) + len;
3555 
3556 	/* Prevent duplicate entries for same type */
3557 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3558 	if (id >= 0)
3559 		return ERR_PTR(-EEXIST);
3560 
3561 	return value;
3562 }
3563 
3564 static int
btf_find_graph_root(const struct btf * btf,const struct btf_type * pt,const struct btf_type * t,int comp_idx,u32 off,int sz,struct btf_field_info * info,enum btf_field_type head_type)3565 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3566 		    const struct btf_type *t, int comp_idx, u32 off,
3567 		    int sz, struct btf_field_info *info,
3568 		    enum btf_field_type head_type)
3569 {
3570 	const char *node_field_name;
3571 	const char *value_type;
3572 	s32 id;
3573 
3574 	if (!__btf_type_is_struct(t))
3575 		return BTF_FIELD_IGNORE;
3576 	if (t->size != sz)
3577 		return BTF_FIELD_IGNORE;
3578 	value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3579 	if (IS_ERR(value_type))
3580 		return -EINVAL;
3581 	node_field_name = strstr(value_type, ":");
3582 	if (!node_field_name)
3583 		return -EINVAL;
3584 	value_type = kstrndup(value_type, node_field_name - value_type,
3585 			      GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
3586 	if (!value_type)
3587 		return -ENOMEM;
3588 	id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3589 	kfree(value_type);
3590 	if (id < 0)
3591 		return id;
3592 	node_field_name++;
3593 	if (str_is_empty(node_field_name))
3594 		return -EINVAL;
3595 	info->type = head_type;
3596 	info->off = off;
3597 	info->graph_root.value_btf_id = id;
3598 	info->graph_root.node_name = node_field_name;
3599 	return BTF_FIELD_FOUND;
3600 }
3601 
btf_get_field_type(const struct btf * btf,const struct btf_type * var_type,u32 field_mask,u32 * seen_mask,int * align,int * sz)3602 static int btf_get_field_type(const struct btf *btf, const struct btf_type *var_type,
3603 			      u32 field_mask, u32 *seen_mask, int *align, int *sz)
3604 {
3605 	const struct {
3606 		enum btf_field_type type;
3607 		const char *const name;
3608 		const bool is_unique;
3609 	} field_types[] = {
3610 		{ BPF_SPIN_LOCK, "bpf_spin_lock", true },
3611 		{ BPF_RES_SPIN_LOCK, "bpf_res_spin_lock", true },
3612 		{ BPF_TIMER, "bpf_timer", true },
3613 		{ BPF_WORKQUEUE, "bpf_wq", true },
3614 		{ BPF_TASK_WORK, "bpf_task_work", true },
3615 		{ BPF_LIST_HEAD, "bpf_list_head", false },
3616 		{ BPF_LIST_NODE, "bpf_list_node", false },
3617 		{ BPF_RB_ROOT, "bpf_rb_root", false },
3618 		{ BPF_RB_NODE, "bpf_rb_node", false },
3619 		{ BPF_REFCOUNT, "bpf_refcount", false },
3620 	};
3621 	int type = 0, i;
3622 	const char *name = __btf_name_by_offset(btf, var_type->name_off);
3623 	const char *field_type_name;
3624 	enum btf_field_type field_type;
3625 	bool is_unique;
3626 
3627 	for (i = 0; i < ARRAY_SIZE(field_types); ++i) {
3628 		field_type = field_types[i].type;
3629 		field_type_name = field_types[i].name;
3630 		is_unique = field_types[i].is_unique;
3631 		if (!(field_mask & field_type) || strcmp(name, field_type_name))
3632 			continue;
3633 		if (is_unique) {
3634 			if (*seen_mask & field_type)
3635 				return -E2BIG;
3636 			*seen_mask |= field_type;
3637 		}
3638 		type = field_type;
3639 		goto end;
3640 	}
3641 
3642 	/* Only return BPF_KPTR when all other types with matchable names fail */
3643 	if (field_mask & (BPF_KPTR | BPF_UPTR) && !__btf_type_is_struct(var_type)) {
3644 		type = BPF_KPTR_REF;
3645 		goto end;
3646 	}
3647 	return 0;
3648 end:
3649 	*sz = btf_field_type_size(type);
3650 	*align = btf_field_type_align(type);
3651 	return type;
3652 }
3653 
3654 /* Repeat a number of fields for a specified number of times.
3655  *
3656  * Copy the fields starting from the first field and repeat them for
3657  * repeat_cnt times. The fields are repeated by adding the offset of each
3658  * field with
3659  *   (i + 1) * elem_size
3660  * where i is the repeat index and elem_size is the size of an element.
3661  */
btf_repeat_fields(struct btf_field_info * info,int info_cnt,u32 field_cnt,u32 repeat_cnt,u32 elem_size)3662 static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
3663 			     u32 field_cnt, u32 repeat_cnt, u32 elem_size)
3664 {
3665 	u32 i, j;
3666 	u32 cur;
3667 
3668 	/* Ensure not repeating fields that should not be repeated. */
3669 	for (i = 0; i < field_cnt; i++) {
3670 		switch (info[i].type) {
3671 		case BPF_KPTR_UNREF:
3672 		case BPF_KPTR_REF:
3673 		case BPF_KPTR_PERCPU:
3674 		case BPF_UPTR:
3675 		case BPF_LIST_HEAD:
3676 		case BPF_RB_ROOT:
3677 			break;
3678 		default:
3679 			return -EINVAL;
3680 		}
3681 	}
3682 
3683 	/* The type of struct size or variable size is u32,
3684 	 * so the multiplication will not overflow.
3685 	 */
3686 	if (field_cnt * (repeat_cnt + 1) > info_cnt)
3687 		return -E2BIG;
3688 
3689 	cur = field_cnt;
3690 	for (i = 0; i < repeat_cnt; i++) {
3691 		memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
3692 		for (j = 0; j < field_cnt; j++)
3693 			info[cur++].off += (i + 1) * elem_size;
3694 	}
3695 
3696 	return 0;
3697 }
3698 
3699 static int btf_find_struct_field(const struct btf *btf,
3700 				 const struct btf_type *t, u32 field_mask,
3701 				 struct btf_field_info *info, int info_cnt,
3702 				 u32 level);
3703 
3704 /* Find special fields in the struct type of a field.
3705  *
3706  * This function is used to find fields of special types that is not a
3707  * global variable or a direct field of a struct type. It also handles the
3708  * repetition if it is the element type of an array.
3709  */
btf_find_nested_struct(const struct btf * btf,const struct btf_type * t,u32 off,u32 nelems,u32 field_mask,struct btf_field_info * info,int info_cnt,u32 level)3710 static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
3711 				  u32 off, u32 nelems,
3712 				  u32 field_mask, struct btf_field_info *info,
3713 				  int info_cnt, u32 level)
3714 {
3715 	int ret, err, i;
3716 
3717 	level++;
3718 	if (level >= MAX_RESOLVE_DEPTH)
3719 		return -E2BIG;
3720 
3721 	ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level);
3722 
3723 	if (ret <= 0)
3724 		return ret;
3725 
3726 	/* Shift the offsets of the nested struct fields to the offsets
3727 	 * related to the container.
3728 	 */
3729 	for (i = 0; i < ret; i++)
3730 		info[i].off += off;
3731 
3732 	if (nelems > 1) {
3733 		err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
3734 		if (err == 0)
3735 			ret *= nelems;
3736 		else
3737 			ret = err;
3738 	}
3739 
3740 	return ret;
3741 }
3742 
btf_find_field_one(const struct btf * btf,const struct btf_type * var,const struct btf_type * var_type,int var_idx,u32 off,u32 expected_size,u32 field_mask,u32 * seen_mask,struct btf_field_info * info,int info_cnt,u32 level)3743 static int btf_find_field_one(const struct btf *btf,
3744 			      const struct btf_type *var,
3745 			      const struct btf_type *var_type,
3746 			      int var_idx,
3747 			      u32 off, u32 expected_size,
3748 			      u32 field_mask, u32 *seen_mask,
3749 			      struct btf_field_info *info, int info_cnt,
3750 			      u32 level)
3751 {
3752 	int ret, align, sz, field_type;
3753 	struct btf_field_info tmp;
3754 	const struct btf_array *array;
3755 	u32 i, nelems = 1;
3756 
3757 	/* Walk into array types to find the element type and the number of
3758 	 * elements in the (flattened) array.
3759 	 */
3760 	for (i = 0; i < MAX_RESOLVE_DEPTH && btf_type_is_array(var_type); i++) {
3761 		array = btf_array(var_type);
3762 		nelems *= array->nelems;
3763 		var_type = btf_type_by_id(btf, array->type);
3764 	}
3765 	if (i == MAX_RESOLVE_DEPTH)
3766 		return -E2BIG;
3767 	if (nelems == 0)
3768 		return 0;
3769 
3770 	field_type = btf_get_field_type(btf, var_type,
3771 					field_mask, seen_mask, &align, &sz);
3772 	/* Look into variables of struct types */
3773 	if (!field_type && __btf_type_is_struct(var_type)) {
3774 		sz = var_type->size;
3775 		if (expected_size && expected_size != sz * nelems)
3776 			return 0;
3777 		ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
3778 					     &info[0], info_cnt, level);
3779 		return ret;
3780 	}
3781 
3782 	if (field_type == 0)
3783 		return 0;
3784 	if (field_type < 0)
3785 		return field_type;
3786 
3787 	if (expected_size && expected_size != sz * nelems)
3788 		return 0;
3789 	if (off % align)
3790 		return 0;
3791 
3792 	switch (field_type) {
3793 	case BPF_SPIN_LOCK:
3794 	case BPF_RES_SPIN_LOCK:
3795 	case BPF_TIMER:
3796 	case BPF_WORKQUEUE:
3797 	case BPF_LIST_NODE:
3798 	case BPF_RB_NODE:
3799 	case BPF_REFCOUNT:
3800 	case BPF_TASK_WORK:
3801 		ret = btf_find_struct(btf, var_type, off, sz, field_type,
3802 				      info_cnt ? &info[0] : &tmp);
3803 		if (ret < 0)
3804 			return ret;
3805 		break;
3806 	case BPF_KPTR_UNREF:
3807 	case BPF_KPTR_REF:
3808 	case BPF_KPTR_PERCPU:
3809 	case BPF_UPTR:
3810 		ret = btf_find_kptr(btf, var_type, off, sz,
3811 				    info_cnt ? &info[0] : &tmp, field_mask);
3812 		if (ret < 0)
3813 			return ret;
3814 		break;
3815 	case BPF_LIST_HEAD:
3816 	case BPF_RB_ROOT:
3817 		ret = btf_find_graph_root(btf, var, var_type,
3818 					  var_idx, off, sz,
3819 					  info_cnt ? &info[0] : &tmp,
3820 					  field_type);
3821 		if (ret < 0)
3822 			return ret;
3823 		break;
3824 	default:
3825 		return -EFAULT;
3826 	}
3827 
3828 	if (ret == BTF_FIELD_IGNORE)
3829 		return 0;
3830 	if (!info_cnt)
3831 		return -E2BIG;
3832 	if (nelems > 1) {
3833 		ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
3834 		if (ret < 0)
3835 			return ret;
3836 	}
3837 	return nelems;
3838 }
3839 
btf_find_struct_field(const struct btf * btf,const struct btf_type * t,u32 field_mask,struct btf_field_info * info,int info_cnt,u32 level)3840 static int btf_find_struct_field(const struct btf *btf,
3841 				 const struct btf_type *t, u32 field_mask,
3842 				 struct btf_field_info *info, int info_cnt,
3843 				 u32 level)
3844 {
3845 	int ret, idx = 0;
3846 	const struct btf_member *member;
3847 	u32 i, off, seen_mask = 0;
3848 
3849 	for_each_member(i, t, member) {
3850 		const struct btf_type *member_type = btf_type_by_id(btf,
3851 								    member->type);
3852 
3853 		off = __btf_member_bit_offset(t, member);
3854 		if (off % 8)
3855 			/* valid C code cannot generate such BTF */
3856 			return -EINVAL;
3857 		off /= 8;
3858 
3859 		ret = btf_find_field_one(btf, t, member_type, i,
3860 					 off, 0,
3861 					 field_mask, &seen_mask,
3862 					 &info[idx], info_cnt - idx, level);
3863 		if (ret < 0)
3864 			return ret;
3865 		idx += ret;
3866 	}
3867 	return idx;
3868 }
3869 
btf_find_datasec_var(const struct btf * btf,const struct btf_type * t,u32 field_mask,struct btf_field_info * info,int info_cnt,u32 level)3870 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3871 				u32 field_mask, struct btf_field_info *info,
3872 				int info_cnt, u32 level)
3873 {
3874 	int ret, idx = 0;
3875 	const struct btf_var_secinfo *vsi;
3876 	u32 i, off, seen_mask = 0;
3877 
3878 	for_each_vsi(i, t, vsi) {
3879 		const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3880 		const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3881 
3882 		off = vsi->offset;
3883 		ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
3884 					 field_mask, &seen_mask,
3885 					 &info[idx], info_cnt - idx,
3886 					 level);
3887 		if (ret < 0)
3888 			return ret;
3889 		idx += ret;
3890 	}
3891 	return idx;
3892 }
3893 
btf_find_field(const struct btf * btf,const struct btf_type * t,u32 field_mask,struct btf_field_info * info,int info_cnt)3894 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3895 			  u32 field_mask, struct btf_field_info *info,
3896 			  int info_cnt)
3897 {
3898 	if (__btf_type_is_struct(t))
3899 		return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0);
3900 	else if (btf_type_is_datasec(t))
3901 		return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0);
3902 	return -EINVAL;
3903 }
3904 
3905 /* Callers have to ensure the life cycle of btf if it is program BTF */
btf_parse_kptr(const struct btf * btf,struct btf_field * field,struct btf_field_info * info)3906 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3907 			  struct btf_field_info *info)
3908 {
3909 	struct module *mod = NULL;
3910 	const struct btf_type *t;
3911 	/* If a matching btf type is found in kernel or module BTFs, kptr_ref
3912 	 * is that BTF, otherwise it's program BTF
3913 	 */
3914 	struct btf *kptr_btf;
3915 	int ret;
3916 	s32 id;
3917 
3918 	/* Find type in map BTF, and use it to look up the matching type
3919 	 * in vmlinux or module BTFs, by name and kind.
3920 	 */
3921 	t = btf_type_by_id(btf, info->kptr.type_id);
3922 	id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3923 			     &kptr_btf);
3924 	if (id == -ENOENT) {
3925 		/* btf_parse_kptr should only be called w/ btf = program BTF */
3926 		WARN_ON_ONCE(btf_is_kernel(btf));
3927 
3928 		/* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3929 		 * kptr allocated via bpf_obj_new
3930 		 */
3931 		field->kptr.dtor = NULL;
3932 		id = info->kptr.type_id;
3933 		kptr_btf = (struct btf *)btf;
3934 		goto found_dtor;
3935 	}
3936 	if (id < 0)
3937 		return id;
3938 
3939 	/* Find and stash the function pointer for the destruction function that
3940 	 * needs to be eventually invoked from the map free path.
3941 	 */
3942 	if (info->type == BPF_KPTR_REF) {
3943 		const struct btf_type *dtor_func;
3944 		const char *dtor_func_name;
3945 		unsigned long addr;
3946 		s32 dtor_btf_id;
3947 
3948 		/* This call also serves as a whitelist of allowed objects that
3949 		 * can be used as a referenced pointer and be stored in a map at
3950 		 * the same time.
3951 		 */
3952 		dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3953 		if (dtor_btf_id < 0) {
3954 			ret = dtor_btf_id;
3955 			goto end_btf;
3956 		}
3957 
3958 		dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3959 		if (!dtor_func) {
3960 			ret = -ENOENT;
3961 			goto end_btf;
3962 		}
3963 
3964 		if (btf_is_module(kptr_btf)) {
3965 			mod = btf_try_get_module(kptr_btf);
3966 			if (!mod) {
3967 				ret = -ENXIO;
3968 				goto end_btf;
3969 			}
3970 		}
3971 
3972 		/* We already verified dtor_func to be btf_type_is_func
3973 		 * in register_btf_id_dtor_kfuncs.
3974 		 */
3975 		dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3976 		addr = kallsyms_lookup_name(dtor_func_name);
3977 		if (!addr) {
3978 			ret = -EINVAL;
3979 			goto end_mod;
3980 		}
3981 		field->kptr.dtor = (void *)addr;
3982 	}
3983 
3984 found_dtor:
3985 	field->kptr.btf_id = id;
3986 	field->kptr.btf = kptr_btf;
3987 	field->kptr.module = mod;
3988 	return 0;
3989 end_mod:
3990 	module_put(mod);
3991 end_btf:
3992 	btf_put(kptr_btf);
3993 	return ret;
3994 }
3995 
btf_parse_graph_root(const struct btf * btf,struct btf_field * field,struct btf_field_info * info,const char * node_type_name,size_t node_type_align)3996 static int btf_parse_graph_root(const struct btf *btf,
3997 				struct btf_field *field,
3998 				struct btf_field_info *info,
3999 				const char *node_type_name,
4000 				size_t node_type_align)
4001 {
4002 	const struct btf_type *t, *n = NULL;
4003 	const struct btf_member *member;
4004 	u32 offset;
4005 	int i;
4006 
4007 	t = btf_type_by_id(btf, info->graph_root.value_btf_id);
4008 	/* We've already checked that value_btf_id is a struct type. We
4009 	 * just need to figure out the offset of the list_node, and
4010 	 * verify its type.
4011 	 */
4012 	for_each_member(i, t, member) {
4013 		if (strcmp(info->graph_root.node_name,
4014 			   __btf_name_by_offset(btf, member->name_off)))
4015 			continue;
4016 		/* Invalid BTF, two members with same name */
4017 		if (n)
4018 			return -EINVAL;
4019 		n = btf_type_by_id(btf, member->type);
4020 		if (!__btf_type_is_struct(n))
4021 			return -EINVAL;
4022 		if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
4023 			return -EINVAL;
4024 		offset = __btf_member_bit_offset(n, member);
4025 		if (offset % 8)
4026 			return -EINVAL;
4027 		offset /= 8;
4028 		if (offset % node_type_align)
4029 			return -EINVAL;
4030 
4031 		field->graph_root.btf = (struct btf *)btf;
4032 		field->graph_root.value_btf_id = info->graph_root.value_btf_id;
4033 		field->graph_root.node_offset = offset;
4034 	}
4035 	if (!n)
4036 		return -ENOENT;
4037 	return 0;
4038 }
4039 
btf_parse_list_head(const struct btf * btf,struct btf_field * field,struct btf_field_info * info)4040 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
4041 			       struct btf_field_info *info)
4042 {
4043 	return btf_parse_graph_root(btf, field, info, "bpf_list_node",
4044 					    __alignof__(struct bpf_list_node));
4045 }
4046 
btf_parse_rb_root(const struct btf * btf,struct btf_field * field,struct btf_field_info * info)4047 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
4048 			     struct btf_field_info *info)
4049 {
4050 	return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
4051 					    __alignof__(struct bpf_rb_node));
4052 }
4053 
btf_field_cmp(const void * _a,const void * _b,const void * priv)4054 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
4055 {
4056 	const struct btf_field *a = (const struct btf_field *)_a;
4057 	const struct btf_field *b = (const struct btf_field *)_b;
4058 
4059 	if (a->offset < b->offset)
4060 		return -1;
4061 	else if (a->offset > b->offset)
4062 		return 1;
4063 	return 0;
4064 }
4065 
btf_parse_fields(const struct btf * btf,const struct btf_type * t,u32 field_mask,u32 value_size)4066 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
4067 				    u32 field_mask, u32 value_size)
4068 {
4069 	struct btf_field_info info_arr[BTF_FIELDS_MAX];
4070 	u32 next_off = 0, field_type_size;
4071 	struct btf_record *rec;
4072 	int ret, i, cnt;
4073 
4074 	ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
4075 	if (ret < 0)
4076 		return ERR_PTR(ret);
4077 	if (!ret)
4078 		return NULL;
4079 
4080 	cnt = ret;
4081 	/* This needs to be kzalloc to zero out padding and unused fields, see
4082 	 * comment in btf_record_equal.
4083 	 */
4084 	rec = kzalloc_flex(*rec, fields, cnt, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
4085 	if (!rec)
4086 		return ERR_PTR(-ENOMEM);
4087 
4088 	rec->spin_lock_off = -EINVAL;
4089 	rec->res_spin_lock_off = -EINVAL;
4090 	rec->timer_off = -EINVAL;
4091 	rec->wq_off = -EINVAL;
4092 	rec->refcount_off = -EINVAL;
4093 	rec->task_work_off = -EINVAL;
4094 	for (i = 0; i < cnt; i++) {
4095 		field_type_size = btf_field_type_size(info_arr[i].type);
4096 		if (info_arr[i].off + field_type_size > value_size) {
4097 			WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
4098 			ret = -EFAULT;
4099 			goto end;
4100 		}
4101 		if (info_arr[i].off < next_off) {
4102 			ret = -EEXIST;
4103 			goto end;
4104 		}
4105 		next_off = info_arr[i].off + field_type_size;
4106 
4107 		rec->field_mask |= info_arr[i].type;
4108 		rec->fields[i].offset = info_arr[i].off;
4109 		rec->fields[i].type = info_arr[i].type;
4110 		rec->fields[i].size = field_type_size;
4111 
4112 		switch (info_arr[i].type) {
4113 		case BPF_SPIN_LOCK:
4114 			WARN_ON_ONCE(rec->spin_lock_off >= 0);
4115 			/* Cache offset for faster lookup at runtime */
4116 			rec->spin_lock_off = rec->fields[i].offset;
4117 			break;
4118 		case BPF_RES_SPIN_LOCK:
4119 			WARN_ON_ONCE(rec->spin_lock_off >= 0);
4120 			/* Cache offset for faster lookup at runtime */
4121 			rec->res_spin_lock_off = rec->fields[i].offset;
4122 			break;
4123 		case BPF_TIMER:
4124 			WARN_ON_ONCE(rec->timer_off >= 0);
4125 			/* Cache offset for faster lookup at runtime */
4126 			rec->timer_off = rec->fields[i].offset;
4127 			break;
4128 		case BPF_WORKQUEUE:
4129 			WARN_ON_ONCE(rec->wq_off >= 0);
4130 			/* Cache offset for faster lookup at runtime */
4131 			rec->wq_off = rec->fields[i].offset;
4132 			break;
4133 		case BPF_TASK_WORK:
4134 			WARN_ON_ONCE(rec->task_work_off >= 0);
4135 			rec->task_work_off = rec->fields[i].offset;
4136 			break;
4137 		case BPF_REFCOUNT:
4138 			WARN_ON_ONCE(rec->refcount_off >= 0);
4139 			/* Cache offset for faster lookup at runtime */
4140 			rec->refcount_off = rec->fields[i].offset;
4141 			break;
4142 		case BPF_KPTR_UNREF:
4143 		case BPF_KPTR_REF:
4144 		case BPF_KPTR_PERCPU:
4145 		case BPF_UPTR:
4146 			ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
4147 			if (ret < 0)
4148 				goto end;
4149 			break;
4150 		case BPF_LIST_HEAD:
4151 			ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
4152 			if (ret < 0)
4153 				goto end;
4154 			break;
4155 		case BPF_RB_ROOT:
4156 			ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
4157 			if (ret < 0)
4158 				goto end;
4159 			break;
4160 		case BPF_LIST_NODE:
4161 		case BPF_RB_NODE:
4162 			break;
4163 		default:
4164 			ret = -EFAULT;
4165 			goto end;
4166 		}
4167 		rec->cnt++;
4168 	}
4169 
4170 	if (rec->spin_lock_off >= 0 && rec->res_spin_lock_off >= 0) {
4171 		ret = -EINVAL;
4172 		goto end;
4173 	}
4174 
4175 	/* bpf_{list_head, rb_node} require bpf_spin_lock */
4176 	if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
4177 	     btf_record_has_field(rec, BPF_RB_ROOT)) &&
4178 		 (rec->spin_lock_off < 0 && rec->res_spin_lock_off < 0)) {
4179 		ret = -EINVAL;
4180 		goto end;
4181 	}
4182 
4183 	if (rec->refcount_off < 0 &&
4184 	    btf_record_has_field(rec, BPF_LIST_NODE) &&
4185 	    btf_record_has_field(rec, BPF_RB_NODE)) {
4186 		ret = -EINVAL;
4187 		goto end;
4188 	}
4189 
4190 	sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
4191 	       NULL, rec);
4192 
4193 	return rec;
4194 end:
4195 	btf_record_free(rec);
4196 	return ERR_PTR(ret);
4197 }
4198 
btf_check_and_fixup_fields(const struct btf * btf,struct btf_record * rec)4199 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
4200 {
4201 	int i;
4202 
4203 	/* There are three types that signify ownership of some other type:
4204 	 *  kptr_ref, bpf_list_head, bpf_rb_root.
4205 	 * kptr_ref only supports storing kernel types, which can't store
4206 	 * references to program allocated local types.
4207 	 *
4208 	 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
4209 	 * does not form cycles.
4210 	 */
4211 	if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & (BPF_GRAPH_ROOT | BPF_UPTR)))
4212 		return 0;
4213 	for (i = 0; i < rec->cnt; i++) {
4214 		struct btf_struct_meta *meta;
4215 		const struct btf_type *t;
4216 		u32 btf_id;
4217 
4218 		if (rec->fields[i].type == BPF_UPTR) {
4219 			/* The uptr only supports pinning one page and cannot
4220 			 * point to a kernel struct
4221 			 */
4222 			if (btf_is_kernel(rec->fields[i].kptr.btf))
4223 				return -EINVAL;
4224 			t = btf_type_by_id(rec->fields[i].kptr.btf,
4225 					   rec->fields[i].kptr.btf_id);
4226 			if (!t->size)
4227 				return -EINVAL;
4228 			if (t->size > PAGE_SIZE)
4229 				return -E2BIG;
4230 			continue;
4231 		}
4232 
4233 		if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
4234 			continue;
4235 		btf_id = rec->fields[i].graph_root.value_btf_id;
4236 		meta = btf_find_struct_meta(btf, btf_id);
4237 		if (!meta)
4238 			return -EFAULT;
4239 		rec->fields[i].graph_root.value_rec = meta->record;
4240 
4241 		/* We need to set value_rec for all root types, but no need
4242 		 * to check ownership cycle for a type unless it's also a
4243 		 * node type.
4244 		 */
4245 		if (!(rec->field_mask & BPF_GRAPH_NODE))
4246 			continue;
4247 
4248 		/* We need to ensure ownership acyclicity among all types. The
4249 		 * proper way to do it would be to topologically sort all BTF
4250 		 * IDs based on the ownership edges, since there can be multiple
4251 		 * bpf_{list_head,rb_node} in a type. Instead, we use the
4252 		 * following resaoning:
4253 		 *
4254 		 * - A type can only be owned by another type in user BTF if it
4255 		 *   has a bpf_{list,rb}_node. Let's call these node types.
4256 		 * - A type can only _own_ another type in user BTF if it has a
4257 		 *   bpf_{list_head,rb_root}. Let's call these root types.
4258 		 *
4259 		 * We ensure that if a type is both a root and node, its
4260 		 * element types cannot be root types.
4261 		 *
4262 		 * To ensure acyclicity:
4263 		 *
4264 		 * When A is an root type but not a node, its ownership
4265 		 * chain can be:
4266 		 *	A -> B -> C
4267 		 * Where:
4268 		 * - A is an root, e.g. has bpf_rb_root.
4269 		 * - B is both a root and node, e.g. has bpf_rb_node and
4270 		 *   bpf_list_head.
4271 		 * - C is only an root, e.g. has bpf_list_node
4272 		 *
4273 		 * When A is both a root and node, some other type already
4274 		 * owns it in the BTF domain, hence it can not own
4275 		 * another root type through any of the ownership edges.
4276 		 *	A -> B
4277 		 * Where:
4278 		 * - A is both an root and node.
4279 		 * - B is only an node.
4280 		 */
4281 		if (meta->record->field_mask & BPF_GRAPH_ROOT)
4282 			return -ELOOP;
4283 	}
4284 	return 0;
4285 }
4286 
__btf_struct_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4287 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
4288 			      u32 type_id, void *data, u8 bits_offset,
4289 			      struct btf_show *show)
4290 {
4291 	const struct btf_member *member;
4292 	void *safe_data;
4293 	u32 i;
4294 
4295 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
4296 	if (!safe_data)
4297 		return;
4298 
4299 	for_each_member(i, t, member) {
4300 		const struct btf_type *member_type = btf_type_by_id(btf,
4301 								member->type);
4302 		const struct btf_kind_operations *ops;
4303 		u32 member_offset, bitfield_size;
4304 		u32 bytes_offset;
4305 		u8 bits8_offset;
4306 
4307 		btf_show_start_member(show, member);
4308 
4309 		member_offset = __btf_member_bit_offset(t, member);
4310 		bitfield_size = __btf_member_bitfield_size(t, member);
4311 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4312 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4313 		if (bitfield_size) {
4314 			safe_data = btf_show_start_type(show, member_type,
4315 							member->type,
4316 							data + bytes_offset);
4317 			if (safe_data)
4318 				btf_bitfield_show(safe_data,
4319 						  bits8_offset,
4320 						  bitfield_size, show);
4321 			btf_show_end_type(show);
4322 		} else {
4323 			ops = btf_type_ops(member_type);
4324 			ops->show(btf, member_type, member->type,
4325 				  data + bytes_offset, bits8_offset, show);
4326 		}
4327 
4328 		btf_show_end_member(show);
4329 	}
4330 
4331 	btf_show_end_struct_type(show);
4332 }
4333 
btf_struct_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4334 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4335 			    u32 type_id, void *data, u8 bits_offset,
4336 			    struct btf_show *show)
4337 {
4338 	const struct btf_member *m = show->state.member;
4339 
4340 	/*
4341 	 * First check if any members would be shown (are non-zero).
4342 	 * See comments above "struct btf_show" definition for more
4343 	 * details on how this works at a high-level.
4344 	 */
4345 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4346 		if (!show->state.depth_check) {
4347 			show->state.depth_check = show->state.depth + 1;
4348 			show->state.depth_to_show = 0;
4349 		}
4350 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4351 		/* Restore saved member data here */
4352 		show->state.member = m;
4353 		if (show->state.depth_check != show->state.depth + 1)
4354 			return;
4355 		show->state.depth_check = 0;
4356 
4357 		if (show->state.depth_to_show <= show->state.depth)
4358 			return;
4359 		/*
4360 		 * Reaching here indicates we have recursed and found
4361 		 * non-zero child values.
4362 		 */
4363 	}
4364 
4365 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4366 }
4367 
4368 static const struct btf_kind_operations struct_ops = {
4369 	.check_meta = btf_struct_check_meta,
4370 	.resolve = btf_struct_resolve,
4371 	.check_member = btf_struct_check_member,
4372 	.check_kflag_member = btf_generic_check_kflag_member,
4373 	.log_details = btf_struct_log,
4374 	.show = btf_struct_show,
4375 };
4376 
btf_enum_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)4377 static int btf_enum_check_member(struct btf_verifier_env *env,
4378 				 const struct btf_type *struct_type,
4379 				 const struct btf_member *member,
4380 				 const struct btf_type *member_type)
4381 {
4382 	u32 struct_bits_off = member->offset;
4383 	u32 struct_size, bytes_offset;
4384 
4385 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4386 		btf_verifier_log_member(env, struct_type, member,
4387 					"Member is not byte aligned");
4388 		return -EINVAL;
4389 	}
4390 
4391 	struct_size = struct_type->size;
4392 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4393 	if (struct_size - bytes_offset < member_type->size) {
4394 		btf_verifier_log_member(env, struct_type, member,
4395 					"Member exceeds struct_size");
4396 		return -EINVAL;
4397 	}
4398 
4399 	return 0;
4400 }
4401 
btf_enum_check_kflag_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)4402 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4403 				       const struct btf_type *struct_type,
4404 				       const struct btf_member *member,
4405 				       const struct btf_type *member_type)
4406 {
4407 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4408 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4409 
4410 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4411 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4412 	if (!nr_bits) {
4413 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4414 			btf_verifier_log_member(env, struct_type, member,
4415 						"Member is not byte aligned");
4416 			return -EINVAL;
4417 		}
4418 
4419 		nr_bits = int_bitsize;
4420 	} else if (nr_bits > int_bitsize) {
4421 		btf_verifier_log_member(env, struct_type, member,
4422 					"Invalid member bitfield_size");
4423 		return -EINVAL;
4424 	}
4425 
4426 	struct_size = struct_type->size;
4427 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4428 	if (struct_size < bytes_end) {
4429 		btf_verifier_log_member(env, struct_type, member,
4430 					"Member exceeds struct_size");
4431 		return -EINVAL;
4432 	}
4433 
4434 	return 0;
4435 }
4436 
btf_enum_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4437 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4438 			       const struct btf_type *t,
4439 			       u32 meta_left)
4440 {
4441 	const struct btf_enum *enums = btf_type_enum(t);
4442 	struct btf *btf = env->btf;
4443 	const char *fmt_str;
4444 	u16 i, nr_enums;
4445 	u32 meta_needed;
4446 
4447 	nr_enums = btf_type_vlen(t);
4448 	meta_needed = nr_enums * sizeof(*enums);
4449 
4450 	if (meta_left < meta_needed) {
4451 		btf_verifier_log_basic(env, t,
4452 				       "meta_left:%u meta_needed:%u",
4453 				       meta_left, meta_needed);
4454 		return -EINVAL;
4455 	}
4456 
4457 	if (t->size > 8 || !is_power_of_2(t->size)) {
4458 		btf_verifier_log_type(env, t, "Unexpected size");
4459 		return -EINVAL;
4460 	}
4461 
4462 	/* enum type either no name or a valid one */
4463 	if (t->name_off &&
4464 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4465 		btf_verifier_log_type(env, t, "Invalid name");
4466 		return -EINVAL;
4467 	}
4468 
4469 	btf_verifier_log_type(env, t, NULL);
4470 
4471 	for (i = 0; i < nr_enums; i++) {
4472 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4473 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4474 					 enums[i].name_off);
4475 			return -EINVAL;
4476 		}
4477 
4478 		/* enum member must have a valid name */
4479 		if (!enums[i].name_off ||
4480 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4481 			btf_verifier_log_type(env, t, "Invalid name");
4482 			return -EINVAL;
4483 		}
4484 
4485 		if (env->log.level == BPF_LOG_KERNEL)
4486 			continue;
4487 		fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4488 		btf_verifier_log(env, fmt_str,
4489 				 __btf_name_by_offset(btf, enums[i].name_off),
4490 				 enums[i].val);
4491 	}
4492 
4493 	return meta_needed;
4494 }
4495 
btf_enum_log(struct btf_verifier_env * env,const struct btf_type * t)4496 static void btf_enum_log(struct btf_verifier_env *env,
4497 			 const struct btf_type *t)
4498 {
4499 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4500 }
4501 
btf_enum_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4502 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4503 			  u32 type_id, void *data, u8 bits_offset,
4504 			  struct btf_show *show)
4505 {
4506 	const struct btf_enum *enums = btf_type_enum(t);
4507 	u32 i, nr_enums = btf_type_vlen(t);
4508 	void *safe_data;
4509 	int v;
4510 
4511 	safe_data = btf_show_start_type(show, t, type_id, data);
4512 	if (!safe_data)
4513 		return;
4514 
4515 	v = *(int *)safe_data;
4516 
4517 	for (i = 0; i < nr_enums; i++) {
4518 		if (v != enums[i].val)
4519 			continue;
4520 
4521 		btf_show_type_value(show, "%s",
4522 				    __btf_name_by_offset(btf,
4523 							 enums[i].name_off));
4524 
4525 		btf_show_end_type(show);
4526 		return;
4527 	}
4528 
4529 	if (btf_type_kflag(t))
4530 		btf_show_type_value(show, "%d", v);
4531 	else
4532 		btf_show_type_value(show, "%u", v);
4533 	btf_show_end_type(show);
4534 }
4535 
4536 static const struct btf_kind_operations enum_ops = {
4537 	.check_meta = btf_enum_check_meta,
4538 	.resolve = btf_df_resolve,
4539 	.check_member = btf_enum_check_member,
4540 	.check_kflag_member = btf_enum_check_kflag_member,
4541 	.log_details = btf_enum_log,
4542 	.show = btf_enum_show,
4543 };
4544 
btf_enum64_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4545 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4546 				 const struct btf_type *t,
4547 				 u32 meta_left)
4548 {
4549 	const struct btf_enum64 *enums = btf_type_enum64(t);
4550 	struct btf *btf = env->btf;
4551 	const char *fmt_str;
4552 	u16 i, nr_enums;
4553 	u32 meta_needed;
4554 
4555 	nr_enums = btf_type_vlen(t);
4556 	meta_needed = nr_enums * sizeof(*enums);
4557 
4558 	if (meta_left < meta_needed) {
4559 		btf_verifier_log_basic(env, t,
4560 				       "meta_left:%u meta_needed:%u",
4561 				       meta_left, meta_needed);
4562 		return -EINVAL;
4563 	}
4564 
4565 	if (t->size > 8 || !is_power_of_2(t->size)) {
4566 		btf_verifier_log_type(env, t, "Unexpected size");
4567 		return -EINVAL;
4568 	}
4569 
4570 	/* enum type either no name or a valid one */
4571 	if (t->name_off &&
4572 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4573 		btf_verifier_log_type(env, t, "Invalid name");
4574 		return -EINVAL;
4575 	}
4576 
4577 	btf_verifier_log_type(env, t, NULL);
4578 
4579 	for (i = 0; i < nr_enums; i++) {
4580 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4581 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4582 					 enums[i].name_off);
4583 			return -EINVAL;
4584 		}
4585 
4586 		/* enum member must have a valid name */
4587 		if (!enums[i].name_off ||
4588 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4589 			btf_verifier_log_type(env, t, "Invalid name");
4590 			return -EINVAL;
4591 		}
4592 
4593 		if (env->log.level == BPF_LOG_KERNEL)
4594 			continue;
4595 
4596 		fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4597 		btf_verifier_log(env, fmt_str,
4598 				 __btf_name_by_offset(btf, enums[i].name_off),
4599 				 btf_enum64_value(enums + i));
4600 	}
4601 
4602 	return meta_needed;
4603 }
4604 
btf_enum64_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4605 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4606 			    u32 type_id, void *data, u8 bits_offset,
4607 			    struct btf_show *show)
4608 {
4609 	const struct btf_enum64 *enums = btf_type_enum64(t);
4610 	u32 i, nr_enums = btf_type_vlen(t);
4611 	void *safe_data;
4612 	s64 v;
4613 
4614 	safe_data = btf_show_start_type(show, t, type_id, data);
4615 	if (!safe_data)
4616 		return;
4617 
4618 	v = *(u64 *)safe_data;
4619 
4620 	for (i = 0; i < nr_enums; i++) {
4621 		if (v != btf_enum64_value(enums + i))
4622 			continue;
4623 
4624 		btf_show_type_value(show, "%s",
4625 				    __btf_name_by_offset(btf,
4626 							 enums[i].name_off));
4627 
4628 		btf_show_end_type(show);
4629 		return;
4630 	}
4631 
4632 	if (btf_type_kflag(t))
4633 		btf_show_type_value(show, "%lld", v);
4634 	else
4635 		btf_show_type_value(show, "%llu", v);
4636 	btf_show_end_type(show);
4637 }
4638 
4639 static const struct btf_kind_operations enum64_ops = {
4640 	.check_meta = btf_enum64_check_meta,
4641 	.resolve = btf_df_resolve,
4642 	.check_member = btf_enum_check_member,
4643 	.check_kflag_member = btf_enum_check_kflag_member,
4644 	.log_details = btf_enum_log,
4645 	.show = btf_enum64_show,
4646 };
4647 
btf_func_proto_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4648 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4649 				     const struct btf_type *t,
4650 				     u32 meta_left)
4651 {
4652 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4653 
4654 	if (meta_left < meta_needed) {
4655 		btf_verifier_log_basic(env, t,
4656 				       "meta_left:%u meta_needed:%u",
4657 				       meta_left, meta_needed);
4658 		return -EINVAL;
4659 	}
4660 
4661 	if (t->name_off) {
4662 		btf_verifier_log_type(env, t, "Invalid name");
4663 		return -EINVAL;
4664 	}
4665 
4666 	if (btf_type_kflag(t)) {
4667 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4668 		return -EINVAL;
4669 	}
4670 
4671 	btf_verifier_log_type(env, t, NULL);
4672 
4673 	return meta_needed;
4674 }
4675 
btf_func_proto_log(struct btf_verifier_env * env,const struct btf_type * t)4676 static void btf_func_proto_log(struct btf_verifier_env *env,
4677 			       const struct btf_type *t)
4678 {
4679 	const struct btf_param *args = (const struct btf_param *)(t + 1);
4680 	u16 nr_args = btf_type_vlen(t), i;
4681 
4682 	btf_verifier_log(env, "return=%u args=(", t->type);
4683 	if (!nr_args) {
4684 		btf_verifier_log(env, "void");
4685 		goto done;
4686 	}
4687 
4688 	if (nr_args == 1 && !args[0].type) {
4689 		/* Only one vararg */
4690 		btf_verifier_log(env, "vararg");
4691 		goto done;
4692 	}
4693 
4694 	btf_verifier_log(env, "%u %s", args[0].type,
4695 			 __btf_name_by_offset(env->btf,
4696 					      args[0].name_off));
4697 	for (i = 1; i < nr_args - 1; i++)
4698 		btf_verifier_log(env, ", %u %s", args[i].type,
4699 				 __btf_name_by_offset(env->btf,
4700 						      args[i].name_off));
4701 
4702 	if (nr_args > 1) {
4703 		const struct btf_param *last_arg = &args[nr_args - 1];
4704 
4705 		if (last_arg->type)
4706 			btf_verifier_log(env, ", %u %s", last_arg->type,
4707 					 __btf_name_by_offset(env->btf,
4708 							      last_arg->name_off));
4709 		else
4710 			btf_verifier_log(env, ", vararg");
4711 	}
4712 
4713 done:
4714 	btf_verifier_log(env, ")");
4715 }
4716 
4717 static const struct btf_kind_operations func_proto_ops = {
4718 	.check_meta = btf_func_proto_check_meta,
4719 	.resolve = btf_df_resolve,
4720 	/*
4721 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4722 	 * a struct's member.
4723 	 *
4724 	 * It should be a function pointer instead.
4725 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4726 	 *
4727 	 * Hence, there is no btf_func_check_member().
4728 	 */
4729 	.check_member = btf_df_check_member,
4730 	.check_kflag_member = btf_df_check_kflag_member,
4731 	.log_details = btf_func_proto_log,
4732 	.show = btf_df_show,
4733 };
4734 
btf_func_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4735 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4736 			       const struct btf_type *t,
4737 			       u32 meta_left)
4738 {
4739 	if (!t->name_off ||
4740 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4741 		btf_verifier_log_type(env, t, "Invalid name");
4742 		return -EINVAL;
4743 	}
4744 
4745 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4746 		btf_verifier_log_type(env, t, "Invalid func linkage");
4747 		return -EINVAL;
4748 	}
4749 
4750 	if (btf_type_kflag(t)) {
4751 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4752 		return -EINVAL;
4753 	}
4754 
4755 	btf_verifier_log_type(env, t, NULL);
4756 
4757 	return 0;
4758 }
4759 
btf_func_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)4760 static int btf_func_resolve(struct btf_verifier_env *env,
4761 			    const struct resolve_vertex *v)
4762 {
4763 	const struct btf_type *t = v->t;
4764 	u32 next_type_id = t->type;
4765 	int err;
4766 
4767 	err = btf_func_check(env, t);
4768 	if (err)
4769 		return err;
4770 
4771 	env_stack_pop_resolved(env, next_type_id, 0);
4772 	return 0;
4773 }
4774 
4775 static const struct btf_kind_operations func_ops = {
4776 	.check_meta = btf_func_check_meta,
4777 	.resolve = btf_func_resolve,
4778 	.check_member = btf_df_check_member,
4779 	.check_kflag_member = btf_df_check_kflag_member,
4780 	.log_details = btf_ref_type_log,
4781 	.show = btf_df_show,
4782 };
4783 
btf_var_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4784 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4785 			      const struct btf_type *t,
4786 			      u32 meta_left)
4787 {
4788 	const struct btf_var *var;
4789 	u32 meta_needed = sizeof(*var);
4790 
4791 	if (meta_left < meta_needed) {
4792 		btf_verifier_log_basic(env, t,
4793 				       "meta_left:%u meta_needed:%u",
4794 				       meta_left, meta_needed);
4795 		return -EINVAL;
4796 	}
4797 
4798 	if (btf_type_vlen(t)) {
4799 		btf_verifier_log_type(env, t, "vlen != 0");
4800 		return -EINVAL;
4801 	}
4802 
4803 	if (btf_type_kflag(t)) {
4804 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4805 		return -EINVAL;
4806 	}
4807 
4808 	if (!t->name_off ||
4809 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4810 		btf_verifier_log_type(env, t, "Invalid name");
4811 		return -EINVAL;
4812 	}
4813 
4814 	/* A var cannot be in type void */
4815 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4816 		btf_verifier_log_type(env, t, "Invalid type_id");
4817 		return -EINVAL;
4818 	}
4819 
4820 	var = btf_type_var(t);
4821 	if (var->linkage != BTF_VAR_STATIC &&
4822 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4823 		btf_verifier_log_type(env, t, "Linkage not supported");
4824 		return -EINVAL;
4825 	}
4826 
4827 	btf_verifier_log_type(env, t, NULL);
4828 
4829 	return meta_needed;
4830 }
4831 
btf_var_log(struct btf_verifier_env * env,const struct btf_type * t)4832 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4833 {
4834 	const struct btf_var *var = btf_type_var(t);
4835 
4836 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4837 }
4838 
4839 static const struct btf_kind_operations var_ops = {
4840 	.check_meta		= btf_var_check_meta,
4841 	.resolve		= btf_var_resolve,
4842 	.check_member		= btf_df_check_member,
4843 	.check_kflag_member	= btf_df_check_kflag_member,
4844 	.log_details		= btf_var_log,
4845 	.show			= btf_var_show,
4846 };
4847 
btf_datasec_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4848 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4849 				  const struct btf_type *t,
4850 				  u32 meta_left)
4851 {
4852 	const struct btf_var_secinfo *vsi;
4853 	u64 last_vsi_end_off = 0, sum = 0;
4854 	u32 i, meta_needed;
4855 
4856 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4857 	if (meta_left < meta_needed) {
4858 		btf_verifier_log_basic(env, t,
4859 				       "meta_left:%u meta_needed:%u",
4860 				       meta_left, meta_needed);
4861 		return -EINVAL;
4862 	}
4863 
4864 	if (!t->size) {
4865 		btf_verifier_log_type(env, t, "size == 0");
4866 		return -EINVAL;
4867 	}
4868 
4869 	if (btf_type_kflag(t)) {
4870 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4871 		return -EINVAL;
4872 	}
4873 
4874 	if (!t->name_off ||
4875 	    !btf_name_valid_section(env->btf, t->name_off)) {
4876 		btf_verifier_log_type(env, t, "Invalid name");
4877 		return -EINVAL;
4878 	}
4879 
4880 	btf_verifier_log_type(env, t, NULL);
4881 
4882 	for_each_vsi(i, t, vsi) {
4883 		/* A var cannot be in type void */
4884 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4885 			btf_verifier_log_vsi(env, t, vsi,
4886 					     "Invalid type_id");
4887 			return -EINVAL;
4888 		}
4889 
4890 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4891 			btf_verifier_log_vsi(env, t, vsi,
4892 					     "Invalid offset");
4893 			return -EINVAL;
4894 		}
4895 
4896 		if (!vsi->size || vsi->size > t->size) {
4897 			btf_verifier_log_vsi(env, t, vsi,
4898 					     "Invalid size");
4899 			return -EINVAL;
4900 		}
4901 
4902 		last_vsi_end_off = vsi->offset + vsi->size;
4903 		if (last_vsi_end_off > t->size) {
4904 			btf_verifier_log_vsi(env, t, vsi,
4905 					     "Invalid offset+size");
4906 			return -EINVAL;
4907 		}
4908 
4909 		btf_verifier_log_vsi(env, t, vsi, NULL);
4910 		sum += vsi->size;
4911 	}
4912 
4913 	if (t->size < sum) {
4914 		btf_verifier_log_type(env, t, "Invalid btf_info size");
4915 		return -EINVAL;
4916 	}
4917 
4918 	return meta_needed;
4919 }
4920 
btf_datasec_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)4921 static int btf_datasec_resolve(struct btf_verifier_env *env,
4922 			       const struct resolve_vertex *v)
4923 {
4924 	const struct btf_var_secinfo *vsi;
4925 	struct btf *btf = env->btf;
4926 	u16 i;
4927 
4928 	env->resolve_mode = RESOLVE_TBD;
4929 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
4930 		u32 var_type_id = vsi->type, type_id, type_size = 0;
4931 		const struct btf_type *var_type = btf_type_by_id(env->btf,
4932 								 var_type_id);
4933 		if (!var_type || !btf_type_is_var(var_type)) {
4934 			btf_verifier_log_vsi(env, v->t, vsi,
4935 					     "Not a VAR kind member");
4936 			return -EINVAL;
4937 		}
4938 
4939 		if (!env_type_is_resolve_sink(env, var_type) &&
4940 		    !env_type_is_resolved(env, var_type_id)) {
4941 			env_stack_set_next_member(env, i + 1);
4942 			return env_stack_push(env, var_type, var_type_id);
4943 		}
4944 
4945 		type_id = var_type->type;
4946 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
4947 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4948 			return -EINVAL;
4949 		}
4950 
4951 		if (vsi->size < type_size) {
4952 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4953 			return -EINVAL;
4954 		}
4955 	}
4956 
4957 	env_stack_pop_resolved(env, 0, 0);
4958 	return 0;
4959 }
4960 
btf_datasec_log(struct btf_verifier_env * env,const struct btf_type * t)4961 static void btf_datasec_log(struct btf_verifier_env *env,
4962 			    const struct btf_type *t)
4963 {
4964 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4965 }
4966 
btf_datasec_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4967 static void btf_datasec_show(const struct btf *btf,
4968 			     const struct btf_type *t, u32 type_id,
4969 			     void *data, u8 bits_offset,
4970 			     struct btf_show *show)
4971 {
4972 	const struct btf_var_secinfo *vsi;
4973 	const struct btf_type *var;
4974 	u32 i;
4975 
4976 	if (!btf_show_start_type(show, t, type_id, data))
4977 		return;
4978 
4979 	btf_show_type_value(show, "section (\"%s\") = {",
4980 			    __btf_name_by_offset(btf, t->name_off));
4981 	for_each_vsi(i, t, vsi) {
4982 		var = btf_type_by_id(btf, vsi->type);
4983 		if (i)
4984 			btf_show(show, ",");
4985 		btf_type_ops(var)->show(btf, var, vsi->type,
4986 					data + vsi->offset, bits_offset, show);
4987 	}
4988 	btf_show_end_type(show);
4989 }
4990 
4991 static const struct btf_kind_operations datasec_ops = {
4992 	.check_meta		= btf_datasec_check_meta,
4993 	.resolve		= btf_datasec_resolve,
4994 	.check_member		= btf_df_check_member,
4995 	.check_kflag_member	= btf_df_check_kflag_member,
4996 	.log_details		= btf_datasec_log,
4997 	.show			= btf_datasec_show,
4998 };
4999 
btf_float_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)5000 static s32 btf_float_check_meta(struct btf_verifier_env *env,
5001 				const struct btf_type *t,
5002 				u32 meta_left)
5003 {
5004 	if (btf_type_vlen(t)) {
5005 		btf_verifier_log_type(env, t, "vlen != 0");
5006 		return -EINVAL;
5007 	}
5008 
5009 	if (btf_type_kflag(t)) {
5010 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5011 		return -EINVAL;
5012 	}
5013 
5014 	if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
5015 	    t->size != 16) {
5016 		btf_verifier_log_type(env, t, "Invalid type_size");
5017 		return -EINVAL;
5018 	}
5019 
5020 	btf_verifier_log_type(env, t, NULL);
5021 
5022 	return 0;
5023 }
5024 
btf_float_check_member(struct btf_verifier_env * env,const struct btf_type * struct_type,const struct btf_member * member,const struct btf_type * member_type)5025 static int btf_float_check_member(struct btf_verifier_env *env,
5026 				  const struct btf_type *struct_type,
5027 				  const struct btf_member *member,
5028 				  const struct btf_type *member_type)
5029 {
5030 	u64 start_offset_bytes;
5031 	u64 end_offset_bytes;
5032 	u64 misalign_bits;
5033 	u64 align_bytes;
5034 	u64 align_bits;
5035 
5036 	/* Different architectures have different alignment requirements, so
5037 	 * here we check only for the reasonable minimum. This way we ensure
5038 	 * that types after CO-RE can pass the kernel BTF verifier.
5039 	 */
5040 	align_bytes = min_t(u64, sizeof(void *), member_type->size);
5041 	align_bits = align_bytes * BITS_PER_BYTE;
5042 	div64_u64_rem(member->offset, align_bits, &misalign_bits);
5043 	if (misalign_bits) {
5044 		btf_verifier_log_member(env, struct_type, member,
5045 					"Member is not properly aligned");
5046 		return -EINVAL;
5047 	}
5048 
5049 	start_offset_bytes = member->offset / BITS_PER_BYTE;
5050 	end_offset_bytes = start_offset_bytes + member_type->size;
5051 	if (end_offset_bytes > struct_type->size) {
5052 		btf_verifier_log_member(env, struct_type, member,
5053 					"Member exceeds struct_size");
5054 		return -EINVAL;
5055 	}
5056 
5057 	return 0;
5058 }
5059 
btf_float_log(struct btf_verifier_env * env,const struct btf_type * t)5060 static void btf_float_log(struct btf_verifier_env *env,
5061 			  const struct btf_type *t)
5062 {
5063 	btf_verifier_log(env, "size=%u", t->size);
5064 }
5065 
5066 static const struct btf_kind_operations float_ops = {
5067 	.check_meta = btf_float_check_meta,
5068 	.resolve = btf_df_resolve,
5069 	.check_member = btf_float_check_member,
5070 	.check_kflag_member = btf_generic_check_kflag_member,
5071 	.log_details = btf_float_log,
5072 	.show = btf_df_show,
5073 };
5074 
btf_decl_tag_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)5075 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
5076 			      const struct btf_type *t,
5077 			      u32 meta_left)
5078 {
5079 	const struct btf_decl_tag *tag;
5080 	u32 meta_needed = sizeof(*tag);
5081 	s32 component_idx;
5082 	const char *value;
5083 
5084 	if (meta_left < meta_needed) {
5085 		btf_verifier_log_basic(env, t,
5086 				       "meta_left:%u meta_needed:%u",
5087 				       meta_left, meta_needed);
5088 		return -EINVAL;
5089 	}
5090 
5091 	value = btf_name_by_offset(env->btf, t->name_off);
5092 	if (!value || !value[0]) {
5093 		btf_verifier_log_type(env, t, "Invalid value");
5094 		return -EINVAL;
5095 	}
5096 
5097 	if (btf_type_vlen(t)) {
5098 		btf_verifier_log_type(env, t, "vlen != 0");
5099 		return -EINVAL;
5100 	}
5101 
5102 	component_idx = btf_type_decl_tag(t)->component_idx;
5103 	if (component_idx < -1) {
5104 		btf_verifier_log_type(env, t, "Invalid component_idx");
5105 		return -EINVAL;
5106 	}
5107 
5108 	btf_verifier_log_type(env, t, NULL);
5109 
5110 	return meta_needed;
5111 }
5112 
btf_decl_tag_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)5113 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
5114 			   const struct resolve_vertex *v)
5115 {
5116 	const struct btf_type *next_type;
5117 	const struct btf_type *t = v->t;
5118 	u32 next_type_id = t->type;
5119 	struct btf *btf = env->btf;
5120 	s32 component_idx;
5121 	u32 vlen;
5122 
5123 	next_type = btf_type_by_id(btf, next_type_id);
5124 	if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
5125 		btf_verifier_log_type(env, v->t, "Invalid type_id");
5126 		return -EINVAL;
5127 	}
5128 
5129 	if (!env_type_is_resolve_sink(env, next_type) &&
5130 	    !env_type_is_resolved(env, next_type_id))
5131 		return env_stack_push(env, next_type, next_type_id);
5132 
5133 	component_idx = btf_type_decl_tag(t)->component_idx;
5134 	if (component_idx != -1) {
5135 		if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
5136 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5137 			return -EINVAL;
5138 		}
5139 
5140 		if (btf_type_is_struct(next_type)) {
5141 			vlen = btf_type_vlen(next_type);
5142 		} else {
5143 			/* next_type should be a function */
5144 			next_type = btf_type_by_id(btf, next_type->type);
5145 			vlen = btf_type_vlen(next_type);
5146 		}
5147 
5148 		if ((u32)component_idx >= vlen) {
5149 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5150 			return -EINVAL;
5151 		}
5152 	}
5153 
5154 	env_stack_pop_resolved(env, next_type_id, 0);
5155 
5156 	return 0;
5157 }
5158 
btf_decl_tag_log(struct btf_verifier_env * env,const struct btf_type * t)5159 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
5160 {
5161 	btf_verifier_log(env, "type=%u component_idx=%d", t->type,
5162 			 btf_type_decl_tag(t)->component_idx);
5163 }
5164 
5165 static const struct btf_kind_operations decl_tag_ops = {
5166 	.check_meta = btf_decl_tag_check_meta,
5167 	.resolve = btf_decl_tag_resolve,
5168 	.check_member = btf_df_check_member,
5169 	.check_kflag_member = btf_df_check_kflag_member,
5170 	.log_details = btf_decl_tag_log,
5171 	.show = btf_df_show,
5172 };
5173 
btf_func_proto_check(struct btf_verifier_env * env,const struct btf_type * t)5174 static int btf_func_proto_check(struct btf_verifier_env *env,
5175 				const struct btf_type *t)
5176 {
5177 	const struct btf_type *ret_type;
5178 	const struct btf_param *args;
5179 	const struct btf *btf;
5180 	u16 nr_args, i;
5181 	int err;
5182 
5183 	btf = env->btf;
5184 	args = (const struct btf_param *)(t + 1);
5185 	nr_args = btf_type_vlen(t);
5186 
5187 	/* Check func return type which could be "void" (t->type == 0) */
5188 	if (t->type) {
5189 		u32 ret_type_id = t->type;
5190 
5191 		ret_type = btf_type_by_id(btf, ret_type_id);
5192 		if (!ret_type) {
5193 			btf_verifier_log_type(env, t, "Invalid return type");
5194 			return -EINVAL;
5195 		}
5196 
5197 		if (btf_type_is_resolve_source_only(ret_type)) {
5198 			btf_verifier_log_type(env, t, "Invalid return type");
5199 			return -EINVAL;
5200 		}
5201 
5202 		if (btf_type_needs_resolve(ret_type) &&
5203 		    !env_type_is_resolved(env, ret_type_id)) {
5204 			err = btf_resolve(env, ret_type, ret_type_id);
5205 			if (err)
5206 				return err;
5207 		}
5208 
5209 		/* Ensure the return type is a type that has a size */
5210 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
5211 			btf_verifier_log_type(env, t, "Invalid return type");
5212 			return -EINVAL;
5213 		}
5214 	}
5215 
5216 	if (!nr_args)
5217 		return 0;
5218 
5219 	/* Last func arg type_id could be 0 if it is a vararg */
5220 	if (!args[nr_args - 1].type) {
5221 		if (args[nr_args - 1].name_off) {
5222 			btf_verifier_log_type(env, t, "Invalid arg#%u",
5223 					      nr_args);
5224 			return -EINVAL;
5225 		}
5226 		nr_args--;
5227 	}
5228 
5229 	for (i = 0; i < nr_args; i++) {
5230 		const struct btf_type *arg_type;
5231 		u32 arg_type_id;
5232 
5233 		arg_type_id = args[i].type;
5234 		arg_type = btf_type_by_id(btf, arg_type_id);
5235 		if (!arg_type) {
5236 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5237 			return -EINVAL;
5238 		}
5239 
5240 		if (btf_type_is_resolve_source_only(arg_type)) {
5241 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5242 			return -EINVAL;
5243 		}
5244 
5245 		if (args[i].name_off &&
5246 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
5247 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
5248 			btf_verifier_log_type(env, t,
5249 					      "Invalid arg#%u", i + 1);
5250 			return -EINVAL;
5251 		}
5252 
5253 		if (btf_type_needs_resolve(arg_type) &&
5254 		    !env_type_is_resolved(env, arg_type_id)) {
5255 			err = btf_resolve(env, arg_type, arg_type_id);
5256 			if (err)
5257 				return err;
5258 		}
5259 
5260 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
5261 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5262 			return -EINVAL;
5263 		}
5264 	}
5265 
5266 	return 0;
5267 }
5268 
btf_func_check(struct btf_verifier_env * env,const struct btf_type * t)5269 static int btf_func_check(struct btf_verifier_env *env,
5270 			  const struct btf_type *t)
5271 {
5272 	const struct btf_type *proto_type;
5273 	const struct btf_param *args;
5274 	const struct btf *btf;
5275 	u16 nr_args, i;
5276 
5277 	btf = env->btf;
5278 	proto_type = btf_type_by_id(btf, t->type);
5279 
5280 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
5281 		btf_verifier_log_type(env, t, "Invalid type_id");
5282 		return -EINVAL;
5283 	}
5284 
5285 	args = (const struct btf_param *)(proto_type + 1);
5286 	nr_args = btf_type_vlen(proto_type);
5287 	for (i = 0; i < nr_args; i++) {
5288 		if (!args[i].name_off && args[i].type) {
5289 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5290 			return -EINVAL;
5291 		}
5292 	}
5293 
5294 	return 0;
5295 }
5296 
5297 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5298 	[BTF_KIND_INT] = &int_ops,
5299 	[BTF_KIND_PTR] = &ptr_ops,
5300 	[BTF_KIND_ARRAY] = &array_ops,
5301 	[BTF_KIND_STRUCT] = &struct_ops,
5302 	[BTF_KIND_UNION] = &struct_ops,
5303 	[BTF_KIND_ENUM] = &enum_ops,
5304 	[BTF_KIND_FWD] = &fwd_ops,
5305 	[BTF_KIND_TYPEDEF] = &modifier_ops,
5306 	[BTF_KIND_VOLATILE] = &modifier_ops,
5307 	[BTF_KIND_CONST] = &modifier_ops,
5308 	[BTF_KIND_RESTRICT] = &modifier_ops,
5309 	[BTF_KIND_FUNC] = &func_ops,
5310 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5311 	[BTF_KIND_VAR] = &var_ops,
5312 	[BTF_KIND_DATASEC] = &datasec_ops,
5313 	[BTF_KIND_FLOAT] = &float_ops,
5314 	[BTF_KIND_DECL_TAG] = &decl_tag_ops,
5315 	[BTF_KIND_TYPE_TAG] = &modifier_ops,
5316 	[BTF_KIND_ENUM64] = &enum64_ops,
5317 };
5318 
btf_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)5319 static s32 btf_check_meta(struct btf_verifier_env *env,
5320 			  const struct btf_type *t,
5321 			  u32 meta_left)
5322 {
5323 	u32 saved_meta_left = meta_left;
5324 	s32 var_meta_size;
5325 
5326 	if (meta_left < sizeof(*t)) {
5327 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5328 				 env->log_type_id, meta_left, sizeof(*t));
5329 		return -EINVAL;
5330 	}
5331 	meta_left -= sizeof(*t);
5332 
5333 	if (t->info & ~BTF_INFO_MASK) {
5334 		btf_verifier_log(env, "[%u] Invalid btf_info:%x",
5335 				 env->log_type_id, t->info);
5336 		return -EINVAL;
5337 	}
5338 
5339 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5340 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5341 		btf_verifier_log(env, "[%u] Invalid kind:%u",
5342 				 env->log_type_id, BTF_INFO_KIND(t->info));
5343 		return -EINVAL;
5344 	}
5345 
5346 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
5347 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5348 				 env->log_type_id, t->name_off);
5349 		return -EINVAL;
5350 	}
5351 
5352 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5353 	if (var_meta_size < 0)
5354 		return var_meta_size;
5355 
5356 	meta_left -= var_meta_size;
5357 
5358 	return saved_meta_left - meta_left;
5359 }
5360 
btf_check_all_metas(struct btf_verifier_env * env)5361 static int btf_check_all_metas(struct btf_verifier_env *env)
5362 {
5363 	struct btf *btf = env->btf;
5364 	struct btf_header *hdr;
5365 	void *cur, *end;
5366 
5367 	hdr = &btf->hdr;
5368 	cur = btf->nohdr_data + hdr->type_off;
5369 	end = cur + hdr->type_len;
5370 
5371 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
5372 	while (cur < end) {
5373 		struct btf_type *t = cur;
5374 		s32 meta_size;
5375 
5376 		meta_size = btf_check_meta(env, t, end - cur);
5377 		if (meta_size < 0)
5378 			return meta_size;
5379 
5380 		btf_add_type(env, t);
5381 		cur += meta_size;
5382 		env->log_type_id++;
5383 	}
5384 
5385 	return 0;
5386 }
5387 
btf_resolve_valid(struct btf_verifier_env * env,const struct btf_type * t,u32 type_id)5388 static bool btf_resolve_valid(struct btf_verifier_env *env,
5389 			      const struct btf_type *t,
5390 			      u32 type_id)
5391 {
5392 	struct btf *btf = env->btf;
5393 
5394 	if (!env_type_is_resolved(env, type_id))
5395 		return false;
5396 
5397 	if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5398 		return !btf_resolved_type_id(btf, type_id) &&
5399 		       !btf_resolved_type_size(btf, type_id);
5400 
5401 	if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5402 		return btf_resolved_type_id(btf, type_id) &&
5403 		       !btf_resolved_type_size(btf, type_id);
5404 
5405 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5406 	    btf_type_is_var(t)) {
5407 		t = btf_type_id_resolve(btf, &type_id);
5408 		return t &&
5409 		       !btf_type_is_modifier(t) &&
5410 		       !btf_type_is_var(t) &&
5411 		       !btf_type_is_datasec(t);
5412 	}
5413 
5414 	if (btf_type_is_array(t)) {
5415 		const struct btf_array *array = btf_type_array(t);
5416 		const struct btf_type *elem_type;
5417 		u32 elem_type_id = array->type;
5418 		u32 elem_size;
5419 
5420 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5421 		return elem_type && !btf_type_is_modifier(elem_type) &&
5422 			(array->nelems * elem_size ==
5423 			 btf_resolved_type_size(btf, type_id));
5424 	}
5425 
5426 	return false;
5427 }
5428 
btf_resolve(struct btf_verifier_env * env,const struct btf_type * t,u32 type_id)5429 static int btf_resolve(struct btf_verifier_env *env,
5430 		       const struct btf_type *t, u32 type_id)
5431 {
5432 	u32 save_log_type_id = env->log_type_id;
5433 	const struct resolve_vertex *v;
5434 	int err = 0;
5435 
5436 	env->resolve_mode = RESOLVE_TBD;
5437 	env_stack_push(env, t, type_id);
5438 	while (!err && (v = env_stack_peak(env))) {
5439 		env->log_type_id = v->type_id;
5440 		err = btf_type_ops(v->t)->resolve(env, v);
5441 	}
5442 
5443 	env->log_type_id = type_id;
5444 	if (err == -E2BIG) {
5445 		btf_verifier_log_type(env, t,
5446 				      "Exceeded max resolving depth:%u",
5447 				      MAX_RESOLVE_DEPTH);
5448 	} else if (err == -EEXIST) {
5449 		btf_verifier_log_type(env, t, "Loop detected");
5450 	}
5451 
5452 	/* Final sanity check */
5453 	if (!err && !btf_resolve_valid(env, t, type_id)) {
5454 		btf_verifier_log_type(env, t, "Invalid resolve state");
5455 		err = -EINVAL;
5456 	}
5457 
5458 	env->log_type_id = save_log_type_id;
5459 	return err;
5460 }
5461 
btf_check_all_types(struct btf_verifier_env * env)5462 static int btf_check_all_types(struct btf_verifier_env *env)
5463 {
5464 	struct btf *btf = env->btf;
5465 	const struct btf_type *t;
5466 	u32 type_id, i;
5467 	int err;
5468 
5469 	err = env_resolve_init(env);
5470 	if (err)
5471 		return err;
5472 
5473 	env->phase++;
5474 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5475 		type_id = btf->start_id + i;
5476 		t = btf_type_by_id(btf, type_id);
5477 
5478 		env->log_type_id = type_id;
5479 		if (btf_type_needs_resolve(t) &&
5480 		    !env_type_is_resolved(env, type_id)) {
5481 			err = btf_resolve(env, t, type_id);
5482 			if (err)
5483 				return err;
5484 		}
5485 
5486 		if (btf_type_is_func_proto(t)) {
5487 			err = btf_func_proto_check(env, t);
5488 			if (err)
5489 				return err;
5490 		}
5491 	}
5492 
5493 	return 0;
5494 }
5495 
btf_parse_type_sec(struct btf_verifier_env * env)5496 static int btf_parse_type_sec(struct btf_verifier_env *env)
5497 {
5498 	const struct btf_header *hdr = &env->btf->hdr;
5499 	int err;
5500 
5501 	/* Type section must align to 4 bytes */
5502 	if (hdr->type_off & (sizeof(u32) - 1)) {
5503 		btf_verifier_log(env, "Unaligned type_off");
5504 		return -EINVAL;
5505 	}
5506 
5507 	if (!env->btf->base_btf && !hdr->type_len) {
5508 		btf_verifier_log(env, "No type found");
5509 		return -EINVAL;
5510 	}
5511 
5512 	err = btf_check_all_metas(env);
5513 	if (err)
5514 		return err;
5515 
5516 	return btf_check_all_types(env);
5517 }
5518 
btf_parse_str_sec(struct btf_verifier_env * env)5519 static int btf_parse_str_sec(struct btf_verifier_env *env)
5520 {
5521 	const struct btf_header *hdr;
5522 	struct btf *btf = env->btf;
5523 	const char *start, *end;
5524 
5525 	hdr = &btf->hdr;
5526 	start = btf->nohdr_data + hdr->str_off;
5527 	end = start + hdr->str_len;
5528 
5529 	if (end != btf->data + btf->data_size) {
5530 		btf_verifier_log(env, "String section is not at the end");
5531 		return -EINVAL;
5532 	}
5533 
5534 	btf->strings = start;
5535 
5536 	if (btf->base_btf && !hdr->str_len)
5537 		return 0;
5538 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5539 		btf_verifier_log(env, "Invalid string section");
5540 		return -EINVAL;
5541 	}
5542 	if (!btf->base_btf && start[0]) {
5543 		btf_verifier_log(env, "Invalid string section");
5544 		return -EINVAL;
5545 	}
5546 
5547 	return 0;
5548 }
5549 
5550 static const size_t btf_sec_info_offset[] = {
5551 	offsetof(struct btf_header, type_off),
5552 	offsetof(struct btf_header, str_off),
5553 };
5554 
btf_sec_info_cmp(const void * a,const void * b)5555 static int btf_sec_info_cmp(const void *a, const void *b)
5556 {
5557 	const struct btf_sec_info *x = a;
5558 	const struct btf_sec_info *y = b;
5559 
5560 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5561 }
5562 
btf_check_sec_info(struct btf_verifier_env * env,u32 btf_data_size)5563 static int btf_check_sec_info(struct btf_verifier_env *env,
5564 			      u32 btf_data_size)
5565 {
5566 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5567 	u32 total, expected_total, i;
5568 	const struct btf_header *hdr;
5569 	const struct btf *btf;
5570 
5571 	btf = env->btf;
5572 	hdr = &btf->hdr;
5573 
5574 	/* Populate the secs from hdr */
5575 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5576 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
5577 						   btf_sec_info_offset[i]);
5578 
5579 	sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5580 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5581 
5582 	/* Check for gaps and overlap among sections */
5583 	total = 0;
5584 	expected_total = btf_data_size - hdr->hdr_len;
5585 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5586 		if (expected_total < secs[i].off) {
5587 			btf_verifier_log(env, "Invalid section offset");
5588 			return -EINVAL;
5589 		}
5590 		if (total < secs[i].off) {
5591 			/* gap */
5592 			btf_verifier_log(env, "Unsupported section found");
5593 			return -EINVAL;
5594 		}
5595 		if (total > secs[i].off) {
5596 			btf_verifier_log(env, "Section overlap found");
5597 			return -EINVAL;
5598 		}
5599 		if (expected_total - total < secs[i].len) {
5600 			btf_verifier_log(env,
5601 					 "Total section length too long");
5602 			return -EINVAL;
5603 		}
5604 		total += secs[i].len;
5605 	}
5606 
5607 	/* There is data other than hdr and known sections */
5608 	if (expected_total != total) {
5609 		btf_verifier_log(env, "Unsupported section found");
5610 		return -EINVAL;
5611 	}
5612 
5613 	return 0;
5614 }
5615 
btf_parse_hdr(struct btf_verifier_env * env)5616 static int btf_parse_hdr(struct btf_verifier_env *env)
5617 {
5618 	u32 hdr_len, hdr_copy, btf_data_size;
5619 	const struct btf_header *hdr;
5620 	struct btf *btf;
5621 
5622 	btf = env->btf;
5623 	btf_data_size = btf->data_size;
5624 
5625 	if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5626 		btf_verifier_log(env, "hdr_len not found");
5627 		return -EINVAL;
5628 	}
5629 
5630 	hdr = btf->data;
5631 	hdr_len = hdr->hdr_len;
5632 	if (btf_data_size < hdr_len) {
5633 		btf_verifier_log(env, "btf_header not found");
5634 		return -EINVAL;
5635 	}
5636 
5637 	/* Ensure the unsupported header fields are zero */
5638 	if (hdr_len > sizeof(btf->hdr)) {
5639 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
5640 		u8 *end = btf->data + hdr_len;
5641 
5642 		for (; expected_zero < end; expected_zero++) {
5643 			if (*expected_zero) {
5644 				btf_verifier_log(env, "Unsupported btf_header");
5645 				return -E2BIG;
5646 			}
5647 		}
5648 	}
5649 
5650 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5651 	memcpy(&btf->hdr, btf->data, hdr_copy);
5652 
5653 	hdr = &btf->hdr;
5654 
5655 	btf_verifier_log_hdr(env, btf_data_size);
5656 
5657 	if (hdr->magic != BTF_MAGIC) {
5658 		btf_verifier_log(env, "Invalid magic");
5659 		return -EINVAL;
5660 	}
5661 
5662 	if (hdr->version != BTF_VERSION) {
5663 		btf_verifier_log(env, "Unsupported version");
5664 		return -ENOTSUPP;
5665 	}
5666 
5667 	if (hdr->flags) {
5668 		btf_verifier_log(env, "Unsupported flags");
5669 		return -ENOTSUPP;
5670 	}
5671 
5672 	if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5673 		btf_verifier_log(env, "No data");
5674 		return -EINVAL;
5675 	}
5676 
5677 	return btf_check_sec_info(env, btf_data_size);
5678 }
5679 
5680 static const char *alloc_obj_fields[] = {
5681 	"bpf_spin_lock",
5682 	"bpf_list_head",
5683 	"bpf_list_node",
5684 	"bpf_rb_root",
5685 	"bpf_rb_node",
5686 	"bpf_refcount",
5687 };
5688 
5689 static struct btf_struct_metas *
btf_parse_struct_metas(struct bpf_verifier_log * log,struct btf * btf)5690 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5691 {
5692 	struct btf_struct_metas *tab = NULL;
5693 	struct btf_id_set *aof;
5694 	int i, n, id, ret;
5695 
5696 	BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5697 	BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5698 
5699 	aof = kmalloc_obj(*aof, GFP_KERNEL | __GFP_NOWARN);
5700 	if (!aof)
5701 		return ERR_PTR(-ENOMEM);
5702 	aof->cnt = 0;
5703 
5704 	for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5705 		/* Try to find whether this special type exists in user BTF, and
5706 		 * if so remember its ID so we can easily find it among members
5707 		 * of structs that we iterate in the next loop.
5708 		 */
5709 		struct btf_id_set *new_aof;
5710 
5711 		id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5712 		if (id < 0)
5713 			continue;
5714 
5715 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
5716 				   GFP_KERNEL | __GFP_NOWARN);
5717 		if (!new_aof) {
5718 			ret = -ENOMEM;
5719 			goto free_aof;
5720 		}
5721 		aof = new_aof;
5722 		aof->ids[aof->cnt++] = id;
5723 	}
5724 
5725 	n = btf_nr_types(btf);
5726 	for (i = 1; i < n; i++) {
5727 		/* Try to find if there are kptrs in user BTF and remember their ID */
5728 		struct btf_id_set *new_aof;
5729 		struct btf_field_info tmp;
5730 		const struct btf_type *t;
5731 
5732 		t = btf_type_by_id(btf, i);
5733 		if (!t) {
5734 			ret = -EINVAL;
5735 			goto free_aof;
5736 		}
5737 
5738 		ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
5739 		if (ret != BTF_FIELD_FOUND)
5740 			continue;
5741 
5742 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
5743 				   GFP_KERNEL | __GFP_NOWARN);
5744 		if (!new_aof) {
5745 			ret = -ENOMEM;
5746 			goto free_aof;
5747 		}
5748 		aof = new_aof;
5749 		aof->ids[aof->cnt++] = i;
5750 	}
5751 
5752 	if (!aof->cnt) {
5753 		kfree(aof);
5754 		return NULL;
5755 	}
5756 	sort(&aof->ids, aof->cnt, sizeof(aof->ids[0]), btf_id_cmp_func, NULL);
5757 
5758 	for (i = 1; i < n; i++) {
5759 		struct btf_struct_metas *new_tab;
5760 		const struct btf_member *member;
5761 		struct btf_struct_meta *type;
5762 		struct btf_record *record;
5763 		const struct btf_type *t;
5764 		int j, tab_cnt;
5765 
5766 		t = btf_type_by_id(btf, i);
5767 		if (!__btf_type_is_struct(t))
5768 			continue;
5769 
5770 		cond_resched();
5771 
5772 		for_each_member(j, t, member) {
5773 			if (btf_id_set_contains(aof, member->type))
5774 				goto parse;
5775 		}
5776 		continue;
5777 	parse:
5778 		tab_cnt = tab ? tab->cnt : 0;
5779 		new_tab = krealloc(tab, struct_size(new_tab, types, tab_cnt + 1),
5780 				   GFP_KERNEL | __GFP_NOWARN);
5781 		if (!new_tab) {
5782 			ret = -ENOMEM;
5783 			goto free;
5784 		}
5785 		if (!tab)
5786 			new_tab->cnt = 0;
5787 		tab = new_tab;
5788 
5789 		type = &tab->types[tab->cnt];
5790 		type->btf_id = i;
5791 		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5792 						  BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
5793 						  BPF_KPTR, t->size);
5794 		/* The record cannot be unset, treat it as an error if so */
5795 		if (IS_ERR_OR_NULL(record)) {
5796 			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5797 			goto free;
5798 		}
5799 		type->record = record;
5800 		tab->cnt++;
5801 	}
5802 	kfree(aof);
5803 	return tab;
5804 free:
5805 	btf_struct_metas_free(tab);
5806 free_aof:
5807 	kfree(aof);
5808 	return ERR_PTR(ret);
5809 }
5810 
btf_find_struct_meta(const struct btf * btf,u32 btf_id)5811 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5812 {
5813 	struct btf_struct_metas *tab;
5814 
5815 	BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5816 	tab = btf->struct_meta_tab;
5817 	if (!tab)
5818 		return NULL;
5819 	return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5820 }
5821 
btf_check_type_tags(struct btf_verifier_env * env,struct btf * btf,int start_id)5822 static int btf_check_type_tags(struct btf_verifier_env *env,
5823 			       struct btf *btf, int start_id)
5824 {
5825 	int i, n, good_id = start_id - 1;
5826 	bool in_tags;
5827 
5828 	n = btf_nr_types(btf);
5829 	for (i = start_id; i < n; i++) {
5830 		const struct btf_type *t;
5831 		int chain_limit = 32;
5832 		u32 cur_id = i;
5833 
5834 		t = btf_type_by_id(btf, i);
5835 		if (!t)
5836 			return -EINVAL;
5837 		if (!btf_type_is_modifier(t))
5838 			continue;
5839 
5840 		cond_resched();
5841 
5842 		in_tags = btf_type_is_type_tag(t);
5843 		while (btf_type_is_modifier(t)) {
5844 			if (!chain_limit--) {
5845 				btf_verifier_log(env, "Max chain length or cycle detected");
5846 				return -ELOOP;
5847 			}
5848 			if (btf_type_is_type_tag(t)) {
5849 				if (!in_tags) {
5850 					btf_verifier_log(env, "Type tags don't precede modifiers");
5851 					return -EINVAL;
5852 				}
5853 			} else if (in_tags) {
5854 				in_tags = false;
5855 			}
5856 			if (cur_id <= good_id)
5857 				break;
5858 			/* Move to next type */
5859 			cur_id = t->type;
5860 			t = btf_type_by_id(btf, cur_id);
5861 			if (!t)
5862 				return -EINVAL;
5863 		}
5864 		good_id = i;
5865 	}
5866 	return 0;
5867 }
5868 
finalize_log(struct bpf_verifier_log * log,bpfptr_t uattr,u32 uattr_size)5869 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5870 {
5871 	u32 log_true_size;
5872 	int err;
5873 
5874 	err = bpf_vlog_finalize(log, &log_true_size);
5875 
5876 	if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5877 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5878 				  &log_true_size, sizeof(log_true_size)))
5879 		err = -EFAULT;
5880 
5881 	return err;
5882 }
5883 
btf_parse(const union bpf_attr * attr,bpfptr_t uattr,u32 uattr_size)5884 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5885 {
5886 	bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5887 	char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5888 	struct btf_struct_metas *struct_meta_tab;
5889 	struct btf_verifier_env *env = NULL;
5890 	struct btf *btf = NULL;
5891 	u8 *data;
5892 	int err, ret;
5893 
5894 	if (attr->btf_size > BTF_MAX_SIZE)
5895 		return ERR_PTR(-E2BIG);
5896 
5897 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
5898 	if (!env)
5899 		return ERR_PTR(-ENOMEM);
5900 
5901 	/* user could have requested verbose verifier output
5902 	 * and supplied buffer to store the verification trace
5903 	 */
5904 	err = bpf_vlog_init(&env->log, attr->btf_log_level,
5905 			    log_ubuf, attr->btf_log_size);
5906 	if (err)
5907 		goto errout_free;
5908 
5909 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
5910 	if (!btf) {
5911 		err = -ENOMEM;
5912 		goto errout;
5913 	}
5914 	env->btf = btf;
5915 	btf->named_start_id = 0;
5916 
5917 	data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5918 	if (!data) {
5919 		err = -ENOMEM;
5920 		goto errout;
5921 	}
5922 
5923 	btf->data = data;
5924 	btf->data_size = attr->btf_size;
5925 
5926 	if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5927 		err = -EFAULT;
5928 		goto errout;
5929 	}
5930 
5931 	err = btf_parse_hdr(env);
5932 	if (err)
5933 		goto errout;
5934 
5935 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5936 
5937 	err = btf_parse_str_sec(env);
5938 	if (err)
5939 		goto errout;
5940 
5941 	err = btf_parse_type_sec(env);
5942 	if (err)
5943 		goto errout;
5944 
5945 	err = btf_check_type_tags(env, btf, 1);
5946 	if (err)
5947 		goto errout;
5948 
5949 	struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5950 	if (IS_ERR(struct_meta_tab)) {
5951 		err = PTR_ERR(struct_meta_tab);
5952 		goto errout;
5953 	}
5954 	btf->struct_meta_tab = struct_meta_tab;
5955 
5956 	if (struct_meta_tab) {
5957 		int i;
5958 
5959 		for (i = 0; i < struct_meta_tab->cnt; i++) {
5960 			err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5961 			if (err < 0)
5962 				goto errout_meta;
5963 		}
5964 	}
5965 
5966 	err = finalize_log(&env->log, uattr, uattr_size);
5967 	if (err)
5968 		goto errout_free;
5969 
5970 	btf_verifier_env_free(env);
5971 	refcount_set(&btf->refcnt, 1);
5972 	return btf;
5973 
5974 errout_meta:
5975 	btf_free_struct_meta_tab(btf);
5976 errout:
5977 	/* overwrite err with -ENOSPC or -EFAULT */
5978 	ret = finalize_log(&env->log, uattr, uattr_size);
5979 	if (ret)
5980 		err = ret;
5981 errout_free:
5982 	btf_verifier_env_free(env);
5983 	if (btf)
5984 		btf_free(btf);
5985 	return ERR_PTR(err);
5986 }
5987 
5988 extern char __start_BTF[];
5989 extern char __stop_BTF[];
5990 extern struct btf *btf_vmlinux;
5991 
5992 #define BPF_MAP_TYPE(_id, _ops)
5993 #define BPF_LINK_TYPE(_id, _name)
5994 static union {
5995 	struct bpf_ctx_convert {
5996 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5997 	prog_ctx_type _id##_prog; \
5998 	kern_ctx_type _id##_kern;
5999 #include <linux/bpf_types.h>
6000 #undef BPF_PROG_TYPE
6001 	} *__t;
6002 	/* 't' is written once under lock. Read many times. */
6003 	const struct btf_type *t;
6004 } bpf_ctx_convert;
6005 enum {
6006 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6007 	__ctx_convert##_id,
6008 #include <linux/bpf_types.h>
6009 #undef BPF_PROG_TYPE
6010 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
6011 };
6012 static u8 bpf_ctx_convert_map[] = {
6013 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6014 	[_id] = __ctx_convert##_id,
6015 #include <linux/bpf_types.h>
6016 #undef BPF_PROG_TYPE
6017 	0, /* avoid empty array */
6018 };
6019 #undef BPF_MAP_TYPE
6020 #undef BPF_LINK_TYPE
6021 
find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)6022 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
6023 {
6024 	const struct btf_type *conv_struct;
6025 	const struct btf_member *ctx_type;
6026 
6027 	conv_struct = bpf_ctx_convert.t;
6028 	if (!conv_struct)
6029 		return NULL;
6030 	/* prog_type is valid bpf program type. No need for bounds check. */
6031 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
6032 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6033 	 * Like 'struct __sk_buff'
6034 	 */
6035 	return btf_type_by_id(btf_vmlinux, ctx_type->type);
6036 }
6037 
find_kern_ctx_type_id(enum bpf_prog_type prog_type)6038 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
6039 {
6040 	const struct btf_type *conv_struct;
6041 	const struct btf_member *ctx_type;
6042 
6043 	conv_struct = bpf_ctx_convert.t;
6044 	if (!conv_struct)
6045 		return -EFAULT;
6046 	/* prog_type is valid bpf program type. No need for bounds check. */
6047 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6048 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6049 	 * Like 'struct sk_buff'
6050 	 */
6051 	return ctx_type->type;
6052 }
6053 
btf_is_projection_of(const char * pname,const char * tname)6054 bool btf_is_projection_of(const char *pname, const char *tname)
6055 {
6056 	if (strcmp(pname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
6057 		return true;
6058 	if (strcmp(pname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
6059 		return true;
6060 	return false;
6061 }
6062 
btf_is_prog_ctx_type(struct bpf_verifier_log * log,const struct btf * btf,const struct btf_type * t,enum bpf_prog_type prog_type,int arg)6063 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6064 			  const struct btf_type *t, enum bpf_prog_type prog_type,
6065 			  int arg)
6066 {
6067 	const struct btf_type *ctx_type;
6068 	const char *tname, *ctx_tname;
6069 
6070 	t = btf_type_by_id(btf, t->type);
6071 
6072 	/* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
6073 	 * check before we skip all the typedef below.
6074 	 */
6075 	if (prog_type == BPF_PROG_TYPE_KPROBE) {
6076 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6077 			t = btf_type_by_id(btf, t->type);
6078 
6079 		if (btf_type_is_typedef(t)) {
6080 			tname = btf_name_by_offset(btf, t->name_off);
6081 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6082 				return true;
6083 		}
6084 	}
6085 
6086 	while (btf_type_is_modifier(t))
6087 		t = btf_type_by_id(btf, t->type);
6088 	if (!btf_type_is_struct(t)) {
6089 		/* Only pointer to struct is supported for now.
6090 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
6091 		 * is not supported yet.
6092 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
6093 		 */
6094 		return false;
6095 	}
6096 	tname = btf_name_by_offset(btf, t->name_off);
6097 	if (!tname) {
6098 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
6099 		return false;
6100 	}
6101 
6102 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6103 	if (!ctx_type) {
6104 		bpf_log(log, "btf_vmlinux is malformed\n");
6105 		/* should not happen */
6106 		return false;
6107 	}
6108 again:
6109 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6110 	if (!ctx_tname) {
6111 		/* should not happen */
6112 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
6113 		return false;
6114 	}
6115 	/* program types without named context types work only with arg:ctx tag */
6116 	if (ctx_tname[0] == '\0')
6117 		return false;
6118 	/* only compare that prog's ctx type name is the same as
6119 	 * kernel expects. No need to compare field by field.
6120 	 * It's ok for bpf prog to do:
6121 	 * struct __sk_buff {};
6122 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
6123 	 * { // no fields of skb are ever used }
6124 	 */
6125 	if (btf_is_projection_of(ctx_tname, tname))
6126 		return true;
6127 	if (strcmp(ctx_tname, tname)) {
6128 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
6129 		 * underlying struct and check name again
6130 		 */
6131 		if (!btf_type_is_modifier(ctx_type))
6132 			return false;
6133 		while (btf_type_is_modifier(ctx_type))
6134 			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6135 		goto again;
6136 	}
6137 	return true;
6138 }
6139 
6140 /* forward declarations for arch-specific underlying types of
6141  * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
6142  * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
6143  * works correctly with __builtin_types_compatible_p() on respective
6144  * architectures
6145  */
6146 struct user_regs_struct;
6147 struct user_pt_regs;
6148 
btf_validate_prog_ctx_type(struct bpf_verifier_log * log,const struct btf * btf,const struct btf_type * t,int arg,enum bpf_prog_type prog_type,enum bpf_attach_type attach_type)6149 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6150 				      const struct btf_type *t, int arg,
6151 				      enum bpf_prog_type prog_type,
6152 				      enum bpf_attach_type attach_type)
6153 {
6154 	const struct btf_type *ctx_type;
6155 	const char *tname, *ctx_tname;
6156 
6157 	if (!btf_is_ptr(t)) {
6158 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
6159 		return -EINVAL;
6160 	}
6161 	t = btf_type_by_id(btf, t->type);
6162 
6163 	/* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
6164 	if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
6165 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6166 			t = btf_type_by_id(btf, t->type);
6167 
6168 		if (btf_type_is_typedef(t)) {
6169 			tname = btf_name_by_offset(btf, t->name_off);
6170 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6171 				return 0;
6172 		}
6173 	}
6174 
6175 	/* all other program types don't use typedefs for context type */
6176 	while (btf_type_is_modifier(t))
6177 		t = btf_type_by_id(btf, t->type);
6178 
6179 	/* `void *ctx __arg_ctx` is always valid */
6180 	if (btf_type_is_void(t))
6181 		return 0;
6182 
6183 	tname = btf_name_by_offset(btf, t->name_off);
6184 	if (str_is_empty(tname)) {
6185 		bpf_log(log, "arg#%d type doesn't have a name\n", arg);
6186 		return -EINVAL;
6187 	}
6188 
6189 	/* special cases */
6190 	switch (prog_type) {
6191 	case BPF_PROG_TYPE_KPROBE:
6192 		if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6193 			return 0;
6194 		break;
6195 	case BPF_PROG_TYPE_PERF_EVENT:
6196 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6197 		    __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6198 			return 0;
6199 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6200 		    __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6201 			return 0;
6202 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6203 		    __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6204 			return 0;
6205 		break;
6206 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6207 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6208 		/* allow u64* as ctx */
6209 		if (btf_is_int(t) && t->size == 8)
6210 			return 0;
6211 		break;
6212 	case BPF_PROG_TYPE_TRACING:
6213 		switch (attach_type) {
6214 		case BPF_TRACE_RAW_TP:
6215 			/* tp_btf program is TRACING, so need special case here */
6216 			if (__btf_type_is_struct(t) &&
6217 			    strcmp(tname, "bpf_raw_tracepoint_args") == 0)
6218 				return 0;
6219 			/* allow u64* as ctx */
6220 			if (btf_is_int(t) && t->size == 8)
6221 				return 0;
6222 			break;
6223 		case BPF_TRACE_ITER:
6224 			/* allow struct bpf_iter__xxx types only */
6225 			if (__btf_type_is_struct(t) &&
6226 			    strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
6227 				return 0;
6228 			break;
6229 		case BPF_TRACE_FENTRY:
6230 		case BPF_TRACE_FEXIT:
6231 		case BPF_MODIFY_RETURN:
6232 		case BPF_TRACE_FSESSION:
6233 			/* allow u64* as ctx */
6234 			if (btf_is_int(t) && t->size == 8)
6235 				return 0;
6236 			break;
6237 		default:
6238 			break;
6239 		}
6240 		break;
6241 	case BPF_PROG_TYPE_LSM:
6242 	case BPF_PROG_TYPE_STRUCT_OPS:
6243 		/* allow u64* as ctx */
6244 		if (btf_is_int(t) && t->size == 8)
6245 			return 0;
6246 		break;
6247 	case BPF_PROG_TYPE_TRACEPOINT:
6248 	case BPF_PROG_TYPE_SYSCALL:
6249 	case BPF_PROG_TYPE_EXT:
6250 		return 0; /* anything goes */
6251 	default:
6252 		break;
6253 	}
6254 
6255 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6256 	if (!ctx_type) {
6257 		/* should not happen */
6258 		bpf_log(log, "btf_vmlinux is malformed\n");
6259 		return -EINVAL;
6260 	}
6261 
6262 	/* resolve typedefs and check that underlying structs are matching as well */
6263 	while (btf_type_is_modifier(ctx_type))
6264 		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6265 
6266 	/* if program type doesn't have distinctly named struct type for
6267 	 * context, then __arg_ctx argument can only be `void *`, which we
6268 	 * already checked above
6269 	 */
6270 	if (!__btf_type_is_struct(ctx_type)) {
6271 		bpf_log(log, "arg#%d should be void pointer\n", arg);
6272 		return -EINVAL;
6273 	}
6274 
6275 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6276 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6277 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6278 		return -EINVAL;
6279 	}
6280 
6281 	return 0;
6282 }
6283 
btf_translate_to_vmlinux(struct bpf_verifier_log * log,struct btf * btf,const struct btf_type * t,enum bpf_prog_type prog_type,int arg)6284 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6285 				     struct btf *btf,
6286 				     const struct btf_type *t,
6287 				     enum bpf_prog_type prog_type,
6288 				     int arg)
6289 {
6290 	if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6291 		return -ENOENT;
6292 	return find_kern_ctx_type_id(prog_type);
6293 }
6294 
get_kern_ctx_btf_id(struct bpf_verifier_log * log,enum bpf_prog_type prog_type)6295 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6296 {
6297 	const struct btf_member *kctx_member;
6298 	const struct btf_type *conv_struct;
6299 	const struct btf_type *kctx_type;
6300 	u32 kctx_type_id;
6301 
6302 	conv_struct = bpf_ctx_convert.t;
6303 	/* get member for kernel ctx type */
6304 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6305 	kctx_type_id = kctx_member->type;
6306 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6307 	if (!btf_type_is_struct(kctx_type)) {
6308 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6309 		return -EINVAL;
6310 	}
6311 
6312 	return kctx_type_id;
6313 }
6314 
BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id,struct,bpf_ctx_convert)6315 BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id, struct, bpf_ctx_convert)
6316 
6317 static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,
6318 				  void *data, unsigned int data_size)
6319 {
6320 	struct btf *btf = NULL;
6321 	int err;
6322 
6323 	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6324 		return ERR_PTR(-ENOENT);
6325 
6326 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6327 	if (!btf) {
6328 		err = -ENOMEM;
6329 		goto errout;
6330 	}
6331 	env->btf = btf;
6332 
6333 	btf->data = data;
6334 	btf->data_size = data_size;
6335 	btf->kernel_btf = true;
6336 	btf->named_start_id = 0;
6337 	strscpy(btf->name, name);
6338 
6339 	err = btf_parse_hdr(env);
6340 	if (err)
6341 		goto errout;
6342 
6343 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6344 
6345 	err = btf_parse_str_sec(env);
6346 	if (err)
6347 		goto errout;
6348 
6349 	err = btf_check_all_metas(env);
6350 	if (err)
6351 		goto errout;
6352 
6353 	err = btf_check_type_tags(env, btf, 1);
6354 	if (err)
6355 		goto errout;
6356 
6357 	btf_check_sorted(btf);
6358 	refcount_set(&btf->refcnt, 1);
6359 
6360 	return btf;
6361 
6362 errout:
6363 	if (btf) {
6364 		kvfree(btf->types);
6365 		kfree(btf);
6366 	}
6367 	return ERR_PTR(err);
6368 }
6369 
btf_parse_vmlinux(void)6370 struct btf *btf_parse_vmlinux(void)
6371 {
6372 	struct btf_verifier_env *env = NULL;
6373 	struct bpf_verifier_log *log;
6374 	struct btf *btf;
6375 	int err;
6376 
6377 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6378 	if (!env)
6379 		return ERR_PTR(-ENOMEM);
6380 
6381 	log = &env->log;
6382 	log->level = BPF_LOG_KERNEL;
6383 	btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
6384 	if (IS_ERR(btf))
6385 		goto err_out;
6386 
6387 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
6388 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6389 	err = btf_alloc_id(btf);
6390 	if (err) {
6391 		btf_free(btf);
6392 		btf = ERR_PTR(err);
6393 	}
6394 err_out:
6395 	btf_verifier_env_free(env);
6396 	return btf;
6397 }
6398 
6399 /* If .BTF_ids section was created with distilled base BTF, both base and
6400  * split BTF ids will need to be mapped to actual base/split ids for
6401  * BTF now that it has been relocated.
6402  */
btf_relocate_id(const struct btf * btf,__u32 id)6403 static __u32 btf_relocate_id(const struct btf *btf, __u32 id)
6404 {
6405 	if (!btf->base_btf || !btf->base_id_map)
6406 		return id;
6407 	return btf->base_id_map[id];
6408 }
6409 
6410 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6411 
btf_parse_module(const char * module_name,const void * data,unsigned int data_size,void * base_data,unsigned int base_data_size)6412 static struct btf *btf_parse_module(const char *module_name, const void *data,
6413 				    unsigned int data_size, void *base_data,
6414 				    unsigned int base_data_size)
6415 {
6416 	struct btf *btf = NULL, *vmlinux_btf, *base_btf = NULL;
6417 	struct btf_verifier_env *env = NULL;
6418 	struct bpf_verifier_log *log;
6419 	int err = 0;
6420 
6421 	vmlinux_btf = bpf_get_btf_vmlinux();
6422 	if (IS_ERR(vmlinux_btf))
6423 		return vmlinux_btf;
6424 	if (!vmlinux_btf)
6425 		return ERR_PTR(-EINVAL);
6426 
6427 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6428 	if (!env)
6429 		return ERR_PTR(-ENOMEM);
6430 
6431 	log = &env->log;
6432 	log->level = BPF_LOG_KERNEL;
6433 
6434 	if (base_data) {
6435 		base_btf = btf_parse_base(env, ".BTF.base", base_data, base_data_size);
6436 		if (IS_ERR(base_btf)) {
6437 			err = PTR_ERR(base_btf);
6438 			goto errout;
6439 		}
6440 	} else {
6441 		base_btf = vmlinux_btf;
6442 	}
6443 
6444 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6445 	if (!btf) {
6446 		err = -ENOMEM;
6447 		goto errout;
6448 	}
6449 	env->btf = btf;
6450 
6451 	btf->base_btf = base_btf;
6452 	btf->start_id = base_btf->nr_types;
6453 	btf->start_str_off = base_btf->hdr.str_len;
6454 	btf->kernel_btf = true;
6455 	btf->named_start_id = 0;
6456 	strscpy(btf->name, module_name);
6457 
6458 	btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
6459 	if (!btf->data) {
6460 		err = -ENOMEM;
6461 		goto errout;
6462 	}
6463 	btf->data_size = data_size;
6464 
6465 	err = btf_parse_hdr(env);
6466 	if (err)
6467 		goto errout;
6468 
6469 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6470 
6471 	err = btf_parse_str_sec(env);
6472 	if (err)
6473 		goto errout;
6474 
6475 	err = btf_check_all_metas(env);
6476 	if (err)
6477 		goto errout;
6478 
6479 	err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6480 	if (err)
6481 		goto errout;
6482 
6483 	if (base_btf != vmlinux_btf) {
6484 		err = btf_relocate(btf, vmlinux_btf, &btf->base_id_map);
6485 		if (err)
6486 			goto errout;
6487 		btf_free(base_btf);
6488 		base_btf = vmlinux_btf;
6489 	}
6490 
6491 	btf_verifier_env_free(env);
6492 	btf_check_sorted(btf);
6493 	refcount_set(&btf->refcnt, 1);
6494 	return btf;
6495 
6496 errout:
6497 	btf_verifier_env_free(env);
6498 	if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
6499 		btf_free(base_btf);
6500 	if (btf) {
6501 		kvfree(btf->data);
6502 		kvfree(btf->types);
6503 		kfree(btf);
6504 	}
6505 	return ERR_PTR(err);
6506 }
6507 
6508 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6509 
bpf_prog_get_target_btf(const struct bpf_prog * prog)6510 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6511 {
6512 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6513 
6514 	if (tgt_prog)
6515 		return tgt_prog->aux->btf;
6516 	else
6517 		return prog->aux->attach_btf;
6518 }
6519 
is_void_or_int_ptr(struct btf * btf,const struct btf_type * t)6520 static bool is_void_or_int_ptr(struct btf *btf, const struct btf_type *t)
6521 {
6522 	/* skip modifiers */
6523 	t = btf_type_skip_modifiers(btf, t->type, NULL);
6524 	return btf_type_is_void(t) || btf_type_is_int(t);
6525 }
6526 
btf_ctx_arg_idx(struct btf * btf,const struct btf_type * func_proto,int off)6527 u32 btf_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6528 		    int off)
6529 {
6530 	const struct btf_param *args;
6531 	const struct btf_type *t;
6532 	u32 offset = 0, nr_args;
6533 	int i;
6534 
6535 	if (!func_proto)
6536 		return off / 8;
6537 
6538 	nr_args = btf_type_vlen(func_proto);
6539 	args = (const struct btf_param *)(func_proto + 1);
6540 	for (i = 0; i < nr_args; i++) {
6541 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6542 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6543 		if (off < offset)
6544 			return i;
6545 	}
6546 
6547 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6548 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6549 	if (off < offset)
6550 		return nr_args;
6551 
6552 	return nr_args + 1;
6553 }
6554 
prog_args_trusted(const struct bpf_prog * prog)6555 static bool prog_args_trusted(const struct bpf_prog *prog)
6556 {
6557 	enum bpf_attach_type atype = prog->expected_attach_type;
6558 
6559 	switch (prog->type) {
6560 	case BPF_PROG_TYPE_TRACING:
6561 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
6562 	case BPF_PROG_TYPE_LSM:
6563 		return bpf_lsm_is_trusted(prog);
6564 	case BPF_PROG_TYPE_STRUCT_OPS:
6565 		return true;
6566 	default:
6567 		return false;
6568 	}
6569 }
6570 
btf_ctx_arg_offset(const struct btf * btf,const struct btf_type * func_proto,u32 arg_no)6571 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6572 		       u32 arg_no)
6573 {
6574 	const struct btf_param *args;
6575 	const struct btf_type *t;
6576 	int off = 0, i;
6577 	u32 sz;
6578 
6579 	args = btf_params(func_proto);
6580 	for (i = 0; i < arg_no; i++) {
6581 		t = btf_type_by_id(btf, args[i].type);
6582 		t = btf_resolve_size(btf, t, &sz);
6583 		if (IS_ERR(t))
6584 			return PTR_ERR(t);
6585 		off += roundup(sz, 8);
6586 	}
6587 
6588 	return off;
6589 }
6590 
6591 struct bpf_raw_tp_null_args {
6592 	const char *func;
6593 	u64 mask;
6594 };
6595 
6596 static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {
6597 	/* sched */
6598 	{ "sched_pi_setprio", 0x10 },
6599 	/* ... from sched_numa_pair_template event class */
6600 	{ "sched_stick_numa", 0x100 },
6601 	{ "sched_swap_numa", 0x100 },
6602 	/* afs */
6603 	{ "afs_make_fs_call", 0x10 },
6604 	{ "afs_make_fs_calli", 0x10 },
6605 	{ "afs_make_fs_call1", 0x10 },
6606 	{ "afs_make_fs_call2", 0x10 },
6607 	{ "afs_protocol_error", 0x1 },
6608 	{ "afs_flock_ev", 0x10 },
6609 	/* cachefiles */
6610 	{ "cachefiles_lookup", 0x1 | 0x200 },
6611 	{ "cachefiles_unlink", 0x1 },
6612 	{ "cachefiles_rename", 0x1 },
6613 	{ "cachefiles_prep_read", 0x1 },
6614 	{ "cachefiles_mark_active", 0x1 },
6615 	{ "cachefiles_mark_failed", 0x1 },
6616 	{ "cachefiles_mark_inactive", 0x1 },
6617 	{ "cachefiles_vfs_error", 0x1 },
6618 	{ "cachefiles_io_error", 0x1 },
6619 	{ "cachefiles_ondemand_open", 0x1 },
6620 	{ "cachefiles_ondemand_copen", 0x1 },
6621 	{ "cachefiles_ondemand_close", 0x1 },
6622 	{ "cachefiles_ondemand_read", 0x1 },
6623 	{ "cachefiles_ondemand_cread", 0x1 },
6624 	{ "cachefiles_ondemand_fd_write", 0x1 },
6625 	{ "cachefiles_ondemand_fd_release", 0x1 },
6626 	/* ext4, from ext4__mballoc event class */
6627 	{ "ext4_mballoc_discard", 0x10 },
6628 	{ "ext4_mballoc_free", 0x10 },
6629 	/* fib */
6630 	{ "fib_table_lookup", 0x100 },
6631 	/* filelock */
6632 	/* ... from filelock_lock event class */
6633 	{ "posix_lock_inode", 0x10 },
6634 	{ "fcntl_setlk", 0x10 },
6635 	{ "locks_remove_posix", 0x10 },
6636 	{ "flock_lock_inode", 0x10 },
6637 	/* ... from filelock_lease event class */
6638 	{ "break_lease_noblock", 0x10 },
6639 	{ "break_lease_block", 0x10 },
6640 	{ "break_lease_unblock", 0x10 },
6641 	{ "generic_delete_lease", 0x10 },
6642 	{ "time_out_leases", 0x10 },
6643 	/* host1x */
6644 	{ "host1x_cdma_push_gather", 0x10000 },
6645 	/* huge_memory */
6646 	{ "mm_khugepaged_scan_pmd", 0x10 },
6647 	{ "mm_collapse_huge_page_isolate", 0x1 },
6648 	{ "mm_khugepaged_scan_file", 0x10 },
6649 	{ "mm_khugepaged_collapse_file", 0x10 },
6650 	/* kmem */
6651 	{ "mm_page_alloc", 0x1 },
6652 	{ "mm_page_pcpu_drain", 0x1 },
6653 	/* .. from mm_page event class */
6654 	{ "mm_page_alloc_zone_locked", 0x1 },
6655 	/* netfs */
6656 	{ "netfs_failure", 0x10 },
6657 	/* power */
6658 	{ "device_pm_callback_start", 0x10 },
6659 	/* qdisc */
6660 	{ "qdisc_dequeue", 0x1000 },
6661 	/* rxrpc */
6662 	{ "rxrpc_recvdata", 0x1 },
6663 	{ "rxrpc_resend", 0x10 },
6664 	{ "rxrpc_tq", 0x10 },
6665 	{ "rxrpc_client", 0x1 },
6666 	/* skb */
6667 	{"kfree_skb", 0x1000},
6668 	/* sunrpc */
6669 	{ "xs_stream_read_data", 0x1 },
6670 	/* ... from xprt_cong_event event class */
6671 	{ "xprt_reserve_cong", 0x10 },
6672 	{ "xprt_release_cong", 0x10 },
6673 	{ "xprt_get_cong", 0x10 },
6674 	{ "xprt_put_cong", 0x10 },
6675 	/* tcp */
6676 	{ "tcp_send_reset", 0x11 },
6677 	{ "tcp_sendmsg_locked", 0x100 },
6678 	/* tegra_apb_dma */
6679 	{ "tegra_dma_tx_status", 0x100 },
6680 	/* timer_migration */
6681 	{ "tmigr_update_events", 0x1 },
6682 	/* writeback, from writeback_folio_template event class */
6683 	{ "writeback_dirty_folio", 0x10 },
6684 	{ "folio_wait_writeback", 0x10 },
6685 	/* rdma */
6686 	{ "mr_integ_alloc", 0x2000 },
6687 	/* bpf_testmod */
6688 	{ "bpf_testmod_test_read", 0x0 },
6689 	/* amdgpu */
6690 	{ "amdgpu_vm_bo_map", 0x1 },
6691 	{ "amdgpu_vm_bo_unmap", 0x1 },
6692 	/* netfs */
6693 	{ "netfs_folioq", 0x1 },
6694 	/* xfs from xfs_defer_pending_class */
6695 	{ "xfs_defer_create_intent", 0x1 },
6696 	{ "xfs_defer_cancel_list", 0x1 },
6697 	{ "xfs_defer_pending_finish", 0x1 },
6698 	{ "xfs_defer_pending_abort", 0x1 },
6699 	{ "xfs_defer_relog_intent", 0x1 },
6700 	{ "xfs_defer_isolate_paused", 0x1 },
6701 	{ "xfs_defer_item_pause", 0x1 },
6702 	{ "xfs_defer_item_unpause", 0x1 },
6703 	/* xfs from xfs_defer_pending_item_class */
6704 	{ "xfs_defer_add_item", 0x1 },
6705 	{ "xfs_defer_cancel_item", 0x1 },
6706 	{ "xfs_defer_finish_item", 0x1 },
6707 	/* xfs from xfs_icwalk_class */
6708 	{ "xfs_ioc_free_eofblocks", 0x10 },
6709 	{ "xfs_blockgc_free_space", 0x10 },
6710 	/* xfs from xfs_btree_cur_class */
6711 	{ "xfs_btree_updkeys", 0x100 },
6712 	{ "xfs_btree_overlapped_query_range", 0x100 },
6713 	/* xfs from xfs_imap_class*/
6714 	{ "xfs_map_blocks_found", 0x10000 },
6715 	{ "xfs_map_blocks_alloc", 0x10000 },
6716 	{ "xfs_iomap_alloc", 0x1000 },
6717 	{ "xfs_iomap_found", 0x1000 },
6718 	/* xfs from xfs_fs_class */
6719 	{ "xfs_inodegc_flush", 0x1 },
6720 	{ "xfs_inodegc_push", 0x1 },
6721 	{ "xfs_inodegc_start", 0x1 },
6722 	{ "xfs_inodegc_stop", 0x1 },
6723 	{ "xfs_inodegc_queue", 0x1 },
6724 	{ "xfs_inodegc_throttle", 0x1 },
6725 	{ "xfs_fs_sync_fs", 0x1 },
6726 	{ "xfs_blockgc_start", 0x1 },
6727 	{ "xfs_blockgc_stop", 0x1 },
6728 	{ "xfs_blockgc_worker", 0x1 },
6729 	{ "xfs_blockgc_flush_all", 0x1 },
6730 	/* xfs_scrub */
6731 	{ "xchk_nlinks_live_update", 0x10 },
6732 	/* xfs_scrub from xchk_metapath_class */
6733 	{ "xchk_metapath_lookup", 0x100 },
6734 	/* nfsd */
6735 	{ "nfsd_dirent", 0x1 },
6736 	{ "nfsd_file_acquire", 0x1001 },
6737 	{ "nfsd_file_insert_err", 0x1 },
6738 	{ "nfsd_file_cons_err", 0x1 },
6739 	/* nfs4 */
6740 	{ "nfs4_setup_sequence", 0x1 },
6741 	{ "pnfs_update_layout", 0x10000 },
6742 	{ "nfs4_inode_callback_event", 0x200 },
6743 	{ "nfs4_inode_stateid_callback_event", 0x200 },
6744 	/* nfs from pnfs_layout_event */
6745 	{ "pnfs_mds_fallback_pg_init_read", 0x10000 },
6746 	{ "pnfs_mds_fallback_pg_init_write", 0x10000 },
6747 	{ "pnfs_mds_fallback_pg_get_mirror_count", 0x10000 },
6748 	{ "pnfs_mds_fallback_read_done", 0x10000 },
6749 	{ "pnfs_mds_fallback_write_done", 0x10000 },
6750 	{ "pnfs_mds_fallback_read_pagelist", 0x10000 },
6751 	{ "pnfs_mds_fallback_write_pagelist", 0x10000 },
6752 	/* coda */
6753 	{ "coda_dec_pic_run", 0x10 },
6754 	{ "coda_dec_pic_done", 0x10 },
6755 	/* cfg80211 */
6756 	{ "cfg80211_scan_done", 0x11 },
6757 	{ "rdev_set_coalesce", 0x10 },
6758 	{ "cfg80211_report_wowlan_wakeup", 0x100 },
6759 	{ "cfg80211_inform_bss_frame", 0x100 },
6760 	{ "cfg80211_michael_mic_failure", 0x10000 },
6761 	/* cfg80211 from wiphy_work_event */
6762 	{ "wiphy_work_queue", 0x10 },
6763 	{ "wiphy_work_run", 0x10 },
6764 	{ "wiphy_work_cancel", 0x10 },
6765 	{ "wiphy_work_flush", 0x10 },
6766 	/* hugetlbfs */
6767 	{ "hugetlbfs_alloc_inode", 0x10 },
6768 	/* spufs */
6769 	{ "spufs_context", 0x10 },
6770 	/* kvm_hv */
6771 	{ "kvm_page_fault_enter", 0x100 },
6772 	/* dpu */
6773 	{ "dpu_crtc_setup_mixer", 0x100 },
6774 	/* binder */
6775 	{ "binder_transaction", 0x100 },
6776 	/* bcachefs */
6777 	{ "btree_path_free", 0x100 },
6778 	/* hfi1_tx */
6779 	{ "hfi1_sdma_progress", 0x1000 },
6780 	/* iptfs */
6781 	{ "iptfs_ingress_postq_event", 0x1000 },
6782 	/* neigh */
6783 	{ "neigh_update", 0x10 },
6784 	/* snd_firewire_lib */
6785 	{ "amdtp_packet", 0x100 },
6786 };
6787 
btf_ctx_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)6788 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
6789 		    const struct bpf_prog *prog,
6790 		    struct bpf_insn_access_aux *info)
6791 {
6792 	const struct btf_type *t = prog->aux->attach_func_proto;
6793 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6794 	struct btf *btf = bpf_prog_get_target_btf(prog);
6795 	const char *tname = prog->aux->attach_func_name;
6796 	struct bpf_verifier_log *log = info->log;
6797 	const struct btf_param *args;
6798 	bool ptr_err_raw_tp = false;
6799 	const char *tag_value;
6800 	u32 nr_args, arg;
6801 	int i, ret;
6802 
6803 	if (off % 8) {
6804 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6805 			tname, off);
6806 		return false;
6807 	}
6808 	arg = btf_ctx_arg_idx(btf, t, off);
6809 	args = (const struct btf_param *)(t + 1);
6810 	/* if (t == NULL) Fall back to default BPF prog with
6811 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
6812 	 */
6813 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
6814 	if (prog->aux->attach_btf_trace) {
6815 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
6816 		args++;
6817 		nr_args--;
6818 	}
6819 
6820 	if (arg > nr_args) {
6821 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6822 			tname, arg + 1);
6823 		return false;
6824 	}
6825 
6826 	if (arg == nr_args) {
6827 		switch (prog->expected_attach_type) {
6828 		case BPF_LSM_MAC:
6829 			/* mark we are accessing the return value */
6830 			info->is_retval = true;
6831 			fallthrough;
6832 		case BPF_LSM_CGROUP:
6833 		case BPF_TRACE_FEXIT:
6834 		case BPF_TRACE_FSESSION:
6835 			/* When LSM programs are attached to void LSM hooks
6836 			 * they use FEXIT trampolines and when attached to
6837 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
6838 			 *
6839 			 * While the LSM programs are BPF_MODIFY_RETURN-like
6840 			 * the check:
6841 			 *
6842 			 *	if (ret_type != 'int')
6843 			 *		return -EINVAL;
6844 			 *
6845 			 * is _not_ done here. This is still safe as LSM hooks
6846 			 * have only void and int return types.
6847 			 */
6848 			if (!t)
6849 				return true;
6850 			t = btf_type_by_id(btf, t->type);
6851 			break;
6852 		case BPF_MODIFY_RETURN:
6853 			/* For now the BPF_MODIFY_RETURN can only be attached to
6854 			 * functions that return an int.
6855 			 */
6856 			if (!t)
6857 				return false;
6858 
6859 			t = btf_type_skip_modifiers(btf, t->type, NULL);
6860 			if (!btf_type_is_small_int(t)) {
6861 				bpf_log(log,
6862 					"ret type %s not allowed for fmod_ret\n",
6863 					btf_type_str(t));
6864 				return false;
6865 			}
6866 			break;
6867 		default:
6868 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6869 				tname, arg + 1);
6870 			return false;
6871 		}
6872 	} else {
6873 		if (!t)
6874 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6875 			return true;
6876 		t = btf_type_by_id(btf, args[arg].type);
6877 	}
6878 
6879 	/* skip modifiers */
6880 	while (btf_type_is_modifier(t))
6881 		t = btf_type_by_id(btf, t->type);
6882 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
6883 		/* accessing a scalar */
6884 		return true;
6885 	if (!btf_type_is_ptr(t)) {
6886 		bpf_log(log,
6887 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6888 			tname, arg,
6889 			__btf_name_by_offset(btf, t->name_off),
6890 			btf_type_str(t));
6891 		return false;
6892 	}
6893 
6894 	if (size != sizeof(u64)) {
6895 		bpf_log(log, "func '%s' size %d must be 8\n",
6896 			tname, size);
6897 		return false;
6898 	}
6899 
6900 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6901 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6902 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6903 		u32 type, flag;
6904 
6905 		type = base_type(ctx_arg_info->reg_type);
6906 		flag = type_flag(ctx_arg_info->reg_type);
6907 		if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6908 		    (flag & PTR_MAYBE_NULL)) {
6909 			info->reg_type = ctx_arg_info->reg_type;
6910 			return true;
6911 		}
6912 	}
6913 
6914 	/*
6915 	 * If it's a pointer to void, it's the same as scalar from the verifier
6916 	 * safety POV. Either way, no futher pointer walking is allowed.
6917 	 */
6918 	if (is_void_or_int_ptr(btf, t))
6919 		return true;
6920 
6921 	/* this is a pointer to another type */
6922 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6923 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6924 
6925 		if (ctx_arg_info->offset == off) {
6926 			if (!ctx_arg_info->btf_id) {
6927 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6928 				return false;
6929 			}
6930 
6931 			info->reg_type = ctx_arg_info->reg_type;
6932 			info->btf = ctx_arg_info->btf ? : btf_vmlinux;
6933 			info->btf_id = ctx_arg_info->btf_id;
6934 			info->ref_obj_id = ctx_arg_info->ref_obj_id;
6935 			return true;
6936 		}
6937 	}
6938 
6939 	info->reg_type = PTR_TO_BTF_ID;
6940 	if (prog_args_trusted(prog))
6941 		info->reg_type |= PTR_TRUSTED;
6942 
6943 	if (btf_param_match_suffix(btf, &args[arg], "__nullable"))
6944 		info->reg_type |= PTR_MAYBE_NULL;
6945 
6946 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
6947 		struct btf *btf = prog->aux->attach_btf;
6948 		const struct btf_type *t;
6949 		const char *tname;
6950 
6951 		/* BTF lookups cannot fail, return false on error */
6952 		t = btf_type_by_id(btf, prog->aux->attach_btf_id);
6953 		if (!t)
6954 			return false;
6955 		tname = btf_name_by_offset(btf, t->name_off);
6956 		if (!tname)
6957 			return false;
6958 		/* Checked by bpf_check_attach_target */
6959 		tname += sizeof("btf_trace_") - 1;
6960 		for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) {
6961 			/* Is this a func with potential NULL args? */
6962 			if (strcmp(tname, raw_tp_null_args[i].func))
6963 				continue;
6964 			if (raw_tp_null_args[i].mask & (0x1ULL << (arg * 4)))
6965 				info->reg_type |= PTR_MAYBE_NULL;
6966 			/* Is the current arg IS_ERR? */
6967 			if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4)))
6968 				ptr_err_raw_tp = true;
6969 			break;
6970 		}
6971 		/* If we don't know NULL-ness specification and the tracepoint
6972 		 * is coming from a loadable module, be conservative and mark
6973 		 * argument as PTR_MAYBE_NULL.
6974 		 */
6975 		if (i == ARRAY_SIZE(raw_tp_null_args) && btf_is_module(btf))
6976 			info->reg_type |= PTR_MAYBE_NULL;
6977 	}
6978 
6979 	if (tgt_prog) {
6980 		enum bpf_prog_type tgt_type;
6981 
6982 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6983 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
6984 		else
6985 			tgt_type = tgt_prog->type;
6986 
6987 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6988 		if (ret > 0) {
6989 			info->btf = btf_vmlinux;
6990 			info->btf_id = ret;
6991 			return true;
6992 		} else {
6993 			return false;
6994 		}
6995 	}
6996 
6997 	info->btf = btf;
6998 	info->btf_id = t->type;
6999 	t = btf_type_by_id(btf, t->type);
7000 
7001 	if (btf_type_is_type_tag(t) && !btf_type_kflag(t)) {
7002 		tag_value = __btf_name_by_offset(btf, t->name_off);
7003 		if (strcmp(tag_value, "user") == 0)
7004 			info->reg_type |= MEM_USER;
7005 		if (strcmp(tag_value, "percpu") == 0)
7006 			info->reg_type |= MEM_PERCPU;
7007 	}
7008 
7009 	/* skip modifiers */
7010 	while (btf_type_is_modifier(t)) {
7011 		info->btf_id = t->type;
7012 		t = btf_type_by_id(btf, t->type);
7013 	}
7014 	if (!btf_type_is_struct(t)) {
7015 		bpf_log(log,
7016 			"func '%s' arg%d type %s is not a struct\n",
7017 			tname, arg, btf_type_str(t));
7018 		return false;
7019 	}
7020 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
7021 		tname, arg, info->btf_id, btf_type_str(t),
7022 		__btf_name_by_offset(btf, t->name_off));
7023 
7024 	/* Perform all checks on the validity of type for this argument, but if
7025 	 * we know it can be IS_ERR at runtime, scrub pointer type and mark as
7026 	 * scalar.
7027 	 */
7028 	if (ptr_err_raw_tp) {
7029 		bpf_log(log, "marking pointer arg%d as scalar as it may encode error", arg);
7030 		info->reg_type = SCALAR_VALUE;
7031 	}
7032 	return true;
7033 }
7034 EXPORT_SYMBOL_GPL(btf_ctx_access);
7035 
7036 enum bpf_struct_walk_result {
7037 	/* < 0 error */
7038 	WALK_SCALAR = 0,
7039 	WALK_PTR,
7040 	WALK_PTR_UNTRUSTED,
7041 	WALK_STRUCT,
7042 };
7043 
btf_struct_walk(struct bpf_verifier_log * log,const struct btf * btf,const struct btf_type * t,int off,int size,u32 * next_btf_id,enum bpf_type_flag * flag,const char ** field_name)7044 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
7045 			   const struct btf_type *t, int off, int size,
7046 			   u32 *next_btf_id, enum bpf_type_flag *flag,
7047 			   const char **field_name)
7048 {
7049 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
7050 	const struct btf_type *mtype, *elem_type = NULL;
7051 	const struct btf_member *member;
7052 	const char *tname, *mname, *tag_value;
7053 	u32 vlen, elem_id, mid;
7054 
7055 again:
7056 	if (btf_type_is_modifier(t))
7057 		t = btf_type_skip_modifiers(btf, t->type, NULL);
7058 	tname = __btf_name_by_offset(btf, t->name_off);
7059 	if (!btf_type_is_struct(t)) {
7060 		bpf_log(log, "Type '%s' is not a struct\n", tname);
7061 		return -EINVAL;
7062 	}
7063 
7064 	vlen = btf_type_vlen(t);
7065 	if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
7066 		/*
7067 		 * walking unions yields untrusted pointers
7068 		 * with exception of __bpf_md_ptr and other
7069 		 * unions with a single member
7070 		 */
7071 		*flag |= PTR_UNTRUSTED;
7072 
7073 	if (off + size > t->size) {
7074 		/* If the last element is a variable size array, we may
7075 		 * need to relax the rule.
7076 		 */
7077 		struct btf_array *array_elem;
7078 
7079 		if (vlen == 0)
7080 			goto error;
7081 
7082 		member = btf_type_member(t) + vlen - 1;
7083 		mtype = btf_type_skip_modifiers(btf, member->type,
7084 						NULL);
7085 		if (!btf_type_is_array(mtype))
7086 			goto error;
7087 
7088 		array_elem = (struct btf_array *)(mtype + 1);
7089 		if (array_elem->nelems != 0)
7090 			goto error;
7091 
7092 		moff = __btf_member_bit_offset(t, member) / 8;
7093 		if (off < moff)
7094 			goto error;
7095 
7096 		/* allow structure and integer */
7097 		t = btf_type_skip_modifiers(btf, array_elem->type,
7098 					    NULL);
7099 
7100 		if (btf_type_is_int(t))
7101 			return WALK_SCALAR;
7102 
7103 		if (!btf_type_is_struct(t))
7104 			goto error;
7105 
7106 		off = (off - moff) % t->size;
7107 		goto again;
7108 
7109 error:
7110 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
7111 			tname, off, size);
7112 		return -EACCES;
7113 	}
7114 
7115 	for_each_member(i, t, member) {
7116 		/* offset of the field in bytes */
7117 		moff = __btf_member_bit_offset(t, member) / 8;
7118 		if (off + size <= moff)
7119 			/* won't find anything, field is already too far */
7120 			break;
7121 
7122 		if (__btf_member_bitfield_size(t, member)) {
7123 			u32 end_bit = __btf_member_bit_offset(t, member) +
7124 				__btf_member_bitfield_size(t, member);
7125 
7126 			/* off <= moff instead of off == moff because clang
7127 			 * does not generate a BTF member for anonymous
7128 			 * bitfield like the ":16" here:
7129 			 * struct {
7130 			 *	int :16;
7131 			 *	int x:8;
7132 			 * };
7133 			 */
7134 			if (off <= moff &&
7135 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
7136 				return WALK_SCALAR;
7137 
7138 			/* off may be accessing a following member
7139 			 *
7140 			 * or
7141 			 *
7142 			 * Doing partial access at either end of this
7143 			 * bitfield.  Continue on this case also to
7144 			 * treat it as not accessing this bitfield
7145 			 * and eventually error out as field not
7146 			 * found to keep it simple.
7147 			 * It could be relaxed if there was a legit
7148 			 * partial access case later.
7149 			 */
7150 			continue;
7151 		}
7152 
7153 		/* In case of "off" is pointing to holes of a struct */
7154 		if (off < moff)
7155 			break;
7156 
7157 		/* type of the field */
7158 		mid = member->type;
7159 		mtype = btf_type_by_id(btf, member->type);
7160 		mname = __btf_name_by_offset(btf, member->name_off);
7161 
7162 		mtype = __btf_resolve_size(btf, mtype, &msize,
7163 					   &elem_type, &elem_id, &total_nelems,
7164 					   &mid);
7165 		if (IS_ERR(mtype)) {
7166 			bpf_log(log, "field %s doesn't have size\n", mname);
7167 			return -EFAULT;
7168 		}
7169 
7170 		mtrue_end = moff + msize;
7171 		if (off >= mtrue_end)
7172 			/* no overlap with member, keep iterating */
7173 			continue;
7174 
7175 		if (btf_type_is_array(mtype)) {
7176 			u32 elem_idx;
7177 
7178 			/* __btf_resolve_size() above helps to
7179 			 * linearize a multi-dimensional array.
7180 			 *
7181 			 * The logic here is treating an array
7182 			 * in a struct as the following way:
7183 			 *
7184 			 * struct outer {
7185 			 *	struct inner array[2][2];
7186 			 * };
7187 			 *
7188 			 * looks like:
7189 			 *
7190 			 * struct outer {
7191 			 *	struct inner array_elem0;
7192 			 *	struct inner array_elem1;
7193 			 *	struct inner array_elem2;
7194 			 *	struct inner array_elem3;
7195 			 * };
7196 			 *
7197 			 * When accessing outer->array[1][0], it moves
7198 			 * moff to "array_elem2", set mtype to
7199 			 * "struct inner", and msize also becomes
7200 			 * sizeof(struct inner).  Then most of the
7201 			 * remaining logic will fall through without
7202 			 * caring the current member is an array or
7203 			 * not.
7204 			 *
7205 			 * Unlike mtype/msize/moff, mtrue_end does not
7206 			 * change.  The naming difference ("_true") tells
7207 			 * that it is not always corresponding to
7208 			 * the current mtype/msize/moff.
7209 			 * It is the true end of the current
7210 			 * member (i.e. array in this case).  That
7211 			 * will allow an int array to be accessed like
7212 			 * a scratch space,
7213 			 * i.e. allow access beyond the size of
7214 			 *      the array's element as long as it is
7215 			 *      within the mtrue_end boundary.
7216 			 */
7217 
7218 			/* skip empty array */
7219 			if (moff == mtrue_end)
7220 				continue;
7221 
7222 			msize /= total_nelems;
7223 			elem_idx = (off - moff) / msize;
7224 			moff += elem_idx * msize;
7225 			mtype = elem_type;
7226 			mid = elem_id;
7227 		}
7228 
7229 		/* the 'off' we're looking for is either equal to start
7230 		 * of this field or inside of this struct
7231 		 */
7232 		if (btf_type_is_struct(mtype)) {
7233 			/* our field must be inside that union or struct */
7234 			t = mtype;
7235 
7236 			/* return if the offset matches the member offset */
7237 			if (off == moff) {
7238 				*next_btf_id = mid;
7239 				return WALK_STRUCT;
7240 			}
7241 
7242 			/* adjust offset we're looking for */
7243 			off -= moff;
7244 			goto again;
7245 		}
7246 
7247 		if (btf_type_is_ptr(mtype)) {
7248 			const struct btf_type *stype, *t;
7249 			enum bpf_type_flag tmp_flag = 0;
7250 			u32 id;
7251 
7252 			if (msize != size || off != moff) {
7253 				bpf_log(log,
7254 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
7255 					mname, moff, tname, off, size);
7256 				return -EACCES;
7257 			}
7258 
7259 			/* check type tag */
7260 			t = btf_type_by_id(btf, mtype->type);
7261 			if (btf_type_is_type_tag(t) && !btf_type_kflag(t)) {
7262 				tag_value = __btf_name_by_offset(btf, t->name_off);
7263 				/* check __user tag */
7264 				if (strcmp(tag_value, "user") == 0)
7265 					tmp_flag = MEM_USER;
7266 				/* check __percpu tag */
7267 				if (strcmp(tag_value, "percpu") == 0)
7268 					tmp_flag = MEM_PERCPU;
7269 				/* check __rcu tag */
7270 				if (strcmp(tag_value, "rcu") == 0)
7271 					tmp_flag = MEM_RCU;
7272 			}
7273 
7274 			stype = btf_type_skip_modifiers(btf, mtype->type, &id);
7275 			if (btf_type_is_struct(stype)) {
7276 				*next_btf_id = id;
7277 				*flag |= tmp_flag;
7278 				if (field_name)
7279 					*field_name = mname;
7280 				return WALK_PTR;
7281 			}
7282 
7283 			return WALK_PTR_UNTRUSTED;
7284 		}
7285 
7286 		/* Allow more flexible access within an int as long as
7287 		 * it is within mtrue_end.
7288 		 * Since mtrue_end could be the end of an array,
7289 		 * that also allows using an array of int as a scratch
7290 		 * space. e.g. skb->cb[].
7291 		 */
7292 		if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
7293 			bpf_log(log,
7294 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
7295 				mname, mtrue_end, tname, off, size);
7296 			return -EACCES;
7297 		}
7298 
7299 		return WALK_SCALAR;
7300 	}
7301 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
7302 	return -EINVAL;
7303 }
7304 
btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size,enum bpf_access_type atype __maybe_unused,u32 * next_btf_id,enum bpf_type_flag * flag,const char ** field_name)7305 int btf_struct_access(struct bpf_verifier_log *log,
7306 		      const struct bpf_reg_state *reg,
7307 		      int off, int size, enum bpf_access_type atype __maybe_unused,
7308 		      u32 *next_btf_id, enum bpf_type_flag *flag,
7309 		      const char **field_name)
7310 {
7311 	const struct btf *btf = reg->btf;
7312 	enum bpf_type_flag tmp_flag = 0;
7313 	const struct btf_type *t;
7314 	u32 id = reg->btf_id;
7315 	int err;
7316 
7317 	while (type_is_alloc(reg->type)) {
7318 		struct btf_struct_meta *meta;
7319 		struct btf_record *rec;
7320 		int i;
7321 
7322 		meta = btf_find_struct_meta(btf, id);
7323 		if (!meta)
7324 			break;
7325 		rec = meta->record;
7326 		for (i = 0; i < rec->cnt; i++) {
7327 			struct btf_field *field = &rec->fields[i];
7328 			u32 offset = field->offset;
7329 			if (off < offset + field->size && offset < off + size) {
7330 				bpf_log(log,
7331 					"direct access to %s is disallowed\n",
7332 					btf_field_type_name(field->type));
7333 				return -EACCES;
7334 			}
7335 		}
7336 		break;
7337 	}
7338 
7339 	t = btf_type_by_id(btf, id);
7340 	do {
7341 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
7342 
7343 		switch (err) {
7344 		case WALK_PTR:
7345 			/* For local types, the destination register cannot
7346 			 * become a pointer again.
7347 			 */
7348 			if (type_is_alloc(reg->type))
7349 				return SCALAR_VALUE;
7350 			/* If we found the pointer or scalar on t+off,
7351 			 * we're done.
7352 			 */
7353 			*next_btf_id = id;
7354 			*flag = tmp_flag;
7355 			return PTR_TO_BTF_ID;
7356 		case WALK_PTR_UNTRUSTED:
7357 			*flag = MEM_RDONLY | PTR_UNTRUSTED;
7358 			return PTR_TO_MEM;
7359 		case WALK_SCALAR:
7360 			return SCALAR_VALUE;
7361 		case WALK_STRUCT:
7362 			/* We found nested struct, so continue the search
7363 			 * by diving in it. At this point the offset is
7364 			 * aligned with the new type, so set it to 0.
7365 			 */
7366 			t = btf_type_by_id(btf, id);
7367 			off = 0;
7368 			break;
7369 		default:
7370 			/* It's either error or unknown return value..
7371 			 * scream and leave.
7372 			 */
7373 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
7374 				return -EINVAL;
7375 			return err;
7376 		}
7377 	} while (t);
7378 
7379 	return -EINVAL;
7380 }
7381 
7382 /* Check that two BTF types, each specified as an BTF object + id, are exactly
7383  * the same. Trivial ID check is not enough due to module BTFs, because we can
7384  * end up with two different module BTFs, but IDs point to the common type in
7385  * vmlinux BTF.
7386  */
btf_types_are_same(const struct btf * btf1,u32 id1,const struct btf * btf2,u32 id2)7387 bool btf_types_are_same(const struct btf *btf1, u32 id1,
7388 			const struct btf *btf2, u32 id2)
7389 {
7390 	if (id1 != id2)
7391 		return false;
7392 	if (btf1 == btf2)
7393 		return true;
7394 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
7395 }
7396 
btf_struct_ids_match(struct bpf_verifier_log * log,const struct btf * btf,u32 id,int off,const struct btf * need_btf,u32 need_type_id,bool strict)7397 bool btf_struct_ids_match(struct bpf_verifier_log *log,
7398 			  const struct btf *btf, u32 id, int off,
7399 			  const struct btf *need_btf, u32 need_type_id,
7400 			  bool strict)
7401 {
7402 	const struct btf_type *type;
7403 	enum bpf_type_flag flag = 0;
7404 	int err;
7405 
7406 	/* Are we already done? */
7407 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
7408 		return true;
7409 	/* In case of strict type match, we do not walk struct, the top level
7410 	 * type match must succeed. When strict is true, off should have already
7411 	 * been 0.
7412 	 */
7413 	if (strict)
7414 		return false;
7415 again:
7416 	type = btf_type_by_id(btf, id);
7417 	if (!type)
7418 		return false;
7419 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
7420 	if (err != WALK_STRUCT)
7421 		return false;
7422 
7423 	/* We found nested struct object. If it matches
7424 	 * the requested ID, we're done. Otherwise let's
7425 	 * continue the search with offset 0 in the new
7426 	 * type.
7427 	 */
7428 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
7429 		off = 0;
7430 		goto again;
7431 	}
7432 
7433 	return true;
7434 }
7435 
__get_type_size(struct btf * btf,u32 btf_id,const struct btf_type ** ret_type)7436 static int __get_type_size(struct btf *btf, u32 btf_id,
7437 			   const struct btf_type **ret_type)
7438 {
7439 	const struct btf_type *t;
7440 
7441 	*ret_type = btf_type_by_id(btf, 0);
7442 	if (!btf_id)
7443 		/* void */
7444 		return 0;
7445 	t = btf_type_by_id(btf, btf_id);
7446 	while (t && btf_type_is_modifier(t))
7447 		t = btf_type_by_id(btf, t->type);
7448 	if (!t)
7449 		return -EINVAL;
7450 	*ret_type = t;
7451 	if (btf_type_is_ptr(t))
7452 		/* kernel size of pointer. Not BPF's size of pointer*/
7453 		return sizeof(void *);
7454 	if (btf_type_is_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
7455 		return t->size;
7456 	return -EINVAL;
7457 }
7458 
__get_type_fmodel_flags(const struct btf_type * t)7459 static u8 __get_type_fmodel_flags(const struct btf_type *t)
7460 {
7461 	u8 flags = 0;
7462 
7463 	if (btf_type_is_struct(t))
7464 		flags |= BTF_FMODEL_STRUCT_ARG;
7465 	if (btf_type_is_signed_int(t))
7466 		flags |= BTF_FMODEL_SIGNED_ARG;
7467 
7468 	return flags;
7469 }
7470 
btf_distill_func_proto(struct bpf_verifier_log * log,struct btf * btf,const struct btf_type * func,const char * tname,struct btf_func_model * m)7471 int btf_distill_func_proto(struct bpf_verifier_log *log,
7472 			   struct btf *btf,
7473 			   const struct btf_type *func,
7474 			   const char *tname,
7475 			   struct btf_func_model *m)
7476 {
7477 	const struct btf_param *args;
7478 	const struct btf_type *t;
7479 	u32 i, nargs;
7480 	int ret;
7481 
7482 	if (!func) {
7483 		/* BTF function prototype doesn't match the verifier types.
7484 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
7485 		 */
7486 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7487 			m->arg_size[i] = 8;
7488 			m->arg_flags[i] = 0;
7489 		}
7490 		m->ret_size = 8;
7491 		m->ret_flags = 0;
7492 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
7493 		return 0;
7494 	}
7495 	args = (const struct btf_param *)(func + 1);
7496 	nargs = btf_type_vlen(func);
7497 	if (nargs > MAX_BPF_FUNC_ARGS) {
7498 		bpf_log(log,
7499 			"The function %s has %d arguments. Too many.\n",
7500 			tname, nargs);
7501 		return -EINVAL;
7502 	}
7503 	ret = __get_type_size(btf, func->type, &t);
7504 	if (ret < 0 || btf_type_is_struct(t)) {
7505 		bpf_log(log,
7506 			"The function %s return type %s is unsupported.\n",
7507 			tname, btf_type_str(t));
7508 		return -EINVAL;
7509 	}
7510 	m->ret_size = ret;
7511 	m->ret_flags = __get_type_fmodel_flags(t);
7512 
7513 	for (i = 0; i < nargs; i++) {
7514 		if (i == nargs - 1 && args[i].type == 0) {
7515 			bpf_log(log,
7516 				"The function %s with variable args is unsupported.\n",
7517 				tname);
7518 			return -EINVAL;
7519 		}
7520 		ret = __get_type_size(btf, args[i].type, &t);
7521 
7522 		/* No support of struct argument size greater than 16 bytes */
7523 		if (ret < 0 || ret > 16) {
7524 			bpf_log(log,
7525 				"The function %s arg%d type %s is unsupported.\n",
7526 				tname, i, btf_type_str(t));
7527 			return -EINVAL;
7528 		}
7529 		if (ret == 0) {
7530 			bpf_log(log,
7531 				"The function %s has malformed void argument.\n",
7532 				tname);
7533 			return -EINVAL;
7534 		}
7535 		m->arg_size[i] = ret;
7536 		m->arg_flags[i] = __get_type_fmodel_flags(t);
7537 	}
7538 	m->nr_args = nargs;
7539 	return 0;
7540 }
7541 
7542 /* Compare BTFs of two functions assuming only scalars and pointers to context.
7543  * t1 points to BTF_KIND_FUNC in btf1
7544  * t2 points to BTF_KIND_FUNC in btf2
7545  * Returns:
7546  * EINVAL - function prototype mismatch
7547  * EFAULT - verifier bug
7548  * 0 - 99% match. The last 1% is validated by the verifier.
7549  */
btf_check_func_type_match(struct bpf_verifier_log * log,struct btf * btf1,const struct btf_type * t1,struct btf * btf2,const struct btf_type * t2)7550 static int btf_check_func_type_match(struct bpf_verifier_log *log,
7551 				     struct btf *btf1, const struct btf_type *t1,
7552 				     struct btf *btf2, const struct btf_type *t2)
7553 {
7554 	const struct btf_param *args1, *args2;
7555 	const char *fn1, *fn2, *s1, *s2;
7556 	u32 nargs1, nargs2, i;
7557 
7558 	fn1 = btf_name_by_offset(btf1, t1->name_off);
7559 	fn2 = btf_name_by_offset(btf2, t2->name_off);
7560 
7561 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
7562 		bpf_log(log, "%s() is not a global function\n", fn1);
7563 		return -EINVAL;
7564 	}
7565 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
7566 		bpf_log(log, "%s() is not a global function\n", fn2);
7567 		return -EINVAL;
7568 	}
7569 
7570 	t1 = btf_type_by_id(btf1, t1->type);
7571 	if (!t1 || !btf_type_is_func_proto(t1))
7572 		return -EFAULT;
7573 	t2 = btf_type_by_id(btf2, t2->type);
7574 	if (!t2 || !btf_type_is_func_proto(t2))
7575 		return -EFAULT;
7576 
7577 	args1 = (const struct btf_param *)(t1 + 1);
7578 	nargs1 = btf_type_vlen(t1);
7579 	args2 = (const struct btf_param *)(t2 + 1);
7580 	nargs2 = btf_type_vlen(t2);
7581 
7582 	if (nargs1 != nargs2) {
7583 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
7584 			fn1, nargs1, fn2, nargs2);
7585 		return -EINVAL;
7586 	}
7587 
7588 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7589 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7590 	if (t1->info != t2->info) {
7591 		bpf_log(log,
7592 			"Return type %s of %s() doesn't match type %s of %s()\n",
7593 			btf_type_str(t1), fn1,
7594 			btf_type_str(t2), fn2);
7595 		return -EINVAL;
7596 	}
7597 
7598 	for (i = 0; i < nargs1; i++) {
7599 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
7600 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
7601 
7602 		if (t1->info != t2->info) {
7603 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
7604 				i, fn1, btf_type_str(t1),
7605 				fn2, btf_type_str(t2));
7606 			return -EINVAL;
7607 		}
7608 		if (btf_type_has_size(t1) && t1->size != t2->size) {
7609 			bpf_log(log,
7610 				"arg%d in %s() has size %d while %s() has %d\n",
7611 				i, fn1, t1->size,
7612 				fn2, t2->size);
7613 			return -EINVAL;
7614 		}
7615 
7616 		/* global functions are validated with scalars and pointers
7617 		 * to context only. And only global functions can be replaced.
7618 		 * Hence type check only those types.
7619 		 */
7620 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
7621 			continue;
7622 		if (!btf_type_is_ptr(t1)) {
7623 			bpf_log(log,
7624 				"arg%d in %s() has unrecognized type\n",
7625 				i, fn1);
7626 			return -EINVAL;
7627 		}
7628 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7629 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7630 		if (!btf_type_is_struct(t1)) {
7631 			bpf_log(log,
7632 				"arg%d in %s() is not a pointer to context\n",
7633 				i, fn1);
7634 			return -EINVAL;
7635 		}
7636 		if (!btf_type_is_struct(t2)) {
7637 			bpf_log(log,
7638 				"arg%d in %s() is not a pointer to context\n",
7639 				i, fn2);
7640 			return -EINVAL;
7641 		}
7642 		/* This is an optional check to make program writing easier.
7643 		 * Compare names of structs and report an error to the user.
7644 		 * btf_prepare_func_args() already checked that t2 struct
7645 		 * is a context type. btf_prepare_func_args() will check
7646 		 * later that t1 struct is a context type as well.
7647 		 */
7648 		s1 = btf_name_by_offset(btf1, t1->name_off);
7649 		s2 = btf_name_by_offset(btf2, t2->name_off);
7650 		if (strcmp(s1, s2)) {
7651 			bpf_log(log,
7652 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7653 				i, fn1, s1, fn2, s2);
7654 			return -EINVAL;
7655 		}
7656 	}
7657 	return 0;
7658 }
7659 
7660 /* Compare BTFs of given program with BTF of target program */
btf_check_type_match(struct bpf_verifier_log * log,const struct bpf_prog * prog,struct btf * btf2,const struct btf_type * t2)7661 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
7662 			 struct btf *btf2, const struct btf_type *t2)
7663 {
7664 	struct btf *btf1 = prog->aux->btf;
7665 	const struct btf_type *t1;
7666 	u32 btf_id = 0;
7667 
7668 	if (!prog->aux->func_info) {
7669 		bpf_log(log, "Program extension requires BTF\n");
7670 		return -EINVAL;
7671 	}
7672 
7673 	btf_id = prog->aux->func_info[0].type_id;
7674 	if (!btf_id)
7675 		return -EFAULT;
7676 
7677 	t1 = btf_type_by_id(btf1, btf_id);
7678 	if (!t1 || !btf_type_is_func(t1))
7679 		return -EFAULT;
7680 
7681 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7682 }
7683 
btf_is_dynptr_ptr(const struct btf * btf,const struct btf_type * t)7684 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7685 {
7686 	const char *name;
7687 
7688 	t = btf_type_by_id(btf, t->type); /* skip PTR */
7689 
7690 	while (btf_type_is_modifier(t))
7691 		t = btf_type_by_id(btf, t->type);
7692 
7693 	/* allow either struct or struct forward declaration */
7694 	if (btf_type_is_struct(t) ||
7695 	    (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
7696 		name = btf_str_by_offset(btf, t->name_off);
7697 		return name && strcmp(name, "bpf_dynptr") == 0;
7698 	}
7699 
7700 	return false;
7701 }
7702 
7703 struct bpf_cand_cache {
7704 	const char *name;
7705 	u32 name_len;
7706 	u16 kind;
7707 	u16 cnt;
7708 	struct {
7709 		const struct btf *btf;
7710 		u32 id;
7711 	} cands[];
7712 };
7713 
7714 static DEFINE_MUTEX(cand_cache_mutex);
7715 
7716 static struct bpf_cand_cache *
7717 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7718 
btf_get_ptr_to_btf_id(struct bpf_verifier_log * log,int arg_idx,const struct btf * btf,const struct btf_type * t)7719 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
7720 				 const struct btf *btf, const struct btf_type *t)
7721 {
7722 	struct bpf_cand_cache *cc;
7723 	struct bpf_core_ctx ctx = {
7724 		.btf = btf,
7725 		.log = log,
7726 	};
7727 	u32 kern_type_id, type_id;
7728 	int err = 0;
7729 
7730 	/* skip PTR and modifiers */
7731 	type_id = t->type;
7732 	t = btf_type_by_id(btf, t->type);
7733 	while (btf_type_is_modifier(t)) {
7734 		type_id = t->type;
7735 		t = btf_type_by_id(btf, t->type);
7736 	}
7737 
7738 	mutex_lock(&cand_cache_mutex);
7739 	cc = bpf_core_find_cands(&ctx, type_id);
7740 	if (IS_ERR(cc)) {
7741 		err = PTR_ERR(cc);
7742 		bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
7743 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7744 			err);
7745 		goto cand_cache_unlock;
7746 	}
7747 	if (cc->cnt != 1) {
7748 		bpf_log(log, "arg#%d reference type('%s %s') %s\n",
7749 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7750 			cc->cnt == 0 ? "has no matches" : "is ambiguous");
7751 		err = cc->cnt == 0 ? -ENOENT : -ESRCH;
7752 		goto cand_cache_unlock;
7753 	}
7754 	if (btf_is_module(cc->cands[0].btf)) {
7755 		bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
7756 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
7757 		err = -EOPNOTSUPP;
7758 		goto cand_cache_unlock;
7759 	}
7760 	kern_type_id = cc->cands[0].id;
7761 
7762 cand_cache_unlock:
7763 	mutex_unlock(&cand_cache_mutex);
7764 	if (err)
7765 		return err;
7766 
7767 	return kern_type_id;
7768 }
7769 
7770 enum btf_arg_tag {
7771 	ARG_TAG_CTX	  = BIT_ULL(0),
7772 	ARG_TAG_NONNULL   = BIT_ULL(1),
7773 	ARG_TAG_TRUSTED   = BIT_ULL(2),
7774 	ARG_TAG_UNTRUSTED = BIT_ULL(3),
7775 	ARG_TAG_NULLABLE  = BIT_ULL(4),
7776 	ARG_TAG_ARENA	  = BIT_ULL(5),
7777 };
7778 
7779 /* Process BTF of a function to produce high-level expectation of function
7780  * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
7781  * is cached in subprog info for reuse.
7782  * Returns:
7783  * EFAULT - there is a verifier bug. Abort verification.
7784  * EINVAL - cannot convert BTF.
7785  * 0 - Successfully processed BTF and constructed argument expectations.
7786  */
btf_prepare_func_args(struct bpf_verifier_env * env,int subprog)7787 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7788 {
7789 	bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
7790 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
7791 	struct bpf_verifier_log *log = &env->log;
7792 	struct bpf_prog *prog = env->prog;
7793 	enum bpf_prog_type prog_type = prog->type;
7794 	struct btf *btf = prog->aux->btf;
7795 	const struct btf_param *args;
7796 	const struct btf_type *t, *ref_t, *fn_t;
7797 	u32 i, nargs, btf_id;
7798 	const char *tname;
7799 
7800 	if (sub->args_cached)
7801 		return 0;
7802 
7803 	if (!prog->aux->func_info) {
7804 		verifier_bug(env, "func_info undefined");
7805 		return -EFAULT;
7806 	}
7807 
7808 	btf_id = prog->aux->func_info[subprog].type_id;
7809 	if (!btf_id) {
7810 		if (!is_global) /* not fatal for static funcs */
7811 			return -EINVAL;
7812 		bpf_log(log, "Global functions need valid BTF\n");
7813 		return -EFAULT;
7814 	}
7815 
7816 	fn_t = btf_type_by_id(btf, btf_id);
7817 	if (!fn_t || !btf_type_is_func(fn_t)) {
7818 		/* These checks were already done by the verifier while loading
7819 		 * struct bpf_func_info
7820 		 */
7821 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7822 			subprog);
7823 		return -EFAULT;
7824 	}
7825 	tname = btf_name_by_offset(btf, fn_t->name_off);
7826 
7827 	if (prog->aux->func_info_aux[subprog].unreliable) {
7828 		verifier_bug(env, "unreliable BTF for function %s()", tname);
7829 		return -EFAULT;
7830 	}
7831 	if (prog_type == BPF_PROG_TYPE_EXT)
7832 		prog_type = prog->aux->dst_prog->type;
7833 
7834 	t = btf_type_by_id(btf, fn_t->type);
7835 	if (!t || !btf_type_is_func_proto(t)) {
7836 		bpf_log(log, "Invalid type of function %s()\n", tname);
7837 		return -EFAULT;
7838 	}
7839 	args = (const struct btf_param *)(t + 1);
7840 	nargs = btf_type_vlen(t);
7841 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7842 		if (!is_global)
7843 			return -EINVAL;
7844 		bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7845 			tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7846 		return -EINVAL;
7847 	}
7848 	/* check that function returns int, exception cb also requires this */
7849 	t = btf_type_by_id(btf, t->type);
7850 	while (btf_type_is_modifier(t))
7851 		t = btf_type_by_id(btf, t->type);
7852 	if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7853 		if (!is_global)
7854 			return -EINVAL;
7855 		bpf_log(log,
7856 			"Global function %s() doesn't return scalar. Only those are supported.\n",
7857 			tname);
7858 		return -EINVAL;
7859 	}
7860 
7861 	/* Convert BTF function arguments into verifier types.
7862 	 * Only PTR_TO_CTX and SCALAR are supported atm.
7863 	 */
7864 	for (i = 0; i < nargs; i++) {
7865 		u32 tags = 0;
7866 		int id = btf_named_start_id(btf, false) - 1;
7867 
7868 		/* 'arg:<tag>' decl_tag takes precedence over derivation of
7869 		 * register type from BTF type itself
7870 		 */
7871 		while ((id = btf_find_next_decl_tag(btf, fn_t, i, "arg:", id)) > 0) {
7872 			const struct btf_type *tag_t = btf_type_by_id(btf, id);
7873 			const char *tag = __btf_name_by_offset(btf, tag_t->name_off) + 4;
7874 
7875 			/* disallow arg tags in static subprogs */
7876 			if (!is_global) {
7877 				bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7878 				return -EOPNOTSUPP;
7879 			}
7880 
7881 			if (strcmp(tag, "ctx") == 0) {
7882 				tags |= ARG_TAG_CTX;
7883 			} else if (strcmp(tag, "trusted") == 0) {
7884 				tags |= ARG_TAG_TRUSTED;
7885 			} else if (strcmp(tag, "untrusted") == 0) {
7886 				tags |= ARG_TAG_UNTRUSTED;
7887 			} else if (strcmp(tag, "nonnull") == 0) {
7888 				tags |= ARG_TAG_NONNULL;
7889 			} else if (strcmp(tag, "nullable") == 0) {
7890 				tags |= ARG_TAG_NULLABLE;
7891 			} else if (strcmp(tag, "arena") == 0) {
7892 				tags |= ARG_TAG_ARENA;
7893 			} else {
7894 				bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7895 				return -EOPNOTSUPP;
7896 			}
7897 		}
7898 		if (id != -ENOENT) {
7899 			bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7900 			return id;
7901 		}
7902 
7903 		t = btf_type_by_id(btf, args[i].type);
7904 		while (btf_type_is_modifier(t))
7905 			t = btf_type_by_id(btf, t->type);
7906 		if (!btf_type_is_ptr(t))
7907 			goto skip_pointer;
7908 
7909 		if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
7910 			if (tags & ~ARG_TAG_CTX) {
7911 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7912 				return -EINVAL;
7913 			}
7914 			if ((tags & ARG_TAG_CTX) &&
7915 			    btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7916 						       prog->expected_attach_type))
7917 				return -EINVAL;
7918 			sub->args[i].arg_type = ARG_PTR_TO_CTX;
7919 			continue;
7920 		}
7921 		if (btf_is_dynptr_ptr(btf, t)) {
7922 			if (tags) {
7923 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7924 				return -EINVAL;
7925 			}
7926 			sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7927 			continue;
7928 		}
7929 		if (tags & ARG_TAG_TRUSTED) {
7930 			int kern_type_id;
7931 
7932 			if (tags & ARG_TAG_NONNULL) {
7933 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7934 				return -EINVAL;
7935 			}
7936 
7937 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7938 			if (kern_type_id < 0)
7939 				return kern_type_id;
7940 
7941 			sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
7942 			if (tags & ARG_TAG_NULLABLE)
7943 				sub->args[i].arg_type |= PTR_MAYBE_NULL;
7944 			sub->args[i].btf_id = kern_type_id;
7945 			continue;
7946 		}
7947 		if (tags & ARG_TAG_UNTRUSTED) {
7948 			struct btf *vmlinux_btf;
7949 			int kern_type_id;
7950 
7951 			if (tags & ~ARG_TAG_UNTRUSTED) {
7952 				bpf_log(log, "arg#%d untrusted cannot be combined with any other tags\n", i);
7953 				return -EINVAL;
7954 			}
7955 
7956 			ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
7957 			if (btf_type_is_void(ref_t) || btf_type_is_primitive(ref_t)) {
7958 				sub->args[i].arg_type = ARG_PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
7959 				sub->args[i].mem_size = 0;
7960 				continue;
7961 			}
7962 
7963 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7964 			if (kern_type_id < 0)
7965 				return kern_type_id;
7966 
7967 			vmlinux_btf = bpf_get_btf_vmlinux();
7968 			ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
7969 			if (!btf_type_is_struct(ref_t)) {
7970 				tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
7971 				bpf_log(log, "arg#%d has type %s '%s', but only struct or primitive types are allowed\n",
7972 					i, btf_type_str(ref_t), tname);
7973 				return -EINVAL;
7974 			}
7975 			sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_UNTRUSTED;
7976 			sub->args[i].btf_id = kern_type_id;
7977 			continue;
7978 		}
7979 		if (tags & ARG_TAG_ARENA) {
7980 			if (tags & ~ARG_TAG_ARENA) {
7981 				bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
7982 				return -EINVAL;
7983 			}
7984 			sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7985 			continue;
7986 		}
7987 		if (is_global) { /* generic user data pointer */
7988 			u32 mem_size;
7989 
7990 			if (tags & ARG_TAG_NULLABLE) {
7991 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7992 				return -EINVAL;
7993 			}
7994 
7995 			t = btf_type_skip_modifiers(btf, t->type, NULL);
7996 			ref_t = btf_resolve_size(btf, t, &mem_size);
7997 			if (IS_ERR(ref_t)) {
7998 				bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7999 					i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
8000 					PTR_ERR(ref_t));
8001 				return -EINVAL;
8002 			}
8003 
8004 			sub->args[i].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
8005 			if (tags & ARG_TAG_NONNULL)
8006 				sub->args[i].arg_type &= ~PTR_MAYBE_NULL;
8007 			sub->args[i].mem_size = mem_size;
8008 			continue;
8009 		}
8010 
8011 skip_pointer:
8012 		if (tags) {
8013 			bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
8014 			return -EINVAL;
8015 		}
8016 		if (btf_type_is_int(t) || btf_is_any_enum(t)) {
8017 			sub->args[i].arg_type = ARG_ANYTHING;
8018 			continue;
8019 		}
8020 		if (!is_global)
8021 			return -EINVAL;
8022 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
8023 			i, btf_type_str(t), tname);
8024 		return -EINVAL;
8025 	}
8026 
8027 	sub->arg_cnt = nargs;
8028 	sub->args_cached = true;
8029 
8030 	return 0;
8031 }
8032 
btf_type_show(const struct btf * btf,u32 type_id,void * obj,struct btf_show * show)8033 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
8034 			  struct btf_show *show)
8035 {
8036 	const struct btf_type *t = btf_type_by_id(btf, type_id);
8037 
8038 	show->btf = btf;
8039 	memset(&show->state, 0, sizeof(show->state));
8040 	memset(&show->obj, 0, sizeof(show->obj));
8041 
8042 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
8043 }
8044 
btf_seq_show(struct btf_show * show,const char * fmt,va_list args)8045 __printf(2, 0) static void btf_seq_show(struct btf_show *show, const char *fmt,
8046 					va_list args)
8047 {
8048 	seq_vprintf((struct seq_file *)show->target, fmt, args);
8049 }
8050 
btf_type_seq_show_flags(const struct btf * btf,u32 type_id,void * obj,struct seq_file * m,u64 flags)8051 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
8052 			    void *obj, struct seq_file *m, u64 flags)
8053 {
8054 	struct btf_show sseq;
8055 
8056 	sseq.target = m;
8057 	sseq.showfn = btf_seq_show;
8058 	sseq.flags = flags;
8059 
8060 	btf_type_show(btf, type_id, obj, &sseq);
8061 
8062 	return sseq.state.status;
8063 }
8064 
btf_type_seq_show(const struct btf * btf,u32 type_id,void * obj,struct seq_file * m)8065 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
8066 		       struct seq_file *m)
8067 {
8068 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
8069 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
8070 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
8071 }
8072 
8073 struct btf_show_snprintf {
8074 	struct btf_show show;
8075 	int len_left;		/* space left in string */
8076 	int len;		/* length we would have written */
8077 };
8078 
btf_snprintf_show(struct btf_show * show,const char * fmt,va_list args)8079 __printf(2, 0) static void btf_snprintf_show(struct btf_show *show, const char *fmt,
8080 					     va_list args)
8081 {
8082 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
8083 	int len;
8084 
8085 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
8086 
8087 	if (len < 0) {
8088 		ssnprintf->len_left = 0;
8089 		ssnprintf->len = len;
8090 	} else if (len >= ssnprintf->len_left) {
8091 		/* no space, drive on to get length we would have written */
8092 		ssnprintf->len_left = 0;
8093 		ssnprintf->len += len;
8094 	} else {
8095 		ssnprintf->len_left -= len;
8096 		ssnprintf->len += len;
8097 		show->target += len;
8098 	}
8099 }
8100 
btf_type_snprintf_show(const struct btf * btf,u32 type_id,void * obj,char * buf,int len,u64 flags)8101 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
8102 			   char *buf, int len, u64 flags)
8103 {
8104 	struct btf_show_snprintf ssnprintf;
8105 
8106 	ssnprintf.show.target = buf;
8107 	ssnprintf.show.flags = flags;
8108 	ssnprintf.show.showfn = btf_snprintf_show;
8109 	ssnprintf.len_left = len;
8110 	ssnprintf.len = 0;
8111 
8112 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
8113 
8114 	/* If we encountered an error, return it. */
8115 	if (ssnprintf.show.state.status)
8116 		return ssnprintf.show.state.status;
8117 
8118 	/* Otherwise return length we would have written */
8119 	return ssnprintf.len;
8120 }
8121 
8122 #ifdef CONFIG_PROC_FS
bpf_btf_show_fdinfo(struct seq_file * m,struct file * filp)8123 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
8124 {
8125 	const struct btf *btf = filp->private_data;
8126 
8127 	seq_printf(m, "btf_id:\t%u\n", READ_ONCE(btf->id));
8128 }
8129 #endif
8130 
btf_release(struct inode * inode,struct file * filp)8131 static int btf_release(struct inode *inode, struct file *filp)
8132 {
8133 	btf_put(filp->private_data);
8134 	return 0;
8135 }
8136 
8137 const struct file_operations btf_fops = {
8138 #ifdef CONFIG_PROC_FS
8139 	.show_fdinfo	= bpf_btf_show_fdinfo,
8140 #endif
8141 	.release	= btf_release,
8142 };
8143 
__btf_new_fd(struct btf * btf)8144 static int __btf_new_fd(struct btf *btf)
8145 {
8146 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
8147 }
8148 
btf_new_fd(const union bpf_attr * attr,bpfptr_t uattr,u32 uattr_size)8149 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
8150 {
8151 	struct btf *btf;
8152 	int ret;
8153 
8154 	btf = btf_parse(attr, uattr, uattr_size);
8155 	if (IS_ERR(btf))
8156 		return PTR_ERR(btf);
8157 
8158 	ret = btf_alloc_id(btf);
8159 	if (ret) {
8160 		btf_free(btf);
8161 		return ret;
8162 	}
8163 
8164 	/*
8165 	 * The BTF ID is published to the userspace.
8166 	 * All BTF free must go through call_rcu() from
8167 	 * now on (i.e. free by calling btf_put()).
8168 	 */
8169 
8170 	ret = __btf_new_fd(btf);
8171 	if (ret < 0)
8172 		btf_put(btf);
8173 
8174 	return ret;
8175 }
8176 
btf_get_by_fd(int fd)8177 struct btf *btf_get_by_fd(int fd)
8178 {
8179 	struct btf *btf;
8180 	CLASS(fd, f)(fd);
8181 
8182 	btf = __btf_get_by_fd(f);
8183 	if (!IS_ERR(btf))
8184 		refcount_inc(&btf->refcnt);
8185 
8186 	return btf;
8187 }
8188 
btf_get_info_by_fd(const struct btf * btf,const union bpf_attr * attr,union bpf_attr __user * uattr)8189 int btf_get_info_by_fd(const struct btf *btf,
8190 		       const union bpf_attr *attr,
8191 		       union bpf_attr __user *uattr)
8192 {
8193 	struct bpf_btf_info __user *uinfo;
8194 	struct bpf_btf_info info;
8195 	u32 info_copy, btf_copy;
8196 	void __user *ubtf;
8197 	char __user *uname;
8198 	u32 uinfo_len, uname_len, name_len;
8199 	int ret = 0;
8200 
8201 	uinfo = u64_to_user_ptr(attr->info.info);
8202 	uinfo_len = attr->info.info_len;
8203 
8204 	info_copy = min_t(u32, uinfo_len, sizeof(info));
8205 	memset(&info, 0, sizeof(info));
8206 	if (copy_from_user(&info, uinfo, info_copy))
8207 		return -EFAULT;
8208 
8209 	info.id = READ_ONCE(btf->id);
8210 	ubtf = u64_to_user_ptr(info.btf);
8211 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
8212 	if (copy_to_user(ubtf, btf->data, btf_copy))
8213 		return -EFAULT;
8214 	info.btf_size = btf->data_size;
8215 
8216 	info.kernel_btf = btf->kernel_btf;
8217 
8218 	uname = u64_to_user_ptr(info.name);
8219 	uname_len = info.name_len;
8220 	if (!uname ^ !uname_len)
8221 		return -EINVAL;
8222 
8223 	name_len = strlen(btf->name);
8224 	info.name_len = name_len;
8225 
8226 	if (uname) {
8227 		if (uname_len >= name_len + 1) {
8228 			if (copy_to_user(uname, btf->name, name_len + 1))
8229 				return -EFAULT;
8230 		} else {
8231 			char zero = '\0';
8232 
8233 			if (copy_to_user(uname, btf->name, uname_len - 1))
8234 				return -EFAULT;
8235 			if (put_user(zero, uname + uname_len - 1))
8236 				return -EFAULT;
8237 			/* let user-space know about too short buffer */
8238 			ret = -ENOSPC;
8239 		}
8240 	}
8241 
8242 	if (copy_to_user(uinfo, &info, info_copy) ||
8243 	    put_user(info_copy, &uattr->info.info_len))
8244 		return -EFAULT;
8245 
8246 	return ret;
8247 }
8248 
btf_get_fd_by_id(u32 id)8249 int btf_get_fd_by_id(u32 id)
8250 {
8251 	struct btf *btf;
8252 	int fd;
8253 
8254 	rcu_read_lock();
8255 	btf = idr_find(&btf_idr, id);
8256 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
8257 		btf = ERR_PTR(-ENOENT);
8258 	rcu_read_unlock();
8259 
8260 	if (IS_ERR(btf))
8261 		return PTR_ERR(btf);
8262 
8263 	fd = __btf_new_fd(btf);
8264 	if (fd < 0)
8265 		btf_put(btf);
8266 
8267 	return fd;
8268 }
8269 
btf_obj_id(const struct btf * btf)8270 u32 btf_obj_id(const struct btf *btf)
8271 {
8272 	return READ_ONCE(btf->id);
8273 }
8274 
btf_is_kernel(const struct btf * btf)8275 bool btf_is_kernel(const struct btf *btf)
8276 {
8277 	return btf->kernel_btf;
8278 }
8279 
btf_is_module(const struct btf * btf)8280 bool btf_is_module(const struct btf *btf)
8281 {
8282 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
8283 }
8284 
8285 enum {
8286 	BTF_MODULE_F_LIVE = (1 << 0),
8287 };
8288 
8289 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8290 struct btf_module {
8291 	struct list_head list;
8292 	struct module *module;
8293 	struct btf *btf;
8294 	struct bin_attribute *sysfs_attr;
8295 	int flags;
8296 };
8297 
8298 static LIST_HEAD(btf_modules);
8299 static DEFINE_MUTEX(btf_module_mutex);
8300 
8301 static void purge_cand_cache(struct btf *btf);
8302 
btf_module_notify(struct notifier_block * nb,unsigned long op,void * module)8303 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
8304 			     void *module)
8305 {
8306 	struct btf_module *btf_mod, *tmp;
8307 	struct module *mod = module;
8308 	struct btf *btf;
8309 	int err = 0;
8310 
8311 	if (mod->btf_data_size == 0 ||
8312 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
8313 	     op != MODULE_STATE_GOING))
8314 		goto out;
8315 
8316 	switch (op) {
8317 	case MODULE_STATE_COMING:
8318 		btf_mod = kzalloc_obj(*btf_mod);
8319 		if (!btf_mod) {
8320 			err = -ENOMEM;
8321 			goto out;
8322 		}
8323 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size,
8324 				       mod->btf_base_data, mod->btf_base_data_size);
8325 		if (IS_ERR(btf)) {
8326 			kfree(btf_mod);
8327 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
8328 				pr_warn("failed to validate module [%s] BTF: %ld\n",
8329 					mod->name, PTR_ERR(btf));
8330 				err = PTR_ERR(btf);
8331 			} else {
8332 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
8333 			}
8334 			goto out;
8335 		}
8336 		err = btf_alloc_id(btf);
8337 		if (err) {
8338 			btf_free(btf);
8339 			kfree(btf_mod);
8340 			goto out;
8341 		}
8342 
8343 		purge_cand_cache(NULL);
8344 		mutex_lock(&btf_module_mutex);
8345 		btf_mod->module = module;
8346 		btf_mod->btf = btf;
8347 		list_add(&btf_mod->list, &btf_modules);
8348 		mutex_unlock(&btf_module_mutex);
8349 
8350 		if (IS_ENABLED(CONFIG_SYSFS)) {
8351 			struct bin_attribute *attr;
8352 
8353 			attr = kzalloc_obj(*attr);
8354 			if (!attr)
8355 				goto out;
8356 
8357 			sysfs_bin_attr_init(attr);
8358 			attr->attr.name = btf->name;
8359 			attr->attr.mode = 0444;
8360 			attr->size = btf->data_size;
8361 			attr->private = btf->data;
8362 			attr->read = sysfs_bin_attr_simple_read;
8363 
8364 			err = sysfs_create_bin_file(btf_kobj, attr);
8365 			if (err) {
8366 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
8367 					mod->name, err);
8368 				kfree(attr);
8369 				err = 0;
8370 				goto out;
8371 			}
8372 
8373 			btf_mod->sysfs_attr = attr;
8374 		}
8375 
8376 		break;
8377 	case MODULE_STATE_LIVE:
8378 		mutex_lock(&btf_module_mutex);
8379 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8380 			if (btf_mod->module != module)
8381 				continue;
8382 
8383 			btf_mod->flags |= BTF_MODULE_F_LIVE;
8384 			break;
8385 		}
8386 		mutex_unlock(&btf_module_mutex);
8387 		break;
8388 	case MODULE_STATE_GOING:
8389 		mutex_lock(&btf_module_mutex);
8390 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8391 			if (btf_mod->module != module)
8392 				continue;
8393 
8394 			/*
8395 			 * For modules, we do the freeing of BTF IDR as soon as
8396 			 * module goes away to disable BTF discovery, since the
8397 			 * btf_try_get_module() on such BTFs will fail. This may
8398 			 * be called again on btf_put(), but it's ok to do so.
8399 			 */
8400 			btf_free_id(btf_mod->btf);
8401 			list_del(&btf_mod->list);
8402 			if (btf_mod->sysfs_attr)
8403 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
8404 			purge_cand_cache(btf_mod->btf);
8405 			btf_put(btf_mod->btf);
8406 			kfree(btf_mod->sysfs_attr);
8407 			kfree(btf_mod);
8408 			break;
8409 		}
8410 		mutex_unlock(&btf_module_mutex);
8411 		break;
8412 	}
8413 out:
8414 	return notifier_from_errno(err);
8415 }
8416 
8417 static struct notifier_block btf_module_nb = {
8418 	.notifier_call = btf_module_notify,
8419 };
8420 
btf_module_init(void)8421 static int __init btf_module_init(void)
8422 {
8423 	register_module_notifier(&btf_module_nb);
8424 	return 0;
8425 }
8426 
8427 fs_initcall(btf_module_init);
8428 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
8429 
btf_try_get_module(const struct btf * btf)8430 struct module *btf_try_get_module(const struct btf *btf)
8431 {
8432 	struct module *res = NULL;
8433 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8434 	struct btf_module *btf_mod, *tmp;
8435 
8436 	mutex_lock(&btf_module_mutex);
8437 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8438 		if (btf_mod->btf != btf)
8439 			continue;
8440 
8441 		/* We must only consider module whose __init routine has
8442 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
8443 		 * which is set from the notifier callback for
8444 		 * MODULE_STATE_LIVE.
8445 		 */
8446 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
8447 			res = btf_mod->module;
8448 
8449 		break;
8450 	}
8451 	mutex_unlock(&btf_module_mutex);
8452 #endif
8453 
8454 	return res;
8455 }
8456 
8457 /* Returns struct btf corresponding to the struct module.
8458  * This function can return NULL or ERR_PTR.
8459  */
btf_get_module_btf(const struct module * module)8460 static struct btf *btf_get_module_btf(const struct module *module)
8461 {
8462 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8463 	struct btf_module *btf_mod, *tmp;
8464 #endif
8465 	struct btf *btf = NULL;
8466 
8467 	if (!module) {
8468 		btf = bpf_get_btf_vmlinux();
8469 		if (!IS_ERR_OR_NULL(btf))
8470 			btf_get(btf);
8471 		return btf;
8472 	}
8473 
8474 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8475 	mutex_lock(&btf_module_mutex);
8476 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8477 		if (btf_mod->module != module)
8478 			continue;
8479 
8480 		btf_get(btf_mod->btf);
8481 		btf = btf_mod->btf;
8482 		break;
8483 	}
8484 	mutex_unlock(&btf_module_mutex);
8485 #endif
8486 
8487 	return btf;
8488 }
8489 
check_btf_kconfigs(const struct module * module,const char * feature)8490 static int check_btf_kconfigs(const struct module *module, const char *feature)
8491 {
8492 	if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
8493 		pr_err("missing vmlinux BTF, cannot register %s\n", feature);
8494 		return -ENOENT;
8495 	}
8496 	if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
8497 		pr_warn("missing module BTF, cannot register %s\n", feature);
8498 	return 0;
8499 }
8500 
BPF_CALL_4(bpf_btf_find_by_name_kind,char *,name,int,name_sz,u32,kind,int,flags)8501 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
8502 {
8503 	struct btf *btf = NULL;
8504 	int btf_obj_fd = 0;
8505 	long ret;
8506 
8507 	if (flags)
8508 		return -EINVAL;
8509 
8510 	if (name_sz <= 1 || name[name_sz - 1])
8511 		return -EINVAL;
8512 
8513 	ret = bpf_find_btf_id(name, kind, &btf);
8514 	if (ret > 0 && btf_is_module(btf)) {
8515 		btf_obj_fd = __btf_new_fd(btf);
8516 		if (btf_obj_fd < 0) {
8517 			btf_put(btf);
8518 			return btf_obj_fd;
8519 		}
8520 		return ret | (((u64)btf_obj_fd) << 32);
8521 	}
8522 	if (ret > 0)
8523 		btf_put(btf);
8524 	return ret;
8525 }
8526 
8527 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
8528 	.func		= bpf_btf_find_by_name_kind,
8529 	.gpl_only	= false,
8530 	.ret_type	= RET_INTEGER,
8531 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
8532 	.arg2_type	= ARG_CONST_SIZE,
8533 	.arg3_type	= ARG_ANYTHING,
8534 	.arg4_type	= ARG_ANYTHING,
8535 };
8536 
BTF_ID_LIST_GLOBAL(btf_tracing_ids,MAX_BTF_TRACING_TYPE)8537 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
8538 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
8539 BTF_TRACING_TYPE_xxx
8540 #undef BTF_TRACING_TYPE
8541 
8542 /* Validate well-formedness of iter argument type.
8543  * On success, return positive BTF ID of iter state's STRUCT type.
8544  * On error, negative error is returned.
8545  */
8546 int btf_check_iter_arg(struct btf *btf, const struct btf_type *func, int arg_idx)
8547 {
8548 	const struct btf_param *arg;
8549 	const struct btf_type *t;
8550 	const char *name;
8551 	int btf_id;
8552 
8553 	if (btf_type_vlen(func) <= arg_idx)
8554 		return -EINVAL;
8555 
8556 	arg = &btf_params(func)[arg_idx];
8557 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
8558 	if (!t || !btf_type_is_ptr(t))
8559 		return -EINVAL;
8560 	t = btf_type_skip_modifiers(btf, t->type, &btf_id);
8561 	if (!t || !__btf_type_is_struct(t))
8562 		return -EINVAL;
8563 
8564 	name = btf_name_by_offset(btf, t->name_off);
8565 	if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
8566 		return -EINVAL;
8567 
8568 	return btf_id;
8569 }
8570 
btf_check_iter_kfuncs(struct btf * btf,const char * func_name,const struct btf_type * func,u32 func_flags)8571 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
8572 				 const struct btf_type *func, u32 func_flags)
8573 {
8574 	u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8575 	const char *sfx, *iter_name;
8576 	const struct btf_type *t;
8577 	char exp_name[128];
8578 	u32 nr_args;
8579 	int btf_id;
8580 
8581 	/* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
8582 	if (!flags || (flags & (flags - 1)))
8583 		return -EINVAL;
8584 
8585 	/* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
8586 	nr_args = btf_type_vlen(func);
8587 	if (nr_args < 1)
8588 		return -EINVAL;
8589 
8590 	btf_id = btf_check_iter_arg(btf, func, 0);
8591 	if (btf_id < 0)
8592 		return btf_id;
8593 
8594 	/* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
8595 	 * fit nicely in stack slots
8596 	 */
8597 	t = btf_type_by_id(btf, btf_id);
8598 	if (t->size == 0 || (t->size % 8))
8599 		return -EINVAL;
8600 
8601 	/* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
8602 	 * naming pattern
8603 	 */
8604 	iter_name = btf_name_by_offset(btf, t->name_off) + sizeof(ITER_PREFIX) - 1;
8605 	if (flags & KF_ITER_NEW)
8606 		sfx = "new";
8607 	else if (flags & KF_ITER_NEXT)
8608 		sfx = "next";
8609 	else /* (flags & KF_ITER_DESTROY) */
8610 		sfx = "destroy";
8611 
8612 	snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
8613 	if (strcmp(func_name, exp_name))
8614 		return -EINVAL;
8615 
8616 	/* only iter constructor should have extra arguments */
8617 	if (!(flags & KF_ITER_NEW) && nr_args != 1)
8618 		return -EINVAL;
8619 
8620 	if (flags & KF_ITER_NEXT) {
8621 		/* bpf_iter_<type>_next() should return pointer */
8622 		t = btf_type_skip_modifiers(btf, func->type, NULL);
8623 		if (!t || !btf_type_is_ptr(t))
8624 			return -EINVAL;
8625 	}
8626 
8627 	if (flags & KF_ITER_DESTROY) {
8628 		/* bpf_iter_<type>_destroy() should return void */
8629 		t = btf_type_by_id(btf, func->type);
8630 		if (!t || !btf_type_is_void(t))
8631 			return -EINVAL;
8632 	}
8633 
8634 	return 0;
8635 }
8636 
btf_check_kfunc_protos(struct btf * btf,u32 func_id,u32 func_flags)8637 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
8638 {
8639 	const struct btf_type *func;
8640 	const char *func_name;
8641 	int err;
8642 
8643 	/* any kfunc should be FUNC -> FUNC_PROTO */
8644 	func = btf_type_by_id(btf, func_id);
8645 	if (!func || !btf_type_is_func(func))
8646 		return -EINVAL;
8647 
8648 	/* sanity check kfunc name */
8649 	func_name = btf_name_by_offset(btf, func->name_off);
8650 	if (!func_name || !func_name[0])
8651 		return -EINVAL;
8652 
8653 	func = btf_type_by_id(btf, func->type);
8654 	if (!func || !btf_type_is_func_proto(func))
8655 		return -EINVAL;
8656 
8657 	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
8658 		err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
8659 		if (err)
8660 			return err;
8661 	}
8662 
8663 	return 0;
8664 }
8665 
8666 /* Kernel Function (kfunc) BTF ID set registration API */
8667 
btf_populate_kfunc_set(struct btf * btf,enum btf_kfunc_hook hook,const struct btf_kfunc_id_set * kset)8668 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
8669 				  const struct btf_kfunc_id_set *kset)
8670 {
8671 	struct btf_kfunc_hook_filter *hook_filter;
8672 	struct btf_id_set8 *add_set = kset->set;
8673 	bool vmlinux_set = !btf_is_module(btf);
8674 	bool add_filter = !!kset->filter;
8675 	struct btf_kfunc_set_tab *tab;
8676 	struct btf_id_set8 *set;
8677 	u32 set_cnt, i;
8678 	int ret;
8679 
8680 	if (hook >= BTF_KFUNC_HOOK_MAX) {
8681 		ret = -EINVAL;
8682 		goto end;
8683 	}
8684 
8685 	if (!add_set->cnt)
8686 		return 0;
8687 
8688 	tab = btf->kfunc_set_tab;
8689 
8690 	if (tab && add_filter) {
8691 		u32 i;
8692 
8693 		hook_filter = &tab->hook_filters[hook];
8694 		for (i = 0; i < hook_filter->nr_filters; i++) {
8695 			if (hook_filter->filters[i] == kset->filter) {
8696 				add_filter = false;
8697 				break;
8698 			}
8699 		}
8700 
8701 		if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8702 			ret = -E2BIG;
8703 			goto end;
8704 		}
8705 	}
8706 
8707 	if (!tab) {
8708 		tab = kzalloc_obj(*tab, GFP_KERNEL | __GFP_NOWARN);
8709 		if (!tab)
8710 			return -ENOMEM;
8711 		btf->kfunc_set_tab = tab;
8712 	}
8713 
8714 	set = tab->sets[hook];
8715 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
8716 	 * for module sets.
8717 	 */
8718 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
8719 		ret = -EINVAL;
8720 		goto end;
8721 	}
8722 
8723 	/* In case of vmlinux sets, there may be more than one set being
8724 	 * registered per hook. To create a unified set, we allocate a new set
8725 	 * and concatenate all individual sets being registered. While each set
8726 	 * is individually sorted, they may become unsorted when concatenated,
8727 	 * hence re-sorting the final set again is required to make binary
8728 	 * searching the set using btf_id_set8_contains function work.
8729 	 *
8730 	 * For module sets, we need to allocate as we may need to relocate
8731 	 * BTF ids.
8732 	 */
8733 	set_cnt = set ? set->cnt : 0;
8734 
8735 	if (set_cnt > U32_MAX - add_set->cnt) {
8736 		ret = -EOVERFLOW;
8737 		goto end;
8738 	}
8739 
8740 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8741 		ret = -E2BIG;
8742 		goto end;
8743 	}
8744 
8745 	/* Grow set */
8746 	set = krealloc(tab->sets[hook],
8747 		       struct_size(set, pairs, set_cnt + add_set->cnt),
8748 		       GFP_KERNEL | __GFP_NOWARN);
8749 	if (!set) {
8750 		ret = -ENOMEM;
8751 		goto end;
8752 	}
8753 
8754 	/* For newly allocated set, initialize set->cnt to 0 */
8755 	if (!tab->sets[hook])
8756 		set->cnt = 0;
8757 	tab->sets[hook] = set;
8758 
8759 	/* Concatenate the two sets */
8760 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
8761 	/* Now that the set is copied, update with relocated BTF ids */
8762 	for (i = set->cnt; i < set->cnt + add_set->cnt; i++)
8763 		set->pairs[i].id = btf_relocate_id(btf, set->pairs[i].id);
8764 
8765 	set->cnt += add_set->cnt;
8766 
8767 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8768 
8769 	if (add_filter) {
8770 		hook_filter = &tab->hook_filters[hook];
8771 		hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8772 	}
8773 	return 0;
8774 end:
8775 	btf_free_kfunc_set_tab(btf);
8776 	return ret;
8777 }
8778 
btf_kfunc_id_set_contains(const struct btf * btf,enum btf_kfunc_hook hook,u32 kfunc_btf_id)8779 static u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8780 				      enum btf_kfunc_hook hook,
8781 				      u32 kfunc_btf_id)
8782 {
8783 	struct btf_id_set8 *set;
8784 	u32 *id;
8785 
8786 	if (hook >= BTF_KFUNC_HOOK_MAX)
8787 		return NULL;
8788 	if (!btf->kfunc_set_tab)
8789 		return NULL;
8790 	set = btf->kfunc_set_tab->sets[hook];
8791 	if (!set)
8792 		return NULL;
8793 	id = btf_id_set8_contains(set, kfunc_btf_id);
8794 	if (!id)
8795 		return NULL;
8796 	/* The flags for BTF ID are located next to it */
8797 	return id + 1;
8798 }
8799 
__btf_kfunc_is_allowed(const struct btf * btf,enum btf_kfunc_hook hook,u32 kfunc_btf_id,const struct bpf_prog * prog)8800 static bool __btf_kfunc_is_allowed(const struct btf *btf,
8801 				   enum btf_kfunc_hook hook,
8802 				   u32 kfunc_btf_id,
8803 				   const struct bpf_prog *prog)
8804 {
8805 	struct btf_kfunc_hook_filter *hook_filter;
8806 	int i;
8807 
8808 	if (hook >= BTF_KFUNC_HOOK_MAX)
8809 		return false;
8810 	if (!btf->kfunc_set_tab)
8811 		return false;
8812 
8813 	hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
8814 	for (i = 0; i < hook_filter->nr_filters; i++) {
8815 		if (hook_filter->filters[i](prog, kfunc_btf_id))
8816 			return false;
8817 	}
8818 
8819 	return true;
8820 }
8821 
bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)8822 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8823 {
8824 	switch (prog_type) {
8825 	case BPF_PROG_TYPE_UNSPEC:
8826 		return BTF_KFUNC_HOOK_COMMON;
8827 	case BPF_PROG_TYPE_XDP:
8828 		return BTF_KFUNC_HOOK_XDP;
8829 	case BPF_PROG_TYPE_SCHED_CLS:
8830 		return BTF_KFUNC_HOOK_TC;
8831 	case BPF_PROG_TYPE_STRUCT_OPS:
8832 		return BTF_KFUNC_HOOK_STRUCT_OPS;
8833 	case BPF_PROG_TYPE_TRACING:
8834 	case BPF_PROG_TYPE_TRACEPOINT:
8835 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8836 	case BPF_PROG_TYPE_PERF_EVENT:
8837 	case BPF_PROG_TYPE_LSM:
8838 		return BTF_KFUNC_HOOK_TRACING;
8839 	case BPF_PROG_TYPE_SYSCALL:
8840 		return BTF_KFUNC_HOOK_SYSCALL;
8841 	case BPF_PROG_TYPE_CGROUP_SKB:
8842 	case BPF_PROG_TYPE_CGROUP_SOCK:
8843 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8844 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8845 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8846 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8847 	case BPF_PROG_TYPE_SOCK_OPS:
8848 		return BTF_KFUNC_HOOK_CGROUP;
8849 	case BPF_PROG_TYPE_SCHED_ACT:
8850 		return BTF_KFUNC_HOOK_SCHED_ACT;
8851 	case BPF_PROG_TYPE_SK_SKB:
8852 		return BTF_KFUNC_HOOK_SK_SKB;
8853 	case BPF_PROG_TYPE_SOCKET_FILTER:
8854 		return BTF_KFUNC_HOOK_SOCKET_FILTER;
8855 	case BPF_PROG_TYPE_LWT_OUT:
8856 	case BPF_PROG_TYPE_LWT_IN:
8857 	case BPF_PROG_TYPE_LWT_XMIT:
8858 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
8859 		return BTF_KFUNC_HOOK_LWT;
8860 	case BPF_PROG_TYPE_NETFILTER:
8861 		return BTF_KFUNC_HOOK_NETFILTER;
8862 	case BPF_PROG_TYPE_KPROBE:
8863 		return BTF_KFUNC_HOOK_KPROBE;
8864 	default:
8865 		return BTF_KFUNC_HOOK_MAX;
8866 	}
8867 }
8868 
btf_kfunc_is_allowed(const struct btf * btf,u32 kfunc_btf_id,const struct bpf_prog * prog)8869 bool btf_kfunc_is_allowed(const struct btf *btf,
8870 			  u32 kfunc_btf_id,
8871 			  const struct bpf_prog *prog)
8872 {
8873 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
8874 	enum btf_kfunc_hook hook;
8875 	u32 *kfunc_flags;
8876 
8877 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
8878 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog))
8879 		return true;
8880 
8881 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
8882 	kfunc_flags = btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
8883 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, hook, kfunc_btf_id, prog))
8884 		return true;
8885 
8886 	return false;
8887 }
8888 
8889 /* Caution:
8890  * Reference to the module (obtained using btf_try_get_module) corresponding to
8891  * the struct btf *MUST* be held when calling this function from verifier
8892  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
8893  * keeping the reference for the duration of the call provides the necessary
8894  * protection for looking up a well-formed btf->kfunc_set_tab.
8895  */
btf_kfunc_flags(const struct btf * btf,u32 kfunc_btf_id,const struct bpf_prog * prog)8896 u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog)
8897 {
8898 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
8899 	enum btf_kfunc_hook hook;
8900 	u32 *kfunc_flags;
8901 
8902 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
8903 	if (kfunc_flags)
8904 		return kfunc_flags;
8905 
8906 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
8907 	return btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
8908 }
8909 
btf_kfunc_is_modify_return(const struct btf * btf,u32 kfunc_btf_id,const struct bpf_prog * prog)8910 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8911 				const struct bpf_prog *prog)
8912 {
8913 	if (!__btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog))
8914 		return NULL;
8915 
8916 	return btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
8917 }
8918 
__register_btf_kfunc_id_set(enum btf_kfunc_hook hook,const struct btf_kfunc_id_set * kset)8919 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8920 				       const struct btf_kfunc_id_set *kset)
8921 {
8922 	struct btf *btf;
8923 	int ret, i;
8924 
8925 	btf = btf_get_module_btf(kset->owner);
8926 	if (!btf)
8927 		return check_btf_kconfigs(kset->owner, "kfunc");
8928 	if (IS_ERR(btf))
8929 		return PTR_ERR(btf);
8930 
8931 	for (i = 0; i < kset->set->cnt; i++) {
8932 		ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
8933 					     kset->set->pairs[i].flags);
8934 		if (ret)
8935 			goto err_out;
8936 	}
8937 
8938 	ret = btf_populate_kfunc_set(btf, hook, kset);
8939 
8940 err_out:
8941 	btf_put(btf);
8942 	return ret;
8943 }
8944 
8945 /* This function must be invoked only from initcalls/module init functions */
register_btf_kfunc_id_set(enum bpf_prog_type prog_type,const struct btf_kfunc_id_set * kset)8946 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
8947 			      const struct btf_kfunc_id_set *kset)
8948 {
8949 	enum btf_kfunc_hook hook;
8950 
8951 	/* All kfuncs need to be tagged as such in BTF.
8952 	 * WARN() for initcall registrations that do not check errors.
8953 	 */
8954 	if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8955 		WARN_ON(!kset->owner);
8956 		return -EINVAL;
8957 	}
8958 
8959 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
8960 	return __register_btf_kfunc_id_set(hook, kset);
8961 }
8962 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8963 
8964 /* This function must be invoked only from initcalls/module init functions */
register_btf_fmodret_id_set(const struct btf_kfunc_id_set * kset)8965 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
8966 {
8967 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8968 }
8969 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8970 
btf_find_dtor_kfunc(struct btf * btf,u32 btf_id)8971 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8972 {
8973 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8974 	struct btf_id_dtor_kfunc *dtor;
8975 
8976 	if (!tab)
8977 		return -ENOENT;
8978 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
8979 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
8980 	 */
8981 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
8982 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
8983 	if (!dtor)
8984 		return -ENOENT;
8985 	return dtor->kfunc_btf_id;
8986 }
8987 
btf_check_dtor_kfuncs(struct btf * btf,const struct btf_id_dtor_kfunc * dtors,u32 cnt)8988 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8989 {
8990 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
8991 	const struct btf_param *args;
8992 	s32 dtor_btf_id;
8993 	u32 nr_args, i;
8994 
8995 	for (i = 0; i < cnt; i++) {
8996 		dtor_btf_id = btf_relocate_id(btf, dtors[i].kfunc_btf_id);
8997 
8998 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
8999 		if (!dtor_func || !btf_type_is_func(dtor_func))
9000 			return -EINVAL;
9001 
9002 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
9003 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
9004 			return -EINVAL;
9005 
9006 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
9007 		t = btf_type_by_id(btf, dtor_func_proto->type);
9008 		if (!t || !btf_type_is_void(t))
9009 			return -EINVAL;
9010 
9011 		nr_args = btf_type_vlen(dtor_func_proto);
9012 		if (nr_args != 1)
9013 			return -EINVAL;
9014 		args = btf_params(dtor_func_proto);
9015 		t = btf_type_by_id(btf, args[0].type);
9016 		/* Allow any pointer type, as width on targets Linux supports
9017 		 * will be same for all pointer types (i.e. sizeof(void *))
9018 		 */
9019 		if (!t || !btf_type_is_ptr(t))
9020 			return -EINVAL;
9021 
9022 		if (IS_ENABLED(CONFIG_CFI_CLANG)) {
9023 			/* Ensure the destructor kfunc type matches btf_dtor_kfunc_t */
9024 			t = btf_type_by_id(btf, t->type);
9025 			if (!btf_type_is_void(t))
9026 				return -EINVAL;
9027 		}
9028 	}
9029 	return 0;
9030 }
9031 
9032 /* This function must be invoked only from initcalls/module init functions */
register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc * dtors,u32 add_cnt,struct module * owner)9033 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
9034 				struct module *owner)
9035 {
9036 	struct btf_id_dtor_kfunc_tab *tab;
9037 	struct btf *btf;
9038 	u32 tab_cnt, i;
9039 	int ret;
9040 
9041 	btf = btf_get_module_btf(owner);
9042 	if (!btf)
9043 		return check_btf_kconfigs(owner, "dtor kfuncs");
9044 	if (IS_ERR(btf))
9045 		return PTR_ERR(btf);
9046 
9047 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
9048 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
9049 		ret = -E2BIG;
9050 		goto end;
9051 	}
9052 
9053 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
9054 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
9055 	if (ret < 0)
9056 		goto end;
9057 
9058 	tab = btf->dtor_kfunc_tab;
9059 	/* Only one call allowed for modules */
9060 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
9061 		ret = -EINVAL;
9062 		goto end;
9063 	}
9064 
9065 	tab_cnt = tab ? tab->cnt : 0;
9066 	if (tab_cnt > U32_MAX - add_cnt) {
9067 		ret = -EOVERFLOW;
9068 		goto end;
9069 	}
9070 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
9071 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
9072 		ret = -E2BIG;
9073 		goto end;
9074 	}
9075 
9076 	tab = krealloc(btf->dtor_kfunc_tab,
9077 		       struct_size(tab, dtors, tab_cnt + add_cnt),
9078 		       GFP_KERNEL | __GFP_NOWARN);
9079 	if (!tab) {
9080 		ret = -ENOMEM;
9081 		goto end;
9082 	}
9083 
9084 	if (!btf->dtor_kfunc_tab)
9085 		tab->cnt = 0;
9086 	btf->dtor_kfunc_tab = tab;
9087 
9088 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
9089 
9090 	/* remap BTF ids based on BTF relocation (if any) */
9091 	for (i = tab_cnt; i < tab_cnt + add_cnt; i++) {
9092 		tab->dtors[i].btf_id = btf_relocate_id(btf, tab->dtors[i].btf_id);
9093 		tab->dtors[i].kfunc_btf_id = btf_relocate_id(btf, tab->dtors[i].kfunc_btf_id);
9094 	}
9095 
9096 	tab->cnt += add_cnt;
9097 
9098 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
9099 
9100 end:
9101 	if (ret)
9102 		btf_free_dtor_kfunc_tab(btf);
9103 	btf_put(btf);
9104 	return ret;
9105 }
9106 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
9107 
9108 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
9109 
9110 /* Check local and target types for compatibility. This check is used for
9111  * type-based CO-RE relocations and follow slightly different rules than
9112  * field-based relocations. This function assumes that root types were already
9113  * checked for name match. Beyond that initial root-level name check, names
9114  * are completely ignored. Compatibility rules are as follows:
9115  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
9116  *     kind should match for local and target types (i.e., STRUCT is not
9117  *     compatible with UNION);
9118  *   - for ENUMs/ENUM64s, the size is ignored;
9119  *   - for INT, size and signedness are ignored;
9120  *   - for ARRAY, dimensionality is ignored, element types are checked for
9121  *     compatibility recursively;
9122  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
9123  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
9124  *   - FUNC_PROTOs are compatible if they have compatible signature: same
9125  *     number of input args and compatible return and argument types.
9126  * These rules are not set in stone and probably will be adjusted as we get
9127  * more experience with using BPF CO-RE relocations.
9128  */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)9129 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
9130 			      const struct btf *targ_btf, __u32 targ_id)
9131 {
9132 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
9133 					   MAX_TYPES_ARE_COMPAT_DEPTH);
9134 }
9135 
9136 #define MAX_TYPES_MATCH_DEPTH 2
9137 
bpf_core_types_match(const struct btf * local_btf,u32 local_id,const struct btf * targ_btf,u32 targ_id)9138 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
9139 			 const struct btf *targ_btf, u32 targ_id)
9140 {
9141 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
9142 				      MAX_TYPES_MATCH_DEPTH);
9143 }
9144 
bpf_core_is_flavor_sep(const char * s)9145 static bool bpf_core_is_flavor_sep(const char *s)
9146 {
9147 	/* check X___Y name pattern, where X and Y are not underscores */
9148 	return s[0] != '_' &&				      /* X */
9149 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
9150 	       s[4] != '_';				      /* Y */
9151 }
9152 
bpf_core_essential_name_len(const char * name)9153 size_t bpf_core_essential_name_len(const char *name)
9154 {
9155 	size_t n = strlen(name);
9156 	int i;
9157 
9158 	for (i = n - 5; i >= 0; i--) {
9159 		if (bpf_core_is_flavor_sep(name + i))
9160 			return i + 1;
9161 	}
9162 	return n;
9163 }
9164 
bpf_free_cands(struct bpf_cand_cache * cands)9165 static void bpf_free_cands(struct bpf_cand_cache *cands)
9166 {
9167 	if (!cands->cnt)
9168 		/* empty candidate array was allocated on stack */
9169 		return;
9170 	kfree(cands);
9171 }
9172 
bpf_free_cands_from_cache(struct bpf_cand_cache * cands)9173 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
9174 {
9175 	kfree(cands->name);
9176 	kfree(cands);
9177 }
9178 
9179 #define VMLINUX_CAND_CACHE_SIZE 31
9180 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
9181 
9182 #define MODULE_CAND_CACHE_SIZE 31
9183 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
9184 
__print_cand_cache(struct bpf_verifier_log * log,struct bpf_cand_cache ** cache,int cache_size)9185 static void __print_cand_cache(struct bpf_verifier_log *log,
9186 			       struct bpf_cand_cache **cache,
9187 			       int cache_size)
9188 {
9189 	struct bpf_cand_cache *cc;
9190 	int i, j;
9191 
9192 	for (i = 0; i < cache_size; i++) {
9193 		cc = cache[i];
9194 		if (!cc)
9195 			continue;
9196 		bpf_log(log, "[%d]%s(", i, cc->name);
9197 		for (j = 0; j < cc->cnt; j++) {
9198 			bpf_log(log, "%d", cc->cands[j].id);
9199 			if (j < cc->cnt - 1)
9200 				bpf_log(log, " ");
9201 		}
9202 		bpf_log(log, "), ");
9203 	}
9204 }
9205 
print_cand_cache(struct bpf_verifier_log * log)9206 static void print_cand_cache(struct bpf_verifier_log *log)
9207 {
9208 	mutex_lock(&cand_cache_mutex);
9209 	bpf_log(log, "vmlinux_cand_cache:");
9210 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9211 	bpf_log(log, "\nmodule_cand_cache:");
9212 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9213 	bpf_log(log, "\n");
9214 	mutex_unlock(&cand_cache_mutex);
9215 }
9216 
hash_cands(struct bpf_cand_cache * cands)9217 static u32 hash_cands(struct bpf_cand_cache *cands)
9218 {
9219 	return jhash(cands->name, cands->name_len, 0);
9220 }
9221 
check_cand_cache(struct bpf_cand_cache * cands,struct bpf_cand_cache ** cache,int cache_size)9222 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
9223 					       struct bpf_cand_cache **cache,
9224 					       int cache_size)
9225 {
9226 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
9227 
9228 	if (cc && cc->name_len == cands->name_len &&
9229 	    !strncmp(cc->name, cands->name, cands->name_len))
9230 		return cc;
9231 	return NULL;
9232 }
9233 
sizeof_cands(int cnt)9234 static size_t sizeof_cands(int cnt)
9235 {
9236 	return offsetof(struct bpf_cand_cache, cands[cnt]);
9237 }
9238 
populate_cand_cache(struct bpf_cand_cache * cands,struct bpf_cand_cache ** cache,int cache_size)9239 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
9240 						  struct bpf_cand_cache **cache,
9241 						  int cache_size)
9242 {
9243 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
9244 
9245 	if (*cc) {
9246 		bpf_free_cands_from_cache(*cc);
9247 		*cc = NULL;
9248 	}
9249 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL_ACCOUNT);
9250 	if (!new_cands) {
9251 		bpf_free_cands(cands);
9252 		return ERR_PTR(-ENOMEM);
9253 	}
9254 	/* strdup the name, since it will stay in cache.
9255 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
9256 	 */
9257 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL_ACCOUNT);
9258 	bpf_free_cands(cands);
9259 	if (!new_cands->name) {
9260 		kfree(new_cands);
9261 		return ERR_PTR(-ENOMEM);
9262 	}
9263 	*cc = new_cands;
9264 	return new_cands;
9265 }
9266 
9267 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
__purge_cand_cache(struct btf * btf,struct bpf_cand_cache ** cache,int cache_size)9268 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
9269 			       int cache_size)
9270 {
9271 	struct bpf_cand_cache *cc;
9272 	int i, j;
9273 
9274 	for (i = 0; i < cache_size; i++) {
9275 		cc = cache[i];
9276 		if (!cc)
9277 			continue;
9278 		if (!btf) {
9279 			/* when new module is loaded purge all of module_cand_cache,
9280 			 * since new module might have candidates with the name
9281 			 * that matches cached cands.
9282 			 */
9283 			bpf_free_cands_from_cache(cc);
9284 			cache[i] = NULL;
9285 			continue;
9286 		}
9287 		/* when module is unloaded purge cache entries
9288 		 * that match module's btf
9289 		 */
9290 		for (j = 0; j < cc->cnt; j++)
9291 			if (cc->cands[j].btf == btf) {
9292 				bpf_free_cands_from_cache(cc);
9293 				cache[i] = NULL;
9294 				break;
9295 			}
9296 	}
9297 
9298 }
9299 
purge_cand_cache(struct btf * btf)9300 static void purge_cand_cache(struct btf *btf)
9301 {
9302 	mutex_lock(&cand_cache_mutex);
9303 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9304 	mutex_unlock(&cand_cache_mutex);
9305 }
9306 #endif
9307 
9308 static struct bpf_cand_cache *
bpf_core_add_cands(struct bpf_cand_cache * cands,const struct btf * targ_btf,int targ_start_id)9309 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
9310 		   int targ_start_id)
9311 {
9312 	struct bpf_cand_cache *new_cands;
9313 	const struct btf_type *t;
9314 	const char *targ_name;
9315 	size_t targ_essent_len;
9316 	int n, i;
9317 
9318 	n = btf_nr_types(targ_btf);
9319 	for (i = targ_start_id; i < n; i++) {
9320 		t = btf_type_by_id(targ_btf, i);
9321 		if (btf_kind(t) != cands->kind)
9322 			continue;
9323 
9324 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
9325 		if (!targ_name)
9326 			continue;
9327 
9328 		/* the resched point is before strncmp to make sure that search
9329 		 * for non-existing name will have a chance to schedule().
9330 		 */
9331 		cond_resched();
9332 
9333 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
9334 			continue;
9335 
9336 		targ_essent_len = bpf_core_essential_name_len(targ_name);
9337 		if (targ_essent_len != cands->name_len)
9338 			continue;
9339 
9340 		/* most of the time there is only one candidate for a given kind+name pair */
9341 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL_ACCOUNT);
9342 		if (!new_cands) {
9343 			bpf_free_cands(cands);
9344 			return ERR_PTR(-ENOMEM);
9345 		}
9346 
9347 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
9348 		bpf_free_cands(cands);
9349 		cands = new_cands;
9350 		cands->cands[cands->cnt].btf = targ_btf;
9351 		cands->cands[cands->cnt].id = i;
9352 		cands->cnt++;
9353 	}
9354 	return cands;
9355 }
9356 
9357 static struct bpf_cand_cache *
bpf_core_find_cands(struct bpf_core_ctx * ctx,u32 local_type_id)9358 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
9359 {
9360 	struct bpf_cand_cache *cands, *cc, local_cand = {};
9361 	const struct btf *local_btf = ctx->btf;
9362 	const struct btf_type *local_type;
9363 	const struct btf *main_btf;
9364 	size_t local_essent_len;
9365 	struct btf *mod_btf;
9366 	const char *name;
9367 	int id;
9368 
9369 	main_btf = bpf_get_btf_vmlinux();
9370 	if (IS_ERR(main_btf))
9371 		return ERR_CAST(main_btf);
9372 	if (!main_btf)
9373 		return ERR_PTR(-EINVAL);
9374 
9375 	local_type = btf_type_by_id(local_btf, local_type_id);
9376 	if (!local_type)
9377 		return ERR_PTR(-EINVAL);
9378 
9379 	name = btf_name_by_offset(local_btf, local_type->name_off);
9380 	if (str_is_empty(name))
9381 		return ERR_PTR(-EINVAL);
9382 	local_essent_len = bpf_core_essential_name_len(name);
9383 
9384 	cands = &local_cand;
9385 	cands->name = name;
9386 	cands->kind = btf_kind(local_type);
9387 	cands->name_len = local_essent_len;
9388 
9389 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9390 	/* cands is a pointer to stack here */
9391 	if (cc) {
9392 		if (cc->cnt)
9393 			return cc;
9394 		goto check_modules;
9395 	}
9396 
9397 	/* Attempt to find target candidates in vmlinux BTF first */
9398 	cands = bpf_core_add_cands(cands, main_btf, btf_named_start_id(main_btf, true));
9399 	if (IS_ERR(cands))
9400 		return ERR_CAST(cands);
9401 
9402 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
9403 
9404 	/* populate cache even when cands->cnt == 0 */
9405 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9406 	if (IS_ERR(cc))
9407 		return ERR_CAST(cc);
9408 
9409 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
9410 	if (cc->cnt)
9411 		return cc;
9412 
9413 check_modules:
9414 	/* cands is a pointer to stack here and cands->cnt == 0 */
9415 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9416 	if (cc)
9417 		/* if cache has it return it even if cc->cnt == 0 */
9418 		return cc;
9419 
9420 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
9421 	spin_lock_bh(&btf_idr_lock);
9422 	idr_for_each_entry(&btf_idr, mod_btf, id) {
9423 		if (!btf_is_module(mod_btf))
9424 			continue;
9425 		/* linear search could be slow hence unlock/lock
9426 		 * the IDR to avoiding holding it for too long
9427 		 */
9428 		btf_get(mod_btf);
9429 		spin_unlock_bh(&btf_idr_lock);
9430 		cands = bpf_core_add_cands(cands, mod_btf, btf_named_start_id(mod_btf, true));
9431 		btf_put(mod_btf);
9432 		if (IS_ERR(cands))
9433 			return ERR_CAST(cands);
9434 		spin_lock_bh(&btf_idr_lock);
9435 	}
9436 	spin_unlock_bh(&btf_idr_lock);
9437 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
9438 	 * or pointer to stack if cands->cnd == 0.
9439 	 * Copy it into the cache even when cands->cnt == 0 and
9440 	 * return the result.
9441 	 */
9442 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9443 }
9444 
bpf_core_apply(struct bpf_core_ctx * ctx,const struct bpf_core_relo * relo,int relo_idx,void * insn)9445 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
9446 		   int relo_idx, void *insn)
9447 {
9448 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
9449 	struct bpf_core_cand_list cands = {};
9450 	struct bpf_core_relo_res targ_res;
9451 	struct bpf_core_spec *specs;
9452 	const struct btf_type *type;
9453 	int err;
9454 
9455 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
9456 	 * into arrays of btf_ids of struct fields and array indices.
9457 	 */
9458 	specs = kzalloc_objs(*specs, 3, GFP_KERNEL_ACCOUNT);
9459 	if (!specs)
9460 		return -ENOMEM;
9461 
9462 	type = btf_type_by_id(ctx->btf, relo->type_id);
9463 	if (!type) {
9464 		bpf_log(ctx->log, "relo #%u: bad type id %u\n",
9465 			relo_idx, relo->type_id);
9466 		kfree(specs);
9467 		return -EINVAL;
9468 	}
9469 
9470 	if (need_cands) {
9471 		struct bpf_cand_cache *cc;
9472 		int i;
9473 
9474 		mutex_lock(&cand_cache_mutex);
9475 		cc = bpf_core_find_cands(ctx, relo->type_id);
9476 		if (IS_ERR(cc)) {
9477 			bpf_log(ctx->log, "target candidate search failed for %d\n",
9478 				relo->type_id);
9479 			err = PTR_ERR(cc);
9480 			goto out;
9481 		}
9482 		if (cc->cnt) {
9483 			cands.cands = kzalloc_objs(*cands.cands, cc->cnt,
9484 						   GFP_KERNEL_ACCOUNT);
9485 			if (!cands.cands) {
9486 				err = -ENOMEM;
9487 				goto out;
9488 			}
9489 		}
9490 		for (i = 0; i < cc->cnt; i++) {
9491 			bpf_log(ctx->log,
9492 				"CO-RE relocating %s %s: found target candidate [%d]\n",
9493 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
9494 			cands.cands[i].btf = cc->cands[i].btf;
9495 			cands.cands[i].id = cc->cands[i].id;
9496 		}
9497 		cands.len = cc->cnt;
9498 		/* cand_cache_mutex needs to span the cache lookup and
9499 		 * copy of btf pointer into bpf_core_cand_list,
9500 		 * since module can be unloaded while bpf_core_calc_relo_insn
9501 		 * is working with module's btf.
9502 		 */
9503 	}
9504 
9505 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
9506 				      &targ_res);
9507 	if (err)
9508 		goto out;
9509 
9510 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
9511 				  &targ_res);
9512 
9513 out:
9514 	kfree(specs);
9515 	if (need_cands) {
9516 		kfree(cands.cands);
9517 		mutex_unlock(&cand_cache_mutex);
9518 		if (ctx->log->level & BPF_LOG_LEVEL2)
9519 			print_cand_cache(ctx->log);
9520 	}
9521 	return err;
9522 }
9523 
btf_nested_type_is_trusted(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,const char * field_name,u32 btf_id,const char * suffix)9524 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
9525 				const struct bpf_reg_state *reg,
9526 				const char *field_name, u32 btf_id, const char *suffix)
9527 {
9528 	struct btf *btf = reg->btf;
9529 	const struct btf_type *walk_type, *safe_type;
9530 	const char *tname;
9531 	char safe_tname[64];
9532 	long ret, safe_id;
9533 	const struct btf_member *member;
9534 	u32 i;
9535 
9536 	walk_type = btf_type_by_id(btf, reg->btf_id);
9537 	if (!walk_type)
9538 		return false;
9539 
9540 	tname = btf_name_by_offset(btf, walk_type->name_off);
9541 
9542 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
9543 	if (ret >= sizeof(safe_tname))
9544 		return false;
9545 
9546 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
9547 	if (safe_id < 0)
9548 		return false;
9549 
9550 	safe_type = btf_type_by_id(btf, safe_id);
9551 	if (!safe_type)
9552 		return false;
9553 
9554 	for_each_member(i, safe_type, member) {
9555 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
9556 		const struct btf_type *mtype = btf_type_by_id(btf, member->type);
9557 		u32 id;
9558 
9559 		if (!btf_type_is_ptr(mtype))
9560 			continue;
9561 
9562 		btf_type_skip_modifiers(btf, mtype->type, &id);
9563 		/* If we match on both type and name, the field is considered trusted. */
9564 		if (btf_id == id && !strcmp(field_name, m_name))
9565 			return true;
9566 	}
9567 
9568 	return false;
9569 }
9570 
btf_type_ids_nocast_alias(struct bpf_verifier_log * log,const struct btf * reg_btf,u32 reg_id,const struct btf * arg_btf,u32 arg_id)9571 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
9572 			       const struct btf *reg_btf, u32 reg_id,
9573 			       const struct btf *arg_btf, u32 arg_id)
9574 {
9575 	const char *reg_name, *arg_name, *search_needle;
9576 	const struct btf_type *reg_type, *arg_type;
9577 	int reg_len, arg_len, cmp_len;
9578 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
9579 
9580 	reg_type = btf_type_by_id(reg_btf, reg_id);
9581 	if (!reg_type)
9582 		return false;
9583 
9584 	arg_type = btf_type_by_id(arg_btf, arg_id);
9585 	if (!arg_type)
9586 		return false;
9587 
9588 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
9589 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
9590 
9591 	reg_len = strlen(reg_name);
9592 	arg_len = strlen(arg_name);
9593 
9594 	/* Exactly one of the two type names may be suffixed with ___init, so
9595 	 * if the strings are the same size, they can't possibly be no-cast
9596 	 * aliases of one another. If you have two of the same type names, e.g.
9597 	 * they're both nf_conn___init, it would be improper to return true
9598 	 * because they are _not_ no-cast aliases, they are the same type.
9599 	 */
9600 	if (reg_len == arg_len)
9601 		return false;
9602 
9603 	/* Either of the two names must be the other name, suffixed with ___init. */
9604 	if ((reg_len != arg_len + pattern_len) &&
9605 	    (arg_len != reg_len + pattern_len))
9606 		return false;
9607 
9608 	if (reg_len < arg_len) {
9609 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
9610 		cmp_len = reg_len;
9611 	} else {
9612 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
9613 		cmp_len = arg_len;
9614 	}
9615 
9616 	if (!search_needle)
9617 		return false;
9618 
9619 	/* ___init suffix must come at the end of the name */
9620 	if (*(search_needle + pattern_len) != '\0')
9621 		return false;
9622 
9623 	return !strncmp(reg_name, arg_name, cmp_len);
9624 }
9625 
9626 #ifdef CONFIG_BPF_JIT
9627 static int
btf_add_struct_ops(struct btf * btf,struct bpf_struct_ops * st_ops,struct bpf_verifier_log * log)9628 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
9629 		   struct bpf_verifier_log *log)
9630 {
9631 	struct btf_struct_ops_tab *tab, *new_tab;
9632 	int i, err;
9633 
9634 	tab = btf->struct_ops_tab;
9635 	if (!tab) {
9636 		tab = kzalloc_flex(*tab, ops, 4);
9637 		if (!tab)
9638 			return -ENOMEM;
9639 		tab->capacity = 4;
9640 		btf->struct_ops_tab = tab;
9641 	}
9642 
9643 	for (i = 0; i < tab->cnt; i++)
9644 		if (tab->ops[i].st_ops == st_ops)
9645 			return -EEXIST;
9646 
9647 	if (tab->cnt == tab->capacity) {
9648 		new_tab = krealloc(tab,
9649 				   struct_size(tab, ops, tab->capacity * 2),
9650 				   GFP_KERNEL);
9651 		if (!new_tab)
9652 			return -ENOMEM;
9653 		tab = new_tab;
9654 		tab->capacity *= 2;
9655 		btf->struct_ops_tab = tab;
9656 	}
9657 
9658 	tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
9659 
9660 	err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
9661 	if (err)
9662 		return err;
9663 
9664 	btf->struct_ops_tab->cnt++;
9665 
9666 	return 0;
9667 }
9668 
9669 const struct bpf_struct_ops_desc *
bpf_struct_ops_find_value(struct btf * btf,u32 value_id)9670 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
9671 {
9672 	const struct bpf_struct_ops_desc *st_ops_list;
9673 	unsigned int i;
9674 	u32 cnt;
9675 
9676 	if (!value_id)
9677 		return NULL;
9678 	if (!btf->struct_ops_tab)
9679 		return NULL;
9680 
9681 	cnt = btf->struct_ops_tab->cnt;
9682 	st_ops_list = btf->struct_ops_tab->ops;
9683 	for (i = 0; i < cnt; i++) {
9684 		if (st_ops_list[i].value_id == value_id)
9685 			return &st_ops_list[i];
9686 	}
9687 
9688 	return NULL;
9689 }
9690 
9691 const struct bpf_struct_ops_desc *
bpf_struct_ops_find(struct btf * btf,u32 type_id)9692 bpf_struct_ops_find(struct btf *btf, u32 type_id)
9693 {
9694 	const struct bpf_struct_ops_desc *st_ops_list;
9695 	unsigned int i;
9696 	u32 cnt;
9697 
9698 	if (!type_id)
9699 		return NULL;
9700 	if (!btf->struct_ops_tab)
9701 		return NULL;
9702 
9703 	cnt = btf->struct_ops_tab->cnt;
9704 	st_ops_list = btf->struct_ops_tab->ops;
9705 	for (i = 0; i < cnt; i++) {
9706 		if (st_ops_list[i].type_id == type_id)
9707 			return &st_ops_list[i];
9708 	}
9709 
9710 	return NULL;
9711 }
9712 
__register_bpf_struct_ops(struct bpf_struct_ops * st_ops)9713 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
9714 {
9715 	struct bpf_verifier_log *log;
9716 	struct btf *btf;
9717 	int err = 0;
9718 
9719 	btf = btf_get_module_btf(st_ops->owner);
9720 	if (!btf)
9721 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
9722 	if (IS_ERR(btf))
9723 		return PTR_ERR(btf);
9724 
9725 	log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
9726 	if (!log) {
9727 		err = -ENOMEM;
9728 		goto errout;
9729 	}
9730 
9731 	log->level = BPF_LOG_KERNEL;
9732 
9733 	err = btf_add_struct_ops(btf, st_ops, log);
9734 
9735 errout:
9736 	kfree(log);
9737 	btf_put(btf);
9738 
9739 	return err;
9740 }
9741 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
9742 #endif
9743 
btf_param_match_suffix(const struct btf * btf,const struct btf_param * arg,const char * suffix)9744 bool btf_param_match_suffix(const struct btf *btf,
9745 			    const struct btf_param *arg,
9746 			    const char *suffix)
9747 {
9748 	int suffix_len = strlen(suffix), len;
9749 	const char *param_name;
9750 
9751 	/* In the future, this can be ported to use BTF tagging */
9752 	param_name = btf_name_by_offset(btf, arg->name_off);
9753 	if (str_is_empty(param_name))
9754 		return false;
9755 	len = strlen(param_name);
9756 	if (len <= suffix_len)
9757 		return false;
9758 	param_name += len - suffix_len;
9759 	return !strncmp(param_name, suffix, suffix_len);
9760 }
9761