xref: /linux/kernel/bpf/btf.c (revision ed30aef3c864f99111e16d4ea5cf29488d99a278)
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/skmsg.h>
23 #include <linux/perf_event.h>
24 #include <linux/bsearch.h>
25 #include <linux/kobject.h>
26 #include <linux/sysfs.h>
27 #include <net/sock.h>
28 
29 /* BTF (BPF Type Format) is the meta data format which describes
30  * the data types of BPF program/map.  Hence, it basically focus
31  * on the C programming language which the modern BPF is primary
32  * using.
33  *
34  * ELF Section:
35  * ~~~~~~~~~~~
36  * The BTF data is stored under the ".BTF" ELF section
37  *
38  * struct btf_type:
39  * ~~~~~~~~~~~~~~~
40  * Each 'struct btf_type' object describes a C data type.
41  * Depending on the type it is describing, a 'struct btf_type'
42  * object may be followed by more data.  F.e.
43  * To describe an array, 'struct btf_type' is followed by
44  * 'struct btf_array'.
45  *
46  * 'struct btf_type' and any extra data following it are
47  * 4 bytes aligned.
48  *
49  * Type section:
50  * ~~~~~~~~~~~~~
51  * The BTF type section contains a list of 'struct btf_type' objects.
52  * Each one describes a C type.  Recall from the above section
53  * that a 'struct btf_type' object could be immediately followed by extra
54  * data in order to desribe some particular C types.
55  *
56  * type_id:
57  * ~~~~~~~
58  * Each btf_type object is identified by a type_id.  The type_id
59  * is implicitly implied by the location of the btf_type object in
60  * the BTF type section.  The first one has type_id 1.  The second
61  * one has type_id 2...etc.  Hence, an earlier btf_type has
62  * a smaller type_id.
63  *
64  * A btf_type object may refer to another btf_type object by using
65  * type_id (i.e. the "type" in the "struct btf_type").
66  *
67  * NOTE that we cannot assume any reference-order.
68  * A btf_type object can refer to an earlier btf_type object
69  * but it can also refer to a later btf_type object.
70  *
71  * For example, to describe "const void *".  A btf_type
72  * object describing "const" may refer to another btf_type
73  * object describing "void *".  This type-reference is done
74  * by specifying type_id:
75  *
76  * [1] CONST (anon) type_id=2
77  * [2] PTR (anon) type_id=0
78  *
79  * The above is the btf_verifier debug log:
80  *   - Each line started with "[?]" is a btf_type object
81  *   - [?] is the type_id of the btf_type object.
82  *   - CONST/PTR is the BTF_KIND_XXX
83  *   - "(anon)" is the name of the type.  It just
84  *     happens that CONST and PTR has no name.
85  *   - type_id=XXX is the 'u32 type' in btf_type
86  *
87  * NOTE: "void" has type_id 0
88  *
89  * String section:
90  * ~~~~~~~~~~~~~~
91  * The BTF string section contains the names used by the type section.
92  * Each string is referred by an "offset" from the beginning of the
93  * string section.
94  *
95  * Each string is '\0' terminated.
96  *
97  * The first character in the string section must be '\0'
98  * which is used to mean 'anonymous'. Some btf_type may not
99  * have a name.
100  */
101 
102 /* BTF verification:
103  *
104  * To verify BTF data, two passes are needed.
105  *
106  * Pass #1
107  * ~~~~~~~
108  * The first pass is to collect all btf_type objects to
109  * an array: "btf->types".
110  *
111  * Depending on the C type that a btf_type is describing,
112  * a btf_type may be followed by extra data.  We don't know
113  * how many btf_type is there, and more importantly we don't
114  * know where each btf_type is located in the type section.
115  *
116  * Without knowing the location of each type_id, most verifications
117  * cannot be done.  e.g. an earlier btf_type may refer to a later
118  * btf_type (recall the "const void *" above), so we cannot
119  * check this type-reference in the first pass.
120  *
121  * In the first pass, it still does some verifications (e.g.
122  * checking the name is a valid offset to the string section).
123  *
124  * Pass #2
125  * ~~~~~~~
126  * The main focus is to resolve a btf_type that is referring
127  * to another type.
128  *
129  * We have to ensure the referring type:
130  * 1) does exist in the BTF (i.e. in btf->types[])
131  * 2) does not cause a loop:
132  *	struct A {
133  *		struct B b;
134  *	};
135  *
136  *	struct B {
137  *		struct A a;
138  *	};
139  *
140  * btf_type_needs_resolve() decides if a btf_type needs
141  * to be resolved.
142  *
143  * The needs_resolve type implements the "resolve()" ops which
144  * essentially does a DFS and detects backedge.
145  *
146  * During resolve (or DFS), different C types have different
147  * "RESOLVED" conditions.
148  *
149  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
150  * members because a member is always referring to another
151  * type.  A struct's member can be treated as "RESOLVED" if
152  * it is referring to a BTF_KIND_PTR.  Otherwise, the
153  * following valid C struct would be rejected:
154  *
155  *	struct A {
156  *		int m;
157  *		struct A *a;
158  *	};
159  *
160  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
161  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
162  * detect a pointer loop, e.g.:
163  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
164  *                        ^                                         |
165  *                        +-----------------------------------------+
166  *
167  */
168 
169 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
170 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
171 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
172 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
173 #define BITS_ROUNDUP_BYTES(bits) \
174 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
175 
176 #define BTF_INFO_MASK 0x8f00ffff
177 #define BTF_INT_MASK 0x0fffffff
178 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
179 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
180 
181 /* 16MB for 64k structs and each has 16 members and
182  * a few MB spaces for the string section.
183  * The hard limit is S32_MAX.
184  */
185 #define BTF_MAX_SIZE (16 * 1024 * 1024)
186 
187 #define for_each_member_from(i, from, struct_type, member)		\
188 	for (i = from, member = btf_type_member(struct_type) + from;	\
189 	     i < btf_type_vlen(struct_type);				\
190 	     i++, member++)
191 
192 #define for_each_vsi_from(i, from, struct_type, member)				\
193 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
194 	     i < btf_type_vlen(struct_type);					\
195 	     i++, member++)
196 
197 DEFINE_IDR(btf_idr);
198 DEFINE_SPINLOCK(btf_idr_lock);
199 
200 struct btf {
201 	void *data;
202 	struct btf_type **types;
203 	u32 *resolved_ids;
204 	u32 *resolved_sizes;
205 	const char *strings;
206 	void *nohdr_data;
207 	struct btf_header hdr;
208 	u32 nr_types; /* includes VOID for base BTF */
209 	u32 types_size;
210 	u32 data_size;
211 	refcount_t refcnt;
212 	u32 id;
213 	struct rcu_head rcu;
214 
215 	/* split BTF support */
216 	struct btf *base_btf;
217 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
218 	u32 start_str_off; /* first string offset (0 for base BTF) */
219 	char name[MODULE_NAME_LEN];
220 	bool kernel_btf;
221 };
222 
223 enum verifier_phase {
224 	CHECK_META,
225 	CHECK_TYPE,
226 };
227 
228 struct resolve_vertex {
229 	const struct btf_type *t;
230 	u32 type_id;
231 	u16 next_member;
232 };
233 
234 enum visit_state {
235 	NOT_VISITED,
236 	VISITED,
237 	RESOLVED,
238 };
239 
240 enum resolve_mode {
241 	RESOLVE_TBD,	/* To Be Determined */
242 	RESOLVE_PTR,	/* Resolving for Pointer */
243 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
244 					 * or array
245 					 */
246 };
247 
248 #define MAX_RESOLVE_DEPTH 32
249 
250 struct btf_sec_info {
251 	u32 off;
252 	u32 len;
253 };
254 
255 struct btf_verifier_env {
256 	struct btf *btf;
257 	u8 *visit_states;
258 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
259 	struct bpf_verifier_log log;
260 	u32 log_type_id;
261 	u32 top_stack;
262 	enum verifier_phase phase;
263 	enum resolve_mode resolve_mode;
264 };
265 
266 static const char * const btf_kind_str[NR_BTF_KINDS] = {
267 	[BTF_KIND_UNKN]		= "UNKNOWN",
268 	[BTF_KIND_INT]		= "INT",
269 	[BTF_KIND_PTR]		= "PTR",
270 	[BTF_KIND_ARRAY]	= "ARRAY",
271 	[BTF_KIND_STRUCT]	= "STRUCT",
272 	[BTF_KIND_UNION]	= "UNION",
273 	[BTF_KIND_ENUM]		= "ENUM",
274 	[BTF_KIND_FWD]		= "FWD",
275 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
276 	[BTF_KIND_VOLATILE]	= "VOLATILE",
277 	[BTF_KIND_CONST]	= "CONST",
278 	[BTF_KIND_RESTRICT]	= "RESTRICT",
279 	[BTF_KIND_FUNC]		= "FUNC",
280 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
281 	[BTF_KIND_VAR]		= "VAR",
282 	[BTF_KIND_DATASEC]	= "DATASEC",
283 };
284 
285 static const char *btf_type_str(const struct btf_type *t)
286 {
287 	return btf_kind_str[BTF_INFO_KIND(t->info)];
288 }
289 
290 /* Chunk size we use in safe copy of data to be shown. */
291 #define BTF_SHOW_OBJ_SAFE_SIZE		32
292 
293 /*
294  * This is the maximum size of a base type value (equivalent to a
295  * 128-bit int); if we are at the end of our safe buffer and have
296  * less than 16 bytes space we can't be assured of being able
297  * to copy the next type safely, so in such cases we will initiate
298  * a new copy.
299  */
300 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
301 
302 /* Type name size */
303 #define BTF_SHOW_NAME_SIZE		80
304 
305 /*
306  * Common data to all BTF show operations. Private show functions can add
307  * their own data to a structure containing a struct btf_show and consult it
308  * in the show callback.  See btf_type_show() below.
309  *
310  * One challenge with showing nested data is we want to skip 0-valued
311  * data, but in order to figure out whether a nested object is all zeros
312  * we need to walk through it.  As a result, we need to make two passes
313  * when handling structs, unions and arrays; the first path simply looks
314  * for nonzero data, while the second actually does the display.  The first
315  * pass is signalled by show->state.depth_check being set, and if we
316  * encounter a non-zero value we set show->state.depth_to_show to
317  * the depth at which we encountered it.  When we have completed the
318  * first pass, we will know if anything needs to be displayed if
319  * depth_to_show > depth.  See btf_[struct,array]_show() for the
320  * implementation of this.
321  *
322  * Another problem is we want to ensure the data for display is safe to
323  * access.  To support this, the anonymous "struct {} obj" tracks the data
324  * object and our safe copy of it.  We copy portions of the data needed
325  * to the object "copy" buffer, but because its size is limited to
326  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
327  * traverse larger objects for display.
328  *
329  * The various data type show functions all start with a call to
330  * btf_show_start_type() which returns a pointer to the safe copy
331  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
332  * raw data itself).  btf_show_obj_safe() is responsible for
333  * using copy_from_kernel_nofault() to update the safe data if necessary
334  * as we traverse the object's data.  skbuff-like semantics are
335  * used:
336  *
337  * - obj.head points to the start of the toplevel object for display
338  * - obj.size is the size of the toplevel object
339  * - obj.data points to the current point in the original data at
340  *   which our safe data starts.  obj.data will advance as we copy
341  *   portions of the data.
342  *
343  * In most cases a single copy will suffice, but larger data structures
344  * such as "struct task_struct" will require many copies.  The logic in
345  * btf_show_obj_safe() handles the logic that determines if a new
346  * copy_from_kernel_nofault() is needed.
347  */
348 struct btf_show {
349 	u64 flags;
350 	void *target;	/* target of show operation (seq file, buffer) */
351 	void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
352 	const struct btf *btf;
353 	/* below are used during iteration */
354 	struct {
355 		u8 depth;
356 		u8 depth_to_show;
357 		u8 depth_check;
358 		u8 array_member:1,
359 		   array_terminated:1;
360 		u16 array_encoding;
361 		u32 type_id;
362 		int status;			/* non-zero for error */
363 		const struct btf_type *type;
364 		const struct btf_member *member;
365 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
366 	} state;
367 	struct {
368 		u32 size;
369 		void *head;
370 		void *data;
371 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
372 	} obj;
373 };
374 
375 struct btf_kind_operations {
376 	s32 (*check_meta)(struct btf_verifier_env *env,
377 			  const struct btf_type *t,
378 			  u32 meta_left);
379 	int (*resolve)(struct btf_verifier_env *env,
380 		       const struct resolve_vertex *v);
381 	int (*check_member)(struct btf_verifier_env *env,
382 			    const struct btf_type *struct_type,
383 			    const struct btf_member *member,
384 			    const struct btf_type *member_type);
385 	int (*check_kflag_member)(struct btf_verifier_env *env,
386 				  const struct btf_type *struct_type,
387 				  const struct btf_member *member,
388 				  const struct btf_type *member_type);
389 	void (*log_details)(struct btf_verifier_env *env,
390 			    const struct btf_type *t);
391 	void (*show)(const struct btf *btf, const struct btf_type *t,
392 			 u32 type_id, void *data, u8 bits_offsets,
393 			 struct btf_show *show);
394 };
395 
396 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
397 static struct btf_type btf_void;
398 
399 static int btf_resolve(struct btf_verifier_env *env,
400 		       const struct btf_type *t, u32 type_id);
401 
402 static bool btf_type_is_modifier(const struct btf_type *t)
403 {
404 	/* Some of them is not strictly a C modifier
405 	 * but they are grouped into the same bucket
406 	 * for BTF concern:
407 	 *   A type (t) that refers to another
408 	 *   type through t->type AND its size cannot
409 	 *   be determined without following the t->type.
410 	 *
411 	 * ptr does not fall into this bucket
412 	 * because its size is always sizeof(void *).
413 	 */
414 	switch (BTF_INFO_KIND(t->info)) {
415 	case BTF_KIND_TYPEDEF:
416 	case BTF_KIND_VOLATILE:
417 	case BTF_KIND_CONST:
418 	case BTF_KIND_RESTRICT:
419 		return true;
420 	}
421 
422 	return false;
423 }
424 
425 bool btf_type_is_void(const struct btf_type *t)
426 {
427 	return t == &btf_void;
428 }
429 
430 static bool btf_type_is_fwd(const struct btf_type *t)
431 {
432 	return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
433 }
434 
435 static bool btf_type_nosize(const struct btf_type *t)
436 {
437 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
438 	       btf_type_is_func(t) || btf_type_is_func_proto(t);
439 }
440 
441 static bool btf_type_nosize_or_null(const struct btf_type *t)
442 {
443 	return !t || btf_type_nosize(t);
444 }
445 
446 static bool __btf_type_is_struct(const struct btf_type *t)
447 {
448 	return BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT;
449 }
450 
451 static bool btf_type_is_array(const struct btf_type *t)
452 {
453 	return BTF_INFO_KIND(t->info) == BTF_KIND_ARRAY;
454 }
455 
456 static bool btf_type_is_datasec(const struct btf_type *t)
457 {
458 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
459 }
460 
461 static u32 btf_nr_types_total(const struct btf *btf)
462 {
463 	u32 total = 0;
464 
465 	while (btf) {
466 		total += btf->nr_types;
467 		btf = btf->base_btf;
468 	}
469 
470 	return total;
471 }
472 
473 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
474 {
475 	const struct btf_type *t;
476 	const char *tname;
477 	u32 i, total;
478 
479 	total = btf_nr_types_total(btf);
480 	for (i = 1; i < total; i++) {
481 		t = btf_type_by_id(btf, i);
482 		if (BTF_INFO_KIND(t->info) != kind)
483 			continue;
484 
485 		tname = btf_name_by_offset(btf, t->name_off);
486 		if (!strcmp(tname, name))
487 			return i;
488 	}
489 
490 	return -ENOENT;
491 }
492 
493 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
494 					       u32 id, u32 *res_id)
495 {
496 	const struct btf_type *t = btf_type_by_id(btf, id);
497 
498 	while (btf_type_is_modifier(t)) {
499 		id = t->type;
500 		t = btf_type_by_id(btf, t->type);
501 	}
502 
503 	if (res_id)
504 		*res_id = id;
505 
506 	return t;
507 }
508 
509 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
510 					    u32 id, u32 *res_id)
511 {
512 	const struct btf_type *t;
513 
514 	t = btf_type_skip_modifiers(btf, id, NULL);
515 	if (!btf_type_is_ptr(t))
516 		return NULL;
517 
518 	return btf_type_skip_modifiers(btf, t->type, res_id);
519 }
520 
521 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
522 						 u32 id, u32 *res_id)
523 {
524 	const struct btf_type *ptype;
525 
526 	ptype = btf_type_resolve_ptr(btf, id, res_id);
527 	if (ptype && btf_type_is_func_proto(ptype))
528 		return ptype;
529 
530 	return NULL;
531 }
532 
533 /* Types that act only as a source, not sink or intermediate
534  * type when resolving.
535  */
536 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
537 {
538 	return btf_type_is_var(t) ||
539 	       btf_type_is_datasec(t);
540 }
541 
542 /* What types need to be resolved?
543  *
544  * btf_type_is_modifier() is an obvious one.
545  *
546  * btf_type_is_struct() because its member refers to
547  * another type (through member->type).
548  *
549  * btf_type_is_var() because the variable refers to
550  * another type. btf_type_is_datasec() holds multiple
551  * btf_type_is_var() types that need resolving.
552  *
553  * btf_type_is_array() because its element (array->type)
554  * refers to another type.  Array can be thought of a
555  * special case of struct while array just has the same
556  * member-type repeated by array->nelems of times.
557  */
558 static bool btf_type_needs_resolve(const struct btf_type *t)
559 {
560 	return btf_type_is_modifier(t) ||
561 	       btf_type_is_ptr(t) ||
562 	       btf_type_is_struct(t) ||
563 	       btf_type_is_array(t) ||
564 	       btf_type_is_var(t) ||
565 	       btf_type_is_datasec(t);
566 }
567 
568 /* t->size can be used */
569 static bool btf_type_has_size(const struct btf_type *t)
570 {
571 	switch (BTF_INFO_KIND(t->info)) {
572 	case BTF_KIND_INT:
573 	case BTF_KIND_STRUCT:
574 	case BTF_KIND_UNION:
575 	case BTF_KIND_ENUM:
576 	case BTF_KIND_DATASEC:
577 		return true;
578 	}
579 
580 	return false;
581 }
582 
583 static const char *btf_int_encoding_str(u8 encoding)
584 {
585 	if (encoding == 0)
586 		return "(none)";
587 	else if (encoding == BTF_INT_SIGNED)
588 		return "SIGNED";
589 	else if (encoding == BTF_INT_CHAR)
590 		return "CHAR";
591 	else if (encoding == BTF_INT_BOOL)
592 		return "BOOL";
593 	else
594 		return "UNKN";
595 }
596 
597 static u32 btf_type_int(const struct btf_type *t)
598 {
599 	return *(u32 *)(t + 1);
600 }
601 
602 static const struct btf_array *btf_type_array(const struct btf_type *t)
603 {
604 	return (const struct btf_array *)(t + 1);
605 }
606 
607 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
608 {
609 	return (const struct btf_enum *)(t + 1);
610 }
611 
612 static const struct btf_var *btf_type_var(const struct btf_type *t)
613 {
614 	return (const struct btf_var *)(t + 1);
615 }
616 
617 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
618 {
619 	return kind_ops[BTF_INFO_KIND(t->info)];
620 }
621 
622 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
623 {
624 	if (!BTF_STR_OFFSET_VALID(offset))
625 		return false;
626 
627 	while (offset < btf->start_str_off)
628 		btf = btf->base_btf;
629 
630 	offset -= btf->start_str_off;
631 	return offset < btf->hdr.str_len;
632 }
633 
634 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
635 {
636 	if ((first ? !isalpha(c) :
637 		     !isalnum(c)) &&
638 	    c != '_' &&
639 	    ((c == '.' && !dot_ok) ||
640 	      c != '.'))
641 		return false;
642 	return true;
643 }
644 
645 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
646 {
647 	while (offset < btf->start_str_off)
648 		btf = btf->base_btf;
649 
650 	offset -= btf->start_str_off;
651 	if (offset < btf->hdr.str_len)
652 		return &btf->strings[offset];
653 
654 	return NULL;
655 }
656 
657 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
658 {
659 	/* offset must be valid */
660 	const char *src = btf_str_by_offset(btf, offset);
661 	const char *src_limit;
662 
663 	if (!__btf_name_char_ok(*src, true, dot_ok))
664 		return false;
665 
666 	/* set a limit on identifier length */
667 	src_limit = src + KSYM_NAME_LEN;
668 	src++;
669 	while (*src && src < src_limit) {
670 		if (!__btf_name_char_ok(*src, false, dot_ok))
671 			return false;
672 		src++;
673 	}
674 
675 	return !*src;
676 }
677 
678 /* Only C-style identifier is permitted. This can be relaxed if
679  * necessary.
680  */
681 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
682 {
683 	return __btf_name_valid(btf, offset, false);
684 }
685 
686 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
687 {
688 	return __btf_name_valid(btf, offset, true);
689 }
690 
691 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
692 {
693 	const char *name;
694 
695 	if (!offset)
696 		return "(anon)";
697 
698 	name = btf_str_by_offset(btf, offset);
699 	return name ?: "(invalid-name-offset)";
700 }
701 
702 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
703 {
704 	return btf_str_by_offset(btf, offset);
705 }
706 
707 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
708 {
709 	while (type_id < btf->start_id)
710 		btf = btf->base_btf;
711 
712 	type_id -= btf->start_id;
713 	if (type_id >= btf->nr_types)
714 		return NULL;
715 	return btf->types[type_id];
716 }
717 
718 /*
719  * Regular int is not a bit field and it must be either
720  * u8/u16/u32/u64 or __int128.
721  */
722 static bool btf_type_int_is_regular(const struct btf_type *t)
723 {
724 	u8 nr_bits, nr_bytes;
725 	u32 int_data;
726 
727 	int_data = btf_type_int(t);
728 	nr_bits = BTF_INT_BITS(int_data);
729 	nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
730 	if (BITS_PER_BYTE_MASKED(nr_bits) ||
731 	    BTF_INT_OFFSET(int_data) ||
732 	    (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
733 	     nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
734 	     nr_bytes != (2 * sizeof(u64)))) {
735 		return false;
736 	}
737 
738 	return true;
739 }
740 
741 /*
742  * Check that given struct member is a regular int with expected
743  * offset and size.
744  */
745 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
746 			   const struct btf_member *m,
747 			   u32 expected_offset, u32 expected_size)
748 {
749 	const struct btf_type *t;
750 	u32 id, int_data;
751 	u8 nr_bits;
752 
753 	id = m->type;
754 	t = btf_type_id_size(btf, &id, NULL);
755 	if (!t || !btf_type_is_int(t))
756 		return false;
757 
758 	int_data = btf_type_int(t);
759 	nr_bits = BTF_INT_BITS(int_data);
760 	if (btf_type_kflag(s)) {
761 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
762 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
763 
764 		/* if kflag set, int should be a regular int and
765 		 * bit offset should be at byte boundary.
766 		 */
767 		return !bitfield_size &&
768 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
769 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
770 	}
771 
772 	if (BTF_INT_OFFSET(int_data) ||
773 	    BITS_PER_BYTE_MASKED(m->offset) ||
774 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
775 	    BITS_PER_BYTE_MASKED(nr_bits) ||
776 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
777 		return false;
778 
779 	return true;
780 }
781 
782 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
783 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
784 						       u32 id)
785 {
786 	const struct btf_type *t = btf_type_by_id(btf, id);
787 
788 	while (btf_type_is_modifier(t) &&
789 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
790 		id = t->type;
791 		t = btf_type_by_id(btf, t->type);
792 	}
793 
794 	return t;
795 }
796 
797 #define BTF_SHOW_MAX_ITER	10
798 
799 #define BTF_KIND_BIT(kind)	(1ULL << kind)
800 
801 /*
802  * Populate show->state.name with type name information.
803  * Format of type name is
804  *
805  * [.member_name = ] (type_name)
806  */
807 static const char *btf_show_name(struct btf_show *show)
808 {
809 	/* BTF_MAX_ITER array suffixes "[]" */
810 	const char *array_suffixes = "[][][][][][][][][][]";
811 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
812 	/* BTF_MAX_ITER pointer suffixes "*" */
813 	const char *ptr_suffixes = "**********";
814 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
815 	const char *name = NULL, *prefix = "", *parens = "";
816 	const struct btf_member *m = show->state.member;
817 	const struct btf_type *t = show->state.type;
818 	const struct btf_array *array;
819 	u32 id = show->state.type_id;
820 	const char *member = NULL;
821 	bool show_member = false;
822 	u64 kinds = 0;
823 	int i;
824 
825 	show->state.name[0] = '\0';
826 
827 	/*
828 	 * Don't show type name if we're showing an array member;
829 	 * in that case we show the array type so don't need to repeat
830 	 * ourselves for each member.
831 	 */
832 	if (show->state.array_member)
833 		return "";
834 
835 	/* Retrieve member name, if any. */
836 	if (m) {
837 		member = btf_name_by_offset(show->btf, m->name_off);
838 		show_member = strlen(member) > 0;
839 		id = m->type;
840 	}
841 
842 	/*
843 	 * Start with type_id, as we have resolved the struct btf_type *
844 	 * via btf_modifier_show() past the parent typedef to the child
845 	 * struct, int etc it is defined as.  In such cases, the type_id
846 	 * still represents the starting type while the struct btf_type *
847 	 * in our show->state points at the resolved type of the typedef.
848 	 */
849 	t = btf_type_by_id(show->btf, id);
850 	if (!t)
851 		return "";
852 
853 	/*
854 	 * The goal here is to build up the right number of pointer and
855 	 * array suffixes while ensuring the type name for a typedef
856 	 * is represented.  Along the way we accumulate a list of
857 	 * BTF kinds we have encountered, since these will inform later
858 	 * display; for example, pointer types will not require an
859 	 * opening "{" for struct, we will just display the pointer value.
860 	 *
861 	 * We also want to accumulate the right number of pointer or array
862 	 * indices in the format string while iterating until we get to
863 	 * the typedef/pointee/array member target type.
864 	 *
865 	 * We start by pointing at the end of pointer and array suffix
866 	 * strings; as we accumulate pointers and arrays we move the pointer
867 	 * or array string backwards so it will show the expected number of
868 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
869 	 * and/or arrays and typedefs are supported as a precaution.
870 	 *
871 	 * We also want to get typedef name while proceeding to resolve
872 	 * type it points to so that we can add parentheses if it is a
873 	 * "typedef struct" etc.
874 	 */
875 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
876 
877 		switch (BTF_INFO_KIND(t->info)) {
878 		case BTF_KIND_TYPEDEF:
879 			if (!name)
880 				name = btf_name_by_offset(show->btf,
881 							       t->name_off);
882 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
883 			id = t->type;
884 			break;
885 		case BTF_KIND_ARRAY:
886 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
887 			parens = "[";
888 			if (!t)
889 				return "";
890 			array = btf_type_array(t);
891 			if (array_suffix > array_suffixes)
892 				array_suffix -= 2;
893 			id = array->type;
894 			break;
895 		case BTF_KIND_PTR:
896 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
897 			if (ptr_suffix > ptr_suffixes)
898 				ptr_suffix -= 1;
899 			id = t->type;
900 			break;
901 		default:
902 			id = 0;
903 			break;
904 		}
905 		if (!id)
906 			break;
907 		t = btf_type_skip_qualifiers(show->btf, id);
908 	}
909 	/* We may not be able to represent this type; bail to be safe */
910 	if (i == BTF_SHOW_MAX_ITER)
911 		return "";
912 
913 	if (!name)
914 		name = btf_name_by_offset(show->btf, t->name_off);
915 
916 	switch (BTF_INFO_KIND(t->info)) {
917 	case BTF_KIND_STRUCT:
918 	case BTF_KIND_UNION:
919 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
920 			 "struct" : "union";
921 		/* if it's an array of struct/union, parens is already set */
922 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
923 			parens = "{";
924 		break;
925 	case BTF_KIND_ENUM:
926 		prefix = "enum";
927 		break;
928 	default:
929 		break;
930 	}
931 
932 	/* pointer does not require parens */
933 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
934 		parens = "";
935 	/* typedef does not require struct/union/enum prefix */
936 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
937 		prefix = "";
938 
939 	if (!name)
940 		name = "";
941 
942 	/* Even if we don't want type name info, we want parentheses etc */
943 	if (show->flags & BTF_SHOW_NONAME)
944 		snprintf(show->state.name, sizeof(show->state.name), "%s",
945 			 parens);
946 	else
947 		snprintf(show->state.name, sizeof(show->state.name),
948 			 "%s%s%s(%s%s%s%s%s%s)%s",
949 			 /* first 3 strings comprise ".member = " */
950 			 show_member ? "." : "",
951 			 show_member ? member : "",
952 			 show_member ? " = " : "",
953 			 /* ...next is our prefix (struct, enum, etc) */
954 			 prefix,
955 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
956 			 /* ...this is the type name itself */
957 			 name,
958 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
959 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
960 			 array_suffix, parens);
961 
962 	return show->state.name;
963 }
964 
965 static const char *__btf_show_indent(struct btf_show *show)
966 {
967 	const char *indents = "                                ";
968 	const char *indent = &indents[strlen(indents)];
969 
970 	if ((indent - show->state.depth) >= indents)
971 		return indent - show->state.depth;
972 	return indents;
973 }
974 
975 static const char *btf_show_indent(struct btf_show *show)
976 {
977 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
978 }
979 
980 static const char *btf_show_newline(struct btf_show *show)
981 {
982 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
983 }
984 
985 static const char *btf_show_delim(struct btf_show *show)
986 {
987 	if (show->state.depth == 0)
988 		return "";
989 
990 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
991 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
992 		return "|";
993 
994 	return ",";
995 }
996 
997 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
998 {
999 	va_list args;
1000 
1001 	if (!show->state.depth_check) {
1002 		va_start(args, fmt);
1003 		show->showfn(show, fmt, args);
1004 		va_end(args);
1005 	}
1006 }
1007 
1008 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1009  * format specifiers to the format specifier passed in; these do the work of
1010  * adding indentation, delimiters etc while the caller simply has to specify
1011  * the type value(s) in the format specifier + value(s).
1012  */
1013 #define btf_show_type_value(show, fmt, value)				       \
1014 	do {								       \
1015 		if ((value) != 0 || (show->flags & BTF_SHOW_ZERO) ||	       \
1016 		    show->state.depth == 0) {				       \
1017 			btf_show(show, "%s%s" fmt "%s%s",		       \
1018 				 btf_show_indent(show),			       \
1019 				 btf_show_name(show),			       \
1020 				 value, btf_show_delim(show),		       \
1021 				 btf_show_newline(show));		       \
1022 			if (show->state.depth > show->state.depth_to_show)     \
1023 				show->state.depth_to_show = show->state.depth; \
1024 		}							       \
1025 	} while (0)
1026 
1027 #define btf_show_type_values(show, fmt, ...)				       \
1028 	do {								       \
1029 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1030 			 btf_show_name(show),				       \
1031 			 __VA_ARGS__, btf_show_delim(show),		       \
1032 			 btf_show_newline(show));			       \
1033 		if (show->state.depth > show->state.depth_to_show)	       \
1034 			show->state.depth_to_show = show->state.depth;	       \
1035 	} while (0)
1036 
1037 /* How much is left to copy to safe buffer after @data? */
1038 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1039 {
1040 	return show->obj.head + show->obj.size - data;
1041 }
1042 
1043 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1044 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1045 {
1046 	return data >= show->obj.data &&
1047 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1048 }
1049 
1050 /*
1051  * If object pointed to by @data of @size falls within our safe buffer, return
1052  * the equivalent pointer to the same safe data.  Assumes
1053  * copy_from_kernel_nofault() has already happened and our safe buffer is
1054  * populated.
1055  */
1056 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1057 {
1058 	if (btf_show_obj_is_safe(show, data, size))
1059 		return show->obj.safe + (data - show->obj.data);
1060 	return NULL;
1061 }
1062 
1063 /*
1064  * Return a safe-to-access version of data pointed to by @data.
1065  * We do this by copying the relevant amount of information
1066  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1067  *
1068  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1069  * safe copy is needed.
1070  *
1071  * Otherwise we need to determine if we have the required amount
1072  * of data (determined by the @data pointer and the size of the
1073  * largest base type we can encounter (represented by
1074  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1075  * that we will be able to print some of the current object,
1076  * and if more is needed a copy will be triggered.
1077  * Some objects such as structs will not fit into the buffer;
1078  * in such cases additional copies when we iterate over their
1079  * members may be needed.
1080  *
1081  * btf_show_obj_safe() is used to return a safe buffer for
1082  * btf_show_start_type(); this ensures that as we recurse into
1083  * nested types we always have safe data for the given type.
1084  * This approach is somewhat wasteful; it's possible for example
1085  * that when iterating over a large union we'll end up copying the
1086  * same data repeatedly, but the goal is safety not performance.
1087  * We use stack data as opposed to per-CPU buffers because the
1088  * iteration over a type can take some time, and preemption handling
1089  * would greatly complicate use of the safe buffer.
1090  */
1091 static void *btf_show_obj_safe(struct btf_show *show,
1092 			       const struct btf_type *t,
1093 			       void *data)
1094 {
1095 	const struct btf_type *rt;
1096 	int size_left, size;
1097 	void *safe = NULL;
1098 
1099 	if (show->flags & BTF_SHOW_UNSAFE)
1100 		return data;
1101 
1102 	rt = btf_resolve_size(show->btf, t, &size);
1103 	if (IS_ERR(rt)) {
1104 		show->state.status = PTR_ERR(rt);
1105 		return NULL;
1106 	}
1107 
1108 	/*
1109 	 * Is this toplevel object? If so, set total object size and
1110 	 * initialize pointers.  Otherwise check if we still fall within
1111 	 * our safe object data.
1112 	 */
1113 	if (show->state.depth == 0) {
1114 		show->obj.size = size;
1115 		show->obj.head = data;
1116 	} else {
1117 		/*
1118 		 * If the size of the current object is > our remaining
1119 		 * safe buffer we _may_ need to do a new copy.  However
1120 		 * consider the case of a nested struct; it's size pushes
1121 		 * us over the safe buffer limit, but showing any individual
1122 		 * struct members does not.  In such cases, we don't need
1123 		 * to initiate a fresh copy yet; however we definitely need
1124 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1125 		 * in our buffer, regardless of the current object size.
1126 		 * The logic here is that as we resolve types we will
1127 		 * hit a base type at some point, and we need to be sure
1128 		 * the next chunk of data is safely available to display
1129 		 * that type info safely.  We cannot rely on the size of
1130 		 * the current object here because it may be much larger
1131 		 * than our current buffer (e.g. task_struct is 8k).
1132 		 * All we want to do here is ensure that we can print the
1133 		 * next basic type, which we can if either
1134 		 * - the current type size is within the safe buffer; or
1135 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1136 		 *   the safe buffer.
1137 		 */
1138 		safe = __btf_show_obj_safe(show, data,
1139 					   min(size,
1140 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1141 	}
1142 
1143 	/*
1144 	 * We need a new copy to our safe object, either because we haven't
1145 	 * yet copied and are intializing safe data, or because the data
1146 	 * we want falls outside the boundaries of the safe object.
1147 	 */
1148 	if (!safe) {
1149 		size_left = btf_show_obj_size_left(show, data);
1150 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1151 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1152 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1153 							      data, size_left);
1154 		if (!show->state.status) {
1155 			show->obj.data = data;
1156 			safe = show->obj.safe;
1157 		}
1158 	}
1159 
1160 	return safe;
1161 }
1162 
1163 /*
1164  * Set the type we are starting to show and return a safe data pointer
1165  * to be used for showing the associated data.
1166  */
1167 static void *btf_show_start_type(struct btf_show *show,
1168 				 const struct btf_type *t,
1169 				 u32 type_id, void *data)
1170 {
1171 	show->state.type = t;
1172 	show->state.type_id = type_id;
1173 	show->state.name[0] = '\0';
1174 
1175 	return btf_show_obj_safe(show, t, data);
1176 }
1177 
1178 static void btf_show_end_type(struct btf_show *show)
1179 {
1180 	show->state.type = NULL;
1181 	show->state.type_id = 0;
1182 	show->state.name[0] = '\0';
1183 }
1184 
1185 static void *btf_show_start_aggr_type(struct btf_show *show,
1186 				      const struct btf_type *t,
1187 				      u32 type_id, void *data)
1188 {
1189 	void *safe_data = btf_show_start_type(show, t, type_id, data);
1190 
1191 	if (!safe_data)
1192 		return safe_data;
1193 
1194 	btf_show(show, "%s%s%s", btf_show_indent(show),
1195 		 btf_show_name(show),
1196 		 btf_show_newline(show));
1197 	show->state.depth++;
1198 	return safe_data;
1199 }
1200 
1201 static void btf_show_end_aggr_type(struct btf_show *show,
1202 				   const char *suffix)
1203 {
1204 	show->state.depth--;
1205 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1206 		 btf_show_delim(show), btf_show_newline(show));
1207 	btf_show_end_type(show);
1208 }
1209 
1210 static void btf_show_start_member(struct btf_show *show,
1211 				  const struct btf_member *m)
1212 {
1213 	show->state.member = m;
1214 }
1215 
1216 static void btf_show_start_array_member(struct btf_show *show)
1217 {
1218 	show->state.array_member = 1;
1219 	btf_show_start_member(show, NULL);
1220 }
1221 
1222 static void btf_show_end_member(struct btf_show *show)
1223 {
1224 	show->state.member = NULL;
1225 }
1226 
1227 static void btf_show_end_array_member(struct btf_show *show)
1228 {
1229 	show->state.array_member = 0;
1230 	btf_show_end_member(show);
1231 }
1232 
1233 static void *btf_show_start_array_type(struct btf_show *show,
1234 				       const struct btf_type *t,
1235 				       u32 type_id,
1236 				       u16 array_encoding,
1237 				       void *data)
1238 {
1239 	show->state.array_encoding = array_encoding;
1240 	show->state.array_terminated = 0;
1241 	return btf_show_start_aggr_type(show, t, type_id, data);
1242 }
1243 
1244 static void btf_show_end_array_type(struct btf_show *show)
1245 {
1246 	show->state.array_encoding = 0;
1247 	show->state.array_terminated = 0;
1248 	btf_show_end_aggr_type(show, "]");
1249 }
1250 
1251 static void *btf_show_start_struct_type(struct btf_show *show,
1252 					const struct btf_type *t,
1253 					u32 type_id,
1254 					void *data)
1255 {
1256 	return btf_show_start_aggr_type(show, t, type_id, data);
1257 }
1258 
1259 static void btf_show_end_struct_type(struct btf_show *show)
1260 {
1261 	btf_show_end_aggr_type(show, "}");
1262 }
1263 
1264 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1265 					      const char *fmt, ...)
1266 {
1267 	va_list args;
1268 
1269 	va_start(args, fmt);
1270 	bpf_verifier_vlog(log, fmt, args);
1271 	va_end(args);
1272 }
1273 
1274 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1275 					    const char *fmt, ...)
1276 {
1277 	struct bpf_verifier_log *log = &env->log;
1278 	va_list args;
1279 
1280 	if (!bpf_verifier_log_needed(log))
1281 		return;
1282 
1283 	va_start(args, fmt);
1284 	bpf_verifier_vlog(log, fmt, args);
1285 	va_end(args);
1286 }
1287 
1288 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1289 						   const struct btf_type *t,
1290 						   bool log_details,
1291 						   const char *fmt, ...)
1292 {
1293 	struct bpf_verifier_log *log = &env->log;
1294 	u8 kind = BTF_INFO_KIND(t->info);
1295 	struct btf *btf = env->btf;
1296 	va_list args;
1297 
1298 	if (!bpf_verifier_log_needed(log))
1299 		return;
1300 
1301 	/* btf verifier prints all types it is processing via
1302 	 * btf_verifier_log_type(..., fmt = NULL).
1303 	 * Skip those prints for in-kernel BTF verification.
1304 	 */
1305 	if (log->level == BPF_LOG_KERNEL && !fmt)
1306 		return;
1307 
1308 	__btf_verifier_log(log, "[%u] %s %s%s",
1309 			   env->log_type_id,
1310 			   btf_kind_str[kind],
1311 			   __btf_name_by_offset(btf, t->name_off),
1312 			   log_details ? " " : "");
1313 
1314 	if (log_details)
1315 		btf_type_ops(t)->log_details(env, t);
1316 
1317 	if (fmt && *fmt) {
1318 		__btf_verifier_log(log, " ");
1319 		va_start(args, fmt);
1320 		bpf_verifier_vlog(log, fmt, args);
1321 		va_end(args);
1322 	}
1323 
1324 	__btf_verifier_log(log, "\n");
1325 }
1326 
1327 #define btf_verifier_log_type(env, t, ...) \
1328 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1329 #define btf_verifier_log_basic(env, t, ...) \
1330 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1331 
1332 __printf(4, 5)
1333 static void btf_verifier_log_member(struct btf_verifier_env *env,
1334 				    const struct btf_type *struct_type,
1335 				    const struct btf_member *member,
1336 				    const char *fmt, ...)
1337 {
1338 	struct bpf_verifier_log *log = &env->log;
1339 	struct btf *btf = env->btf;
1340 	va_list args;
1341 
1342 	if (!bpf_verifier_log_needed(log))
1343 		return;
1344 
1345 	if (log->level == BPF_LOG_KERNEL && !fmt)
1346 		return;
1347 	/* The CHECK_META phase already did a btf dump.
1348 	 *
1349 	 * If member is logged again, it must hit an error in
1350 	 * parsing this member.  It is useful to print out which
1351 	 * struct this member belongs to.
1352 	 */
1353 	if (env->phase != CHECK_META)
1354 		btf_verifier_log_type(env, struct_type, NULL);
1355 
1356 	if (btf_type_kflag(struct_type))
1357 		__btf_verifier_log(log,
1358 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1359 				   __btf_name_by_offset(btf, member->name_off),
1360 				   member->type,
1361 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1362 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1363 	else
1364 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1365 				   __btf_name_by_offset(btf, member->name_off),
1366 				   member->type, member->offset);
1367 
1368 	if (fmt && *fmt) {
1369 		__btf_verifier_log(log, " ");
1370 		va_start(args, fmt);
1371 		bpf_verifier_vlog(log, fmt, args);
1372 		va_end(args);
1373 	}
1374 
1375 	__btf_verifier_log(log, "\n");
1376 }
1377 
1378 __printf(4, 5)
1379 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1380 				 const struct btf_type *datasec_type,
1381 				 const struct btf_var_secinfo *vsi,
1382 				 const char *fmt, ...)
1383 {
1384 	struct bpf_verifier_log *log = &env->log;
1385 	va_list args;
1386 
1387 	if (!bpf_verifier_log_needed(log))
1388 		return;
1389 	if (log->level == BPF_LOG_KERNEL && !fmt)
1390 		return;
1391 	if (env->phase != CHECK_META)
1392 		btf_verifier_log_type(env, datasec_type, NULL);
1393 
1394 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1395 			   vsi->type, vsi->offset, vsi->size);
1396 	if (fmt && *fmt) {
1397 		__btf_verifier_log(log, " ");
1398 		va_start(args, fmt);
1399 		bpf_verifier_vlog(log, fmt, args);
1400 		va_end(args);
1401 	}
1402 
1403 	__btf_verifier_log(log, "\n");
1404 }
1405 
1406 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1407 				 u32 btf_data_size)
1408 {
1409 	struct bpf_verifier_log *log = &env->log;
1410 	const struct btf *btf = env->btf;
1411 	const struct btf_header *hdr;
1412 
1413 	if (!bpf_verifier_log_needed(log))
1414 		return;
1415 
1416 	if (log->level == BPF_LOG_KERNEL)
1417 		return;
1418 	hdr = &btf->hdr;
1419 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1420 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1421 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1422 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1423 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1424 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1425 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1426 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1427 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1428 }
1429 
1430 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1431 {
1432 	struct btf *btf = env->btf;
1433 
1434 	if (btf->types_size == btf->nr_types) {
1435 		/* Expand 'types' array */
1436 
1437 		struct btf_type **new_types;
1438 		u32 expand_by, new_size;
1439 
1440 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1441 			btf_verifier_log(env, "Exceeded max num of types");
1442 			return -E2BIG;
1443 		}
1444 
1445 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1446 		new_size = min_t(u32, BTF_MAX_TYPE,
1447 				 btf->types_size + expand_by);
1448 
1449 		new_types = kvcalloc(new_size, sizeof(*new_types),
1450 				     GFP_KERNEL | __GFP_NOWARN);
1451 		if (!new_types)
1452 			return -ENOMEM;
1453 
1454 		if (btf->nr_types == 0) {
1455 			if (!btf->base_btf) {
1456 				/* lazily init VOID type */
1457 				new_types[0] = &btf_void;
1458 				btf->nr_types++;
1459 			}
1460 		} else {
1461 			memcpy(new_types, btf->types,
1462 			       sizeof(*btf->types) * btf->nr_types);
1463 		}
1464 
1465 		kvfree(btf->types);
1466 		btf->types = new_types;
1467 		btf->types_size = new_size;
1468 	}
1469 
1470 	btf->types[btf->nr_types++] = t;
1471 
1472 	return 0;
1473 }
1474 
1475 static int btf_alloc_id(struct btf *btf)
1476 {
1477 	int id;
1478 
1479 	idr_preload(GFP_KERNEL);
1480 	spin_lock_bh(&btf_idr_lock);
1481 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1482 	if (id > 0)
1483 		btf->id = id;
1484 	spin_unlock_bh(&btf_idr_lock);
1485 	idr_preload_end();
1486 
1487 	if (WARN_ON_ONCE(!id))
1488 		return -ENOSPC;
1489 
1490 	return id > 0 ? 0 : id;
1491 }
1492 
1493 static void btf_free_id(struct btf *btf)
1494 {
1495 	unsigned long flags;
1496 
1497 	/*
1498 	 * In map-in-map, calling map_delete_elem() on outer
1499 	 * map will call bpf_map_put on the inner map.
1500 	 * It will then eventually call btf_free_id()
1501 	 * on the inner map.  Some of the map_delete_elem()
1502 	 * implementation may have irq disabled, so
1503 	 * we need to use the _irqsave() version instead
1504 	 * of the _bh() version.
1505 	 */
1506 	spin_lock_irqsave(&btf_idr_lock, flags);
1507 	idr_remove(&btf_idr, btf->id);
1508 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1509 }
1510 
1511 static void btf_free(struct btf *btf)
1512 {
1513 	kvfree(btf->types);
1514 	kvfree(btf->resolved_sizes);
1515 	kvfree(btf->resolved_ids);
1516 	kvfree(btf->data);
1517 	kfree(btf);
1518 }
1519 
1520 static void btf_free_rcu(struct rcu_head *rcu)
1521 {
1522 	struct btf *btf = container_of(rcu, struct btf, rcu);
1523 
1524 	btf_free(btf);
1525 }
1526 
1527 void btf_put(struct btf *btf)
1528 {
1529 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1530 		btf_free_id(btf);
1531 		call_rcu(&btf->rcu, btf_free_rcu);
1532 	}
1533 }
1534 
1535 static int env_resolve_init(struct btf_verifier_env *env)
1536 {
1537 	struct btf *btf = env->btf;
1538 	u32 nr_types = btf->nr_types;
1539 	u32 *resolved_sizes = NULL;
1540 	u32 *resolved_ids = NULL;
1541 	u8 *visit_states = NULL;
1542 
1543 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1544 				  GFP_KERNEL | __GFP_NOWARN);
1545 	if (!resolved_sizes)
1546 		goto nomem;
1547 
1548 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1549 				GFP_KERNEL | __GFP_NOWARN);
1550 	if (!resolved_ids)
1551 		goto nomem;
1552 
1553 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1554 				GFP_KERNEL | __GFP_NOWARN);
1555 	if (!visit_states)
1556 		goto nomem;
1557 
1558 	btf->resolved_sizes = resolved_sizes;
1559 	btf->resolved_ids = resolved_ids;
1560 	env->visit_states = visit_states;
1561 
1562 	return 0;
1563 
1564 nomem:
1565 	kvfree(resolved_sizes);
1566 	kvfree(resolved_ids);
1567 	kvfree(visit_states);
1568 	return -ENOMEM;
1569 }
1570 
1571 static void btf_verifier_env_free(struct btf_verifier_env *env)
1572 {
1573 	kvfree(env->visit_states);
1574 	kfree(env);
1575 }
1576 
1577 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1578 				     const struct btf_type *next_type)
1579 {
1580 	switch (env->resolve_mode) {
1581 	case RESOLVE_TBD:
1582 		/* int, enum or void is a sink */
1583 		return !btf_type_needs_resolve(next_type);
1584 	case RESOLVE_PTR:
1585 		/* int, enum, void, struct, array, func or func_proto is a sink
1586 		 * for ptr
1587 		 */
1588 		return !btf_type_is_modifier(next_type) &&
1589 			!btf_type_is_ptr(next_type);
1590 	case RESOLVE_STRUCT_OR_ARRAY:
1591 		/* int, enum, void, ptr, func or func_proto is a sink
1592 		 * for struct and array
1593 		 */
1594 		return !btf_type_is_modifier(next_type) &&
1595 			!btf_type_is_array(next_type) &&
1596 			!btf_type_is_struct(next_type);
1597 	default:
1598 		BUG();
1599 	}
1600 }
1601 
1602 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1603 				 u32 type_id)
1604 {
1605 	/* base BTF types should be resolved by now */
1606 	if (type_id < env->btf->start_id)
1607 		return true;
1608 
1609 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1610 }
1611 
1612 static int env_stack_push(struct btf_verifier_env *env,
1613 			  const struct btf_type *t, u32 type_id)
1614 {
1615 	const struct btf *btf = env->btf;
1616 	struct resolve_vertex *v;
1617 
1618 	if (env->top_stack == MAX_RESOLVE_DEPTH)
1619 		return -E2BIG;
1620 
1621 	if (type_id < btf->start_id
1622 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1623 		return -EEXIST;
1624 
1625 	env->visit_states[type_id - btf->start_id] = VISITED;
1626 
1627 	v = &env->stack[env->top_stack++];
1628 	v->t = t;
1629 	v->type_id = type_id;
1630 	v->next_member = 0;
1631 
1632 	if (env->resolve_mode == RESOLVE_TBD) {
1633 		if (btf_type_is_ptr(t))
1634 			env->resolve_mode = RESOLVE_PTR;
1635 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
1636 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1637 	}
1638 
1639 	return 0;
1640 }
1641 
1642 static void env_stack_set_next_member(struct btf_verifier_env *env,
1643 				      u16 next_member)
1644 {
1645 	env->stack[env->top_stack - 1].next_member = next_member;
1646 }
1647 
1648 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1649 				   u32 resolved_type_id,
1650 				   u32 resolved_size)
1651 {
1652 	u32 type_id = env->stack[--(env->top_stack)].type_id;
1653 	struct btf *btf = env->btf;
1654 
1655 	type_id -= btf->start_id; /* adjust to local type id */
1656 	btf->resolved_sizes[type_id] = resolved_size;
1657 	btf->resolved_ids[type_id] = resolved_type_id;
1658 	env->visit_states[type_id] = RESOLVED;
1659 }
1660 
1661 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1662 {
1663 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1664 }
1665 
1666 /* Resolve the size of a passed-in "type"
1667  *
1668  * type: is an array (e.g. u32 array[x][y])
1669  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1670  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1671  *             corresponds to the return type.
1672  * *elem_type: u32
1673  * *elem_id: id of u32
1674  * *total_nelems: (x * y).  Hence, individual elem size is
1675  *                (*type_size / *total_nelems)
1676  * *type_id: id of type if it's changed within the function, 0 if not
1677  *
1678  * type: is not an array (e.g. const struct X)
1679  * return type: type "struct X"
1680  * *type_size: sizeof(struct X)
1681  * *elem_type: same as return type ("struct X")
1682  * *elem_id: 0
1683  * *total_nelems: 1
1684  * *type_id: id of type if it's changed within the function, 0 if not
1685  */
1686 static const struct btf_type *
1687 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1688 		   u32 *type_size, const struct btf_type **elem_type,
1689 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
1690 {
1691 	const struct btf_type *array_type = NULL;
1692 	const struct btf_array *array = NULL;
1693 	u32 i, size, nelems = 1, id = 0;
1694 
1695 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1696 		switch (BTF_INFO_KIND(type->info)) {
1697 		/* type->size can be used */
1698 		case BTF_KIND_INT:
1699 		case BTF_KIND_STRUCT:
1700 		case BTF_KIND_UNION:
1701 		case BTF_KIND_ENUM:
1702 			size = type->size;
1703 			goto resolved;
1704 
1705 		case BTF_KIND_PTR:
1706 			size = sizeof(void *);
1707 			goto resolved;
1708 
1709 		/* Modifiers */
1710 		case BTF_KIND_TYPEDEF:
1711 		case BTF_KIND_VOLATILE:
1712 		case BTF_KIND_CONST:
1713 		case BTF_KIND_RESTRICT:
1714 			id = type->type;
1715 			type = btf_type_by_id(btf, type->type);
1716 			break;
1717 
1718 		case BTF_KIND_ARRAY:
1719 			if (!array_type)
1720 				array_type = type;
1721 			array = btf_type_array(type);
1722 			if (nelems && array->nelems > U32_MAX / nelems)
1723 				return ERR_PTR(-EINVAL);
1724 			nelems *= array->nelems;
1725 			type = btf_type_by_id(btf, array->type);
1726 			break;
1727 
1728 		/* type without size */
1729 		default:
1730 			return ERR_PTR(-EINVAL);
1731 		}
1732 	}
1733 
1734 	return ERR_PTR(-EINVAL);
1735 
1736 resolved:
1737 	if (nelems && size > U32_MAX / nelems)
1738 		return ERR_PTR(-EINVAL);
1739 
1740 	*type_size = nelems * size;
1741 	if (total_nelems)
1742 		*total_nelems = nelems;
1743 	if (elem_type)
1744 		*elem_type = type;
1745 	if (elem_id)
1746 		*elem_id = array ? array->type : 0;
1747 	if (type_id && id)
1748 		*type_id = id;
1749 
1750 	return array_type ? : type;
1751 }
1752 
1753 const struct btf_type *
1754 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1755 		 u32 *type_size)
1756 {
1757 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1758 }
1759 
1760 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1761 {
1762 	while (type_id < btf->start_id)
1763 		btf = btf->base_btf;
1764 
1765 	return btf->resolved_ids[type_id - btf->start_id];
1766 }
1767 
1768 /* The input param "type_id" must point to a needs_resolve type */
1769 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1770 						  u32 *type_id)
1771 {
1772 	*type_id = btf_resolved_type_id(btf, *type_id);
1773 	return btf_type_by_id(btf, *type_id);
1774 }
1775 
1776 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1777 {
1778 	while (type_id < btf->start_id)
1779 		btf = btf->base_btf;
1780 
1781 	return btf->resolved_sizes[type_id - btf->start_id];
1782 }
1783 
1784 const struct btf_type *btf_type_id_size(const struct btf *btf,
1785 					u32 *type_id, u32 *ret_size)
1786 {
1787 	const struct btf_type *size_type;
1788 	u32 size_type_id = *type_id;
1789 	u32 size = 0;
1790 
1791 	size_type = btf_type_by_id(btf, size_type_id);
1792 	if (btf_type_nosize_or_null(size_type))
1793 		return NULL;
1794 
1795 	if (btf_type_has_size(size_type)) {
1796 		size = size_type->size;
1797 	} else if (btf_type_is_array(size_type)) {
1798 		size = btf_resolved_type_size(btf, size_type_id);
1799 	} else if (btf_type_is_ptr(size_type)) {
1800 		size = sizeof(void *);
1801 	} else {
1802 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1803 				 !btf_type_is_var(size_type)))
1804 			return NULL;
1805 
1806 		size_type_id = btf_resolved_type_id(btf, size_type_id);
1807 		size_type = btf_type_by_id(btf, size_type_id);
1808 		if (btf_type_nosize_or_null(size_type))
1809 			return NULL;
1810 		else if (btf_type_has_size(size_type))
1811 			size = size_type->size;
1812 		else if (btf_type_is_array(size_type))
1813 			size = btf_resolved_type_size(btf, size_type_id);
1814 		else if (btf_type_is_ptr(size_type))
1815 			size = sizeof(void *);
1816 		else
1817 			return NULL;
1818 	}
1819 
1820 	*type_id = size_type_id;
1821 	if (ret_size)
1822 		*ret_size = size;
1823 
1824 	return size_type;
1825 }
1826 
1827 static int btf_df_check_member(struct btf_verifier_env *env,
1828 			       const struct btf_type *struct_type,
1829 			       const struct btf_member *member,
1830 			       const struct btf_type *member_type)
1831 {
1832 	btf_verifier_log_basic(env, struct_type,
1833 			       "Unsupported check_member");
1834 	return -EINVAL;
1835 }
1836 
1837 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1838 				     const struct btf_type *struct_type,
1839 				     const struct btf_member *member,
1840 				     const struct btf_type *member_type)
1841 {
1842 	btf_verifier_log_basic(env, struct_type,
1843 			       "Unsupported check_kflag_member");
1844 	return -EINVAL;
1845 }
1846 
1847 /* Used for ptr, array and struct/union type members.
1848  * int, enum and modifier types have their specific callback functions.
1849  */
1850 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1851 					  const struct btf_type *struct_type,
1852 					  const struct btf_member *member,
1853 					  const struct btf_type *member_type)
1854 {
1855 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1856 		btf_verifier_log_member(env, struct_type, member,
1857 					"Invalid member bitfield_size");
1858 		return -EINVAL;
1859 	}
1860 
1861 	/* bitfield size is 0, so member->offset represents bit offset only.
1862 	 * It is safe to call non kflag check_member variants.
1863 	 */
1864 	return btf_type_ops(member_type)->check_member(env, struct_type,
1865 						       member,
1866 						       member_type);
1867 }
1868 
1869 static int btf_df_resolve(struct btf_verifier_env *env,
1870 			  const struct resolve_vertex *v)
1871 {
1872 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
1873 	return -EINVAL;
1874 }
1875 
1876 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
1877 			u32 type_id, void *data, u8 bits_offsets,
1878 			struct btf_show *show)
1879 {
1880 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
1881 }
1882 
1883 static int btf_int_check_member(struct btf_verifier_env *env,
1884 				const struct btf_type *struct_type,
1885 				const struct btf_member *member,
1886 				const struct btf_type *member_type)
1887 {
1888 	u32 int_data = btf_type_int(member_type);
1889 	u32 struct_bits_off = member->offset;
1890 	u32 struct_size = struct_type->size;
1891 	u32 nr_copy_bits;
1892 	u32 bytes_offset;
1893 
1894 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
1895 		btf_verifier_log_member(env, struct_type, member,
1896 					"bits_offset exceeds U32_MAX");
1897 		return -EINVAL;
1898 	}
1899 
1900 	struct_bits_off += BTF_INT_OFFSET(int_data);
1901 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1902 	nr_copy_bits = BTF_INT_BITS(int_data) +
1903 		BITS_PER_BYTE_MASKED(struct_bits_off);
1904 
1905 	if (nr_copy_bits > BITS_PER_U128) {
1906 		btf_verifier_log_member(env, struct_type, member,
1907 					"nr_copy_bits exceeds 128");
1908 		return -EINVAL;
1909 	}
1910 
1911 	if (struct_size < bytes_offset ||
1912 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1913 		btf_verifier_log_member(env, struct_type, member,
1914 					"Member exceeds struct_size");
1915 		return -EINVAL;
1916 	}
1917 
1918 	return 0;
1919 }
1920 
1921 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
1922 				      const struct btf_type *struct_type,
1923 				      const struct btf_member *member,
1924 				      const struct btf_type *member_type)
1925 {
1926 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
1927 	u32 int_data = btf_type_int(member_type);
1928 	u32 struct_size = struct_type->size;
1929 	u32 nr_copy_bits;
1930 
1931 	/* a regular int type is required for the kflag int member */
1932 	if (!btf_type_int_is_regular(member_type)) {
1933 		btf_verifier_log_member(env, struct_type, member,
1934 					"Invalid member base type");
1935 		return -EINVAL;
1936 	}
1937 
1938 	/* check sanity of bitfield size */
1939 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
1940 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
1941 	nr_int_data_bits = BTF_INT_BITS(int_data);
1942 	if (!nr_bits) {
1943 		/* Not a bitfield member, member offset must be at byte
1944 		 * boundary.
1945 		 */
1946 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
1947 			btf_verifier_log_member(env, struct_type, member,
1948 						"Invalid member offset");
1949 			return -EINVAL;
1950 		}
1951 
1952 		nr_bits = nr_int_data_bits;
1953 	} else if (nr_bits > nr_int_data_bits) {
1954 		btf_verifier_log_member(env, struct_type, member,
1955 					"Invalid member bitfield_size");
1956 		return -EINVAL;
1957 	}
1958 
1959 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1960 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
1961 	if (nr_copy_bits > BITS_PER_U128) {
1962 		btf_verifier_log_member(env, struct_type, member,
1963 					"nr_copy_bits exceeds 128");
1964 		return -EINVAL;
1965 	}
1966 
1967 	if (struct_size < bytes_offset ||
1968 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1969 		btf_verifier_log_member(env, struct_type, member,
1970 					"Member exceeds struct_size");
1971 		return -EINVAL;
1972 	}
1973 
1974 	return 0;
1975 }
1976 
1977 static s32 btf_int_check_meta(struct btf_verifier_env *env,
1978 			      const struct btf_type *t,
1979 			      u32 meta_left)
1980 {
1981 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
1982 	u16 encoding;
1983 
1984 	if (meta_left < meta_needed) {
1985 		btf_verifier_log_basic(env, t,
1986 				       "meta_left:%u meta_needed:%u",
1987 				       meta_left, meta_needed);
1988 		return -EINVAL;
1989 	}
1990 
1991 	if (btf_type_vlen(t)) {
1992 		btf_verifier_log_type(env, t, "vlen != 0");
1993 		return -EINVAL;
1994 	}
1995 
1996 	if (btf_type_kflag(t)) {
1997 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
1998 		return -EINVAL;
1999 	}
2000 
2001 	int_data = btf_type_int(t);
2002 	if (int_data & ~BTF_INT_MASK) {
2003 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2004 				       int_data);
2005 		return -EINVAL;
2006 	}
2007 
2008 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2009 
2010 	if (nr_bits > BITS_PER_U128) {
2011 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2012 				      BITS_PER_U128);
2013 		return -EINVAL;
2014 	}
2015 
2016 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2017 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2018 		return -EINVAL;
2019 	}
2020 
2021 	/*
2022 	 * Only one of the encoding bits is allowed and it
2023 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2024 	 * Multiple bits can be allowed later if it is found
2025 	 * to be insufficient.
2026 	 */
2027 	encoding = BTF_INT_ENCODING(int_data);
2028 	if (encoding &&
2029 	    encoding != BTF_INT_SIGNED &&
2030 	    encoding != BTF_INT_CHAR &&
2031 	    encoding != BTF_INT_BOOL) {
2032 		btf_verifier_log_type(env, t, "Unsupported encoding");
2033 		return -ENOTSUPP;
2034 	}
2035 
2036 	btf_verifier_log_type(env, t, NULL);
2037 
2038 	return meta_needed;
2039 }
2040 
2041 static void btf_int_log(struct btf_verifier_env *env,
2042 			const struct btf_type *t)
2043 {
2044 	int int_data = btf_type_int(t);
2045 
2046 	btf_verifier_log(env,
2047 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2048 			 t->size, BTF_INT_OFFSET(int_data),
2049 			 BTF_INT_BITS(int_data),
2050 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2051 }
2052 
2053 static void btf_int128_print(struct btf_show *show, void *data)
2054 {
2055 	/* data points to a __int128 number.
2056 	 * Suppose
2057 	 *     int128_num = *(__int128 *)data;
2058 	 * The below formulas shows what upper_num and lower_num represents:
2059 	 *     upper_num = int128_num >> 64;
2060 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2061 	 */
2062 	u64 upper_num, lower_num;
2063 
2064 #ifdef __BIG_ENDIAN_BITFIELD
2065 	upper_num = *(u64 *)data;
2066 	lower_num = *(u64 *)(data + 8);
2067 #else
2068 	upper_num = *(u64 *)(data + 8);
2069 	lower_num = *(u64 *)data;
2070 #endif
2071 	if (upper_num == 0)
2072 		btf_show_type_value(show, "0x%llx", lower_num);
2073 	else
2074 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2075 				     lower_num);
2076 }
2077 
2078 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2079 			     u16 right_shift_bits)
2080 {
2081 	u64 upper_num, lower_num;
2082 
2083 #ifdef __BIG_ENDIAN_BITFIELD
2084 	upper_num = print_num[0];
2085 	lower_num = print_num[1];
2086 #else
2087 	upper_num = print_num[1];
2088 	lower_num = print_num[0];
2089 #endif
2090 
2091 	/* shake out un-needed bits by shift/or operations */
2092 	if (left_shift_bits >= 64) {
2093 		upper_num = lower_num << (left_shift_bits - 64);
2094 		lower_num = 0;
2095 	} else {
2096 		upper_num = (upper_num << left_shift_bits) |
2097 			    (lower_num >> (64 - left_shift_bits));
2098 		lower_num = lower_num << left_shift_bits;
2099 	}
2100 
2101 	if (right_shift_bits >= 64) {
2102 		lower_num = upper_num >> (right_shift_bits - 64);
2103 		upper_num = 0;
2104 	} else {
2105 		lower_num = (lower_num >> right_shift_bits) |
2106 			    (upper_num << (64 - right_shift_bits));
2107 		upper_num = upper_num >> right_shift_bits;
2108 	}
2109 
2110 #ifdef __BIG_ENDIAN_BITFIELD
2111 	print_num[0] = upper_num;
2112 	print_num[1] = lower_num;
2113 #else
2114 	print_num[0] = lower_num;
2115 	print_num[1] = upper_num;
2116 #endif
2117 }
2118 
2119 static void btf_bitfield_show(void *data, u8 bits_offset,
2120 			      u8 nr_bits, struct btf_show *show)
2121 {
2122 	u16 left_shift_bits, right_shift_bits;
2123 	u8 nr_copy_bytes;
2124 	u8 nr_copy_bits;
2125 	u64 print_num[2] = {};
2126 
2127 	nr_copy_bits = nr_bits + bits_offset;
2128 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2129 
2130 	memcpy(print_num, data, nr_copy_bytes);
2131 
2132 #ifdef __BIG_ENDIAN_BITFIELD
2133 	left_shift_bits = bits_offset;
2134 #else
2135 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2136 #endif
2137 	right_shift_bits = BITS_PER_U128 - nr_bits;
2138 
2139 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2140 	btf_int128_print(show, print_num);
2141 }
2142 
2143 
2144 static void btf_int_bits_show(const struct btf *btf,
2145 			      const struct btf_type *t,
2146 			      void *data, u8 bits_offset,
2147 			      struct btf_show *show)
2148 {
2149 	u32 int_data = btf_type_int(t);
2150 	u8 nr_bits = BTF_INT_BITS(int_data);
2151 	u8 total_bits_offset;
2152 
2153 	/*
2154 	 * bits_offset is at most 7.
2155 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2156 	 */
2157 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2158 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2159 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2160 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2161 }
2162 
2163 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2164 			 u32 type_id, void *data, u8 bits_offset,
2165 			 struct btf_show *show)
2166 {
2167 	u32 int_data = btf_type_int(t);
2168 	u8 encoding = BTF_INT_ENCODING(int_data);
2169 	bool sign = encoding & BTF_INT_SIGNED;
2170 	u8 nr_bits = BTF_INT_BITS(int_data);
2171 	void *safe_data;
2172 
2173 	safe_data = btf_show_start_type(show, t, type_id, data);
2174 	if (!safe_data)
2175 		return;
2176 
2177 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2178 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2179 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2180 		goto out;
2181 	}
2182 
2183 	switch (nr_bits) {
2184 	case 128:
2185 		btf_int128_print(show, safe_data);
2186 		break;
2187 	case 64:
2188 		if (sign)
2189 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2190 		else
2191 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2192 		break;
2193 	case 32:
2194 		if (sign)
2195 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2196 		else
2197 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2198 		break;
2199 	case 16:
2200 		if (sign)
2201 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2202 		else
2203 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2204 		break;
2205 	case 8:
2206 		if (show->state.array_encoding == BTF_INT_CHAR) {
2207 			/* check for null terminator */
2208 			if (show->state.array_terminated)
2209 				break;
2210 			if (*(char *)data == '\0') {
2211 				show->state.array_terminated = 1;
2212 				break;
2213 			}
2214 			if (isprint(*(char *)data)) {
2215 				btf_show_type_value(show, "'%c'",
2216 						    *(char *)safe_data);
2217 				break;
2218 			}
2219 		}
2220 		if (sign)
2221 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2222 		else
2223 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2224 		break;
2225 	default:
2226 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2227 		break;
2228 	}
2229 out:
2230 	btf_show_end_type(show);
2231 }
2232 
2233 static const struct btf_kind_operations int_ops = {
2234 	.check_meta = btf_int_check_meta,
2235 	.resolve = btf_df_resolve,
2236 	.check_member = btf_int_check_member,
2237 	.check_kflag_member = btf_int_check_kflag_member,
2238 	.log_details = btf_int_log,
2239 	.show = btf_int_show,
2240 };
2241 
2242 static int btf_modifier_check_member(struct btf_verifier_env *env,
2243 				     const struct btf_type *struct_type,
2244 				     const struct btf_member *member,
2245 				     const struct btf_type *member_type)
2246 {
2247 	const struct btf_type *resolved_type;
2248 	u32 resolved_type_id = member->type;
2249 	struct btf_member resolved_member;
2250 	struct btf *btf = env->btf;
2251 
2252 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2253 	if (!resolved_type) {
2254 		btf_verifier_log_member(env, struct_type, member,
2255 					"Invalid member");
2256 		return -EINVAL;
2257 	}
2258 
2259 	resolved_member = *member;
2260 	resolved_member.type = resolved_type_id;
2261 
2262 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2263 							 &resolved_member,
2264 							 resolved_type);
2265 }
2266 
2267 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2268 					   const struct btf_type *struct_type,
2269 					   const struct btf_member *member,
2270 					   const struct btf_type *member_type)
2271 {
2272 	const struct btf_type *resolved_type;
2273 	u32 resolved_type_id = member->type;
2274 	struct btf_member resolved_member;
2275 	struct btf *btf = env->btf;
2276 
2277 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2278 	if (!resolved_type) {
2279 		btf_verifier_log_member(env, struct_type, member,
2280 					"Invalid member");
2281 		return -EINVAL;
2282 	}
2283 
2284 	resolved_member = *member;
2285 	resolved_member.type = resolved_type_id;
2286 
2287 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2288 							       &resolved_member,
2289 							       resolved_type);
2290 }
2291 
2292 static int btf_ptr_check_member(struct btf_verifier_env *env,
2293 				const struct btf_type *struct_type,
2294 				const struct btf_member *member,
2295 				const struct btf_type *member_type)
2296 {
2297 	u32 struct_size, struct_bits_off, bytes_offset;
2298 
2299 	struct_size = struct_type->size;
2300 	struct_bits_off = member->offset;
2301 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2302 
2303 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2304 		btf_verifier_log_member(env, struct_type, member,
2305 					"Member is not byte aligned");
2306 		return -EINVAL;
2307 	}
2308 
2309 	if (struct_size - bytes_offset < sizeof(void *)) {
2310 		btf_verifier_log_member(env, struct_type, member,
2311 					"Member exceeds struct_size");
2312 		return -EINVAL;
2313 	}
2314 
2315 	return 0;
2316 }
2317 
2318 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2319 				   const struct btf_type *t,
2320 				   u32 meta_left)
2321 {
2322 	if (btf_type_vlen(t)) {
2323 		btf_verifier_log_type(env, t, "vlen != 0");
2324 		return -EINVAL;
2325 	}
2326 
2327 	if (btf_type_kflag(t)) {
2328 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2329 		return -EINVAL;
2330 	}
2331 
2332 	if (!BTF_TYPE_ID_VALID(t->type)) {
2333 		btf_verifier_log_type(env, t, "Invalid type_id");
2334 		return -EINVAL;
2335 	}
2336 
2337 	/* typedef type must have a valid name, and other ref types,
2338 	 * volatile, const, restrict, should have a null name.
2339 	 */
2340 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2341 		if (!t->name_off ||
2342 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2343 			btf_verifier_log_type(env, t, "Invalid name");
2344 			return -EINVAL;
2345 		}
2346 	} else {
2347 		if (t->name_off) {
2348 			btf_verifier_log_type(env, t, "Invalid name");
2349 			return -EINVAL;
2350 		}
2351 	}
2352 
2353 	btf_verifier_log_type(env, t, NULL);
2354 
2355 	return 0;
2356 }
2357 
2358 static int btf_modifier_resolve(struct btf_verifier_env *env,
2359 				const struct resolve_vertex *v)
2360 {
2361 	const struct btf_type *t = v->t;
2362 	const struct btf_type *next_type;
2363 	u32 next_type_id = t->type;
2364 	struct btf *btf = env->btf;
2365 
2366 	next_type = btf_type_by_id(btf, next_type_id);
2367 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2368 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2369 		return -EINVAL;
2370 	}
2371 
2372 	if (!env_type_is_resolve_sink(env, next_type) &&
2373 	    !env_type_is_resolved(env, next_type_id))
2374 		return env_stack_push(env, next_type, next_type_id);
2375 
2376 	/* Figure out the resolved next_type_id with size.
2377 	 * They will be stored in the current modifier's
2378 	 * resolved_ids and resolved_sizes such that it can
2379 	 * save us a few type-following when we use it later (e.g. in
2380 	 * pretty print).
2381 	 */
2382 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2383 		if (env_type_is_resolved(env, next_type_id))
2384 			next_type = btf_type_id_resolve(btf, &next_type_id);
2385 
2386 		/* "typedef void new_void", "const void"...etc */
2387 		if (!btf_type_is_void(next_type) &&
2388 		    !btf_type_is_fwd(next_type) &&
2389 		    !btf_type_is_func_proto(next_type)) {
2390 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2391 			return -EINVAL;
2392 		}
2393 	}
2394 
2395 	env_stack_pop_resolved(env, next_type_id, 0);
2396 
2397 	return 0;
2398 }
2399 
2400 static int btf_var_resolve(struct btf_verifier_env *env,
2401 			   const struct resolve_vertex *v)
2402 {
2403 	const struct btf_type *next_type;
2404 	const struct btf_type *t = v->t;
2405 	u32 next_type_id = t->type;
2406 	struct btf *btf = env->btf;
2407 
2408 	next_type = btf_type_by_id(btf, next_type_id);
2409 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2410 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2411 		return -EINVAL;
2412 	}
2413 
2414 	if (!env_type_is_resolve_sink(env, next_type) &&
2415 	    !env_type_is_resolved(env, next_type_id))
2416 		return env_stack_push(env, next_type, next_type_id);
2417 
2418 	if (btf_type_is_modifier(next_type)) {
2419 		const struct btf_type *resolved_type;
2420 		u32 resolved_type_id;
2421 
2422 		resolved_type_id = next_type_id;
2423 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2424 
2425 		if (btf_type_is_ptr(resolved_type) &&
2426 		    !env_type_is_resolve_sink(env, resolved_type) &&
2427 		    !env_type_is_resolved(env, resolved_type_id))
2428 			return env_stack_push(env, resolved_type,
2429 					      resolved_type_id);
2430 	}
2431 
2432 	/* We must resolve to something concrete at this point, no
2433 	 * forward types or similar that would resolve to size of
2434 	 * zero is allowed.
2435 	 */
2436 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2437 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2438 		return -EINVAL;
2439 	}
2440 
2441 	env_stack_pop_resolved(env, next_type_id, 0);
2442 
2443 	return 0;
2444 }
2445 
2446 static int btf_ptr_resolve(struct btf_verifier_env *env,
2447 			   const struct resolve_vertex *v)
2448 {
2449 	const struct btf_type *next_type;
2450 	const struct btf_type *t = v->t;
2451 	u32 next_type_id = t->type;
2452 	struct btf *btf = env->btf;
2453 
2454 	next_type = btf_type_by_id(btf, next_type_id);
2455 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2456 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2457 		return -EINVAL;
2458 	}
2459 
2460 	if (!env_type_is_resolve_sink(env, next_type) &&
2461 	    !env_type_is_resolved(env, next_type_id))
2462 		return env_stack_push(env, next_type, next_type_id);
2463 
2464 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2465 	 * the modifier may have stopped resolving when it was resolved
2466 	 * to a ptr (last-resolved-ptr).
2467 	 *
2468 	 * We now need to continue from the last-resolved-ptr to
2469 	 * ensure the last-resolved-ptr will not referring back to
2470 	 * the currenct ptr (t).
2471 	 */
2472 	if (btf_type_is_modifier(next_type)) {
2473 		const struct btf_type *resolved_type;
2474 		u32 resolved_type_id;
2475 
2476 		resolved_type_id = next_type_id;
2477 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2478 
2479 		if (btf_type_is_ptr(resolved_type) &&
2480 		    !env_type_is_resolve_sink(env, resolved_type) &&
2481 		    !env_type_is_resolved(env, resolved_type_id))
2482 			return env_stack_push(env, resolved_type,
2483 					      resolved_type_id);
2484 	}
2485 
2486 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2487 		if (env_type_is_resolved(env, next_type_id))
2488 			next_type = btf_type_id_resolve(btf, &next_type_id);
2489 
2490 		if (!btf_type_is_void(next_type) &&
2491 		    !btf_type_is_fwd(next_type) &&
2492 		    !btf_type_is_func_proto(next_type)) {
2493 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2494 			return -EINVAL;
2495 		}
2496 	}
2497 
2498 	env_stack_pop_resolved(env, next_type_id, 0);
2499 
2500 	return 0;
2501 }
2502 
2503 static void btf_modifier_show(const struct btf *btf,
2504 			      const struct btf_type *t,
2505 			      u32 type_id, void *data,
2506 			      u8 bits_offset, struct btf_show *show)
2507 {
2508 	if (btf->resolved_ids)
2509 		t = btf_type_id_resolve(btf, &type_id);
2510 	else
2511 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2512 
2513 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2514 }
2515 
2516 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2517 			 u32 type_id, void *data, u8 bits_offset,
2518 			 struct btf_show *show)
2519 {
2520 	t = btf_type_id_resolve(btf, &type_id);
2521 
2522 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2523 }
2524 
2525 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2526 			 u32 type_id, void *data, u8 bits_offset,
2527 			 struct btf_show *show)
2528 {
2529 	void *safe_data;
2530 
2531 	safe_data = btf_show_start_type(show, t, type_id, data);
2532 	if (!safe_data)
2533 		return;
2534 
2535 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2536 	if (show->flags & BTF_SHOW_PTR_RAW)
2537 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2538 	else
2539 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2540 	btf_show_end_type(show);
2541 }
2542 
2543 static void btf_ref_type_log(struct btf_verifier_env *env,
2544 			     const struct btf_type *t)
2545 {
2546 	btf_verifier_log(env, "type_id=%u", t->type);
2547 }
2548 
2549 static struct btf_kind_operations modifier_ops = {
2550 	.check_meta = btf_ref_type_check_meta,
2551 	.resolve = btf_modifier_resolve,
2552 	.check_member = btf_modifier_check_member,
2553 	.check_kflag_member = btf_modifier_check_kflag_member,
2554 	.log_details = btf_ref_type_log,
2555 	.show = btf_modifier_show,
2556 };
2557 
2558 static struct btf_kind_operations ptr_ops = {
2559 	.check_meta = btf_ref_type_check_meta,
2560 	.resolve = btf_ptr_resolve,
2561 	.check_member = btf_ptr_check_member,
2562 	.check_kflag_member = btf_generic_check_kflag_member,
2563 	.log_details = btf_ref_type_log,
2564 	.show = btf_ptr_show,
2565 };
2566 
2567 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2568 			      const struct btf_type *t,
2569 			      u32 meta_left)
2570 {
2571 	if (btf_type_vlen(t)) {
2572 		btf_verifier_log_type(env, t, "vlen != 0");
2573 		return -EINVAL;
2574 	}
2575 
2576 	if (t->type) {
2577 		btf_verifier_log_type(env, t, "type != 0");
2578 		return -EINVAL;
2579 	}
2580 
2581 	/* fwd type must have a valid name */
2582 	if (!t->name_off ||
2583 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2584 		btf_verifier_log_type(env, t, "Invalid name");
2585 		return -EINVAL;
2586 	}
2587 
2588 	btf_verifier_log_type(env, t, NULL);
2589 
2590 	return 0;
2591 }
2592 
2593 static void btf_fwd_type_log(struct btf_verifier_env *env,
2594 			     const struct btf_type *t)
2595 {
2596 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2597 }
2598 
2599 static struct btf_kind_operations fwd_ops = {
2600 	.check_meta = btf_fwd_check_meta,
2601 	.resolve = btf_df_resolve,
2602 	.check_member = btf_df_check_member,
2603 	.check_kflag_member = btf_df_check_kflag_member,
2604 	.log_details = btf_fwd_type_log,
2605 	.show = btf_df_show,
2606 };
2607 
2608 static int btf_array_check_member(struct btf_verifier_env *env,
2609 				  const struct btf_type *struct_type,
2610 				  const struct btf_member *member,
2611 				  const struct btf_type *member_type)
2612 {
2613 	u32 struct_bits_off = member->offset;
2614 	u32 struct_size, bytes_offset;
2615 	u32 array_type_id, array_size;
2616 	struct btf *btf = env->btf;
2617 
2618 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2619 		btf_verifier_log_member(env, struct_type, member,
2620 					"Member is not byte aligned");
2621 		return -EINVAL;
2622 	}
2623 
2624 	array_type_id = member->type;
2625 	btf_type_id_size(btf, &array_type_id, &array_size);
2626 	struct_size = struct_type->size;
2627 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2628 	if (struct_size - bytes_offset < array_size) {
2629 		btf_verifier_log_member(env, struct_type, member,
2630 					"Member exceeds struct_size");
2631 		return -EINVAL;
2632 	}
2633 
2634 	return 0;
2635 }
2636 
2637 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2638 				const struct btf_type *t,
2639 				u32 meta_left)
2640 {
2641 	const struct btf_array *array = btf_type_array(t);
2642 	u32 meta_needed = sizeof(*array);
2643 
2644 	if (meta_left < meta_needed) {
2645 		btf_verifier_log_basic(env, t,
2646 				       "meta_left:%u meta_needed:%u",
2647 				       meta_left, meta_needed);
2648 		return -EINVAL;
2649 	}
2650 
2651 	/* array type should not have a name */
2652 	if (t->name_off) {
2653 		btf_verifier_log_type(env, t, "Invalid name");
2654 		return -EINVAL;
2655 	}
2656 
2657 	if (btf_type_vlen(t)) {
2658 		btf_verifier_log_type(env, t, "vlen != 0");
2659 		return -EINVAL;
2660 	}
2661 
2662 	if (btf_type_kflag(t)) {
2663 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2664 		return -EINVAL;
2665 	}
2666 
2667 	if (t->size) {
2668 		btf_verifier_log_type(env, t, "size != 0");
2669 		return -EINVAL;
2670 	}
2671 
2672 	/* Array elem type and index type cannot be in type void,
2673 	 * so !array->type and !array->index_type are not allowed.
2674 	 */
2675 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2676 		btf_verifier_log_type(env, t, "Invalid elem");
2677 		return -EINVAL;
2678 	}
2679 
2680 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2681 		btf_verifier_log_type(env, t, "Invalid index");
2682 		return -EINVAL;
2683 	}
2684 
2685 	btf_verifier_log_type(env, t, NULL);
2686 
2687 	return meta_needed;
2688 }
2689 
2690 static int btf_array_resolve(struct btf_verifier_env *env,
2691 			     const struct resolve_vertex *v)
2692 {
2693 	const struct btf_array *array = btf_type_array(v->t);
2694 	const struct btf_type *elem_type, *index_type;
2695 	u32 elem_type_id, index_type_id;
2696 	struct btf *btf = env->btf;
2697 	u32 elem_size;
2698 
2699 	/* Check array->index_type */
2700 	index_type_id = array->index_type;
2701 	index_type = btf_type_by_id(btf, index_type_id);
2702 	if (btf_type_nosize_or_null(index_type) ||
2703 	    btf_type_is_resolve_source_only(index_type)) {
2704 		btf_verifier_log_type(env, v->t, "Invalid index");
2705 		return -EINVAL;
2706 	}
2707 
2708 	if (!env_type_is_resolve_sink(env, index_type) &&
2709 	    !env_type_is_resolved(env, index_type_id))
2710 		return env_stack_push(env, index_type, index_type_id);
2711 
2712 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
2713 	if (!index_type || !btf_type_is_int(index_type) ||
2714 	    !btf_type_int_is_regular(index_type)) {
2715 		btf_verifier_log_type(env, v->t, "Invalid index");
2716 		return -EINVAL;
2717 	}
2718 
2719 	/* Check array->type */
2720 	elem_type_id = array->type;
2721 	elem_type = btf_type_by_id(btf, elem_type_id);
2722 	if (btf_type_nosize_or_null(elem_type) ||
2723 	    btf_type_is_resolve_source_only(elem_type)) {
2724 		btf_verifier_log_type(env, v->t,
2725 				      "Invalid elem");
2726 		return -EINVAL;
2727 	}
2728 
2729 	if (!env_type_is_resolve_sink(env, elem_type) &&
2730 	    !env_type_is_resolved(env, elem_type_id))
2731 		return env_stack_push(env, elem_type, elem_type_id);
2732 
2733 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2734 	if (!elem_type) {
2735 		btf_verifier_log_type(env, v->t, "Invalid elem");
2736 		return -EINVAL;
2737 	}
2738 
2739 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2740 		btf_verifier_log_type(env, v->t, "Invalid array of int");
2741 		return -EINVAL;
2742 	}
2743 
2744 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
2745 		btf_verifier_log_type(env, v->t,
2746 				      "Array size overflows U32_MAX");
2747 		return -EINVAL;
2748 	}
2749 
2750 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2751 
2752 	return 0;
2753 }
2754 
2755 static void btf_array_log(struct btf_verifier_env *env,
2756 			  const struct btf_type *t)
2757 {
2758 	const struct btf_array *array = btf_type_array(t);
2759 
2760 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2761 			 array->type, array->index_type, array->nelems);
2762 }
2763 
2764 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2765 			     u32 type_id, void *data, u8 bits_offset,
2766 			     struct btf_show *show)
2767 {
2768 	const struct btf_array *array = btf_type_array(t);
2769 	const struct btf_kind_operations *elem_ops;
2770 	const struct btf_type *elem_type;
2771 	u32 i, elem_size = 0, elem_type_id;
2772 	u16 encoding = 0;
2773 
2774 	elem_type_id = array->type;
2775 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2776 	if (elem_type && btf_type_has_size(elem_type))
2777 		elem_size = elem_type->size;
2778 
2779 	if (elem_type && btf_type_is_int(elem_type)) {
2780 		u32 int_type = btf_type_int(elem_type);
2781 
2782 		encoding = BTF_INT_ENCODING(int_type);
2783 
2784 		/*
2785 		 * BTF_INT_CHAR encoding never seems to be set for
2786 		 * char arrays, so if size is 1 and element is
2787 		 * printable as a char, we'll do that.
2788 		 */
2789 		if (elem_size == 1)
2790 			encoding = BTF_INT_CHAR;
2791 	}
2792 
2793 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2794 		return;
2795 
2796 	if (!elem_type)
2797 		goto out;
2798 	elem_ops = btf_type_ops(elem_type);
2799 
2800 	for (i = 0; i < array->nelems; i++) {
2801 
2802 		btf_show_start_array_member(show);
2803 
2804 		elem_ops->show(btf, elem_type, elem_type_id, data,
2805 			       bits_offset, show);
2806 		data += elem_size;
2807 
2808 		btf_show_end_array_member(show);
2809 
2810 		if (show->state.array_terminated)
2811 			break;
2812 	}
2813 out:
2814 	btf_show_end_array_type(show);
2815 }
2816 
2817 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2818 			   u32 type_id, void *data, u8 bits_offset,
2819 			   struct btf_show *show)
2820 {
2821 	const struct btf_member *m = show->state.member;
2822 
2823 	/*
2824 	 * First check if any members would be shown (are non-zero).
2825 	 * See comments above "struct btf_show" definition for more
2826 	 * details on how this works at a high-level.
2827 	 */
2828 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2829 		if (!show->state.depth_check) {
2830 			show->state.depth_check = show->state.depth + 1;
2831 			show->state.depth_to_show = 0;
2832 		}
2833 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
2834 		show->state.member = m;
2835 
2836 		if (show->state.depth_check != show->state.depth + 1)
2837 			return;
2838 		show->state.depth_check = 0;
2839 
2840 		if (show->state.depth_to_show <= show->state.depth)
2841 			return;
2842 		/*
2843 		 * Reaching here indicates we have recursed and found
2844 		 * non-zero array member(s).
2845 		 */
2846 	}
2847 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
2848 }
2849 
2850 static struct btf_kind_operations array_ops = {
2851 	.check_meta = btf_array_check_meta,
2852 	.resolve = btf_array_resolve,
2853 	.check_member = btf_array_check_member,
2854 	.check_kflag_member = btf_generic_check_kflag_member,
2855 	.log_details = btf_array_log,
2856 	.show = btf_array_show,
2857 };
2858 
2859 static int btf_struct_check_member(struct btf_verifier_env *env,
2860 				   const struct btf_type *struct_type,
2861 				   const struct btf_member *member,
2862 				   const struct btf_type *member_type)
2863 {
2864 	u32 struct_bits_off = member->offset;
2865 	u32 struct_size, bytes_offset;
2866 
2867 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2868 		btf_verifier_log_member(env, struct_type, member,
2869 					"Member is not byte aligned");
2870 		return -EINVAL;
2871 	}
2872 
2873 	struct_size = struct_type->size;
2874 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2875 	if (struct_size - bytes_offset < member_type->size) {
2876 		btf_verifier_log_member(env, struct_type, member,
2877 					"Member exceeds struct_size");
2878 		return -EINVAL;
2879 	}
2880 
2881 	return 0;
2882 }
2883 
2884 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
2885 				 const struct btf_type *t,
2886 				 u32 meta_left)
2887 {
2888 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
2889 	const struct btf_member *member;
2890 	u32 meta_needed, last_offset;
2891 	struct btf *btf = env->btf;
2892 	u32 struct_size = t->size;
2893 	u32 offset;
2894 	u16 i;
2895 
2896 	meta_needed = btf_type_vlen(t) * sizeof(*member);
2897 	if (meta_left < meta_needed) {
2898 		btf_verifier_log_basic(env, t,
2899 				       "meta_left:%u meta_needed:%u",
2900 				       meta_left, meta_needed);
2901 		return -EINVAL;
2902 	}
2903 
2904 	/* struct type either no name or a valid one */
2905 	if (t->name_off &&
2906 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2907 		btf_verifier_log_type(env, t, "Invalid name");
2908 		return -EINVAL;
2909 	}
2910 
2911 	btf_verifier_log_type(env, t, NULL);
2912 
2913 	last_offset = 0;
2914 	for_each_member(i, t, member) {
2915 		if (!btf_name_offset_valid(btf, member->name_off)) {
2916 			btf_verifier_log_member(env, t, member,
2917 						"Invalid member name_offset:%u",
2918 						member->name_off);
2919 			return -EINVAL;
2920 		}
2921 
2922 		/* struct member either no name or a valid one */
2923 		if (member->name_off &&
2924 		    !btf_name_valid_identifier(btf, member->name_off)) {
2925 			btf_verifier_log_member(env, t, member, "Invalid name");
2926 			return -EINVAL;
2927 		}
2928 		/* A member cannot be in type void */
2929 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
2930 			btf_verifier_log_member(env, t, member,
2931 						"Invalid type_id");
2932 			return -EINVAL;
2933 		}
2934 
2935 		offset = btf_member_bit_offset(t, member);
2936 		if (is_union && offset) {
2937 			btf_verifier_log_member(env, t, member,
2938 						"Invalid member bits_offset");
2939 			return -EINVAL;
2940 		}
2941 
2942 		/*
2943 		 * ">" instead of ">=" because the last member could be
2944 		 * "char a[0];"
2945 		 */
2946 		if (last_offset > offset) {
2947 			btf_verifier_log_member(env, t, member,
2948 						"Invalid member bits_offset");
2949 			return -EINVAL;
2950 		}
2951 
2952 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
2953 			btf_verifier_log_member(env, t, member,
2954 						"Member bits_offset exceeds its struct size");
2955 			return -EINVAL;
2956 		}
2957 
2958 		btf_verifier_log_member(env, t, member, NULL);
2959 		last_offset = offset;
2960 	}
2961 
2962 	return meta_needed;
2963 }
2964 
2965 static int btf_struct_resolve(struct btf_verifier_env *env,
2966 			      const struct resolve_vertex *v)
2967 {
2968 	const struct btf_member *member;
2969 	int err;
2970 	u16 i;
2971 
2972 	/* Before continue resolving the next_member,
2973 	 * ensure the last member is indeed resolved to a
2974 	 * type with size info.
2975 	 */
2976 	if (v->next_member) {
2977 		const struct btf_type *last_member_type;
2978 		const struct btf_member *last_member;
2979 		u16 last_member_type_id;
2980 
2981 		last_member = btf_type_member(v->t) + v->next_member - 1;
2982 		last_member_type_id = last_member->type;
2983 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
2984 						       last_member_type_id)))
2985 			return -EINVAL;
2986 
2987 		last_member_type = btf_type_by_id(env->btf,
2988 						  last_member_type_id);
2989 		if (btf_type_kflag(v->t))
2990 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
2991 								last_member,
2992 								last_member_type);
2993 		else
2994 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
2995 								last_member,
2996 								last_member_type);
2997 		if (err)
2998 			return err;
2999 	}
3000 
3001 	for_each_member_from(i, v->next_member, v->t, member) {
3002 		u32 member_type_id = member->type;
3003 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3004 								member_type_id);
3005 
3006 		if (btf_type_nosize_or_null(member_type) ||
3007 		    btf_type_is_resolve_source_only(member_type)) {
3008 			btf_verifier_log_member(env, v->t, member,
3009 						"Invalid member");
3010 			return -EINVAL;
3011 		}
3012 
3013 		if (!env_type_is_resolve_sink(env, member_type) &&
3014 		    !env_type_is_resolved(env, member_type_id)) {
3015 			env_stack_set_next_member(env, i + 1);
3016 			return env_stack_push(env, member_type, member_type_id);
3017 		}
3018 
3019 		if (btf_type_kflag(v->t))
3020 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3021 									    member,
3022 									    member_type);
3023 		else
3024 			err = btf_type_ops(member_type)->check_member(env, v->t,
3025 								      member,
3026 								      member_type);
3027 		if (err)
3028 			return err;
3029 	}
3030 
3031 	env_stack_pop_resolved(env, 0, 0);
3032 
3033 	return 0;
3034 }
3035 
3036 static void btf_struct_log(struct btf_verifier_env *env,
3037 			   const struct btf_type *t)
3038 {
3039 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3040 }
3041 
3042 /* find 'struct bpf_spin_lock' in map value.
3043  * return >= 0 offset if found
3044  * and < 0 in case of error
3045  */
3046 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3047 {
3048 	const struct btf_member *member;
3049 	u32 i, off = -ENOENT;
3050 
3051 	if (!__btf_type_is_struct(t))
3052 		return -EINVAL;
3053 
3054 	for_each_member(i, t, member) {
3055 		const struct btf_type *member_type = btf_type_by_id(btf,
3056 								    member->type);
3057 		if (!__btf_type_is_struct(member_type))
3058 			continue;
3059 		if (member_type->size != sizeof(struct bpf_spin_lock))
3060 			continue;
3061 		if (strcmp(__btf_name_by_offset(btf, member_type->name_off),
3062 			   "bpf_spin_lock"))
3063 			continue;
3064 		if (off != -ENOENT)
3065 			/* only one 'struct bpf_spin_lock' is allowed */
3066 			return -E2BIG;
3067 		off = btf_member_bit_offset(t, member);
3068 		if (off % 8)
3069 			/* valid C code cannot generate such BTF */
3070 			return -EINVAL;
3071 		off /= 8;
3072 		if (off % __alignof__(struct bpf_spin_lock))
3073 			/* valid struct bpf_spin_lock will be 4 byte aligned */
3074 			return -EINVAL;
3075 	}
3076 	return off;
3077 }
3078 
3079 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3080 			      u32 type_id, void *data, u8 bits_offset,
3081 			      struct btf_show *show)
3082 {
3083 	const struct btf_member *member;
3084 	void *safe_data;
3085 	u32 i;
3086 
3087 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
3088 	if (!safe_data)
3089 		return;
3090 
3091 	for_each_member(i, t, member) {
3092 		const struct btf_type *member_type = btf_type_by_id(btf,
3093 								member->type);
3094 		const struct btf_kind_operations *ops;
3095 		u32 member_offset, bitfield_size;
3096 		u32 bytes_offset;
3097 		u8 bits8_offset;
3098 
3099 		btf_show_start_member(show, member);
3100 
3101 		member_offset = btf_member_bit_offset(t, member);
3102 		bitfield_size = btf_member_bitfield_size(t, member);
3103 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3104 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3105 		if (bitfield_size) {
3106 			safe_data = btf_show_start_type(show, member_type,
3107 							member->type,
3108 							data + bytes_offset);
3109 			if (safe_data)
3110 				btf_bitfield_show(safe_data,
3111 						  bits8_offset,
3112 						  bitfield_size, show);
3113 			btf_show_end_type(show);
3114 		} else {
3115 			ops = btf_type_ops(member_type);
3116 			ops->show(btf, member_type, member->type,
3117 				  data + bytes_offset, bits8_offset, show);
3118 		}
3119 
3120 		btf_show_end_member(show);
3121 	}
3122 
3123 	btf_show_end_struct_type(show);
3124 }
3125 
3126 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3127 			    u32 type_id, void *data, u8 bits_offset,
3128 			    struct btf_show *show)
3129 {
3130 	const struct btf_member *m = show->state.member;
3131 
3132 	/*
3133 	 * First check if any members would be shown (are non-zero).
3134 	 * See comments above "struct btf_show" definition for more
3135 	 * details on how this works at a high-level.
3136 	 */
3137 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3138 		if (!show->state.depth_check) {
3139 			show->state.depth_check = show->state.depth + 1;
3140 			show->state.depth_to_show = 0;
3141 		}
3142 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3143 		/* Restore saved member data here */
3144 		show->state.member = m;
3145 		if (show->state.depth_check != show->state.depth + 1)
3146 			return;
3147 		show->state.depth_check = 0;
3148 
3149 		if (show->state.depth_to_show <= show->state.depth)
3150 			return;
3151 		/*
3152 		 * Reaching here indicates we have recursed and found
3153 		 * non-zero child values.
3154 		 */
3155 	}
3156 
3157 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3158 }
3159 
3160 static struct btf_kind_operations struct_ops = {
3161 	.check_meta = btf_struct_check_meta,
3162 	.resolve = btf_struct_resolve,
3163 	.check_member = btf_struct_check_member,
3164 	.check_kflag_member = btf_generic_check_kflag_member,
3165 	.log_details = btf_struct_log,
3166 	.show = btf_struct_show,
3167 };
3168 
3169 static int btf_enum_check_member(struct btf_verifier_env *env,
3170 				 const struct btf_type *struct_type,
3171 				 const struct btf_member *member,
3172 				 const struct btf_type *member_type)
3173 {
3174 	u32 struct_bits_off = member->offset;
3175 	u32 struct_size, bytes_offset;
3176 
3177 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3178 		btf_verifier_log_member(env, struct_type, member,
3179 					"Member is not byte aligned");
3180 		return -EINVAL;
3181 	}
3182 
3183 	struct_size = struct_type->size;
3184 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3185 	if (struct_size - bytes_offset < member_type->size) {
3186 		btf_verifier_log_member(env, struct_type, member,
3187 					"Member exceeds struct_size");
3188 		return -EINVAL;
3189 	}
3190 
3191 	return 0;
3192 }
3193 
3194 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3195 				       const struct btf_type *struct_type,
3196 				       const struct btf_member *member,
3197 				       const struct btf_type *member_type)
3198 {
3199 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3200 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3201 
3202 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3203 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3204 	if (!nr_bits) {
3205 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3206 			btf_verifier_log_member(env, struct_type, member,
3207 						"Member is not byte aligned");
3208 			return -EINVAL;
3209 		}
3210 
3211 		nr_bits = int_bitsize;
3212 	} else if (nr_bits > int_bitsize) {
3213 		btf_verifier_log_member(env, struct_type, member,
3214 					"Invalid member bitfield_size");
3215 		return -EINVAL;
3216 	}
3217 
3218 	struct_size = struct_type->size;
3219 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3220 	if (struct_size < bytes_end) {
3221 		btf_verifier_log_member(env, struct_type, member,
3222 					"Member exceeds struct_size");
3223 		return -EINVAL;
3224 	}
3225 
3226 	return 0;
3227 }
3228 
3229 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3230 			       const struct btf_type *t,
3231 			       u32 meta_left)
3232 {
3233 	const struct btf_enum *enums = btf_type_enum(t);
3234 	struct btf *btf = env->btf;
3235 	u16 i, nr_enums;
3236 	u32 meta_needed;
3237 
3238 	nr_enums = btf_type_vlen(t);
3239 	meta_needed = nr_enums * sizeof(*enums);
3240 
3241 	if (meta_left < meta_needed) {
3242 		btf_verifier_log_basic(env, t,
3243 				       "meta_left:%u meta_needed:%u",
3244 				       meta_left, meta_needed);
3245 		return -EINVAL;
3246 	}
3247 
3248 	if (btf_type_kflag(t)) {
3249 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3250 		return -EINVAL;
3251 	}
3252 
3253 	if (t->size > 8 || !is_power_of_2(t->size)) {
3254 		btf_verifier_log_type(env, t, "Unexpected size");
3255 		return -EINVAL;
3256 	}
3257 
3258 	/* enum type either no name or a valid one */
3259 	if (t->name_off &&
3260 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3261 		btf_verifier_log_type(env, t, "Invalid name");
3262 		return -EINVAL;
3263 	}
3264 
3265 	btf_verifier_log_type(env, t, NULL);
3266 
3267 	for (i = 0; i < nr_enums; i++) {
3268 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3269 			btf_verifier_log(env, "\tInvalid name_offset:%u",
3270 					 enums[i].name_off);
3271 			return -EINVAL;
3272 		}
3273 
3274 		/* enum member must have a valid name */
3275 		if (!enums[i].name_off ||
3276 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
3277 			btf_verifier_log_type(env, t, "Invalid name");
3278 			return -EINVAL;
3279 		}
3280 
3281 		if (env->log.level == BPF_LOG_KERNEL)
3282 			continue;
3283 		btf_verifier_log(env, "\t%s val=%d\n",
3284 				 __btf_name_by_offset(btf, enums[i].name_off),
3285 				 enums[i].val);
3286 	}
3287 
3288 	return meta_needed;
3289 }
3290 
3291 static void btf_enum_log(struct btf_verifier_env *env,
3292 			 const struct btf_type *t)
3293 {
3294 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3295 }
3296 
3297 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3298 			  u32 type_id, void *data, u8 bits_offset,
3299 			  struct btf_show *show)
3300 {
3301 	const struct btf_enum *enums = btf_type_enum(t);
3302 	u32 i, nr_enums = btf_type_vlen(t);
3303 	void *safe_data;
3304 	int v;
3305 
3306 	safe_data = btf_show_start_type(show, t, type_id, data);
3307 	if (!safe_data)
3308 		return;
3309 
3310 	v = *(int *)safe_data;
3311 
3312 	for (i = 0; i < nr_enums; i++) {
3313 		if (v != enums[i].val)
3314 			continue;
3315 
3316 		btf_show_type_value(show, "%s",
3317 				    __btf_name_by_offset(btf,
3318 							 enums[i].name_off));
3319 
3320 		btf_show_end_type(show);
3321 		return;
3322 	}
3323 
3324 	btf_show_type_value(show, "%d", v);
3325 	btf_show_end_type(show);
3326 }
3327 
3328 static struct btf_kind_operations enum_ops = {
3329 	.check_meta = btf_enum_check_meta,
3330 	.resolve = btf_df_resolve,
3331 	.check_member = btf_enum_check_member,
3332 	.check_kflag_member = btf_enum_check_kflag_member,
3333 	.log_details = btf_enum_log,
3334 	.show = btf_enum_show,
3335 };
3336 
3337 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3338 				     const struct btf_type *t,
3339 				     u32 meta_left)
3340 {
3341 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3342 
3343 	if (meta_left < meta_needed) {
3344 		btf_verifier_log_basic(env, t,
3345 				       "meta_left:%u meta_needed:%u",
3346 				       meta_left, meta_needed);
3347 		return -EINVAL;
3348 	}
3349 
3350 	if (t->name_off) {
3351 		btf_verifier_log_type(env, t, "Invalid name");
3352 		return -EINVAL;
3353 	}
3354 
3355 	if (btf_type_kflag(t)) {
3356 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3357 		return -EINVAL;
3358 	}
3359 
3360 	btf_verifier_log_type(env, t, NULL);
3361 
3362 	return meta_needed;
3363 }
3364 
3365 static void btf_func_proto_log(struct btf_verifier_env *env,
3366 			       const struct btf_type *t)
3367 {
3368 	const struct btf_param *args = (const struct btf_param *)(t + 1);
3369 	u16 nr_args = btf_type_vlen(t), i;
3370 
3371 	btf_verifier_log(env, "return=%u args=(", t->type);
3372 	if (!nr_args) {
3373 		btf_verifier_log(env, "void");
3374 		goto done;
3375 	}
3376 
3377 	if (nr_args == 1 && !args[0].type) {
3378 		/* Only one vararg */
3379 		btf_verifier_log(env, "vararg");
3380 		goto done;
3381 	}
3382 
3383 	btf_verifier_log(env, "%u %s", args[0].type,
3384 			 __btf_name_by_offset(env->btf,
3385 					      args[0].name_off));
3386 	for (i = 1; i < nr_args - 1; i++)
3387 		btf_verifier_log(env, ", %u %s", args[i].type,
3388 				 __btf_name_by_offset(env->btf,
3389 						      args[i].name_off));
3390 
3391 	if (nr_args > 1) {
3392 		const struct btf_param *last_arg = &args[nr_args - 1];
3393 
3394 		if (last_arg->type)
3395 			btf_verifier_log(env, ", %u %s", last_arg->type,
3396 					 __btf_name_by_offset(env->btf,
3397 							      last_arg->name_off));
3398 		else
3399 			btf_verifier_log(env, ", vararg");
3400 	}
3401 
3402 done:
3403 	btf_verifier_log(env, ")");
3404 }
3405 
3406 static struct btf_kind_operations func_proto_ops = {
3407 	.check_meta = btf_func_proto_check_meta,
3408 	.resolve = btf_df_resolve,
3409 	/*
3410 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
3411 	 * a struct's member.
3412 	 *
3413 	 * It should be a funciton pointer instead.
3414 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3415 	 *
3416 	 * Hence, there is no btf_func_check_member().
3417 	 */
3418 	.check_member = btf_df_check_member,
3419 	.check_kflag_member = btf_df_check_kflag_member,
3420 	.log_details = btf_func_proto_log,
3421 	.show = btf_df_show,
3422 };
3423 
3424 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3425 			       const struct btf_type *t,
3426 			       u32 meta_left)
3427 {
3428 	if (!t->name_off ||
3429 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3430 		btf_verifier_log_type(env, t, "Invalid name");
3431 		return -EINVAL;
3432 	}
3433 
3434 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3435 		btf_verifier_log_type(env, t, "Invalid func linkage");
3436 		return -EINVAL;
3437 	}
3438 
3439 	if (btf_type_kflag(t)) {
3440 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3441 		return -EINVAL;
3442 	}
3443 
3444 	btf_verifier_log_type(env, t, NULL);
3445 
3446 	return 0;
3447 }
3448 
3449 static struct btf_kind_operations func_ops = {
3450 	.check_meta = btf_func_check_meta,
3451 	.resolve = btf_df_resolve,
3452 	.check_member = btf_df_check_member,
3453 	.check_kflag_member = btf_df_check_kflag_member,
3454 	.log_details = btf_ref_type_log,
3455 	.show = btf_df_show,
3456 };
3457 
3458 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3459 			      const struct btf_type *t,
3460 			      u32 meta_left)
3461 {
3462 	const struct btf_var *var;
3463 	u32 meta_needed = sizeof(*var);
3464 
3465 	if (meta_left < meta_needed) {
3466 		btf_verifier_log_basic(env, t,
3467 				       "meta_left:%u meta_needed:%u",
3468 				       meta_left, meta_needed);
3469 		return -EINVAL;
3470 	}
3471 
3472 	if (btf_type_vlen(t)) {
3473 		btf_verifier_log_type(env, t, "vlen != 0");
3474 		return -EINVAL;
3475 	}
3476 
3477 	if (btf_type_kflag(t)) {
3478 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3479 		return -EINVAL;
3480 	}
3481 
3482 	if (!t->name_off ||
3483 	    !__btf_name_valid(env->btf, t->name_off, true)) {
3484 		btf_verifier_log_type(env, t, "Invalid name");
3485 		return -EINVAL;
3486 	}
3487 
3488 	/* A var cannot be in type void */
3489 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3490 		btf_verifier_log_type(env, t, "Invalid type_id");
3491 		return -EINVAL;
3492 	}
3493 
3494 	var = btf_type_var(t);
3495 	if (var->linkage != BTF_VAR_STATIC &&
3496 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3497 		btf_verifier_log_type(env, t, "Linkage not supported");
3498 		return -EINVAL;
3499 	}
3500 
3501 	btf_verifier_log_type(env, t, NULL);
3502 
3503 	return meta_needed;
3504 }
3505 
3506 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3507 {
3508 	const struct btf_var *var = btf_type_var(t);
3509 
3510 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3511 }
3512 
3513 static const struct btf_kind_operations var_ops = {
3514 	.check_meta		= btf_var_check_meta,
3515 	.resolve		= btf_var_resolve,
3516 	.check_member		= btf_df_check_member,
3517 	.check_kflag_member	= btf_df_check_kflag_member,
3518 	.log_details		= btf_var_log,
3519 	.show			= btf_var_show,
3520 };
3521 
3522 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3523 				  const struct btf_type *t,
3524 				  u32 meta_left)
3525 {
3526 	const struct btf_var_secinfo *vsi;
3527 	u64 last_vsi_end_off = 0, sum = 0;
3528 	u32 i, meta_needed;
3529 
3530 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3531 	if (meta_left < meta_needed) {
3532 		btf_verifier_log_basic(env, t,
3533 				       "meta_left:%u meta_needed:%u",
3534 				       meta_left, meta_needed);
3535 		return -EINVAL;
3536 	}
3537 
3538 	if (!btf_type_vlen(t)) {
3539 		btf_verifier_log_type(env, t, "vlen == 0");
3540 		return -EINVAL;
3541 	}
3542 
3543 	if (!t->size) {
3544 		btf_verifier_log_type(env, t, "size == 0");
3545 		return -EINVAL;
3546 	}
3547 
3548 	if (btf_type_kflag(t)) {
3549 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3550 		return -EINVAL;
3551 	}
3552 
3553 	if (!t->name_off ||
3554 	    !btf_name_valid_section(env->btf, t->name_off)) {
3555 		btf_verifier_log_type(env, t, "Invalid name");
3556 		return -EINVAL;
3557 	}
3558 
3559 	btf_verifier_log_type(env, t, NULL);
3560 
3561 	for_each_vsi(i, t, vsi) {
3562 		/* A var cannot be in type void */
3563 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
3564 			btf_verifier_log_vsi(env, t, vsi,
3565 					     "Invalid type_id");
3566 			return -EINVAL;
3567 		}
3568 
3569 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
3570 			btf_verifier_log_vsi(env, t, vsi,
3571 					     "Invalid offset");
3572 			return -EINVAL;
3573 		}
3574 
3575 		if (!vsi->size || vsi->size > t->size) {
3576 			btf_verifier_log_vsi(env, t, vsi,
3577 					     "Invalid size");
3578 			return -EINVAL;
3579 		}
3580 
3581 		last_vsi_end_off = vsi->offset + vsi->size;
3582 		if (last_vsi_end_off > t->size) {
3583 			btf_verifier_log_vsi(env, t, vsi,
3584 					     "Invalid offset+size");
3585 			return -EINVAL;
3586 		}
3587 
3588 		btf_verifier_log_vsi(env, t, vsi, NULL);
3589 		sum += vsi->size;
3590 	}
3591 
3592 	if (t->size < sum) {
3593 		btf_verifier_log_type(env, t, "Invalid btf_info size");
3594 		return -EINVAL;
3595 	}
3596 
3597 	return meta_needed;
3598 }
3599 
3600 static int btf_datasec_resolve(struct btf_verifier_env *env,
3601 			       const struct resolve_vertex *v)
3602 {
3603 	const struct btf_var_secinfo *vsi;
3604 	struct btf *btf = env->btf;
3605 	u16 i;
3606 
3607 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
3608 		u32 var_type_id = vsi->type, type_id, type_size = 0;
3609 		const struct btf_type *var_type = btf_type_by_id(env->btf,
3610 								 var_type_id);
3611 		if (!var_type || !btf_type_is_var(var_type)) {
3612 			btf_verifier_log_vsi(env, v->t, vsi,
3613 					     "Not a VAR kind member");
3614 			return -EINVAL;
3615 		}
3616 
3617 		if (!env_type_is_resolve_sink(env, var_type) &&
3618 		    !env_type_is_resolved(env, var_type_id)) {
3619 			env_stack_set_next_member(env, i + 1);
3620 			return env_stack_push(env, var_type, var_type_id);
3621 		}
3622 
3623 		type_id = var_type->type;
3624 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
3625 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
3626 			return -EINVAL;
3627 		}
3628 
3629 		if (vsi->size < type_size) {
3630 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
3631 			return -EINVAL;
3632 		}
3633 	}
3634 
3635 	env_stack_pop_resolved(env, 0, 0);
3636 	return 0;
3637 }
3638 
3639 static void btf_datasec_log(struct btf_verifier_env *env,
3640 			    const struct btf_type *t)
3641 {
3642 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3643 }
3644 
3645 static void btf_datasec_show(const struct btf *btf,
3646 			     const struct btf_type *t, u32 type_id,
3647 			     void *data, u8 bits_offset,
3648 			     struct btf_show *show)
3649 {
3650 	const struct btf_var_secinfo *vsi;
3651 	const struct btf_type *var;
3652 	u32 i;
3653 
3654 	if (!btf_show_start_type(show, t, type_id, data))
3655 		return;
3656 
3657 	btf_show_type_value(show, "section (\"%s\") = {",
3658 			    __btf_name_by_offset(btf, t->name_off));
3659 	for_each_vsi(i, t, vsi) {
3660 		var = btf_type_by_id(btf, vsi->type);
3661 		if (i)
3662 			btf_show(show, ",");
3663 		btf_type_ops(var)->show(btf, var, vsi->type,
3664 					data + vsi->offset, bits_offset, show);
3665 	}
3666 	btf_show_end_type(show);
3667 }
3668 
3669 static const struct btf_kind_operations datasec_ops = {
3670 	.check_meta		= btf_datasec_check_meta,
3671 	.resolve		= btf_datasec_resolve,
3672 	.check_member		= btf_df_check_member,
3673 	.check_kflag_member	= btf_df_check_kflag_member,
3674 	.log_details		= btf_datasec_log,
3675 	.show			= btf_datasec_show,
3676 };
3677 
3678 static int btf_func_proto_check(struct btf_verifier_env *env,
3679 				const struct btf_type *t)
3680 {
3681 	const struct btf_type *ret_type;
3682 	const struct btf_param *args;
3683 	const struct btf *btf;
3684 	u16 nr_args, i;
3685 	int err;
3686 
3687 	btf = env->btf;
3688 	args = (const struct btf_param *)(t + 1);
3689 	nr_args = btf_type_vlen(t);
3690 
3691 	/* Check func return type which could be "void" (t->type == 0) */
3692 	if (t->type) {
3693 		u32 ret_type_id = t->type;
3694 
3695 		ret_type = btf_type_by_id(btf, ret_type_id);
3696 		if (!ret_type) {
3697 			btf_verifier_log_type(env, t, "Invalid return type");
3698 			return -EINVAL;
3699 		}
3700 
3701 		if (btf_type_needs_resolve(ret_type) &&
3702 		    !env_type_is_resolved(env, ret_type_id)) {
3703 			err = btf_resolve(env, ret_type, ret_type_id);
3704 			if (err)
3705 				return err;
3706 		}
3707 
3708 		/* Ensure the return type is a type that has a size */
3709 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
3710 			btf_verifier_log_type(env, t, "Invalid return type");
3711 			return -EINVAL;
3712 		}
3713 	}
3714 
3715 	if (!nr_args)
3716 		return 0;
3717 
3718 	/* Last func arg type_id could be 0 if it is a vararg */
3719 	if (!args[nr_args - 1].type) {
3720 		if (args[nr_args - 1].name_off) {
3721 			btf_verifier_log_type(env, t, "Invalid arg#%u",
3722 					      nr_args);
3723 			return -EINVAL;
3724 		}
3725 		nr_args--;
3726 	}
3727 
3728 	err = 0;
3729 	for (i = 0; i < nr_args; i++) {
3730 		const struct btf_type *arg_type;
3731 		u32 arg_type_id;
3732 
3733 		arg_type_id = args[i].type;
3734 		arg_type = btf_type_by_id(btf, arg_type_id);
3735 		if (!arg_type) {
3736 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3737 			err = -EINVAL;
3738 			break;
3739 		}
3740 
3741 		if (args[i].name_off &&
3742 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
3743 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
3744 			btf_verifier_log_type(env, t,
3745 					      "Invalid arg#%u", i + 1);
3746 			err = -EINVAL;
3747 			break;
3748 		}
3749 
3750 		if (btf_type_needs_resolve(arg_type) &&
3751 		    !env_type_is_resolved(env, arg_type_id)) {
3752 			err = btf_resolve(env, arg_type, arg_type_id);
3753 			if (err)
3754 				break;
3755 		}
3756 
3757 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
3758 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3759 			err = -EINVAL;
3760 			break;
3761 		}
3762 	}
3763 
3764 	return err;
3765 }
3766 
3767 static int btf_func_check(struct btf_verifier_env *env,
3768 			  const struct btf_type *t)
3769 {
3770 	const struct btf_type *proto_type;
3771 	const struct btf_param *args;
3772 	const struct btf *btf;
3773 	u16 nr_args, i;
3774 
3775 	btf = env->btf;
3776 	proto_type = btf_type_by_id(btf, t->type);
3777 
3778 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
3779 		btf_verifier_log_type(env, t, "Invalid type_id");
3780 		return -EINVAL;
3781 	}
3782 
3783 	args = (const struct btf_param *)(proto_type + 1);
3784 	nr_args = btf_type_vlen(proto_type);
3785 	for (i = 0; i < nr_args; i++) {
3786 		if (!args[i].name_off && args[i].type) {
3787 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3788 			return -EINVAL;
3789 		}
3790 	}
3791 
3792 	return 0;
3793 }
3794 
3795 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
3796 	[BTF_KIND_INT] = &int_ops,
3797 	[BTF_KIND_PTR] = &ptr_ops,
3798 	[BTF_KIND_ARRAY] = &array_ops,
3799 	[BTF_KIND_STRUCT] = &struct_ops,
3800 	[BTF_KIND_UNION] = &struct_ops,
3801 	[BTF_KIND_ENUM] = &enum_ops,
3802 	[BTF_KIND_FWD] = &fwd_ops,
3803 	[BTF_KIND_TYPEDEF] = &modifier_ops,
3804 	[BTF_KIND_VOLATILE] = &modifier_ops,
3805 	[BTF_KIND_CONST] = &modifier_ops,
3806 	[BTF_KIND_RESTRICT] = &modifier_ops,
3807 	[BTF_KIND_FUNC] = &func_ops,
3808 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
3809 	[BTF_KIND_VAR] = &var_ops,
3810 	[BTF_KIND_DATASEC] = &datasec_ops,
3811 };
3812 
3813 static s32 btf_check_meta(struct btf_verifier_env *env,
3814 			  const struct btf_type *t,
3815 			  u32 meta_left)
3816 {
3817 	u32 saved_meta_left = meta_left;
3818 	s32 var_meta_size;
3819 
3820 	if (meta_left < sizeof(*t)) {
3821 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
3822 				 env->log_type_id, meta_left, sizeof(*t));
3823 		return -EINVAL;
3824 	}
3825 	meta_left -= sizeof(*t);
3826 
3827 	if (t->info & ~BTF_INFO_MASK) {
3828 		btf_verifier_log(env, "[%u] Invalid btf_info:%x",
3829 				 env->log_type_id, t->info);
3830 		return -EINVAL;
3831 	}
3832 
3833 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
3834 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
3835 		btf_verifier_log(env, "[%u] Invalid kind:%u",
3836 				 env->log_type_id, BTF_INFO_KIND(t->info));
3837 		return -EINVAL;
3838 	}
3839 
3840 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
3841 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
3842 				 env->log_type_id, t->name_off);
3843 		return -EINVAL;
3844 	}
3845 
3846 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
3847 	if (var_meta_size < 0)
3848 		return var_meta_size;
3849 
3850 	meta_left -= var_meta_size;
3851 
3852 	return saved_meta_left - meta_left;
3853 }
3854 
3855 static int btf_check_all_metas(struct btf_verifier_env *env)
3856 {
3857 	struct btf *btf = env->btf;
3858 	struct btf_header *hdr;
3859 	void *cur, *end;
3860 
3861 	hdr = &btf->hdr;
3862 	cur = btf->nohdr_data + hdr->type_off;
3863 	end = cur + hdr->type_len;
3864 
3865 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
3866 	while (cur < end) {
3867 		struct btf_type *t = cur;
3868 		s32 meta_size;
3869 
3870 		meta_size = btf_check_meta(env, t, end - cur);
3871 		if (meta_size < 0)
3872 			return meta_size;
3873 
3874 		btf_add_type(env, t);
3875 		cur += meta_size;
3876 		env->log_type_id++;
3877 	}
3878 
3879 	return 0;
3880 }
3881 
3882 static bool btf_resolve_valid(struct btf_verifier_env *env,
3883 			      const struct btf_type *t,
3884 			      u32 type_id)
3885 {
3886 	struct btf *btf = env->btf;
3887 
3888 	if (!env_type_is_resolved(env, type_id))
3889 		return false;
3890 
3891 	if (btf_type_is_struct(t) || btf_type_is_datasec(t))
3892 		return !btf_resolved_type_id(btf, type_id) &&
3893 		       !btf_resolved_type_size(btf, type_id);
3894 
3895 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
3896 	    btf_type_is_var(t)) {
3897 		t = btf_type_id_resolve(btf, &type_id);
3898 		return t &&
3899 		       !btf_type_is_modifier(t) &&
3900 		       !btf_type_is_var(t) &&
3901 		       !btf_type_is_datasec(t);
3902 	}
3903 
3904 	if (btf_type_is_array(t)) {
3905 		const struct btf_array *array = btf_type_array(t);
3906 		const struct btf_type *elem_type;
3907 		u32 elem_type_id = array->type;
3908 		u32 elem_size;
3909 
3910 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3911 		return elem_type && !btf_type_is_modifier(elem_type) &&
3912 			(array->nelems * elem_size ==
3913 			 btf_resolved_type_size(btf, type_id));
3914 	}
3915 
3916 	return false;
3917 }
3918 
3919 static int btf_resolve(struct btf_verifier_env *env,
3920 		       const struct btf_type *t, u32 type_id)
3921 {
3922 	u32 save_log_type_id = env->log_type_id;
3923 	const struct resolve_vertex *v;
3924 	int err = 0;
3925 
3926 	env->resolve_mode = RESOLVE_TBD;
3927 	env_stack_push(env, t, type_id);
3928 	while (!err && (v = env_stack_peak(env))) {
3929 		env->log_type_id = v->type_id;
3930 		err = btf_type_ops(v->t)->resolve(env, v);
3931 	}
3932 
3933 	env->log_type_id = type_id;
3934 	if (err == -E2BIG) {
3935 		btf_verifier_log_type(env, t,
3936 				      "Exceeded max resolving depth:%u",
3937 				      MAX_RESOLVE_DEPTH);
3938 	} else if (err == -EEXIST) {
3939 		btf_verifier_log_type(env, t, "Loop detected");
3940 	}
3941 
3942 	/* Final sanity check */
3943 	if (!err && !btf_resolve_valid(env, t, type_id)) {
3944 		btf_verifier_log_type(env, t, "Invalid resolve state");
3945 		err = -EINVAL;
3946 	}
3947 
3948 	env->log_type_id = save_log_type_id;
3949 	return err;
3950 }
3951 
3952 static int btf_check_all_types(struct btf_verifier_env *env)
3953 {
3954 	struct btf *btf = env->btf;
3955 	const struct btf_type *t;
3956 	u32 type_id, i;
3957 	int err;
3958 
3959 	err = env_resolve_init(env);
3960 	if (err)
3961 		return err;
3962 
3963 	env->phase++;
3964 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
3965 		type_id = btf->start_id + i;
3966 		t = btf_type_by_id(btf, type_id);
3967 
3968 		env->log_type_id = type_id;
3969 		if (btf_type_needs_resolve(t) &&
3970 		    !env_type_is_resolved(env, type_id)) {
3971 			err = btf_resolve(env, t, type_id);
3972 			if (err)
3973 				return err;
3974 		}
3975 
3976 		if (btf_type_is_func_proto(t)) {
3977 			err = btf_func_proto_check(env, t);
3978 			if (err)
3979 				return err;
3980 		}
3981 
3982 		if (btf_type_is_func(t)) {
3983 			err = btf_func_check(env, t);
3984 			if (err)
3985 				return err;
3986 		}
3987 	}
3988 
3989 	return 0;
3990 }
3991 
3992 static int btf_parse_type_sec(struct btf_verifier_env *env)
3993 {
3994 	const struct btf_header *hdr = &env->btf->hdr;
3995 	int err;
3996 
3997 	/* Type section must align to 4 bytes */
3998 	if (hdr->type_off & (sizeof(u32) - 1)) {
3999 		btf_verifier_log(env, "Unaligned type_off");
4000 		return -EINVAL;
4001 	}
4002 
4003 	if (!env->btf->base_btf && !hdr->type_len) {
4004 		btf_verifier_log(env, "No type found");
4005 		return -EINVAL;
4006 	}
4007 
4008 	err = btf_check_all_metas(env);
4009 	if (err)
4010 		return err;
4011 
4012 	return btf_check_all_types(env);
4013 }
4014 
4015 static int btf_parse_str_sec(struct btf_verifier_env *env)
4016 {
4017 	const struct btf_header *hdr;
4018 	struct btf *btf = env->btf;
4019 	const char *start, *end;
4020 
4021 	hdr = &btf->hdr;
4022 	start = btf->nohdr_data + hdr->str_off;
4023 	end = start + hdr->str_len;
4024 
4025 	if (end != btf->data + btf->data_size) {
4026 		btf_verifier_log(env, "String section is not at the end");
4027 		return -EINVAL;
4028 	}
4029 
4030 	btf->strings = start;
4031 
4032 	if (btf->base_btf && !hdr->str_len)
4033 		return 0;
4034 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
4035 		btf_verifier_log(env, "Invalid string section");
4036 		return -EINVAL;
4037 	}
4038 	if (!btf->base_btf && start[0]) {
4039 		btf_verifier_log(env, "Invalid string section");
4040 		return -EINVAL;
4041 	}
4042 
4043 	return 0;
4044 }
4045 
4046 static const size_t btf_sec_info_offset[] = {
4047 	offsetof(struct btf_header, type_off),
4048 	offsetof(struct btf_header, str_off),
4049 };
4050 
4051 static int btf_sec_info_cmp(const void *a, const void *b)
4052 {
4053 	const struct btf_sec_info *x = a;
4054 	const struct btf_sec_info *y = b;
4055 
4056 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
4057 }
4058 
4059 static int btf_check_sec_info(struct btf_verifier_env *env,
4060 			      u32 btf_data_size)
4061 {
4062 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
4063 	u32 total, expected_total, i;
4064 	const struct btf_header *hdr;
4065 	const struct btf *btf;
4066 
4067 	btf = env->btf;
4068 	hdr = &btf->hdr;
4069 
4070 	/* Populate the secs from hdr */
4071 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
4072 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
4073 						   btf_sec_info_offset[i]);
4074 
4075 	sort(secs, ARRAY_SIZE(btf_sec_info_offset),
4076 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
4077 
4078 	/* Check for gaps and overlap among sections */
4079 	total = 0;
4080 	expected_total = btf_data_size - hdr->hdr_len;
4081 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
4082 		if (expected_total < secs[i].off) {
4083 			btf_verifier_log(env, "Invalid section offset");
4084 			return -EINVAL;
4085 		}
4086 		if (total < secs[i].off) {
4087 			/* gap */
4088 			btf_verifier_log(env, "Unsupported section found");
4089 			return -EINVAL;
4090 		}
4091 		if (total > secs[i].off) {
4092 			btf_verifier_log(env, "Section overlap found");
4093 			return -EINVAL;
4094 		}
4095 		if (expected_total - total < secs[i].len) {
4096 			btf_verifier_log(env,
4097 					 "Total section length too long");
4098 			return -EINVAL;
4099 		}
4100 		total += secs[i].len;
4101 	}
4102 
4103 	/* There is data other than hdr and known sections */
4104 	if (expected_total != total) {
4105 		btf_verifier_log(env, "Unsupported section found");
4106 		return -EINVAL;
4107 	}
4108 
4109 	return 0;
4110 }
4111 
4112 static int btf_parse_hdr(struct btf_verifier_env *env)
4113 {
4114 	u32 hdr_len, hdr_copy, btf_data_size;
4115 	const struct btf_header *hdr;
4116 	struct btf *btf;
4117 	int err;
4118 
4119 	btf = env->btf;
4120 	btf_data_size = btf->data_size;
4121 
4122 	if (btf_data_size <
4123 	    offsetof(struct btf_header, hdr_len) + sizeof(hdr->hdr_len)) {
4124 		btf_verifier_log(env, "hdr_len not found");
4125 		return -EINVAL;
4126 	}
4127 
4128 	hdr = btf->data;
4129 	hdr_len = hdr->hdr_len;
4130 	if (btf_data_size < hdr_len) {
4131 		btf_verifier_log(env, "btf_header not found");
4132 		return -EINVAL;
4133 	}
4134 
4135 	/* Ensure the unsupported header fields are zero */
4136 	if (hdr_len > sizeof(btf->hdr)) {
4137 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
4138 		u8 *end = btf->data + hdr_len;
4139 
4140 		for (; expected_zero < end; expected_zero++) {
4141 			if (*expected_zero) {
4142 				btf_verifier_log(env, "Unsupported btf_header");
4143 				return -E2BIG;
4144 			}
4145 		}
4146 	}
4147 
4148 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4149 	memcpy(&btf->hdr, btf->data, hdr_copy);
4150 
4151 	hdr = &btf->hdr;
4152 
4153 	btf_verifier_log_hdr(env, btf_data_size);
4154 
4155 	if (hdr->magic != BTF_MAGIC) {
4156 		btf_verifier_log(env, "Invalid magic");
4157 		return -EINVAL;
4158 	}
4159 
4160 	if (hdr->version != BTF_VERSION) {
4161 		btf_verifier_log(env, "Unsupported version");
4162 		return -ENOTSUPP;
4163 	}
4164 
4165 	if (hdr->flags) {
4166 		btf_verifier_log(env, "Unsupported flags");
4167 		return -ENOTSUPP;
4168 	}
4169 
4170 	if (btf_data_size == hdr->hdr_len) {
4171 		btf_verifier_log(env, "No data");
4172 		return -EINVAL;
4173 	}
4174 
4175 	err = btf_check_sec_info(env, btf_data_size);
4176 	if (err)
4177 		return err;
4178 
4179 	return 0;
4180 }
4181 
4182 static struct btf *btf_parse(void __user *btf_data, u32 btf_data_size,
4183 			     u32 log_level, char __user *log_ubuf, u32 log_size)
4184 {
4185 	struct btf_verifier_env *env = NULL;
4186 	struct bpf_verifier_log *log;
4187 	struct btf *btf = NULL;
4188 	u8 *data;
4189 	int err;
4190 
4191 	if (btf_data_size > BTF_MAX_SIZE)
4192 		return ERR_PTR(-E2BIG);
4193 
4194 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4195 	if (!env)
4196 		return ERR_PTR(-ENOMEM);
4197 
4198 	log = &env->log;
4199 	if (log_level || log_ubuf || log_size) {
4200 		/* user requested verbose verifier output
4201 		 * and supplied buffer to store the verification trace
4202 		 */
4203 		log->level = log_level;
4204 		log->ubuf = log_ubuf;
4205 		log->len_total = log_size;
4206 
4207 		/* log attributes have to be sane */
4208 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
4209 		    !log->level || !log->ubuf) {
4210 			err = -EINVAL;
4211 			goto errout;
4212 		}
4213 	}
4214 
4215 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4216 	if (!btf) {
4217 		err = -ENOMEM;
4218 		goto errout;
4219 	}
4220 	env->btf = btf;
4221 
4222 	data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4223 	if (!data) {
4224 		err = -ENOMEM;
4225 		goto errout;
4226 	}
4227 
4228 	btf->data = data;
4229 	btf->data_size = btf_data_size;
4230 
4231 	if (copy_from_user(data, btf_data, btf_data_size)) {
4232 		err = -EFAULT;
4233 		goto errout;
4234 	}
4235 
4236 	err = btf_parse_hdr(env);
4237 	if (err)
4238 		goto errout;
4239 
4240 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4241 
4242 	err = btf_parse_str_sec(env);
4243 	if (err)
4244 		goto errout;
4245 
4246 	err = btf_parse_type_sec(env);
4247 	if (err)
4248 		goto errout;
4249 
4250 	if (log->level && bpf_verifier_log_full(log)) {
4251 		err = -ENOSPC;
4252 		goto errout;
4253 	}
4254 
4255 	btf_verifier_env_free(env);
4256 	refcount_set(&btf->refcnt, 1);
4257 	return btf;
4258 
4259 errout:
4260 	btf_verifier_env_free(env);
4261 	if (btf)
4262 		btf_free(btf);
4263 	return ERR_PTR(err);
4264 }
4265 
4266 extern char __weak __start_BTF[];
4267 extern char __weak __stop_BTF[];
4268 extern struct btf *btf_vmlinux;
4269 
4270 #define BPF_MAP_TYPE(_id, _ops)
4271 #define BPF_LINK_TYPE(_id, _name)
4272 static union {
4273 	struct bpf_ctx_convert {
4274 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4275 	prog_ctx_type _id##_prog; \
4276 	kern_ctx_type _id##_kern;
4277 #include <linux/bpf_types.h>
4278 #undef BPF_PROG_TYPE
4279 	} *__t;
4280 	/* 't' is written once under lock. Read many times. */
4281 	const struct btf_type *t;
4282 } bpf_ctx_convert;
4283 enum {
4284 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4285 	__ctx_convert##_id,
4286 #include <linux/bpf_types.h>
4287 #undef BPF_PROG_TYPE
4288 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
4289 };
4290 static u8 bpf_ctx_convert_map[] = {
4291 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4292 	[_id] = __ctx_convert##_id,
4293 #include <linux/bpf_types.h>
4294 #undef BPF_PROG_TYPE
4295 	0, /* avoid empty array */
4296 };
4297 #undef BPF_MAP_TYPE
4298 #undef BPF_LINK_TYPE
4299 
4300 static const struct btf_member *
4301 btf_get_prog_ctx_type(struct bpf_verifier_log *log, struct btf *btf,
4302 		      const struct btf_type *t, enum bpf_prog_type prog_type,
4303 		      int arg)
4304 {
4305 	const struct btf_type *conv_struct;
4306 	const struct btf_type *ctx_struct;
4307 	const struct btf_member *ctx_type;
4308 	const char *tname, *ctx_tname;
4309 
4310 	conv_struct = bpf_ctx_convert.t;
4311 	if (!conv_struct) {
4312 		bpf_log(log, "btf_vmlinux is malformed\n");
4313 		return NULL;
4314 	}
4315 	t = btf_type_by_id(btf, t->type);
4316 	while (btf_type_is_modifier(t))
4317 		t = btf_type_by_id(btf, t->type);
4318 	if (!btf_type_is_struct(t)) {
4319 		/* Only pointer to struct is supported for now.
4320 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4321 		 * is not supported yet.
4322 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
4323 		 */
4324 		if (log->level & BPF_LOG_LEVEL)
4325 			bpf_log(log, "arg#%d type is not a struct\n", arg);
4326 		return NULL;
4327 	}
4328 	tname = btf_name_by_offset(btf, t->name_off);
4329 	if (!tname) {
4330 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
4331 		return NULL;
4332 	}
4333 	/* prog_type is valid bpf program type. No need for bounds check. */
4334 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
4335 	/* ctx_struct is a pointer to prog_ctx_type in vmlinux.
4336 	 * Like 'struct __sk_buff'
4337 	 */
4338 	ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
4339 	if (!ctx_struct)
4340 		/* should not happen */
4341 		return NULL;
4342 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
4343 	if (!ctx_tname) {
4344 		/* should not happen */
4345 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
4346 		return NULL;
4347 	}
4348 	/* only compare that prog's ctx type name is the same as
4349 	 * kernel expects. No need to compare field by field.
4350 	 * It's ok for bpf prog to do:
4351 	 * struct __sk_buff {};
4352 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
4353 	 * { // no fields of skb are ever used }
4354 	 */
4355 	if (strcmp(ctx_tname, tname))
4356 		return NULL;
4357 	return ctx_type;
4358 }
4359 
4360 static const struct bpf_map_ops * const btf_vmlinux_map_ops[] = {
4361 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
4362 #define BPF_LINK_TYPE(_id, _name)
4363 #define BPF_MAP_TYPE(_id, _ops) \
4364 	[_id] = &_ops,
4365 #include <linux/bpf_types.h>
4366 #undef BPF_PROG_TYPE
4367 #undef BPF_LINK_TYPE
4368 #undef BPF_MAP_TYPE
4369 };
4370 
4371 static int btf_vmlinux_map_ids_init(const struct btf *btf,
4372 				    struct bpf_verifier_log *log)
4373 {
4374 	const struct bpf_map_ops *ops;
4375 	int i, btf_id;
4376 
4377 	for (i = 0; i < ARRAY_SIZE(btf_vmlinux_map_ops); ++i) {
4378 		ops = btf_vmlinux_map_ops[i];
4379 		if (!ops || (!ops->map_btf_name && !ops->map_btf_id))
4380 			continue;
4381 		if (!ops->map_btf_name || !ops->map_btf_id) {
4382 			bpf_log(log, "map type %d is misconfigured\n", i);
4383 			return -EINVAL;
4384 		}
4385 		btf_id = btf_find_by_name_kind(btf, ops->map_btf_name,
4386 					       BTF_KIND_STRUCT);
4387 		if (btf_id < 0)
4388 			return btf_id;
4389 		*ops->map_btf_id = btf_id;
4390 	}
4391 
4392 	return 0;
4393 }
4394 
4395 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
4396 				     struct btf *btf,
4397 				     const struct btf_type *t,
4398 				     enum bpf_prog_type prog_type,
4399 				     int arg)
4400 {
4401 	const struct btf_member *prog_ctx_type, *kern_ctx_type;
4402 
4403 	prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
4404 	if (!prog_ctx_type)
4405 		return -ENOENT;
4406 	kern_ctx_type = prog_ctx_type + 1;
4407 	return kern_ctx_type->type;
4408 }
4409 
4410 BTF_ID_LIST(bpf_ctx_convert_btf_id)
4411 BTF_ID(struct, bpf_ctx_convert)
4412 
4413 struct btf *btf_parse_vmlinux(void)
4414 {
4415 	struct btf_verifier_env *env = NULL;
4416 	struct bpf_verifier_log *log;
4417 	struct btf *btf = NULL;
4418 	int err;
4419 
4420 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4421 	if (!env)
4422 		return ERR_PTR(-ENOMEM);
4423 
4424 	log = &env->log;
4425 	log->level = BPF_LOG_KERNEL;
4426 
4427 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4428 	if (!btf) {
4429 		err = -ENOMEM;
4430 		goto errout;
4431 	}
4432 	env->btf = btf;
4433 
4434 	btf->data = __start_BTF;
4435 	btf->data_size = __stop_BTF - __start_BTF;
4436 	btf->kernel_btf = true;
4437 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
4438 
4439 	err = btf_parse_hdr(env);
4440 	if (err)
4441 		goto errout;
4442 
4443 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4444 
4445 	err = btf_parse_str_sec(env);
4446 	if (err)
4447 		goto errout;
4448 
4449 	err = btf_check_all_metas(env);
4450 	if (err)
4451 		goto errout;
4452 
4453 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
4454 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
4455 
4456 	/* find bpf map structs for map_ptr access checking */
4457 	err = btf_vmlinux_map_ids_init(btf, log);
4458 	if (err < 0)
4459 		goto errout;
4460 
4461 	bpf_struct_ops_init(btf, log);
4462 
4463 	refcount_set(&btf->refcnt, 1);
4464 
4465 	err = btf_alloc_id(btf);
4466 	if (err)
4467 		goto errout;
4468 
4469 	btf_verifier_env_free(env);
4470 	return btf;
4471 
4472 errout:
4473 	btf_verifier_env_free(env);
4474 	if (btf) {
4475 		kvfree(btf->types);
4476 		kfree(btf);
4477 	}
4478 	return ERR_PTR(err);
4479 }
4480 
4481 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
4482 
4483 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
4484 {
4485 	struct btf_verifier_env *env = NULL;
4486 	struct bpf_verifier_log *log;
4487 	struct btf *btf = NULL, *base_btf;
4488 	int err;
4489 
4490 	base_btf = bpf_get_btf_vmlinux();
4491 	if (IS_ERR(base_btf))
4492 		return base_btf;
4493 	if (!base_btf)
4494 		return ERR_PTR(-EINVAL);
4495 
4496 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4497 	if (!env)
4498 		return ERR_PTR(-ENOMEM);
4499 
4500 	log = &env->log;
4501 	log->level = BPF_LOG_KERNEL;
4502 
4503 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4504 	if (!btf) {
4505 		err = -ENOMEM;
4506 		goto errout;
4507 	}
4508 	env->btf = btf;
4509 
4510 	btf->base_btf = base_btf;
4511 	btf->start_id = base_btf->nr_types;
4512 	btf->start_str_off = base_btf->hdr.str_len;
4513 	btf->kernel_btf = true;
4514 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
4515 
4516 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
4517 	if (!btf->data) {
4518 		err = -ENOMEM;
4519 		goto errout;
4520 	}
4521 	memcpy(btf->data, data, data_size);
4522 	btf->data_size = data_size;
4523 
4524 	err = btf_parse_hdr(env);
4525 	if (err)
4526 		goto errout;
4527 
4528 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4529 
4530 	err = btf_parse_str_sec(env);
4531 	if (err)
4532 		goto errout;
4533 
4534 	err = btf_check_all_metas(env);
4535 	if (err)
4536 		goto errout;
4537 
4538 	btf_verifier_env_free(env);
4539 	refcount_set(&btf->refcnt, 1);
4540 	return btf;
4541 
4542 errout:
4543 	btf_verifier_env_free(env);
4544 	if (btf) {
4545 		kvfree(btf->data);
4546 		kvfree(btf->types);
4547 		kfree(btf);
4548 	}
4549 	return ERR_PTR(err);
4550 }
4551 
4552 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
4553 
4554 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
4555 {
4556 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4557 
4558 	if (tgt_prog) {
4559 		return tgt_prog->aux->btf;
4560 	} else {
4561 		return btf_vmlinux;
4562 	}
4563 }
4564 
4565 static bool is_string_ptr(struct btf *btf, const struct btf_type *t)
4566 {
4567 	/* t comes in already as a pointer */
4568 	t = btf_type_by_id(btf, t->type);
4569 
4570 	/* allow const */
4571 	if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
4572 		t = btf_type_by_id(btf, t->type);
4573 
4574 	/* char, signed char, unsigned char */
4575 	return btf_type_is_int(t) && t->size == 1;
4576 }
4577 
4578 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
4579 		    const struct bpf_prog *prog,
4580 		    struct bpf_insn_access_aux *info)
4581 {
4582 	const struct btf_type *t = prog->aux->attach_func_proto;
4583 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4584 	struct btf *btf = bpf_prog_get_target_btf(prog);
4585 	const char *tname = prog->aux->attach_func_name;
4586 	struct bpf_verifier_log *log = info->log;
4587 	const struct btf_param *args;
4588 	u32 nr_args, arg;
4589 	int i, ret;
4590 
4591 	if (off % 8) {
4592 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
4593 			tname, off);
4594 		return false;
4595 	}
4596 	arg = off / 8;
4597 	args = (const struct btf_param *)(t + 1);
4598 	/* if (t == NULL) Fall back to default BPF prog with 5 u64 arguments */
4599 	nr_args = t ? btf_type_vlen(t) : 5;
4600 	if (prog->aux->attach_btf_trace) {
4601 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
4602 		args++;
4603 		nr_args--;
4604 	}
4605 
4606 	if (arg > nr_args) {
4607 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4608 			tname, arg + 1);
4609 		return false;
4610 	}
4611 
4612 	if (arg == nr_args) {
4613 		switch (prog->expected_attach_type) {
4614 		case BPF_LSM_MAC:
4615 		case BPF_TRACE_FEXIT:
4616 			/* When LSM programs are attached to void LSM hooks
4617 			 * they use FEXIT trampolines and when attached to
4618 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
4619 			 *
4620 			 * While the LSM programs are BPF_MODIFY_RETURN-like
4621 			 * the check:
4622 			 *
4623 			 *	if (ret_type != 'int')
4624 			 *		return -EINVAL;
4625 			 *
4626 			 * is _not_ done here. This is still safe as LSM hooks
4627 			 * have only void and int return types.
4628 			 */
4629 			if (!t)
4630 				return true;
4631 			t = btf_type_by_id(btf, t->type);
4632 			break;
4633 		case BPF_MODIFY_RETURN:
4634 			/* For now the BPF_MODIFY_RETURN can only be attached to
4635 			 * functions that return an int.
4636 			 */
4637 			if (!t)
4638 				return false;
4639 
4640 			t = btf_type_skip_modifiers(btf, t->type, NULL);
4641 			if (!btf_type_is_small_int(t)) {
4642 				bpf_log(log,
4643 					"ret type %s not allowed for fmod_ret\n",
4644 					btf_kind_str[BTF_INFO_KIND(t->info)]);
4645 				return false;
4646 			}
4647 			break;
4648 		default:
4649 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4650 				tname, arg + 1);
4651 			return false;
4652 		}
4653 	} else {
4654 		if (!t)
4655 			/* Default prog with 5 args */
4656 			return true;
4657 		t = btf_type_by_id(btf, args[arg].type);
4658 	}
4659 
4660 	/* skip modifiers */
4661 	while (btf_type_is_modifier(t))
4662 		t = btf_type_by_id(btf, t->type);
4663 	if (btf_type_is_small_int(t) || btf_type_is_enum(t))
4664 		/* accessing a scalar */
4665 		return true;
4666 	if (!btf_type_is_ptr(t)) {
4667 		bpf_log(log,
4668 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
4669 			tname, arg,
4670 			__btf_name_by_offset(btf, t->name_off),
4671 			btf_kind_str[BTF_INFO_KIND(t->info)]);
4672 		return false;
4673 	}
4674 
4675 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
4676 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4677 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4678 
4679 		if (ctx_arg_info->offset == off &&
4680 		    (ctx_arg_info->reg_type == PTR_TO_RDONLY_BUF_OR_NULL ||
4681 		     ctx_arg_info->reg_type == PTR_TO_RDWR_BUF_OR_NULL)) {
4682 			info->reg_type = ctx_arg_info->reg_type;
4683 			return true;
4684 		}
4685 	}
4686 
4687 	if (t->type == 0)
4688 		/* This is a pointer to void.
4689 		 * It is the same as scalar from the verifier safety pov.
4690 		 * No further pointer walking is allowed.
4691 		 */
4692 		return true;
4693 
4694 	if (is_string_ptr(btf, t))
4695 		return true;
4696 
4697 	/* this is a pointer to another type */
4698 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4699 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4700 
4701 		if (ctx_arg_info->offset == off) {
4702 			info->reg_type = ctx_arg_info->reg_type;
4703 			info->btf_id = ctx_arg_info->btf_id;
4704 			return true;
4705 		}
4706 	}
4707 
4708 	info->reg_type = PTR_TO_BTF_ID;
4709 	if (tgt_prog) {
4710 		enum bpf_prog_type tgt_type;
4711 
4712 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
4713 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
4714 		else
4715 			tgt_type = tgt_prog->type;
4716 
4717 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
4718 		if (ret > 0) {
4719 			info->btf_id = ret;
4720 			return true;
4721 		} else {
4722 			return false;
4723 		}
4724 	}
4725 
4726 	info->btf_id = t->type;
4727 	t = btf_type_by_id(btf, t->type);
4728 	/* skip modifiers */
4729 	while (btf_type_is_modifier(t)) {
4730 		info->btf_id = t->type;
4731 		t = btf_type_by_id(btf, t->type);
4732 	}
4733 	if (!btf_type_is_struct(t)) {
4734 		bpf_log(log,
4735 			"func '%s' arg%d type %s is not a struct\n",
4736 			tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
4737 		return false;
4738 	}
4739 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
4740 		tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
4741 		__btf_name_by_offset(btf, t->name_off));
4742 	return true;
4743 }
4744 
4745 enum bpf_struct_walk_result {
4746 	/* < 0 error */
4747 	WALK_SCALAR = 0,
4748 	WALK_PTR,
4749 	WALK_STRUCT,
4750 };
4751 
4752 static int btf_struct_walk(struct bpf_verifier_log *log,
4753 			   const struct btf_type *t, int off, int size,
4754 			   u32 *next_btf_id)
4755 {
4756 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
4757 	const struct btf_type *mtype, *elem_type = NULL;
4758 	const struct btf_member *member;
4759 	const char *tname, *mname;
4760 	u32 vlen, elem_id, mid;
4761 
4762 again:
4763 	tname = __btf_name_by_offset(btf_vmlinux, t->name_off);
4764 	if (!btf_type_is_struct(t)) {
4765 		bpf_log(log, "Type '%s' is not a struct\n", tname);
4766 		return -EINVAL;
4767 	}
4768 
4769 	vlen = btf_type_vlen(t);
4770 	if (off + size > t->size) {
4771 		/* If the last element is a variable size array, we may
4772 		 * need to relax the rule.
4773 		 */
4774 		struct btf_array *array_elem;
4775 
4776 		if (vlen == 0)
4777 			goto error;
4778 
4779 		member = btf_type_member(t) + vlen - 1;
4780 		mtype = btf_type_skip_modifiers(btf_vmlinux, member->type,
4781 						NULL);
4782 		if (!btf_type_is_array(mtype))
4783 			goto error;
4784 
4785 		array_elem = (struct btf_array *)(mtype + 1);
4786 		if (array_elem->nelems != 0)
4787 			goto error;
4788 
4789 		moff = btf_member_bit_offset(t, member) / 8;
4790 		if (off < moff)
4791 			goto error;
4792 
4793 		/* Only allow structure for now, can be relaxed for
4794 		 * other types later.
4795 		 */
4796 		t = btf_type_skip_modifiers(btf_vmlinux, array_elem->type,
4797 					    NULL);
4798 		if (!btf_type_is_struct(t))
4799 			goto error;
4800 
4801 		off = (off - moff) % t->size;
4802 		goto again;
4803 
4804 error:
4805 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
4806 			tname, off, size);
4807 		return -EACCES;
4808 	}
4809 
4810 	for_each_member(i, t, member) {
4811 		/* offset of the field in bytes */
4812 		moff = btf_member_bit_offset(t, member) / 8;
4813 		if (off + size <= moff)
4814 			/* won't find anything, field is already too far */
4815 			break;
4816 
4817 		if (btf_member_bitfield_size(t, member)) {
4818 			u32 end_bit = btf_member_bit_offset(t, member) +
4819 				btf_member_bitfield_size(t, member);
4820 
4821 			/* off <= moff instead of off == moff because clang
4822 			 * does not generate a BTF member for anonymous
4823 			 * bitfield like the ":16" here:
4824 			 * struct {
4825 			 *	int :16;
4826 			 *	int x:8;
4827 			 * };
4828 			 */
4829 			if (off <= moff &&
4830 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
4831 				return WALK_SCALAR;
4832 
4833 			/* off may be accessing a following member
4834 			 *
4835 			 * or
4836 			 *
4837 			 * Doing partial access at either end of this
4838 			 * bitfield.  Continue on this case also to
4839 			 * treat it as not accessing this bitfield
4840 			 * and eventually error out as field not
4841 			 * found to keep it simple.
4842 			 * It could be relaxed if there was a legit
4843 			 * partial access case later.
4844 			 */
4845 			continue;
4846 		}
4847 
4848 		/* In case of "off" is pointing to holes of a struct */
4849 		if (off < moff)
4850 			break;
4851 
4852 		/* type of the field */
4853 		mid = member->type;
4854 		mtype = btf_type_by_id(btf_vmlinux, member->type);
4855 		mname = __btf_name_by_offset(btf_vmlinux, member->name_off);
4856 
4857 		mtype = __btf_resolve_size(btf_vmlinux, mtype, &msize,
4858 					   &elem_type, &elem_id, &total_nelems,
4859 					   &mid);
4860 		if (IS_ERR(mtype)) {
4861 			bpf_log(log, "field %s doesn't have size\n", mname);
4862 			return -EFAULT;
4863 		}
4864 
4865 		mtrue_end = moff + msize;
4866 		if (off >= mtrue_end)
4867 			/* no overlap with member, keep iterating */
4868 			continue;
4869 
4870 		if (btf_type_is_array(mtype)) {
4871 			u32 elem_idx;
4872 
4873 			/* __btf_resolve_size() above helps to
4874 			 * linearize a multi-dimensional array.
4875 			 *
4876 			 * The logic here is treating an array
4877 			 * in a struct as the following way:
4878 			 *
4879 			 * struct outer {
4880 			 *	struct inner array[2][2];
4881 			 * };
4882 			 *
4883 			 * looks like:
4884 			 *
4885 			 * struct outer {
4886 			 *	struct inner array_elem0;
4887 			 *	struct inner array_elem1;
4888 			 *	struct inner array_elem2;
4889 			 *	struct inner array_elem3;
4890 			 * };
4891 			 *
4892 			 * When accessing outer->array[1][0], it moves
4893 			 * moff to "array_elem2", set mtype to
4894 			 * "struct inner", and msize also becomes
4895 			 * sizeof(struct inner).  Then most of the
4896 			 * remaining logic will fall through without
4897 			 * caring the current member is an array or
4898 			 * not.
4899 			 *
4900 			 * Unlike mtype/msize/moff, mtrue_end does not
4901 			 * change.  The naming difference ("_true") tells
4902 			 * that it is not always corresponding to
4903 			 * the current mtype/msize/moff.
4904 			 * It is the true end of the current
4905 			 * member (i.e. array in this case).  That
4906 			 * will allow an int array to be accessed like
4907 			 * a scratch space,
4908 			 * i.e. allow access beyond the size of
4909 			 *      the array's element as long as it is
4910 			 *      within the mtrue_end boundary.
4911 			 */
4912 
4913 			/* skip empty array */
4914 			if (moff == mtrue_end)
4915 				continue;
4916 
4917 			msize /= total_nelems;
4918 			elem_idx = (off - moff) / msize;
4919 			moff += elem_idx * msize;
4920 			mtype = elem_type;
4921 			mid = elem_id;
4922 		}
4923 
4924 		/* the 'off' we're looking for is either equal to start
4925 		 * of this field or inside of this struct
4926 		 */
4927 		if (btf_type_is_struct(mtype)) {
4928 			/* our field must be inside that union or struct */
4929 			t = mtype;
4930 
4931 			/* return if the offset matches the member offset */
4932 			if (off == moff) {
4933 				*next_btf_id = mid;
4934 				return WALK_STRUCT;
4935 			}
4936 
4937 			/* adjust offset we're looking for */
4938 			off -= moff;
4939 			goto again;
4940 		}
4941 
4942 		if (btf_type_is_ptr(mtype)) {
4943 			const struct btf_type *stype;
4944 			u32 id;
4945 
4946 			if (msize != size || off != moff) {
4947 				bpf_log(log,
4948 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
4949 					mname, moff, tname, off, size);
4950 				return -EACCES;
4951 			}
4952 			stype = btf_type_skip_modifiers(btf_vmlinux, mtype->type, &id);
4953 			if (btf_type_is_struct(stype)) {
4954 				*next_btf_id = id;
4955 				return WALK_PTR;
4956 			}
4957 		}
4958 
4959 		/* Allow more flexible access within an int as long as
4960 		 * it is within mtrue_end.
4961 		 * Since mtrue_end could be the end of an array,
4962 		 * that also allows using an array of int as a scratch
4963 		 * space. e.g. skb->cb[].
4964 		 */
4965 		if (off + size > mtrue_end) {
4966 			bpf_log(log,
4967 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
4968 				mname, mtrue_end, tname, off, size);
4969 			return -EACCES;
4970 		}
4971 
4972 		return WALK_SCALAR;
4973 	}
4974 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
4975 	return -EINVAL;
4976 }
4977 
4978 int btf_struct_access(struct bpf_verifier_log *log,
4979 		      const struct btf_type *t, int off, int size,
4980 		      enum bpf_access_type atype __maybe_unused,
4981 		      u32 *next_btf_id)
4982 {
4983 	int err;
4984 	u32 id;
4985 
4986 	do {
4987 		err = btf_struct_walk(log, t, off, size, &id);
4988 
4989 		switch (err) {
4990 		case WALK_PTR:
4991 			/* If we found the pointer or scalar on t+off,
4992 			 * we're done.
4993 			 */
4994 			*next_btf_id = id;
4995 			return PTR_TO_BTF_ID;
4996 		case WALK_SCALAR:
4997 			return SCALAR_VALUE;
4998 		case WALK_STRUCT:
4999 			/* We found nested struct, so continue the search
5000 			 * by diving in it. At this point the offset is
5001 			 * aligned with the new type, so set it to 0.
5002 			 */
5003 			t = btf_type_by_id(btf_vmlinux, id);
5004 			off = 0;
5005 			break;
5006 		default:
5007 			/* It's either error or unknown return value..
5008 			 * scream and leave.
5009 			 */
5010 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5011 				return -EINVAL;
5012 			return err;
5013 		}
5014 	} while (t);
5015 
5016 	return -EINVAL;
5017 }
5018 
5019 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5020 			  int off, u32 id, u32 need_type_id)
5021 {
5022 	const struct btf_type *type;
5023 	int err;
5024 
5025 	/* Are we already done? */
5026 	if (need_type_id == id && off == 0)
5027 		return true;
5028 
5029 again:
5030 	type = btf_type_by_id(btf_vmlinux, id);
5031 	if (!type)
5032 		return false;
5033 	err = btf_struct_walk(log, type, off, 1, &id);
5034 	if (err != WALK_STRUCT)
5035 		return false;
5036 
5037 	/* We found nested struct object. If it matches
5038 	 * the requested ID, we're done. Otherwise let's
5039 	 * continue the search with offset 0 in the new
5040 	 * type.
5041 	 */
5042 	if (need_type_id != id) {
5043 		off = 0;
5044 		goto again;
5045 	}
5046 
5047 	return true;
5048 }
5049 
5050 static int __get_type_size(struct btf *btf, u32 btf_id,
5051 			   const struct btf_type **bad_type)
5052 {
5053 	const struct btf_type *t;
5054 
5055 	if (!btf_id)
5056 		/* void */
5057 		return 0;
5058 	t = btf_type_by_id(btf, btf_id);
5059 	while (t && btf_type_is_modifier(t))
5060 		t = btf_type_by_id(btf, t->type);
5061 	if (!t) {
5062 		*bad_type = btf_type_by_id(btf, 0);
5063 		return -EINVAL;
5064 	}
5065 	if (btf_type_is_ptr(t))
5066 		/* kernel size of pointer. Not BPF's size of pointer*/
5067 		return sizeof(void *);
5068 	if (btf_type_is_int(t) || btf_type_is_enum(t))
5069 		return t->size;
5070 	*bad_type = t;
5071 	return -EINVAL;
5072 }
5073 
5074 int btf_distill_func_proto(struct bpf_verifier_log *log,
5075 			   struct btf *btf,
5076 			   const struct btf_type *func,
5077 			   const char *tname,
5078 			   struct btf_func_model *m)
5079 {
5080 	const struct btf_param *args;
5081 	const struct btf_type *t;
5082 	u32 i, nargs;
5083 	int ret;
5084 
5085 	if (!func) {
5086 		/* BTF function prototype doesn't match the verifier types.
5087 		 * Fall back to 5 u64 args.
5088 		 */
5089 		for (i = 0; i < 5; i++)
5090 			m->arg_size[i] = 8;
5091 		m->ret_size = 8;
5092 		m->nr_args = 5;
5093 		return 0;
5094 	}
5095 	args = (const struct btf_param *)(func + 1);
5096 	nargs = btf_type_vlen(func);
5097 	if (nargs >= MAX_BPF_FUNC_ARGS) {
5098 		bpf_log(log,
5099 			"The function %s has %d arguments. Too many.\n",
5100 			tname, nargs);
5101 		return -EINVAL;
5102 	}
5103 	ret = __get_type_size(btf, func->type, &t);
5104 	if (ret < 0) {
5105 		bpf_log(log,
5106 			"The function %s return type %s is unsupported.\n",
5107 			tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5108 		return -EINVAL;
5109 	}
5110 	m->ret_size = ret;
5111 
5112 	for (i = 0; i < nargs; i++) {
5113 		ret = __get_type_size(btf, args[i].type, &t);
5114 		if (ret < 0) {
5115 			bpf_log(log,
5116 				"The function %s arg%d type %s is unsupported.\n",
5117 				tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5118 			return -EINVAL;
5119 		}
5120 		m->arg_size[i] = ret;
5121 	}
5122 	m->nr_args = nargs;
5123 	return 0;
5124 }
5125 
5126 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5127  * t1 points to BTF_KIND_FUNC in btf1
5128  * t2 points to BTF_KIND_FUNC in btf2
5129  * Returns:
5130  * EINVAL - function prototype mismatch
5131  * EFAULT - verifier bug
5132  * 0 - 99% match. The last 1% is validated by the verifier.
5133  */
5134 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5135 				     struct btf *btf1, const struct btf_type *t1,
5136 				     struct btf *btf2, const struct btf_type *t2)
5137 {
5138 	const struct btf_param *args1, *args2;
5139 	const char *fn1, *fn2, *s1, *s2;
5140 	u32 nargs1, nargs2, i;
5141 
5142 	fn1 = btf_name_by_offset(btf1, t1->name_off);
5143 	fn2 = btf_name_by_offset(btf2, t2->name_off);
5144 
5145 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5146 		bpf_log(log, "%s() is not a global function\n", fn1);
5147 		return -EINVAL;
5148 	}
5149 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5150 		bpf_log(log, "%s() is not a global function\n", fn2);
5151 		return -EINVAL;
5152 	}
5153 
5154 	t1 = btf_type_by_id(btf1, t1->type);
5155 	if (!t1 || !btf_type_is_func_proto(t1))
5156 		return -EFAULT;
5157 	t2 = btf_type_by_id(btf2, t2->type);
5158 	if (!t2 || !btf_type_is_func_proto(t2))
5159 		return -EFAULT;
5160 
5161 	args1 = (const struct btf_param *)(t1 + 1);
5162 	nargs1 = btf_type_vlen(t1);
5163 	args2 = (const struct btf_param *)(t2 + 1);
5164 	nargs2 = btf_type_vlen(t2);
5165 
5166 	if (nargs1 != nargs2) {
5167 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
5168 			fn1, nargs1, fn2, nargs2);
5169 		return -EINVAL;
5170 	}
5171 
5172 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5173 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5174 	if (t1->info != t2->info) {
5175 		bpf_log(log,
5176 			"Return type %s of %s() doesn't match type %s of %s()\n",
5177 			btf_type_str(t1), fn1,
5178 			btf_type_str(t2), fn2);
5179 		return -EINVAL;
5180 	}
5181 
5182 	for (i = 0; i < nargs1; i++) {
5183 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5184 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5185 
5186 		if (t1->info != t2->info) {
5187 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5188 				i, fn1, btf_type_str(t1),
5189 				fn2, btf_type_str(t2));
5190 			return -EINVAL;
5191 		}
5192 		if (btf_type_has_size(t1) && t1->size != t2->size) {
5193 			bpf_log(log,
5194 				"arg%d in %s() has size %d while %s() has %d\n",
5195 				i, fn1, t1->size,
5196 				fn2, t2->size);
5197 			return -EINVAL;
5198 		}
5199 
5200 		/* global functions are validated with scalars and pointers
5201 		 * to context only. And only global functions can be replaced.
5202 		 * Hence type check only those types.
5203 		 */
5204 		if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5205 			continue;
5206 		if (!btf_type_is_ptr(t1)) {
5207 			bpf_log(log,
5208 				"arg%d in %s() has unrecognized type\n",
5209 				i, fn1);
5210 			return -EINVAL;
5211 		}
5212 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5213 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5214 		if (!btf_type_is_struct(t1)) {
5215 			bpf_log(log,
5216 				"arg%d in %s() is not a pointer to context\n",
5217 				i, fn1);
5218 			return -EINVAL;
5219 		}
5220 		if (!btf_type_is_struct(t2)) {
5221 			bpf_log(log,
5222 				"arg%d in %s() is not a pointer to context\n",
5223 				i, fn2);
5224 			return -EINVAL;
5225 		}
5226 		/* This is an optional check to make program writing easier.
5227 		 * Compare names of structs and report an error to the user.
5228 		 * btf_prepare_func_args() already checked that t2 struct
5229 		 * is a context type. btf_prepare_func_args() will check
5230 		 * later that t1 struct is a context type as well.
5231 		 */
5232 		s1 = btf_name_by_offset(btf1, t1->name_off);
5233 		s2 = btf_name_by_offset(btf2, t2->name_off);
5234 		if (strcmp(s1, s2)) {
5235 			bpf_log(log,
5236 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5237 				i, fn1, s1, fn2, s2);
5238 			return -EINVAL;
5239 		}
5240 	}
5241 	return 0;
5242 }
5243 
5244 /* Compare BTFs of given program with BTF of target program */
5245 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5246 			 struct btf *btf2, const struct btf_type *t2)
5247 {
5248 	struct btf *btf1 = prog->aux->btf;
5249 	const struct btf_type *t1;
5250 	u32 btf_id = 0;
5251 
5252 	if (!prog->aux->func_info) {
5253 		bpf_log(log, "Program extension requires BTF\n");
5254 		return -EINVAL;
5255 	}
5256 
5257 	btf_id = prog->aux->func_info[0].type_id;
5258 	if (!btf_id)
5259 		return -EFAULT;
5260 
5261 	t1 = btf_type_by_id(btf1, btf_id);
5262 	if (!t1 || !btf_type_is_func(t1))
5263 		return -EFAULT;
5264 
5265 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5266 }
5267 
5268 /* Compare BTF of a function with given bpf_reg_state.
5269  * Returns:
5270  * EFAULT - there is a verifier bug. Abort verification.
5271  * EINVAL - there is a type mismatch or BTF is not available.
5272  * 0 - BTF matches with what bpf_reg_state expects.
5273  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
5274  */
5275 int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
5276 			     struct bpf_reg_state *reg)
5277 {
5278 	struct bpf_verifier_log *log = &env->log;
5279 	struct bpf_prog *prog = env->prog;
5280 	struct btf *btf = prog->aux->btf;
5281 	const struct btf_param *args;
5282 	const struct btf_type *t;
5283 	u32 i, nargs, btf_id;
5284 	const char *tname;
5285 
5286 	if (!prog->aux->func_info)
5287 		return -EINVAL;
5288 
5289 	btf_id = prog->aux->func_info[subprog].type_id;
5290 	if (!btf_id)
5291 		return -EFAULT;
5292 
5293 	if (prog->aux->func_info_aux[subprog].unreliable)
5294 		return -EINVAL;
5295 
5296 	t = btf_type_by_id(btf, btf_id);
5297 	if (!t || !btf_type_is_func(t)) {
5298 		/* These checks were already done by the verifier while loading
5299 		 * struct bpf_func_info
5300 		 */
5301 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5302 			subprog);
5303 		return -EFAULT;
5304 	}
5305 	tname = btf_name_by_offset(btf, t->name_off);
5306 
5307 	t = btf_type_by_id(btf, t->type);
5308 	if (!t || !btf_type_is_func_proto(t)) {
5309 		bpf_log(log, "Invalid BTF of func %s\n", tname);
5310 		return -EFAULT;
5311 	}
5312 	args = (const struct btf_param *)(t + 1);
5313 	nargs = btf_type_vlen(t);
5314 	if (nargs > 5) {
5315 		bpf_log(log, "Function %s has %d > 5 args\n", tname, nargs);
5316 		goto out;
5317 	}
5318 	/* check that BTF function arguments match actual types that the
5319 	 * verifier sees.
5320 	 */
5321 	for (i = 0; i < nargs; i++) {
5322 		t = btf_type_by_id(btf, args[i].type);
5323 		while (btf_type_is_modifier(t))
5324 			t = btf_type_by_id(btf, t->type);
5325 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5326 			if (reg[i + 1].type == SCALAR_VALUE)
5327 				continue;
5328 			bpf_log(log, "R%d is not a scalar\n", i + 1);
5329 			goto out;
5330 		}
5331 		if (btf_type_is_ptr(t)) {
5332 			if (reg[i + 1].type == SCALAR_VALUE) {
5333 				bpf_log(log, "R%d is not a pointer\n", i + 1);
5334 				goto out;
5335 			}
5336 			/* If function expects ctx type in BTF check that caller
5337 			 * is passing PTR_TO_CTX.
5338 			 */
5339 			if (btf_get_prog_ctx_type(log, btf, t, prog->type, i)) {
5340 				if (reg[i + 1].type != PTR_TO_CTX) {
5341 					bpf_log(log,
5342 						"arg#%d expected pointer to ctx, but got %s\n",
5343 						i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5344 					goto out;
5345 				}
5346 				if (check_ctx_reg(env, &reg[i + 1], i + 1))
5347 					goto out;
5348 				continue;
5349 			}
5350 		}
5351 		bpf_log(log, "Unrecognized arg#%d type %s\n",
5352 			i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5353 		goto out;
5354 	}
5355 	return 0;
5356 out:
5357 	/* Compiler optimizations can remove arguments from static functions
5358 	 * or mismatched type can be passed into a global function.
5359 	 * In such cases mark the function as unreliable from BTF point of view.
5360 	 */
5361 	prog->aux->func_info_aux[subprog].unreliable = true;
5362 	return -EINVAL;
5363 }
5364 
5365 /* Convert BTF of a function into bpf_reg_state if possible
5366  * Returns:
5367  * EFAULT - there is a verifier bug. Abort verification.
5368  * EINVAL - cannot convert BTF.
5369  * 0 - Successfully converted BTF into bpf_reg_state
5370  * (either PTR_TO_CTX or SCALAR_VALUE).
5371  */
5372 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
5373 			  struct bpf_reg_state *reg)
5374 {
5375 	struct bpf_verifier_log *log = &env->log;
5376 	struct bpf_prog *prog = env->prog;
5377 	enum bpf_prog_type prog_type = prog->type;
5378 	struct btf *btf = prog->aux->btf;
5379 	const struct btf_param *args;
5380 	const struct btf_type *t;
5381 	u32 i, nargs, btf_id;
5382 	const char *tname;
5383 
5384 	if (!prog->aux->func_info ||
5385 	    prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
5386 		bpf_log(log, "Verifier bug\n");
5387 		return -EFAULT;
5388 	}
5389 
5390 	btf_id = prog->aux->func_info[subprog].type_id;
5391 	if (!btf_id) {
5392 		bpf_log(log, "Global functions need valid BTF\n");
5393 		return -EFAULT;
5394 	}
5395 
5396 	t = btf_type_by_id(btf, btf_id);
5397 	if (!t || !btf_type_is_func(t)) {
5398 		/* These checks were already done by the verifier while loading
5399 		 * struct bpf_func_info
5400 		 */
5401 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5402 			subprog);
5403 		return -EFAULT;
5404 	}
5405 	tname = btf_name_by_offset(btf, t->name_off);
5406 
5407 	if (log->level & BPF_LOG_LEVEL)
5408 		bpf_log(log, "Validating %s() func#%d...\n",
5409 			tname, subprog);
5410 
5411 	if (prog->aux->func_info_aux[subprog].unreliable) {
5412 		bpf_log(log, "Verifier bug in function %s()\n", tname);
5413 		return -EFAULT;
5414 	}
5415 	if (prog_type == BPF_PROG_TYPE_EXT)
5416 		prog_type = prog->aux->dst_prog->type;
5417 
5418 	t = btf_type_by_id(btf, t->type);
5419 	if (!t || !btf_type_is_func_proto(t)) {
5420 		bpf_log(log, "Invalid type of function %s()\n", tname);
5421 		return -EFAULT;
5422 	}
5423 	args = (const struct btf_param *)(t + 1);
5424 	nargs = btf_type_vlen(t);
5425 	if (nargs > 5) {
5426 		bpf_log(log, "Global function %s() with %d > 5 args. Buggy compiler.\n",
5427 			tname, nargs);
5428 		return -EINVAL;
5429 	}
5430 	/* check that function returns int */
5431 	t = btf_type_by_id(btf, t->type);
5432 	while (btf_type_is_modifier(t))
5433 		t = btf_type_by_id(btf, t->type);
5434 	if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
5435 		bpf_log(log,
5436 			"Global function %s() doesn't return scalar. Only those are supported.\n",
5437 			tname);
5438 		return -EINVAL;
5439 	}
5440 	/* Convert BTF function arguments into verifier types.
5441 	 * Only PTR_TO_CTX and SCALAR are supported atm.
5442 	 */
5443 	for (i = 0; i < nargs; i++) {
5444 		t = btf_type_by_id(btf, args[i].type);
5445 		while (btf_type_is_modifier(t))
5446 			t = btf_type_by_id(btf, t->type);
5447 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5448 			reg[i + 1].type = SCALAR_VALUE;
5449 			continue;
5450 		}
5451 		if (btf_type_is_ptr(t) &&
5452 		    btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5453 			reg[i + 1].type = PTR_TO_CTX;
5454 			continue;
5455 		}
5456 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
5457 			i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
5458 		return -EINVAL;
5459 	}
5460 	return 0;
5461 }
5462 
5463 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
5464 			  struct btf_show *show)
5465 {
5466 	const struct btf_type *t = btf_type_by_id(btf, type_id);
5467 
5468 	show->btf = btf;
5469 	memset(&show->state, 0, sizeof(show->state));
5470 	memset(&show->obj, 0, sizeof(show->obj));
5471 
5472 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
5473 }
5474 
5475 static void btf_seq_show(struct btf_show *show, const char *fmt,
5476 			 va_list args)
5477 {
5478 	seq_vprintf((struct seq_file *)show->target, fmt, args);
5479 }
5480 
5481 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
5482 			    void *obj, struct seq_file *m, u64 flags)
5483 {
5484 	struct btf_show sseq;
5485 
5486 	sseq.target = m;
5487 	sseq.showfn = btf_seq_show;
5488 	sseq.flags = flags;
5489 
5490 	btf_type_show(btf, type_id, obj, &sseq);
5491 
5492 	return sseq.state.status;
5493 }
5494 
5495 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
5496 		       struct seq_file *m)
5497 {
5498 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
5499 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
5500 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
5501 }
5502 
5503 struct btf_show_snprintf {
5504 	struct btf_show show;
5505 	int len_left;		/* space left in string */
5506 	int len;		/* length we would have written */
5507 };
5508 
5509 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
5510 			      va_list args)
5511 {
5512 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
5513 	int len;
5514 
5515 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
5516 
5517 	if (len < 0) {
5518 		ssnprintf->len_left = 0;
5519 		ssnprintf->len = len;
5520 	} else if (len > ssnprintf->len_left) {
5521 		/* no space, drive on to get length we would have written */
5522 		ssnprintf->len_left = 0;
5523 		ssnprintf->len += len;
5524 	} else {
5525 		ssnprintf->len_left -= len;
5526 		ssnprintf->len += len;
5527 		show->target += len;
5528 	}
5529 }
5530 
5531 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
5532 			   char *buf, int len, u64 flags)
5533 {
5534 	struct btf_show_snprintf ssnprintf;
5535 
5536 	ssnprintf.show.target = buf;
5537 	ssnprintf.show.flags = flags;
5538 	ssnprintf.show.showfn = btf_snprintf_show;
5539 	ssnprintf.len_left = len;
5540 	ssnprintf.len = 0;
5541 
5542 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
5543 
5544 	/* If we encontered an error, return it. */
5545 	if (ssnprintf.show.state.status)
5546 		return ssnprintf.show.state.status;
5547 
5548 	/* Otherwise return length we would have written */
5549 	return ssnprintf.len;
5550 }
5551 
5552 #ifdef CONFIG_PROC_FS
5553 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
5554 {
5555 	const struct btf *btf = filp->private_data;
5556 
5557 	seq_printf(m, "btf_id:\t%u\n", btf->id);
5558 }
5559 #endif
5560 
5561 static int btf_release(struct inode *inode, struct file *filp)
5562 {
5563 	btf_put(filp->private_data);
5564 	return 0;
5565 }
5566 
5567 const struct file_operations btf_fops = {
5568 #ifdef CONFIG_PROC_FS
5569 	.show_fdinfo	= bpf_btf_show_fdinfo,
5570 #endif
5571 	.release	= btf_release,
5572 };
5573 
5574 static int __btf_new_fd(struct btf *btf)
5575 {
5576 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
5577 }
5578 
5579 int btf_new_fd(const union bpf_attr *attr)
5580 {
5581 	struct btf *btf;
5582 	int ret;
5583 
5584 	btf = btf_parse(u64_to_user_ptr(attr->btf),
5585 			attr->btf_size, attr->btf_log_level,
5586 			u64_to_user_ptr(attr->btf_log_buf),
5587 			attr->btf_log_size);
5588 	if (IS_ERR(btf))
5589 		return PTR_ERR(btf);
5590 
5591 	ret = btf_alloc_id(btf);
5592 	if (ret) {
5593 		btf_free(btf);
5594 		return ret;
5595 	}
5596 
5597 	/*
5598 	 * The BTF ID is published to the userspace.
5599 	 * All BTF free must go through call_rcu() from
5600 	 * now on (i.e. free by calling btf_put()).
5601 	 */
5602 
5603 	ret = __btf_new_fd(btf);
5604 	if (ret < 0)
5605 		btf_put(btf);
5606 
5607 	return ret;
5608 }
5609 
5610 struct btf *btf_get_by_fd(int fd)
5611 {
5612 	struct btf *btf;
5613 	struct fd f;
5614 
5615 	f = fdget(fd);
5616 
5617 	if (!f.file)
5618 		return ERR_PTR(-EBADF);
5619 
5620 	if (f.file->f_op != &btf_fops) {
5621 		fdput(f);
5622 		return ERR_PTR(-EINVAL);
5623 	}
5624 
5625 	btf = f.file->private_data;
5626 	refcount_inc(&btf->refcnt);
5627 	fdput(f);
5628 
5629 	return btf;
5630 }
5631 
5632 int btf_get_info_by_fd(const struct btf *btf,
5633 		       const union bpf_attr *attr,
5634 		       union bpf_attr __user *uattr)
5635 {
5636 	struct bpf_btf_info __user *uinfo;
5637 	struct bpf_btf_info info;
5638 	u32 info_copy, btf_copy;
5639 	void __user *ubtf;
5640 	char __user *uname;
5641 	u32 uinfo_len, uname_len, name_len;
5642 	int ret = 0;
5643 
5644 	uinfo = u64_to_user_ptr(attr->info.info);
5645 	uinfo_len = attr->info.info_len;
5646 
5647 	info_copy = min_t(u32, uinfo_len, sizeof(info));
5648 	memset(&info, 0, sizeof(info));
5649 	if (copy_from_user(&info, uinfo, info_copy))
5650 		return -EFAULT;
5651 
5652 	info.id = btf->id;
5653 	ubtf = u64_to_user_ptr(info.btf);
5654 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
5655 	if (copy_to_user(ubtf, btf->data, btf_copy))
5656 		return -EFAULT;
5657 	info.btf_size = btf->data_size;
5658 
5659 	info.kernel_btf = btf->kernel_btf;
5660 
5661 	uname = u64_to_user_ptr(info.name);
5662 	uname_len = info.name_len;
5663 	if (!uname ^ !uname_len)
5664 		return -EINVAL;
5665 
5666 	name_len = strlen(btf->name);
5667 	info.name_len = name_len;
5668 
5669 	if (uname) {
5670 		if (uname_len >= name_len + 1) {
5671 			if (copy_to_user(uname, btf->name, name_len + 1))
5672 				return -EFAULT;
5673 		} else {
5674 			char zero = '\0';
5675 
5676 			if (copy_to_user(uname, btf->name, uname_len - 1))
5677 				return -EFAULT;
5678 			if (put_user(zero, uname + uname_len - 1))
5679 				return -EFAULT;
5680 			/* let user-space know about too short buffer */
5681 			ret = -ENOSPC;
5682 		}
5683 	}
5684 
5685 	if (copy_to_user(uinfo, &info, info_copy) ||
5686 	    put_user(info_copy, &uattr->info.info_len))
5687 		return -EFAULT;
5688 
5689 	return ret;
5690 }
5691 
5692 int btf_get_fd_by_id(u32 id)
5693 {
5694 	struct btf *btf;
5695 	int fd;
5696 
5697 	rcu_read_lock();
5698 	btf = idr_find(&btf_idr, id);
5699 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
5700 		btf = ERR_PTR(-ENOENT);
5701 	rcu_read_unlock();
5702 
5703 	if (IS_ERR(btf))
5704 		return PTR_ERR(btf);
5705 
5706 	fd = __btf_new_fd(btf);
5707 	if (fd < 0)
5708 		btf_put(btf);
5709 
5710 	return fd;
5711 }
5712 
5713 u32 btf_id(const struct btf *btf)
5714 {
5715 	return btf->id;
5716 }
5717 
5718 static int btf_id_cmp_func(const void *a, const void *b)
5719 {
5720 	const int *pa = a, *pb = b;
5721 
5722 	return *pa - *pb;
5723 }
5724 
5725 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
5726 {
5727 	return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
5728 }
5729 
5730 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5731 struct btf_module {
5732 	struct list_head list;
5733 	struct module *module;
5734 	struct btf *btf;
5735 	struct bin_attribute *sysfs_attr;
5736 };
5737 
5738 static LIST_HEAD(btf_modules);
5739 static DEFINE_MUTEX(btf_module_mutex);
5740 
5741 static ssize_t
5742 btf_module_read(struct file *file, struct kobject *kobj,
5743 		struct bin_attribute *bin_attr,
5744 		char *buf, loff_t off, size_t len)
5745 {
5746 	const struct btf *btf = bin_attr->private;
5747 
5748 	memcpy(buf, btf->data + off, len);
5749 	return len;
5750 }
5751 
5752 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
5753 			     void *module)
5754 {
5755 	struct btf_module *btf_mod, *tmp;
5756 	struct module *mod = module;
5757 	struct btf *btf;
5758 	int err = 0;
5759 
5760 	if (mod->btf_data_size == 0 ||
5761 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
5762 		goto out;
5763 
5764 	switch (op) {
5765 	case MODULE_STATE_COMING:
5766 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
5767 		if (!btf_mod) {
5768 			err = -ENOMEM;
5769 			goto out;
5770 		}
5771 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
5772 		if (IS_ERR(btf)) {
5773 			pr_warn("failed to validate module [%s] BTF: %ld\n",
5774 				mod->name, PTR_ERR(btf));
5775 			kfree(btf_mod);
5776 			err = PTR_ERR(btf);
5777 			goto out;
5778 		}
5779 		err = btf_alloc_id(btf);
5780 		if (err) {
5781 			btf_free(btf);
5782 			kfree(btf_mod);
5783 			goto out;
5784 		}
5785 
5786 		mutex_lock(&btf_module_mutex);
5787 		btf_mod->module = module;
5788 		btf_mod->btf = btf;
5789 		list_add(&btf_mod->list, &btf_modules);
5790 		mutex_unlock(&btf_module_mutex);
5791 
5792 		if (IS_ENABLED(CONFIG_SYSFS)) {
5793 			struct bin_attribute *attr;
5794 
5795 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
5796 			if (!attr)
5797 				goto out;
5798 
5799 			sysfs_bin_attr_init(attr);
5800 			attr->attr.name = btf->name;
5801 			attr->attr.mode = 0444;
5802 			attr->size = btf->data_size;
5803 			attr->private = btf;
5804 			attr->read = btf_module_read;
5805 
5806 			err = sysfs_create_bin_file(btf_kobj, attr);
5807 			if (err) {
5808 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
5809 					mod->name, err);
5810 				kfree(attr);
5811 				err = 0;
5812 				goto out;
5813 			}
5814 
5815 			btf_mod->sysfs_attr = attr;
5816 		}
5817 
5818 		break;
5819 	case MODULE_STATE_GOING:
5820 		mutex_lock(&btf_module_mutex);
5821 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
5822 			if (btf_mod->module != module)
5823 				continue;
5824 
5825 			list_del(&btf_mod->list);
5826 			if (btf_mod->sysfs_attr)
5827 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
5828 			btf_put(btf_mod->btf);
5829 			kfree(btf_mod->sysfs_attr);
5830 			kfree(btf_mod);
5831 			break;
5832 		}
5833 		mutex_unlock(&btf_module_mutex);
5834 		break;
5835 	}
5836 out:
5837 	return notifier_from_errno(err);
5838 }
5839 
5840 static struct notifier_block btf_module_nb = {
5841 	.notifier_call = btf_module_notify,
5842 };
5843 
5844 static int __init btf_module_init(void)
5845 {
5846 	register_module_notifier(&btf_module_nb);
5847 	return 0;
5848 }
5849 
5850 fs_initcall(btf_module_init);
5851 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5852