xref: /openbmc/linux/kernel/bpf/btf.c (revision 7f9321ff)
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 u32 btf_nr_types(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(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_get(struct btf *btf)
1528 {
1529 	refcount_inc(&btf->refcnt);
1530 }
1531 
1532 void btf_put(struct btf *btf)
1533 {
1534 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1535 		btf_free_id(btf);
1536 		call_rcu(&btf->rcu, btf_free_rcu);
1537 	}
1538 }
1539 
1540 static int env_resolve_init(struct btf_verifier_env *env)
1541 {
1542 	struct btf *btf = env->btf;
1543 	u32 nr_types = btf->nr_types;
1544 	u32 *resolved_sizes = NULL;
1545 	u32 *resolved_ids = NULL;
1546 	u8 *visit_states = NULL;
1547 
1548 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1549 				  GFP_KERNEL | __GFP_NOWARN);
1550 	if (!resolved_sizes)
1551 		goto nomem;
1552 
1553 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1554 				GFP_KERNEL | __GFP_NOWARN);
1555 	if (!resolved_ids)
1556 		goto nomem;
1557 
1558 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1559 				GFP_KERNEL | __GFP_NOWARN);
1560 	if (!visit_states)
1561 		goto nomem;
1562 
1563 	btf->resolved_sizes = resolved_sizes;
1564 	btf->resolved_ids = resolved_ids;
1565 	env->visit_states = visit_states;
1566 
1567 	return 0;
1568 
1569 nomem:
1570 	kvfree(resolved_sizes);
1571 	kvfree(resolved_ids);
1572 	kvfree(visit_states);
1573 	return -ENOMEM;
1574 }
1575 
1576 static void btf_verifier_env_free(struct btf_verifier_env *env)
1577 {
1578 	kvfree(env->visit_states);
1579 	kfree(env);
1580 }
1581 
1582 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1583 				     const struct btf_type *next_type)
1584 {
1585 	switch (env->resolve_mode) {
1586 	case RESOLVE_TBD:
1587 		/* int, enum or void is a sink */
1588 		return !btf_type_needs_resolve(next_type);
1589 	case RESOLVE_PTR:
1590 		/* int, enum, void, struct, array, func or func_proto is a sink
1591 		 * for ptr
1592 		 */
1593 		return !btf_type_is_modifier(next_type) &&
1594 			!btf_type_is_ptr(next_type);
1595 	case RESOLVE_STRUCT_OR_ARRAY:
1596 		/* int, enum, void, ptr, func or func_proto is a sink
1597 		 * for struct and array
1598 		 */
1599 		return !btf_type_is_modifier(next_type) &&
1600 			!btf_type_is_array(next_type) &&
1601 			!btf_type_is_struct(next_type);
1602 	default:
1603 		BUG();
1604 	}
1605 }
1606 
1607 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1608 				 u32 type_id)
1609 {
1610 	/* base BTF types should be resolved by now */
1611 	if (type_id < env->btf->start_id)
1612 		return true;
1613 
1614 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1615 }
1616 
1617 static int env_stack_push(struct btf_verifier_env *env,
1618 			  const struct btf_type *t, u32 type_id)
1619 {
1620 	const struct btf *btf = env->btf;
1621 	struct resolve_vertex *v;
1622 
1623 	if (env->top_stack == MAX_RESOLVE_DEPTH)
1624 		return -E2BIG;
1625 
1626 	if (type_id < btf->start_id
1627 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1628 		return -EEXIST;
1629 
1630 	env->visit_states[type_id - btf->start_id] = VISITED;
1631 
1632 	v = &env->stack[env->top_stack++];
1633 	v->t = t;
1634 	v->type_id = type_id;
1635 	v->next_member = 0;
1636 
1637 	if (env->resolve_mode == RESOLVE_TBD) {
1638 		if (btf_type_is_ptr(t))
1639 			env->resolve_mode = RESOLVE_PTR;
1640 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
1641 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1642 	}
1643 
1644 	return 0;
1645 }
1646 
1647 static void env_stack_set_next_member(struct btf_verifier_env *env,
1648 				      u16 next_member)
1649 {
1650 	env->stack[env->top_stack - 1].next_member = next_member;
1651 }
1652 
1653 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1654 				   u32 resolved_type_id,
1655 				   u32 resolved_size)
1656 {
1657 	u32 type_id = env->stack[--(env->top_stack)].type_id;
1658 	struct btf *btf = env->btf;
1659 
1660 	type_id -= btf->start_id; /* adjust to local type id */
1661 	btf->resolved_sizes[type_id] = resolved_size;
1662 	btf->resolved_ids[type_id] = resolved_type_id;
1663 	env->visit_states[type_id] = RESOLVED;
1664 }
1665 
1666 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1667 {
1668 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1669 }
1670 
1671 /* Resolve the size of a passed-in "type"
1672  *
1673  * type: is an array (e.g. u32 array[x][y])
1674  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1675  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1676  *             corresponds to the return type.
1677  * *elem_type: u32
1678  * *elem_id: id of u32
1679  * *total_nelems: (x * y).  Hence, individual elem size is
1680  *                (*type_size / *total_nelems)
1681  * *type_id: id of type if it's changed within the function, 0 if not
1682  *
1683  * type: is not an array (e.g. const struct X)
1684  * return type: type "struct X"
1685  * *type_size: sizeof(struct X)
1686  * *elem_type: same as return type ("struct X")
1687  * *elem_id: 0
1688  * *total_nelems: 1
1689  * *type_id: id of type if it's changed within the function, 0 if not
1690  */
1691 static const struct btf_type *
1692 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1693 		   u32 *type_size, const struct btf_type **elem_type,
1694 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
1695 {
1696 	const struct btf_type *array_type = NULL;
1697 	const struct btf_array *array = NULL;
1698 	u32 i, size, nelems = 1, id = 0;
1699 
1700 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1701 		switch (BTF_INFO_KIND(type->info)) {
1702 		/* type->size can be used */
1703 		case BTF_KIND_INT:
1704 		case BTF_KIND_STRUCT:
1705 		case BTF_KIND_UNION:
1706 		case BTF_KIND_ENUM:
1707 			size = type->size;
1708 			goto resolved;
1709 
1710 		case BTF_KIND_PTR:
1711 			size = sizeof(void *);
1712 			goto resolved;
1713 
1714 		/* Modifiers */
1715 		case BTF_KIND_TYPEDEF:
1716 		case BTF_KIND_VOLATILE:
1717 		case BTF_KIND_CONST:
1718 		case BTF_KIND_RESTRICT:
1719 			id = type->type;
1720 			type = btf_type_by_id(btf, type->type);
1721 			break;
1722 
1723 		case BTF_KIND_ARRAY:
1724 			if (!array_type)
1725 				array_type = type;
1726 			array = btf_type_array(type);
1727 			if (nelems && array->nelems > U32_MAX / nelems)
1728 				return ERR_PTR(-EINVAL);
1729 			nelems *= array->nelems;
1730 			type = btf_type_by_id(btf, array->type);
1731 			break;
1732 
1733 		/* type without size */
1734 		default:
1735 			return ERR_PTR(-EINVAL);
1736 		}
1737 	}
1738 
1739 	return ERR_PTR(-EINVAL);
1740 
1741 resolved:
1742 	if (nelems && size > U32_MAX / nelems)
1743 		return ERR_PTR(-EINVAL);
1744 
1745 	*type_size = nelems * size;
1746 	if (total_nelems)
1747 		*total_nelems = nelems;
1748 	if (elem_type)
1749 		*elem_type = type;
1750 	if (elem_id)
1751 		*elem_id = array ? array->type : 0;
1752 	if (type_id && id)
1753 		*type_id = id;
1754 
1755 	return array_type ? : type;
1756 }
1757 
1758 const struct btf_type *
1759 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1760 		 u32 *type_size)
1761 {
1762 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1763 }
1764 
1765 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1766 {
1767 	while (type_id < btf->start_id)
1768 		btf = btf->base_btf;
1769 
1770 	return btf->resolved_ids[type_id - btf->start_id];
1771 }
1772 
1773 /* The input param "type_id" must point to a needs_resolve type */
1774 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1775 						  u32 *type_id)
1776 {
1777 	*type_id = btf_resolved_type_id(btf, *type_id);
1778 	return btf_type_by_id(btf, *type_id);
1779 }
1780 
1781 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1782 {
1783 	while (type_id < btf->start_id)
1784 		btf = btf->base_btf;
1785 
1786 	return btf->resolved_sizes[type_id - btf->start_id];
1787 }
1788 
1789 const struct btf_type *btf_type_id_size(const struct btf *btf,
1790 					u32 *type_id, u32 *ret_size)
1791 {
1792 	const struct btf_type *size_type;
1793 	u32 size_type_id = *type_id;
1794 	u32 size = 0;
1795 
1796 	size_type = btf_type_by_id(btf, size_type_id);
1797 	if (btf_type_nosize_or_null(size_type))
1798 		return NULL;
1799 
1800 	if (btf_type_has_size(size_type)) {
1801 		size = size_type->size;
1802 	} else if (btf_type_is_array(size_type)) {
1803 		size = btf_resolved_type_size(btf, size_type_id);
1804 	} else if (btf_type_is_ptr(size_type)) {
1805 		size = sizeof(void *);
1806 	} else {
1807 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1808 				 !btf_type_is_var(size_type)))
1809 			return NULL;
1810 
1811 		size_type_id = btf_resolved_type_id(btf, size_type_id);
1812 		size_type = btf_type_by_id(btf, size_type_id);
1813 		if (btf_type_nosize_or_null(size_type))
1814 			return NULL;
1815 		else if (btf_type_has_size(size_type))
1816 			size = size_type->size;
1817 		else if (btf_type_is_array(size_type))
1818 			size = btf_resolved_type_size(btf, size_type_id);
1819 		else if (btf_type_is_ptr(size_type))
1820 			size = sizeof(void *);
1821 		else
1822 			return NULL;
1823 	}
1824 
1825 	*type_id = size_type_id;
1826 	if (ret_size)
1827 		*ret_size = size;
1828 
1829 	return size_type;
1830 }
1831 
1832 static int btf_df_check_member(struct btf_verifier_env *env,
1833 			       const struct btf_type *struct_type,
1834 			       const struct btf_member *member,
1835 			       const struct btf_type *member_type)
1836 {
1837 	btf_verifier_log_basic(env, struct_type,
1838 			       "Unsupported check_member");
1839 	return -EINVAL;
1840 }
1841 
1842 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1843 				     const struct btf_type *struct_type,
1844 				     const struct btf_member *member,
1845 				     const struct btf_type *member_type)
1846 {
1847 	btf_verifier_log_basic(env, struct_type,
1848 			       "Unsupported check_kflag_member");
1849 	return -EINVAL;
1850 }
1851 
1852 /* Used for ptr, array and struct/union type members.
1853  * int, enum and modifier types have their specific callback functions.
1854  */
1855 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1856 					  const struct btf_type *struct_type,
1857 					  const struct btf_member *member,
1858 					  const struct btf_type *member_type)
1859 {
1860 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1861 		btf_verifier_log_member(env, struct_type, member,
1862 					"Invalid member bitfield_size");
1863 		return -EINVAL;
1864 	}
1865 
1866 	/* bitfield size is 0, so member->offset represents bit offset only.
1867 	 * It is safe to call non kflag check_member variants.
1868 	 */
1869 	return btf_type_ops(member_type)->check_member(env, struct_type,
1870 						       member,
1871 						       member_type);
1872 }
1873 
1874 static int btf_df_resolve(struct btf_verifier_env *env,
1875 			  const struct resolve_vertex *v)
1876 {
1877 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
1878 	return -EINVAL;
1879 }
1880 
1881 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
1882 			u32 type_id, void *data, u8 bits_offsets,
1883 			struct btf_show *show)
1884 {
1885 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
1886 }
1887 
1888 static int btf_int_check_member(struct btf_verifier_env *env,
1889 				const struct btf_type *struct_type,
1890 				const struct btf_member *member,
1891 				const struct btf_type *member_type)
1892 {
1893 	u32 int_data = btf_type_int(member_type);
1894 	u32 struct_bits_off = member->offset;
1895 	u32 struct_size = struct_type->size;
1896 	u32 nr_copy_bits;
1897 	u32 bytes_offset;
1898 
1899 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
1900 		btf_verifier_log_member(env, struct_type, member,
1901 					"bits_offset exceeds U32_MAX");
1902 		return -EINVAL;
1903 	}
1904 
1905 	struct_bits_off += BTF_INT_OFFSET(int_data);
1906 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1907 	nr_copy_bits = BTF_INT_BITS(int_data) +
1908 		BITS_PER_BYTE_MASKED(struct_bits_off);
1909 
1910 	if (nr_copy_bits > BITS_PER_U128) {
1911 		btf_verifier_log_member(env, struct_type, member,
1912 					"nr_copy_bits exceeds 128");
1913 		return -EINVAL;
1914 	}
1915 
1916 	if (struct_size < bytes_offset ||
1917 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1918 		btf_verifier_log_member(env, struct_type, member,
1919 					"Member exceeds struct_size");
1920 		return -EINVAL;
1921 	}
1922 
1923 	return 0;
1924 }
1925 
1926 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
1927 				      const struct btf_type *struct_type,
1928 				      const struct btf_member *member,
1929 				      const struct btf_type *member_type)
1930 {
1931 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
1932 	u32 int_data = btf_type_int(member_type);
1933 	u32 struct_size = struct_type->size;
1934 	u32 nr_copy_bits;
1935 
1936 	/* a regular int type is required for the kflag int member */
1937 	if (!btf_type_int_is_regular(member_type)) {
1938 		btf_verifier_log_member(env, struct_type, member,
1939 					"Invalid member base type");
1940 		return -EINVAL;
1941 	}
1942 
1943 	/* check sanity of bitfield size */
1944 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
1945 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
1946 	nr_int_data_bits = BTF_INT_BITS(int_data);
1947 	if (!nr_bits) {
1948 		/* Not a bitfield member, member offset must be at byte
1949 		 * boundary.
1950 		 */
1951 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
1952 			btf_verifier_log_member(env, struct_type, member,
1953 						"Invalid member offset");
1954 			return -EINVAL;
1955 		}
1956 
1957 		nr_bits = nr_int_data_bits;
1958 	} else if (nr_bits > nr_int_data_bits) {
1959 		btf_verifier_log_member(env, struct_type, member,
1960 					"Invalid member bitfield_size");
1961 		return -EINVAL;
1962 	}
1963 
1964 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1965 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
1966 	if (nr_copy_bits > BITS_PER_U128) {
1967 		btf_verifier_log_member(env, struct_type, member,
1968 					"nr_copy_bits exceeds 128");
1969 		return -EINVAL;
1970 	}
1971 
1972 	if (struct_size < bytes_offset ||
1973 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1974 		btf_verifier_log_member(env, struct_type, member,
1975 					"Member exceeds struct_size");
1976 		return -EINVAL;
1977 	}
1978 
1979 	return 0;
1980 }
1981 
1982 static s32 btf_int_check_meta(struct btf_verifier_env *env,
1983 			      const struct btf_type *t,
1984 			      u32 meta_left)
1985 {
1986 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
1987 	u16 encoding;
1988 
1989 	if (meta_left < meta_needed) {
1990 		btf_verifier_log_basic(env, t,
1991 				       "meta_left:%u meta_needed:%u",
1992 				       meta_left, meta_needed);
1993 		return -EINVAL;
1994 	}
1995 
1996 	if (btf_type_vlen(t)) {
1997 		btf_verifier_log_type(env, t, "vlen != 0");
1998 		return -EINVAL;
1999 	}
2000 
2001 	if (btf_type_kflag(t)) {
2002 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2003 		return -EINVAL;
2004 	}
2005 
2006 	int_data = btf_type_int(t);
2007 	if (int_data & ~BTF_INT_MASK) {
2008 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2009 				       int_data);
2010 		return -EINVAL;
2011 	}
2012 
2013 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2014 
2015 	if (nr_bits > BITS_PER_U128) {
2016 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2017 				      BITS_PER_U128);
2018 		return -EINVAL;
2019 	}
2020 
2021 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2022 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2023 		return -EINVAL;
2024 	}
2025 
2026 	/*
2027 	 * Only one of the encoding bits is allowed and it
2028 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2029 	 * Multiple bits can be allowed later if it is found
2030 	 * to be insufficient.
2031 	 */
2032 	encoding = BTF_INT_ENCODING(int_data);
2033 	if (encoding &&
2034 	    encoding != BTF_INT_SIGNED &&
2035 	    encoding != BTF_INT_CHAR &&
2036 	    encoding != BTF_INT_BOOL) {
2037 		btf_verifier_log_type(env, t, "Unsupported encoding");
2038 		return -ENOTSUPP;
2039 	}
2040 
2041 	btf_verifier_log_type(env, t, NULL);
2042 
2043 	return meta_needed;
2044 }
2045 
2046 static void btf_int_log(struct btf_verifier_env *env,
2047 			const struct btf_type *t)
2048 {
2049 	int int_data = btf_type_int(t);
2050 
2051 	btf_verifier_log(env,
2052 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2053 			 t->size, BTF_INT_OFFSET(int_data),
2054 			 BTF_INT_BITS(int_data),
2055 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2056 }
2057 
2058 static void btf_int128_print(struct btf_show *show, void *data)
2059 {
2060 	/* data points to a __int128 number.
2061 	 * Suppose
2062 	 *     int128_num = *(__int128 *)data;
2063 	 * The below formulas shows what upper_num and lower_num represents:
2064 	 *     upper_num = int128_num >> 64;
2065 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2066 	 */
2067 	u64 upper_num, lower_num;
2068 
2069 #ifdef __BIG_ENDIAN_BITFIELD
2070 	upper_num = *(u64 *)data;
2071 	lower_num = *(u64 *)(data + 8);
2072 #else
2073 	upper_num = *(u64 *)(data + 8);
2074 	lower_num = *(u64 *)data;
2075 #endif
2076 	if (upper_num == 0)
2077 		btf_show_type_value(show, "0x%llx", lower_num);
2078 	else
2079 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2080 				     lower_num);
2081 }
2082 
2083 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2084 			     u16 right_shift_bits)
2085 {
2086 	u64 upper_num, lower_num;
2087 
2088 #ifdef __BIG_ENDIAN_BITFIELD
2089 	upper_num = print_num[0];
2090 	lower_num = print_num[1];
2091 #else
2092 	upper_num = print_num[1];
2093 	lower_num = print_num[0];
2094 #endif
2095 
2096 	/* shake out un-needed bits by shift/or operations */
2097 	if (left_shift_bits >= 64) {
2098 		upper_num = lower_num << (left_shift_bits - 64);
2099 		lower_num = 0;
2100 	} else {
2101 		upper_num = (upper_num << left_shift_bits) |
2102 			    (lower_num >> (64 - left_shift_bits));
2103 		lower_num = lower_num << left_shift_bits;
2104 	}
2105 
2106 	if (right_shift_bits >= 64) {
2107 		lower_num = upper_num >> (right_shift_bits - 64);
2108 		upper_num = 0;
2109 	} else {
2110 		lower_num = (lower_num >> right_shift_bits) |
2111 			    (upper_num << (64 - right_shift_bits));
2112 		upper_num = upper_num >> right_shift_bits;
2113 	}
2114 
2115 #ifdef __BIG_ENDIAN_BITFIELD
2116 	print_num[0] = upper_num;
2117 	print_num[1] = lower_num;
2118 #else
2119 	print_num[0] = lower_num;
2120 	print_num[1] = upper_num;
2121 #endif
2122 }
2123 
2124 static void btf_bitfield_show(void *data, u8 bits_offset,
2125 			      u8 nr_bits, struct btf_show *show)
2126 {
2127 	u16 left_shift_bits, right_shift_bits;
2128 	u8 nr_copy_bytes;
2129 	u8 nr_copy_bits;
2130 	u64 print_num[2] = {};
2131 
2132 	nr_copy_bits = nr_bits + bits_offset;
2133 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2134 
2135 	memcpy(print_num, data, nr_copy_bytes);
2136 
2137 #ifdef __BIG_ENDIAN_BITFIELD
2138 	left_shift_bits = bits_offset;
2139 #else
2140 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2141 #endif
2142 	right_shift_bits = BITS_PER_U128 - nr_bits;
2143 
2144 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2145 	btf_int128_print(show, print_num);
2146 }
2147 
2148 
2149 static void btf_int_bits_show(const struct btf *btf,
2150 			      const struct btf_type *t,
2151 			      void *data, u8 bits_offset,
2152 			      struct btf_show *show)
2153 {
2154 	u32 int_data = btf_type_int(t);
2155 	u8 nr_bits = BTF_INT_BITS(int_data);
2156 	u8 total_bits_offset;
2157 
2158 	/*
2159 	 * bits_offset is at most 7.
2160 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2161 	 */
2162 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2163 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2164 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2165 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2166 }
2167 
2168 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2169 			 u32 type_id, void *data, u8 bits_offset,
2170 			 struct btf_show *show)
2171 {
2172 	u32 int_data = btf_type_int(t);
2173 	u8 encoding = BTF_INT_ENCODING(int_data);
2174 	bool sign = encoding & BTF_INT_SIGNED;
2175 	u8 nr_bits = BTF_INT_BITS(int_data);
2176 	void *safe_data;
2177 
2178 	safe_data = btf_show_start_type(show, t, type_id, data);
2179 	if (!safe_data)
2180 		return;
2181 
2182 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2183 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2184 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2185 		goto out;
2186 	}
2187 
2188 	switch (nr_bits) {
2189 	case 128:
2190 		btf_int128_print(show, safe_data);
2191 		break;
2192 	case 64:
2193 		if (sign)
2194 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2195 		else
2196 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2197 		break;
2198 	case 32:
2199 		if (sign)
2200 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2201 		else
2202 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2203 		break;
2204 	case 16:
2205 		if (sign)
2206 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2207 		else
2208 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2209 		break;
2210 	case 8:
2211 		if (show->state.array_encoding == BTF_INT_CHAR) {
2212 			/* check for null terminator */
2213 			if (show->state.array_terminated)
2214 				break;
2215 			if (*(char *)data == '\0') {
2216 				show->state.array_terminated = 1;
2217 				break;
2218 			}
2219 			if (isprint(*(char *)data)) {
2220 				btf_show_type_value(show, "'%c'",
2221 						    *(char *)safe_data);
2222 				break;
2223 			}
2224 		}
2225 		if (sign)
2226 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2227 		else
2228 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2229 		break;
2230 	default:
2231 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2232 		break;
2233 	}
2234 out:
2235 	btf_show_end_type(show);
2236 }
2237 
2238 static const struct btf_kind_operations int_ops = {
2239 	.check_meta = btf_int_check_meta,
2240 	.resolve = btf_df_resolve,
2241 	.check_member = btf_int_check_member,
2242 	.check_kflag_member = btf_int_check_kflag_member,
2243 	.log_details = btf_int_log,
2244 	.show = btf_int_show,
2245 };
2246 
2247 static int btf_modifier_check_member(struct btf_verifier_env *env,
2248 				     const struct btf_type *struct_type,
2249 				     const struct btf_member *member,
2250 				     const struct btf_type *member_type)
2251 {
2252 	const struct btf_type *resolved_type;
2253 	u32 resolved_type_id = member->type;
2254 	struct btf_member resolved_member;
2255 	struct btf *btf = env->btf;
2256 
2257 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2258 	if (!resolved_type) {
2259 		btf_verifier_log_member(env, struct_type, member,
2260 					"Invalid member");
2261 		return -EINVAL;
2262 	}
2263 
2264 	resolved_member = *member;
2265 	resolved_member.type = resolved_type_id;
2266 
2267 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2268 							 &resolved_member,
2269 							 resolved_type);
2270 }
2271 
2272 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2273 					   const struct btf_type *struct_type,
2274 					   const struct btf_member *member,
2275 					   const struct btf_type *member_type)
2276 {
2277 	const struct btf_type *resolved_type;
2278 	u32 resolved_type_id = member->type;
2279 	struct btf_member resolved_member;
2280 	struct btf *btf = env->btf;
2281 
2282 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2283 	if (!resolved_type) {
2284 		btf_verifier_log_member(env, struct_type, member,
2285 					"Invalid member");
2286 		return -EINVAL;
2287 	}
2288 
2289 	resolved_member = *member;
2290 	resolved_member.type = resolved_type_id;
2291 
2292 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2293 							       &resolved_member,
2294 							       resolved_type);
2295 }
2296 
2297 static int btf_ptr_check_member(struct btf_verifier_env *env,
2298 				const struct btf_type *struct_type,
2299 				const struct btf_member *member,
2300 				const struct btf_type *member_type)
2301 {
2302 	u32 struct_size, struct_bits_off, bytes_offset;
2303 
2304 	struct_size = struct_type->size;
2305 	struct_bits_off = member->offset;
2306 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2307 
2308 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2309 		btf_verifier_log_member(env, struct_type, member,
2310 					"Member is not byte aligned");
2311 		return -EINVAL;
2312 	}
2313 
2314 	if (struct_size - bytes_offset < sizeof(void *)) {
2315 		btf_verifier_log_member(env, struct_type, member,
2316 					"Member exceeds struct_size");
2317 		return -EINVAL;
2318 	}
2319 
2320 	return 0;
2321 }
2322 
2323 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2324 				   const struct btf_type *t,
2325 				   u32 meta_left)
2326 {
2327 	if (btf_type_vlen(t)) {
2328 		btf_verifier_log_type(env, t, "vlen != 0");
2329 		return -EINVAL;
2330 	}
2331 
2332 	if (btf_type_kflag(t)) {
2333 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2334 		return -EINVAL;
2335 	}
2336 
2337 	if (!BTF_TYPE_ID_VALID(t->type)) {
2338 		btf_verifier_log_type(env, t, "Invalid type_id");
2339 		return -EINVAL;
2340 	}
2341 
2342 	/* typedef type must have a valid name, and other ref types,
2343 	 * volatile, const, restrict, should have a null name.
2344 	 */
2345 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2346 		if (!t->name_off ||
2347 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2348 			btf_verifier_log_type(env, t, "Invalid name");
2349 			return -EINVAL;
2350 		}
2351 	} else {
2352 		if (t->name_off) {
2353 			btf_verifier_log_type(env, t, "Invalid name");
2354 			return -EINVAL;
2355 		}
2356 	}
2357 
2358 	btf_verifier_log_type(env, t, NULL);
2359 
2360 	return 0;
2361 }
2362 
2363 static int btf_modifier_resolve(struct btf_verifier_env *env,
2364 				const struct resolve_vertex *v)
2365 {
2366 	const struct btf_type *t = v->t;
2367 	const struct btf_type *next_type;
2368 	u32 next_type_id = t->type;
2369 	struct btf *btf = env->btf;
2370 
2371 	next_type = btf_type_by_id(btf, next_type_id);
2372 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2373 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2374 		return -EINVAL;
2375 	}
2376 
2377 	if (!env_type_is_resolve_sink(env, next_type) &&
2378 	    !env_type_is_resolved(env, next_type_id))
2379 		return env_stack_push(env, next_type, next_type_id);
2380 
2381 	/* Figure out the resolved next_type_id with size.
2382 	 * They will be stored in the current modifier's
2383 	 * resolved_ids and resolved_sizes such that it can
2384 	 * save us a few type-following when we use it later (e.g. in
2385 	 * pretty print).
2386 	 */
2387 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2388 		if (env_type_is_resolved(env, next_type_id))
2389 			next_type = btf_type_id_resolve(btf, &next_type_id);
2390 
2391 		/* "typedef void new_void", "const void"...etc */
2392 		if (!btf_type_is_void(next_type) &&
2393 		    !btf_type_is_fwd(next_type) &&
2394 		    !btf_type_is_func_proto(next_type)) {
2395 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2396 			return -EINVAL;
2397 		}
2398 	}
2399 
2400 	env_stack_pop_resolved(env, next_type_id, 0);
2401 
2402 	return 0;
2403 }
2404 
2405 static int btf_var_resolve(struct btf_verifier_env *env,
2406 			   const struct resolve_vertex *v)
2407 {
2408 	const struct btf_type *next_type;
2409 	const struct btf_type *t = v->t;
2410 	u32 next_type_id = t->type;
2411 	struct btf *btf = env->btf;
2412 
2413 	next_type = btf_type_by_id(btf, next_type_id);
2414 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2415 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2416 		return -EINVAL;
2417 	}
2418 
2419 	if (!env_type_is_resolve_sink(env, next_type) &&
2420 	    !env_type_is_resolved(env, next_type_id))
2421 		return env_stack_push(env, next_type, next_type_id);
2422 
2423 	if (btf_type_is_modifier(next_type)) {
2424 		const struct btf_type *resolved_type;
2425 		u32 resolved_type_id;
2426 
2427 		resolved_type_id = next_type_id;
2428 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2429 
2430 		if (btf_type_is_ptr(resolved_type) &&
2431 		    !env_type_is_resolve_sink(env, resolved_type) &&
2432 		    !env_type_is_resolved(env, resolved_type_id))
2433 			return env_stack_push(env, resolved_type,
2434 					      resolved_type_id);
2435 	}
2436 
2437 	/* We must resolve to something concrete at this point, no
2438 	 * forward types or similar that would resolve to size of
2439 	 * zero is allowed.
2440 	 */
2441 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2442 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2443 		return -EINVAL;
2444 	}
2445 
2446 	env_stack_pop_resolved(env, next_type_id, 0);
2447 
2448 	return 0;
2449 }
2450 
2451 static int btf_ptr_resolve(struct btf_verifier_env *env,
2452 			   const struct resolve_vertex *v)
2453 {
2454 	const struct btf_type *next_type;
2455 	const struct btf_type *t = v->t;
2456 	u32 next_type_id = t->type;
2457 	struct btf *btf = env->btf;
2458 
2459 	next_type = btf_type_by_id(btf, next_type_id);
2460 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2461 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2462 		return -EINVAL;
2463 	}
2464 
2465 	if (!env_type_is_resolve_sink(env, next_type) &&
2466 	    !env_type_is_resolved(env, next_type_id))
2467 		return env_stack_push(env, next_type, next_type_id);
2468 
2469 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2470 	 * the modifier may have stopped resolving when it was resolved
2471 	 * to a ptr (last-resolved-ptr).
2472 	 *
2473 	 * We now need to continue from the last-resolved-ptr to
2474 	 * ensure the last-resolved-ptr will not referring back to
2475 	 * the currenct ptr (t).
2476 	 */
2477 	if (btf_type_is_modifier(next_type)) {
2478 		const struct btf_type *resolved_type;
2479 		u32 resolved_type_id;
2480 
2481 		resolved_type_id = next_type_id;
2482 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2483 
2484 		if (btf_type_is_ptr(resolved_type) &&
2485 		    !env_type_is_resolve_sink(env, resolved_type) &&
2486 		    !env_type_is_resolved(env, resolved_type_id))
2487 			return env_stack_push(env, resolved_type,
2488 					      resolved_type_id);
2489 	}
2490 
2491 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2492 		if (env_type_is_resolved(env, next_type_id))
2493 			next_type = btf_type_id_resolve(btf, &next_type_id);
2494 
2495 		if (!btf_type_is_void(next_type) &&
2496 		    !btf_type_is_fwd(next_type) &&
2497 		    !btf_type_is_func_proto(next_type)) {
2498 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2499 			return -EINVAL;
2500 		}
2501 	}
2502 
2503 	env_stack_pop_resolved(env, next_type_id, 0);
2504 
2505 	return 0;
2506 }
2507 
2508 static void btf_modifier_show(const struct btf *btf,
2509 			      const struct btf_type *t,
2510 			      u32 type_id, void *data,
2511 			      u8 bits_offset, struct btf_show *show)
2512 {
2513 	if (btf->resolved_ids)
2514 		t = btf_type_id_resolve(btf, &type_id);
2515 	else
2516 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2517 
2518 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2519 }
2520 
2521 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2522 			 u32 type_id, void *data, u8 bits_offset,
2523 			 struct btf_show *show)
2524 {
2525 	t = btf_type_id_resolve(btf, &type_id);
2526 
2527 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2528 }
2529 
2530 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2531 			 u32 type_id, void *data, u8 bits_offset,
2532 			 struct btf_show *show)
2533 {
2534 	void *safe_data;
2535 
2536 	safe_data = btf_show_start_type(show, t, type_id, data);
2537 	if (!safe_data)
2538 		return;
2539 
2540 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2541 	if (show->flags & BTF_SHOW_PTR_RAW)
2542 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2543 	else
2544 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2545 	btf_show_end_type(show);
2546 }
2547 
2548 static void btf_ref_type_log(struct btf_verifier_env *env,
2549 			     const struct btf_type *t)
2550 {
2551 	btf_verifier_log(env, "type_id=%u", t->type);
2552 }
2553 
2554 static struct btf_kind_operations modifier_ops = {
2555 	.check_meta = btf_ref_type_check_meta,
2556 	.resolve = btf_modifier_resolve,
2557 	.check_member = btf_modifier_check_member,
2558 	.check_kflag_member = btf_modifier_check_kflag_member,
2559 	.log_details = btf_ref_type_log,
2560 	.show = btf_modifier_show,
2561 };
2562 
2563 static struct btf_kind_operations ptr_ops = {
2564 	.check_meta = btf_ref_type_check_meta,
2565 	.resolve = btf_ptr_resolve,
2566 	.check_member = btf_ptr_check_member,
2567 	.check_kflag_member = btf_generic_check_kflag_member,
2568 	.log_details = btf_ref_type_log,
2569 	.show = btf_ptr_show,
2570 };
2571 
2572 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2573 			      const struct btf_type *t,
2574 			      u32 meta_left)
2575 {
2576 	if (btf_type_vlen(t)) {
2577 		btf_verifier_log_type(env, t, "vlen != 0");
2578 		return -EINVAL;
2579 	}
2580 
2581 	if (t->type) {
2582 		btf_verifier_log_type(env, t, "type != 0");
2583 		return -EINVAL;
2584 	}
2585 
2586 	/* fwd type must have a valid name */
2587 	if (!t->name_off ||
2588 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2589 		btf_verifier_log_type(env, t, "Invalid name");
2590 		return -EINVAL;
2591 	}
2592 
2593 	btf_verifier_log_type(env, t, NULL);
2594 
2595 	return 0;
2596 }
2597 
2598 static void btf_fwd_type_log(struct btf_verifier_env *env,
2599 			     const struct btf_type *t)
2600 {
2601 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2602 }
2603 
2604 static struct btf_kind_operations fwd_ops = {
2605 	.check_meta = btf_fwd_check_meta,
2606 	.resolve = btf_df_resolve,
2607 	.check_member = btf_df_check_member,
2608 	.check_kflag_member = btf_df_check_kflag_member,
2609 	.log_details = btf_fwd_type_log,
2610 	.show = btf_df_show,
2611 };
2612 
2613 static int btf_array_check_member(struct btf_verifier_env *env,
2614 				  const struct btf_type *struct_type,
2615 				  const struct btf_member *member,
2616 				  const struct btf_type *member_type)
2617 {
2618 	u32 struct_bits_off = member->offset;
2619 	u32 struct_size, bytes_offset;
2620 	u32 array_type_id, array_size;
2621 	struct btf *btf = env->btf;
2622 
2623 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2624 		btf_verifier_log_member(env, struct_type, member,
2625 					"Member is not byte aligned");
2626 		return -EINVAL;
2627 	}
2628 
2629 	array_type_id = member->type;
2630 	btf_type_id_size(btf, &array_type_id, &array_size);
2631 	struct_size = struct_type->size;
2632 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2633 	if (struct_size - bytes_offset < array_size) {
2634 		btf_verifier_log_member(env, struct_type, member,
2635 					"Member exceeds struct_size");
2636 		return -EINVAL;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2643 				const struct btf_type *t,
2644 				u32 meta_left)
2645 {
2646 	const struct btf_array *array = btf_type_array(t);
2647 	u32 meta_needed = sizeof(*array);
2648 
2649 	if (meta_left < meta_needed) {
2650 		btf_verifier_log_basic(env, t,
2651 				       "meta_left:%u meta_needed:%u",
2652 				       meta_left, meta_needed);
2653 		return -EINVAL;
2654 	}
2655 
2656 	/* array type should not have a name */
2657 	if (t->name_off) {
2658 		btf_verifier_log_type(env, t, "Invalid name");
2659 		return -EINVAL;
2660 	}
2661 
2662 	if (btf_type_vlen(t)) {
2663 		btf_verifier_log_type(env, t, "vlen != 0");
2664 		return -EINVAL;
2665 	}
2666 
2667 	if (btf_type_kflag(t)) {
2668 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2669 		return -EINVAL;
2670 	}
2671 
2672 	if (t->size) {
2673 		btf_verifier_log_type(env, t, "size != 0");
2674 		return -EINVAL;
2675 	}
2676 
2677 	/* Array elem type and index type cannot be in type void,
2678 	 * so !array->type and !array->index_type are not allowed.
2679 	 */
2680 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2681 		btf_verifier_log_type(env, t, "Invalid elem");
2682 		return -EINVAL;
2683 	}
2684 
2685 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2686 		btf_verifier_log_type(env, t, "Invalid index");
2687 		return -EINVAL;
2688 	}
2689 
2690 	btf_verifier_log_type(env, t, NULL);
2691 
2692 	return meta_needed;
2693 }
2694 
2695 static int btf_array_resolve(struct btf_verifier_env *env,
2696 			     const struct resolve_vertex *v)
2697 {
2698 	const struct btf_array *array = btf_type_array(v->t);
2699 	const struct btf_type *elem_type, *index_type;
2700 	u32 elem_type_id, index_type_id;
2701 	struct btf *btf = env->btf;
2702 	u32 elem_size;
2703 
2704 	/* Check array->index_type */
2705 	index_type_id = array->index_type;
2706 	index_type = btf_type_by_id(btf, index_type_id);
2707 	if (btf_type_nosize_or_null(index_type) ||
2708 	    btf_type_is_resolve_source_only(index_type)) {
2709 		btf_verifier_log_type(env, v->t, "Invalid index");
2710 		return -EINVAL;
2711 	}
2712 
2713 	if (!env_type_is_resolve_sink(env, index_type) &&
2714 	    !env_type_is_resolved(env, index_type_id))
2715 		return env_stack_push(env, index_type, index_type_id);
2716 
2717 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
2718 	if (!index_type || !btf_type_is_int(index_type) ||
2719 	    !btf_type_int_is_regular(index_type)) {
2720 		btf_verifier_log_type(env, v->t, "Invalid index");
2721 		return -EINVAL;
2722 	}
2723 
2724 	/* Check array->type */
2725 	elem_type_id = array->type;
2726 	elem_type = btf_type_by_id(btf, elem_type_id);
2727 	if (btf_type_nosize_or_null(elem_type) ||
2728 	    btf_type_is_resolve_source_only(elem_type)) {
2729 		btf_verifier_log_type(env, v->t,
2730 				      "Invalid elem");
2731 		return -EINVAL;
2732 	}
2733 
2734 	if (!env_type_is_resolve_sink(env, elem_type) &&
2735 	    !env_type_is_resolved(env, elem_type_id))
2736 		return env_stack_push(env, elem_type, elem_type_id);
2737 
2738 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2739 	if (!elem_type) {
2740 		btf_verifier_log_type(env, v->t, "Invalid elem");
2741 		return -EINVAL;
2742 	}
2743 
2744 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2745 		btf_verifier_log_type(env, v->t, "Invalid array of int");
2746 		return -EINVAL;
2747 	}
2748 
2749 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
2750 		btf_verifier_log_type(env, v->t,
2751 				      "Array size overflows U32_MAX");
2752 		return -EINVAL;
2753 	}
2754 
2755 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2756 
2757 	return 0;
2758 }
2759 
2760 static void btf_array_log(struct btf_verifier_env *env,
2761 			  const struct btf_type *t)
2762 {
2763 	const struct btf_array *array = btf_type_array(t);
2764 
2765 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2766 			 array->type, array->index_type, array->nelems);
2767 }
2768 
2769 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2770 			     u32 type_id, void *data, u8 bits_offset,
2771 			     struct btf_show *show)
2772 {
2773 	const struct btf_array *array = btf_type_array(t);
2774 	const struct btf_kind_operations *elem_ops;
2775 	const struct btf_type *elem_type;
2776 	u32 i, elem_size = 0, elem_type_id;
2777 	u16 encoding = 0;
2778 
2779 	elem_type_id = array->type;
2780 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2781 	if (elem_type && btf_type_has_size(elem_type))
2782 		elem_size = elem_type->size;
2783 
2784 	if (elem_type && btf_type_is_int(elem_type)) {
2785 		u32 int_type = btf_type_int(elem_type);
2786 
2787 		encoding = BTF_INT_ENCODING(int_type);
2788 
2789 		/*
2790 		 * BTF_INT_CHAR encoding never seems to be set for
2791 		 * char arrays, so if size is 1 and element is
2792 		 * printable as a char, we'll do that.
2793 		 */
2794 		if (elem_size == 1)
2795 			encoding = BTF_INT_CHAR;
2796 	}
2797 
2798 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2799 		return;
2800 
2801 	if (!elem_type)
2802 		goto out;
2803 	elem_ops = btf_type_ops(elem_type);
2804 
2805 	for (i = 0; i < array->nelems; i++) {
2806 
2807 		btf_show_start_array_member(show);
2808 
2809 		elem_ops->show(btf, elem_type, elem_type_id, data,
2810 			       bits_offset, show);
2811 		data += elem_size;
2812 
2813 		btf_show_end_array_member(show);
2814 
2815 		if (show->state.array_terminated)
2816 			break;
2817 	}
2818 out:
2819 	btf_show_end_array_type(show);
2820 }
2821 
2822 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2823 			   u32 type_id, void *data, u8 bits_offset,
2824 			   struct btf_show *show)
2825 {
2826 	const struct btf_member *m = show->state.member;
2827 
2828 	/*
2829 	 * First check if any members would be shown (are non-zero).
2830 	 * See comments above "struct btf_show" definition for more
2831 	 * details on how this works at a high-level.
2832 	 */
2833 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2834 		if (!show->state.depth_check) {
2835 			show->state.depth_check = show->state.depth + 1;
2836 			show->state.depth_to_show = 0;
2837 		}
2838 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
2839 		show->state.member = m;
2840 
2841 		if (show->state.depth_check != show->state.depth + 1)
2842 			return;
2843 		show->state.depth_check = 0;
2844 
2845 		if (show->state.depth_to_show <= show->state.depth)
2846 			return;
2847 		/*
2848 		 * Reaching here indicates we have recursed and found
2849 		 * non-zero array member(s).
2850 		 */
2851 	}
2852 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
2853 }
2854 
2855 static struct btf_kind_operations array_ops = {
2856 	.check_meta = btf_array_check_meta,
2857 	.resolve = btf_array_resolve,
2858 	.check_member = btf_array_check_member,
2859 	.check_kflag_member = btf_generic_check_kflag_member,
2860 	.log_details = btf_array_log,
2861 	.show = btf_array_show,
2862 };
2863 
2864 static int btf_struct_check_member(struct btf_verifier_env *env,
2865 				   const struct btf_type *struct_type,
2866 				   const struct btf_member *member,
2867 				   const struct btf_type *member_type)
2868 {
2869 	u32 struct_bits_off = member->offset;
2870 	u32 struct_size, bytes_offset;
2871 
2872 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2873 		btf_verifier_log_member(env, struct_type, member,
2874 					"Member is not byte aligned");
2875 		return -EINVAL;
2876 	}
2877 
2878 	struct_size = struct_type->size;
2879 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2880 	if (struct_size - bytes_offset < member_type->size) {
2881 		btf_verifier_log_member(env, struct_type, member,
2882 					"Member exceeds struct_size");
2883 		return -EINVAL;
2884 	}
2885 
2886 	return 0;
2887 }
2888 
2889 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
2890 				 const struct btf_type *t,
2891 				 u32 meta_left)
2892 {
2893 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
2894 	const struct btf_member *member;
2895 	u32 meta_needed, last_offset;
2896 	struct btf *btf = env->btf;
2897 	u32 struct_size = t->size;
2898 	u32 offset;
2899 	u16 i;
2900 
2901 	meta_needed = btf_type_vlen(t) * sizeof(*member);
2902 	if (meta_left < meta_needed) {
2903 		btf_verifier_log_basic(env, t,
2904 				       "meta_left:%u meta_needed:%u",
2905 				       meta_left, meta_needed);
2906 		return -EINVAL;
2907 	}
2908 
2909 	/* struct type either no name or a valid one */
2910 	if (t->name_off &&
2911 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2912 		btf_verifier_log_type(env, t, "Invalid name");
2913 		return -EINVAL;
2914 	}
2915 
2916 	btf_verifier_log_type(env, t, NULL);
2917 
2918 	last_offset = 0;
2919 	for_each_member(i, t, member) {
2920 		if (!btf_name_offset_valid(btf, member->name_off)) {
2921 			btf_verifier_log_member(env, t, member,
2922 						"Invalid member name_offset:%u",
2923 						member->name_off);
2924 			return -EINVAL;
2925 		}
2926 
2927 		/* struct member either no name or a valid one */
2928 		if (member->name_off &&
2929 		    !btf_name_valid_identifier(btf, member->name_off)) {
2930 			btf_verifier_log_member(env, t, member, "Invalid name");
2931 			return -EINVAL;
2932 		}
2933 		/* A member cannot be in type void */
2934 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
2935 			btf_verifier_log_member(env, t, member,
2936 						"Invalid type_id");
2937 			return -EINVAL;
2938 		}
2939 
2940 		offset = btf_member_bit_offset(t, member);
2941 		if (is_union && offset) {
2942 			btf_verifier_log_member(env, t, member,
2943 						"Invalid member bits_offset");
2944 			return -EINVAL;
2945 		}
2946 
2947 		/*
2948 		 * ">" instead of ">=" because the last member could be
2949 		 * "char a[0];"
2950 		 */
2951 		if (last_offset > offset) {
2952 			btf_verifier_log_member(env, t, member,
2953 						"Invalid member bits_offset");
2954 			return -EINVAL;
2955 		}
2956 
2957 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
2958 			btf_verifier_log_member(env, t, member,
2959 						"Member bits_offset exceeds its struct size");
2960 			return -EINVAL;
2961 		}
2962 
2963 		btf_verifier_log_member(env, t, member, NULL);
2964 		last_offset = offset;
2965 	}
2966 
2967 	return meta_needed;
2968 }
2969 
2970 static int btf_struct_resolve(struct btf_verifier_env *env,
2971 			      const struct resolve_vertex *v)
2972 {
2973 	const struct btf_member *member;
2974 	int err;
2975 	u16 i;
2976 
2977 	/* Before continue resolving the next_member,
2978 	 * ensure the last member is indeed resolved to a
2979 	 * type with size info.
2980 	 */
2981 	if (v->next_member) {
2982 		const struct btf_type *last_member_type;
2983 		const struct btf_member *last_member;
2984 		u16 last_member_type_id;
2985 
2986 		last_member = btf_type_member(v->t) + v->next_member - 1;
2987 		last_member_type_id = last_member->type;
2988 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
2989 						       last_member_type_id)))
2990 			return -EINVAL;
2991 
2992 		last_member_type = btf_type_by_id(env->btf,
2993 						  last_member_type_id);
2994 		if (btf_type_kflag(v->t))
2995 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
2996 								last_member,
2997 								last_member_type);
2998 		else
2999 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3000 								last_member,
3001 								last_member_type);
3002 		if (err)
3003 			return err;
3004 	}
3005 
3006 	for_each_member_from(i, v->next_member, v->t, member) {
3007 		u32 member_type_id = member->type;
3008 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3009 								member_type_id);
3010 
3011 		if (btf_type_nosize_or_null(member_type) ||
3012 		    btf_type_is_resolve_source_only(member_type)) {
3013 			btf_verifier_log_member(env, v->t, member,
3014 						"Invalid member");
3015 			return -EINVAL;
3016 		}
3017 
3018 		if (!env_type_is_resolve_sink(env, member_type) &&
3019 		    !env_type_is_resolved(env, member_type_id)) {
3020 			env_stack_set_next_member(env, i + 1);
3021 			return env_stack_push(env, member_type, member_type_id);
3022 		}
3023 
3024 		if (btf_type_kflag(v->t))
3025 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3026 									    member,
3027 									    member_type);
3028 		else
3029 			err = btf_type_ops(member_type)->check_member(env, v->t,
3030 								      member,
3031 								      member_type);
3032 		if (err)
3033 			return err;
3034 	}
3035 
3036 	env_stack_pop_resolved(env, 0, 0);
3037 
3038 	return 0;
3039 }
3040 
3041 static void btf_struct_log(struct btf_verifier_env *env,
3042 			   const struct btf_type *t)
3043 {
3044 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3045 }
3046 
3047 /* find 'struct bpf_spin_lock' in map value.
3048  * return >= 0 offset if found
3049  * and < 0 in case of error
3050  */
3051 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3052 {
3053 	const struct btf_member *member;
3054 	u32 i, off = -ENOENT;
3055 
3056 	if (!__btf_type_is_struct(t))
3057 		return -EINVAL;
3058 
3059 	for_each_member(i, t, member) {
3060 		const struct btf_type *member_type = btf_type_by_id(btf,
3061 								    member->type);
3062 		if (!__btf_type_is_struct(member_type))
3063 			continue;
3064 		if (member_type->size != sizeof(struct bpf_spin_lock))
3065 			continue;
3066 		if (strcmp(__btf_name_by_offset(btf, member_type->name_off),
3067 			   "bpf_spin_lock"))
3068 			continue;
3069 		if (off != -ENOENT)
3070 			/* only one 'struct bpf_spin_lock' is allowed */
3071 			return -E2BIG;
3072 		off = btf_member_bit_offset(t, member);
3073 		if (off % 8)
3074 			/* valid C code cannot generate such BTF */
3075 			return -EINVAL;
3076 		off /= 8;
3077 		if (off % __alignof__(struct bpf_spin_lock))
3078 			/* valid struct bpf_spin_lock will be 4 byte aligned */
3079 			return -EINVAL;
3080 	}
3081 	return off;
3082 }
3083 
3084 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3085 			      u32 type_id, void *data, u8 bits_offset,
3086 			      struct btf_show *show)
3087 {
3088 	const struct btf_member *member;
3089 	void *safe_data;
3090 	u32 i;
3091 
3092 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
3093 	if (!safe_data)
3094 		return;
3095 
3096 	for_each_member(i, t, member) {
3097 		const struct btf_type *member_type = btf_type_by_id(btf,
3098 								member->type);
3099 		const struct btf_kind_operations *ops;
3100 		u32 member_offset, bitfield_size;
3101 		u32 bytes_offset;
3102 		u8 bits8_offset;
3103 
3104 		btf_show_start_member(show, member);
3105 
3106 		member_offset = btf_member_bit_offset(t, member);
3107 		bitfield_size = btf_member_bitfield_size(t, member);
3108 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3109 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3110 		if (bitfield_size) {
3111 			safe_data = btf_show_start_type(show, member_type,
3112 							member->type,
3113 							data + bytes_offset);
3114 			if (safe_data)
3115 				btf_bitfield_show(safe_data,
3116 						  bits8_offset,
3117 						  bitfield_size, show);
3118 			btf_show_end_type(show);
3119 		} else {
3120 			ops = btf_type_ops(member_type);
3121 			ops->show(btf, member_type, member->type,
3122 				  data + bytes_offset, bits8_offset, show);
3123 		}
3124 
3125 		btf_show_end_member(show);
3126 	}
3127 
3128 	btf_show_end_struct_type(show);
3129 }
3130 
3131 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3132 			    u32 type_id, void *data, u8 bits_offset,
3133 			    struct btf_show *show)
3134 {
3135 	const struct btf_member *m = show->state.member;
3136 
3137 	/*
3138 	 * First check if any members would be shown (are non-zero).
3139 	 * See comments above "struct btf_show" definition for more
3140 	 * details on how this works at a high-level.
3141 	 */
3142 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3143 		if (!show->state.depth_check) {
3144 			show->state.depth_check = show->state.depth + 1;
3145 			show->state.depth_to_show = 0;
3146 		}
3147 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3148 		/* Restore saved member data here */
3149 		show->state.member = m;
3150 		if (show->state.depth_check != show->state.depth + 1)
3151 			return;
3152 		show->state.depth_check = 0;
3153 
3154 		if (show->state.depth_to_show <= show->state.depth)
3155 			return;
3156 		/*
3157 		 * Reaching here indicates we have recursed and found
3158 		 * non-zero child values.
3159 		 */
3160 	}
3161 
3162 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3163 }
3164 
3165 static struct btf_kind_operations struct_ops = {
3166 	.check_meta = btf_struct_check_meta,
3167 	.resolve = btf_struct_resolve,
3168 	.check_member = btf_struct_check_member,
3169 	.check_kflag_member = btf_generic_check_kflag_member,
3170 	.log_details = btf_struct_log,
3171 	.show = btf_struct_show,
3172 };
3173 
3174 static int btf_enum_check_member(struct btf_verifier_env *env,
3175 				 const struct btf_type *struct_type,
3176 				 const struct btf_member *member,
3177 				 const struct btf_type *member_type)
3178 {
3179 	u32 struct_bits_off = member->offset;
3180 	u32 struct_size, bytes_offset;
3181 
3182 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3183 		btf_verifier_log_member(env, struct_type, member,
3184 					"Member is not byte aligned");
3185 		return -EINVAL;
3186 	}
3187 
3188 	struct_size = struct_type->size;
3189 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3190 	if (struct_size - bytes_offset < member_type->size) {
3191 		btf_verifier_log_member(env, struct_type, member,
3192 					"Member exceeds struct_size");
3193 		return -EINVAL;
3194 	}
3195 
3196 	return 0;
3197 }
3198 
3199 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3200 				       const struct btf_type *struct_type,
3201 				       const struct btf_member *member,
3202 				       const struct btf_type *member_type)
3203 {
3204 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3205 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3206 
3207 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3208 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3209 	if (!nr_bits) {
3210 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3211 			btf_verifier_log_member(env, struct_type, member,
3212 						"Member is not byte aligned");
3213 			return -EINVAL;
3214 		}
3215 
3216 		nr_bits = int_bitsize;
3217 	} else if (nr_bits > int_bitsize) {
3218 		btf_verifier_log_member(env, struct_type, member,
3219 					"Invalid member bitfield_size");
3220 		return -EINVAL;
3221 	}
3222 
3223 	struct_size = struct_type->size;
3224 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3225 	if (struct_size < bytes_end) {
3226 		btf_verifier_log_member(env, struct_type, member,
3227 					"Member exceeds struct_size");
3228 		return -EINVAL;
3229 	}
3230 
3231 	return 0;
3232 }
3233 
3234 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3235 			       const struct btf_type *t,
3236 			       u32 meta_left)
3237 {
3238 	const struct btf_enum *enums = btf_type_enum(t);
3239 	struct btf *btf = env->btf;
3240 	u16 i, nr_enums;
3241 	u32 meta_needed;
3242 
3243 	nr_enums = btf_type_vlen(t);
3244 	meta_needed = nr_enums * sizeof(*enums);
3245 
3246 	if (meta_left < meta_needed) {
3247 		btf_verifier_log_basic(env, t,
3248 				       "meta_left:%u meta_needed:%u",
3249 				       meta_left, meta_needed);
3250 		return -EINVAL;
3251 	}
3252 
3253 	if (btf_type_kflag(t)) {
3254 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3255 		return -EINVAL;
3256 	}
3257 
3258 	if (t->size > 8 || !is_power_of_2(t->size)) {
3259 		btf_verifier_log_type(env, t, "Unexpected size");
3260 		return -EINVAL;
3261 	}
3262 
3263 	/* enum type either no name or a valid one */
3264 	if (t->name_off &&
3265 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3266 		btf_verifier_log_type(env, t, "Invalid name");
3267 		return -EINVAL;
3268 	}
3269 
3270 	btf_verifier_log_type(env, t, NULL);
3271 
3272 	for (i = 0; i < nr_enums; i++) {
3273 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3274 			btf_verifier_log(env, "\tInvalid name_offset:%u",
3275 					 enums[i].name_off);
3276 			return -EINVAL;
3277 		}
3278 
3279 		/* enum member must have a valid name */
3280 		if (!enums[i].name_off ||
3281 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
3282 			btf_verifier_log_type(env, t, "Invalid name");
3283 			return -EINVAL;
3284 		}
3285 
3286 		if (env->log.level == BPF_LOG_KERNEL)
3287 			continue;
3288 		btf_verifier_log(env, "\t%s val=%d\n",
3289 				 __btf_name_by_offset(btf, enums[i].name_off),
3290 				 enums[i].val);
3291 	}
3292 
3293 	return meta_needed;
3294 }
3295 
3296 static void btf_enum_log(struct btf_verifier_env *env,
3297 			 const struct btf_type *t)
3298 {
3299 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3300 }
3301 
3302 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3303 			  u32 type_id, void *data, u8 bits_offset,
3304 			  struct btf_show *show)
3305 {
3306 	const struct btf_enum *enums = btf_type_enum(t);
3307 	u32 i, nr_enums = btf_type_vlen(t);
3308 	void *safe_data;
3309 	int v;
3310 
3311 	safe_data = btf_show_start_type(show, t, type_id, data);
3312 	if (!safe_data)
3313 		return;
3314 
3315 	v = *(int *)safe_data;
3316 
3317 	for (i = 0; i < nr_enums; i++) {
3318 		if (v != enums[i].val)
3319 			continue;
3320 
3321 		btf_show_type_value(show, "%s",
3322 				    __btf_name_by_offset(btf,
3323 							 enums[i].name_off));
3324 
3325 		btf_show_end_type(show);
3326 		return;
3327 	}
3328 
3329 	btf_show_type_value(show, "%d", v);
3330 	btf_show_end_type(show);
3331 }
3332 
3333 static struct btf_kind_operations enum_ops = {
3334 	.check_meta = btf_enum_check_meta,
3335 	.resolve = btf_df_resolve,
3336 	.check_member = btf_enum_check_member,
3337 	.check_kflag_member = btf_enum_check_kflag_member,
3338 	.log_details = btf_enum_log,
3339 	.show = btf_enum_show,
3340 };
3341 
3342 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3343 				     const struct btf_type *t,
3344 				     u32 meta_left)
3345 {
3346 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3347 
3348 	if (meta_left < meta_needed) {
3349 		btf_verifier_log_basic(env, t,
3350 				       "meta_left:%u meta_needed:%u",
3351 				       meta_left, meta_needed);
3352 		return -EINVAL;
3353 	}
3354 
3355 	if (t->name_off) {
3356 		btf_verifier_log_type(env, t, "Invalid name");
3357 		return -EINVAL;
3358 	}
3359 
3360 	if (btf_type_kflag(t)) {
3361 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3362 		return -EINVAL;
3363 	}
3364 
3365 	btf_verifier_log_type(env, t, NULL);
3366 
3367 	return meta_needed;
3368 }
3369 
3370 static void btf_func_proto_log(struct btf_verifier_env *env,
3371 			       const struct btf_type *t)
3372 {
3373 	const struct btf_param *args = (const struct btf_param *)(t + 1);
3374 	u16 nr_args = btf_type_vlen(t), i;
3375 
3376 	btf_verifier_log(env, "return=%u args=(", t->type);
3377 	if (!nr_args) {
3378 		btf_verifier_log(env, "void");
3379 		goto done;
3380 	}
3381 
3382 	if (nr_args == 1 && !args[0].type) {
3383 		/* Only one vararg */
3384 		btf_verifier_log(env, "vararg");
3385 		goto done;
3386 	}
3387 
3388 	btf_verifier_log(env, "%u %s", args[0].type,
3389 			 __btf_name_by_offset(env->btf,
3390 					      args[0].name_off));
3391 	for (i = 1; i < nr_args - 1; i++)
3392 		btf_verifier_log(env, ", %u %s", args[i].type,
3393 				 __btf_name_by_offset(env->btf,
3394 						      args[i].name_off));
3395 
3396 	if (nr_args > 1) {
3397 		const struct btf_param *last_arg = &args[nr_args - 1];
3398 
3399 		if (last_arg->type)
3400 			btf_verifier_log(env, ", %u %s", last_arg->type,
3401 					 __btf_name_by_offset(env->btf,
3402 							      last_arg->name_off));
3403 		else
3404 			btf_verifier_log(env, ", vararg");
3405 	}
3406 
3407 done:
3408 	btf_verifier_log(env, ")");
3409 }
3410 
3411 static struct btf_kind_operations func_proto_ops = {
3412 	.check_meta = btf_func_proto_check_meta,
3413 	.resolve = btf_df_resolve,
3414 	/*
3415 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
3416 	 * a struct's member.
3417 	 *
3418 	 * It should be a funciton pointer instead.
3419 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3420 	 *
3421 	 * Hence, there is no btf_func_check_member().
3422 	 */
3423 	.check_member = btf_df_check_member,
3424 	.check_kflag_member = btf_df_check_kflag_member,
3425 	.log_details = btf_func_proto_log,
3426 	.show = btf_df_show,
3427 };
3428 
3429 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3430 			       const struct btf_type *t,
3431 			       u32 meta_left)
3432 {
3433 	if (!t->name_off ||
3434 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3435 		btf_verifier_log_type(env, t, "Invalid name");
3436 		return -EINVAL;
3437 	}
3438 
3439 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3440 		btf_verifier_log_type(env, t, "Invalid func linkage");
3441 		return -EINVAL;
3442 	}
3443 
3444 	if (btf_type_kflag(t)) {
3445 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3446 		return -EINVAL;
3447 	}
3448 
3449 	btf_verifier_log_type(env, t, NULL);
3450 
3451 	return 0;
3452 }
3453 
3454 static struct btf_kind_operations func_ops = {
3455 	.check_meta = btf_func_check_meta,
3456 	.resolve = btf_df_resolve,
3457 	.check_member = btf_df_check_member,
3458 	.check_kflag_member = btf_df_check_kflag_member,
3459 	.log_details = btf_ref_type_log,
3460 	.show = btf_df_show,
3461 };
3462 
3463 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3464 			      const struct btf_type *t,
3465 			      u32 meta_left)
3466 {
3467 	const struct btf_var *var;
3468 	u32 meta_needed = sizeof(*var);
3469 
3470 	if (meta_left < meta_needed) {
3471 		btf_verifier_log_basic(env, t,
3472 				       "meta_left:%u meta_needed:%u",
3473 				       meta_left, meta_needed);
3474 		return -EINVAL;
3475 	}
3476 
3477 	if (btf_type_vlen(t)) {
3478 		btf_verifier_log_type(env, t, "vlen != 0");
3479 		return -EINVAL;
3480 	}
3481 
3482 	if (btf_type_kflag(t)) {
3483 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3484 		return -EINVAL;
3485 	}
3486 
3487 	if (!t->name_off ||
3488 	    !__btf_name_valid(env->btf, t->name_off, true)) {
3489 		btf_verifier_log_type(env, t, "Invalid name");
3490 		return -EINVAL;
3491 	}
3492 
3493 	/* A var cannot be in type void */
3494 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3495 		btf_verifier_log_type(env, t, "Invalid type_id");
3496 		return -EINVAL;
3497 	}
3498 
3499 	var = btf_type_var(t);
3500 	if (var->linkage != BTF_VAR_STATIC &&
3501 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3502 		btf_verifier_log_type(env, t, "Linkage not supported");
3503 		return -EINVAL;
3504 	}
3505 
3506 	btf_verifier_log_type(env, t, NULL);
3507 
3508 	return meta_needed;
3509 }
3510 
3511 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3512 {
3513 	const struct btf_var *var = btf_type_var(t);
3514 
3515 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3516 }
3517 
3518 static const struct btf_kind_operations var_ops = {
3519 	.check_meta		= btf_var_check_meta,
3520 	.resolve		= btf_var_resolve,
3521 	.check_member		= btf_df_check_member,
3522 	.check_kflag_member	= btf_df_check_kflag_member,
3523 	.log_details		= btf_var_log,
3524 	.show			= btf_var_show,
3525 };
3526 
3527 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3528 				  const struct btf_type *t,
3529 				  u32 meta_left)
3530 {
3531 	const struct btf_var_secinfo *vsi;
3532 	u64 last_vsi_end_off = 0, sum = 0;
3533 	u32 i, meta_needed;
3534 
3535 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3536 	if (meta_left < meta_needed) {
3537 		btf_verifier_log_basic(env, t,
3538 				       "meta_left:%u meta_needed:%u",
3539 				       meta_left, meta_needed);
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->base_btf && 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 		return NULL;
4325 	}
4326 	tname = btf_name_by_offset(btf, t->name_off);
4327 	if (!tname) {
4328 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
4329 		return NULL;
4330 	}
4331 	/* prog_type is valid bpf program type. No need for bounds check. */
4332 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
4333 	/* ctx_struct is a pointer to prog_ctx_type in vmlinux.
4334 	 * Like 'struct __sk_buff'
4335 	 */
4336 	ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
4337 	if (!ctx_struct)
4338 		/* should not happen */
4339 		return NULL;
4340 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
4341 	if (!ctx_tname) {
4342 		/* should not happen */
4343 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
4344 		return NULL;
4345 	}
4346 	/* only compare that prog's ctx type name is the same as
4347 	 * kernel expects. No need to compare field by field.
4348 	 * It's ok for bpf prog to do:
4349 	 * struct __sk_buff {};
4350 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
4351 	 * { // no fields of skb are ever used }
4352 	 */
4353 	if (strcmp(ctx_tname, tname))
4354 		return NULL;
4355 	return ctx_type;
4356 }
4357 
4358 static const struct bpf_map_ops * const btf_vmlinux_map_ops[] = {
4359 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
4360 #define BPF_LINK_TYPE(_id, _name)
4361 #define BPF_MAP_TYPE(_id, _ops) \
4362 	[_id] = &_ops,
4363 #include <linux/bpf_types.h>
4364 #undef BPF_PROG_TYPE
4365 #undef BPF_LINK_TYPE
4366 #undef BPF_MAP_TYPE
4367 };
4368 
4369 static int btf_vmlinux_map_ids_init(const struct btf *btf,
4370 				    struct bpf_verifier_log *log)
4371 {
4372 	const struct bpf_map_ops *ops;
4373 	int i, btf_id;
4374 
4375 	for (i = 0; i < ARRAY_SIZE(btf_vmlinux_map_ops); ++i) {
4376 		ops = btf_vmlinux_map_ops[i];
4377 		if (!ops || (!ops->map_btf_name && !ops->map_btf_id))
4378 			continue;
4379 		if (!ops->map_btf_name || !ops->map_btf_id) {
4380 			bpf_log(log, "map type %d is misconfigured\n", i);
4381 			return -EINVAL;
4382 		}
4383 		btf_id = btf_find_by_name_kind(btf, ops->map_btf_name,
4384 					       BTF_KIND_STRUCT);
4385 		if (btf_id < 0)
4386 			return btf_id;
4387 		*ops->map_btf_id = btf_id;
4388 	}
4389 
4390 	return 0;
4391 }
4392 
4393 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
4394 				     struct btf *btf,
4395 				     const struct btf_type *t,
4396 				     enum bpf_prog_type prog_type,
4397 				     int arg)
4398 {
4399 	const struct btf_member *prog_ctx_type, *kern_ctx_type;
4400 
4401 	prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
4402 	if (!prog_ctx_type)
4403 		return -ENOENT;
4404 	kern_ctx_type = prog_ctx_type + 1;
4405 	return kern_ctx_type->type;
4406 }
4407 
4408 BTF_ID_LIST(bpf_ctx_convert_btf_id)
4409 BTF_ID(struct, bpf_ctx_convert)
4410 
4411 struct btf *btf_parse_vmlinux(void)
4412 {
4413 	struct btf_verifier_env *env = NULL;
4414 	struct bpf_verifier_log *log;
4415 	struct btf *btf = NULL;
4416 	int err;
4417 
4418 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4419 	if (!env)
4420 		return ERR_PTR(-ENOMEM);
4421 
4422 	log = &env->log;
4423 	log->level = BPF_LOG_KERNEL;
4424 
4425 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4426 	if (!btf) {
4427 		err = -ENOMEM;
4428 		goto errout;
4429 	}
4430 	env->btf = btf;
4431 
4432 	btf->data = __start_BTF;
4433 	btf->data_size = __stop_BTF - __start_BTF;
4434 	btf->kernel_btf = true;
4435 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
4436 
4437 	err = btf_parse_hdr(env);
4438 	if (err)
4439 		goto errout;
4440 
4441 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4442 
4443 	err = btf_parse_str_sec(env);
4444 	if (err)
4445 		goto errout;
4446 
4447 	err = btf_check_all_metas(env);
4448 	if (err)
4449 		goto errout;
4450 
4451 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
4452 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
4453 
4454 	/* find bpf map structs for map_ptr access checking */
4455 	err = btf_vmlinux_map_ids_init(btf, log);
4456 	if (err < 0)
4457 		goto errout;
4458 
4459 	bpf_struct_ops_init(btf, log);
4460 
4461 	refcount_set(&btf->refcnt, 1);
4462 
4463 	err = btf_alloc_id(btf);
4464 	if (err)
4465 		goto errout;
4466 
4467 	btf_verifier_env_free(env);
4468 	return btf;
4469 
4470 errout:
4471 	btf_verifier_env_free(env);
4472 	if (btf) {
4473 		kvfree(btf->types);
4474 		kfree(btf);
4475 	}
4476 	return ERR_PTR(err);
4477 }
4478 
4479 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
4480 
4481 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
4482 {
4483 	struct btf_verifier_env *env = NULL;
4484 	struct bpf_verifier_log *log;
4485 	struct btf *btf = NULL, *base_btf;
4486 	int err;
4487 
4488 	base_btf = bpf_get_btf_vmlinux();
4489 	if (IS_ERR(base_btf))
4490 		return base_btf;
4491 	if (!base_btf)
4492 		return ERR_PTR(-EINVAL);
4493 
4494 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4495 	if (!env)
4496 		return ERR_PTR(-ENOMEM);
4497 
4498 	log = &env->log;
4499 	log->level = BPF_LOG_KERNEL;
4500 
4501 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4502 	if (!btf) {
4503 		err = -ENOMEM;
4504 		goto errout;
4505 	}
4506 	env->btf = btf;
4507 
4508 	btf->base_btf = base_btf;
4509 	btf->start_id = base_btf->nr_types;
4510 	btf->start_str_off = base_btf->hdr.str_len;
4511 	btf->kernel_btf = true;
4512 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
4513 
4514 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
4515 	if (!btf->data) {
4516 		err = -ENOMEM;
4517 		goto errout;
4518 	}
4519 	memcpy(btf->data, data, data_size);
4520 	btf->data_size = data_size;
4521 
4522 	err = btf_parse_hdr(env);
4523 	if (err)
4524 		goto errout;
4525 
4526 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4527 
4528 	err = btf_parse_str_sec(env);
4529 	if (err)
4530 		goto errout;
4531 
4532 	err = btf_check_all_metas(env);
4533 	if (err)
4534 		goto errout;
4535 
4536 	btf_verifier_env_free(env);
4537 	refcount_set(&btf->refcnt, 1);
4538 	return btf;
4539 
4540 errout:
4541 	btf_verifier_env_free(env);
4542 	if (btf) {
4543 		kvfree(btf->data);
4544 		kvfree(btf->types);
4545 		kfree(btf);
4546 	}
4547 	return ERR_PTR(err);
4548 }
4549 
4550 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
4551 
4552 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
4553 {
4554 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4555 
4556 	if (tgt_prog)
4557 		return tgt_prog->aux->btf;
4558 	else
4559 		return prog->aux->attach_btf;
4560 }
4561 
4562 static bool is_string_ptr(struct btf *btf, const struct btf_type *t)
4563 {
4564 	/* t comes in already as a pointer */
4565 	t = btf_type_by_id(btf, t->type);
4566 
4567 	/* allow const */
4568 	if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
4569 		t = btf_type_by_id(btf, t->type);
4570 
4571 	/* char, signed char, unsigned char */
4572 	return btf_type_is_int(t) && t->size == 1;
4573 }
4574 
4575 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
4576 		    const struct bpf_prog *prog,
4577 		    struct bpf_insn_access_aux *info)
4578 {
4579 	const struct btf_type *t = prog->aux->attach_func_proto;
4580 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4581 	struct btf *btf = bpf_prog_get_target_btf(prog);
4582 	const char *tname = prog->aux->attach_func_name;
4583 	struct bpf_verifier_log *log = info->log;
4584 	const struct btf_param *args;
4585 	u32 nr_args, arg;
4586 	int i, ret;
4587 
4588 	if (off % 8) {
4589 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
4590 			tname, off);
4591 		return false;
4592 	}
4593 	arg = off / 8;
4594 	args = (const struct btf_param *)(t + 1);
4595 	/* if (t == NULL) Fall back to default BPF prog with 5 u64 arguments */
4596 	nr_args = t ? btf_type_vlen(t) : 5;
4597 	if (prog->aux->attach_btf_trace) {
4598 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
4599 		args++;
4600 		nr_args--;
4601 	}
4602 
4603 	if (arg > nr_args) {
4604 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4605 			tname, arg + 1);
4606 		return false;
4607 	}
4608 
4609 	if (arg == nr_args) {
4610 		switch (prog->expected_attach_type) {
4611 		case BPF_LSM_MAC:
4612 		case BPF_TRACE_FEXIT:
4613 			/* When LSM programs are attached to void LSM hooks
4614 			 * they use FEXIT trampolines and when attached to
4615 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
4616 			 *
4617 			 * While the LSM programs are BPF_MODIFY_RETURN-like
4618 			 * the check:
4619 			 *
4620 			 *	if (ret_type != 'int')
4621 			 *		return -EINVAL;
4622 			 *
4623 			 * is _not_ done here. This is still safe as LSM hooks
4624 			 * have only void and int return types.
4625 			 */
4626 			if (!t)
4627 				return true;
4628 			t = btf_type_by_id(btf, t->type);
4629 			break;
4630 		case BPF_MODIFY_RETURN:
4631 			/* For now the BPF_MODIFY_RETURN can only be attached to
4632 			 * functions that return an int.
4633 			 */
4634 			if (!t)
4635 				return false;
4636 
4637 			t = btf_type_skip_modifiers(btf, t->type, NULL);
4638 			if (!btf_type_is_small_int(t)) {
4639 				bpf_log(log,
4640 					"ret type %s not allowed for fmod_ret\n",
4641 					btf_kind_str[BTF_INFO_KIND(t->info)]);
4642 				return false;
4643 			}
4644 			break;
4645 		default:
4646 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4647 				tname, arg + 1);
4648 			return false;
4649 		}
4650 	} else {
4651 		if (!t)
4652 			/* Default prog with 5 args */
4653 			return true;
4654 		t = btf_type_by_id(btf, args[arg].type);
4655 	}
4656 
4657 	/* skip modifiers */
4658 	while (btf_type_is_modifier(t))
4659 		t = btf_type_by_id(btf, t->type);
4660 	if (btf_type_is_small_int(t) || btf_type_is_enum(t))
4661 		/* accessing a scalar */
4662 		return true;
4663 	if (!btf_type_is_ptr(t)) {
4664 		bpf_log(log,
4665 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
4666 			tname, arg,
4667 			__btf_name_by_offset(btf, t->name_off),
4668 			btf_kind_str[BTF_INFO_KIND(t->info)]);
4669 		return false;
4670 	}
4671 
4672 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
4673 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4674 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4675 
4676 		if (ctx_arg_info->offset == off &&
4677 		    (ctx_arg_info->reg_type == PTR_TO_RDONLY_BUF_OR_NULL ||
4678 		     ctx_arg_info->reg_type == PTR_TO_RDWR_BUF_OR_NULL)) {
4679 			info->reg_type = ctx_arg_info->reg_type;
4680 			return true;
4681 		}
4682 	}
4683 
4684 	if (t->type == 0)
4685 		/* This is a pointer to void.
4686 		 * It is the same as scalar from the verifier safety pov.
4687 		 * No further pointer walking is allowed.
4688 		 */
4689 		return true;
4690 
4691 	if (is_string_ptr(btf, t))
4692 		return true;
4693 
4694 	/* this is a pointer to another type */
4695 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4696 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4697 
4698 		if (ctx_arg_info->offset == off) {
4699 			info->reg_type = ctx_arg_info->reg_type;
4700 			info->btf = btf_vmlinux;
4701 			info->btf_id = ctx_arg_info->btf_id;
4702 			return true;
4703 		}
4704 	}
4705 
4706 	info->reg_type = PTR_TO_BTF_ID;
4707 	if (tgt_prog) {
4708 		enum bpf_prog_type tgt_type;
4709 
4710 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
4711 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
4712 		else
4713 			tgt_type = tgt_prog->type;
4714 
4715 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
4716 		if (ret > 0) {
4717 			info->btf = btf_vmlinux;
4718 			info->btf_id = ret;
4719 			return true;
4720 		} else {
4721 			return false;
4722 		}
4723 	}
4724 
4725 	info->btf = btf;
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, const struct btf *btf,
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, 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, 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, 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, member->type);
4855 		mname = __btf_name_by_offset(btf, member->name_off);
4856 
4857 		mtype = __btf_resolve_size(btf, 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, 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, const struct btf *btf,
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, btf, 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, 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 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5020  * the same. Trivial ID check is not enough due to module BTFs, because we can
5021  * end up with two different module BTFs, but IDs point to the common type in
5022  * vmlinux BTF.
5023  */
5024 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5025 			       const struct btf *btf2, u32 id2)
5026 {
5027 	if (id1 != id2)
5028 		return false;
5029 	if (btf1 == btf2)
5030 		return true;
5031 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5032 }
5033 
5034 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5035 			  const struct btf *btf, u32 id, int off,
5036 			  const struct btf *need_btf, u32 need_type_id)
5037 {
5038 	const struct btf_type *type;
5039 	int err;
5040 
5041 	/* Are we already done? */
5042 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5043 		return true;
5044 
5045 again:
5046 	type = btf_type_by_id(btf, id);
5047 	if (!type)
5048 		return false;
5049 	err = btf_struct_walk(log, btf, type, off, 1, &id);
5050 	if (err != WALK_STRUCT)
5051 		return false;
5052 
5053 	/* We found nested struct object. If it matches
5054 	 * the requested ID, we're done. Otherwise let's
5055 	 * continue the search with offset 0 in the new
5056 	 * type.
5057 	 */
5058 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5059 		off = 0;
5060 		goto again;
5061 	}
5062 
5063 	return true;
5064 }
5065 
5066 static int __get_type_size(struct btf *btf, u32 btf_id,
5067 			   const struct btf_type **bad_type)
5068 {
5069 	const struct btf_type *t;
5070 
5071 	if (!btf_id)
5072 		/* void */
5073 		return 0;
5074 	t = btf_type_by_id(btf, btf_id);
5075 	while (t && btf_type_is_modifier(t))
5076 		t = btf_type_by_id(btf, t->type);
5077 	if (!t) {
5078 		*bad_type = btf_type_by_id(btf, 0);
5079 		return -EINVAL;
5080 	}
5081 	if (btf_type_is_ptr(t))
5082 		/* kernel size of pointer. Not BPF's size of pointer*/
5083 		return sizeof(void *);
5084 	if (btf_type_is_int(t) || btf_type_is_enum(t))
5085 		return t->size;
5086 	*bad_type = t;
5087 	return -EINVAL;
5088 }
5089 
5090 int btf_distill_func_proto(struct bpf_verifier_log *log,
5091 			   struct btf *btf,
5092 			   const struct btf_type *func,
5093 			   const char *tname,
5094 			   struct btf_func_model *m)
5095 {
5096 	const struct btf_param *args;
5097 	const struct btf_type *t;
5098 	u32 i, nargs;
5099 	int ret;
5100 
5101 	if (!func) {
5102 		/* BTF function prototype doesn't match the verifier types.
5103 		 * Fall back to 5 u64 args.
5104 		 */
5105 		for (i = 0; i < 5; i++)
5106 			m->arg_size[i] = 8;
5107 		m->ret_size = 8;
5108 		m->nr_args = 5;
5109 		return 0;
5110 	}
5111 	args = (const struct btf_param *)(func + 1);
5112 	nargs = btf_type_vlen(func);
5113 	if (nargs >= MAX_BPF_FUNC_ARGS) {
5114 		bpf_log(log,
5115 			"The function %s has %d arguments. Too many.\n",
5116 			tname, nargs);
5117 		return -EINVAL;
5118 	}
5119 	ret = __get_type_size(btf, func->type, &t);
5120 	if (ret < 0) {
5121 		bpf_log(log,
5122 			"The function %s return type %s is unsupported.\n",
5123 			tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5124 		return -EINVAL;
5125 	}
5126 	m->ret_size = ret;
5127 
5128 	for (i = 0; i < nargs; i++) {
5129 		ret = __get_type_size(btf, args[i].type, &t);
5130 		if (ret < 0) {
5131 			bpf_log(log,
5132 				"The function %s arg%d type %s is unsupported.\n",
5133 				tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5134 			return -EINVAL;
5135 		}
5136 		m->arg_size[i] = ret;
5137 	}
5138 	m->nr_args = nargs;
5139 	return 0;
5140 }
5141 
5142 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5143  * t1 points to BTF_KIND_FUNC in btf1
5144  * t2 points to BTF_KIND_FUNC in btf2
5145  * Returns:
5146  * EINVAL - function prototype mismatch
5147  * EFAULT - verifier bug
5148  * 0 - 99% match. The last 1% is validated by the verifier.
5149  */
5150 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5151 				     struct btf *btf1, const struct btf_type *t1,
5152 				     struct btf *btf2, const struct btf_type *t2)
5153 {
5154 	const struct btf_param *args1, *args2;
5155 	const char *fn1, *fn2, *s1, *s2;
5156 	u32 nargs1, nargs2, i;
5157 
5158 	fn1 = btf_name_by_offset(btf1, t1->name_off);
5159 	fn2 = btf_name_by_offset(btf2, t2->name_off);
5160 
5161 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5162 		bpf_log(log, "%s() is not a global function\n", fn1);
5163 		return -EINVAL;
5164 	}
5165 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5166 		bpf_log(log, "%s() is not a global function\n", fn2);
5167 		return -EINVAL;
5168 	}
5169 
5170 	t1 = btf_type_by_id(btf1, t1->type);
5171 	if (!t1 || !btf_type_is_func_proto(t1))
5172 		return -EFAULT;
5173 	t2 = btf_type_by_id(btf2, t2->type);
5174 	if (!t2 || !btf_type_is_func_proto(t2))
5175 		return -EFAULT;
5176 
5177 	args1 = (const struct btf_param *)(t1 + 1);
5178 	nargs1 = btf_type_vlen(t1);
5179 	args2 = (const struct btf_param *)(t2 + 1);
5180 	nargs2 = btf_type_vlen(t2);
5181 
5182 	if (nargs1 != nargs2) {
5183 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
5184 			fn1, nargs1, fn2, nargs2);
5185 		return -EINVAL;
5186 	}
5187 
5188 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5189 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5190 	if (t1->info != t2->info) {
5191 		bpf_log(log,
5192 			"Return type %s of %s() doesn't match type %s of %s()\n",
5193 			btf_type_str(t1), fn1,
5194 			btf_type_str(t2), fn2);
5195 		return -EINVAL;
5196 	}
5197 
5198 	for (i = 0; i < nargs1; i++) {
5199 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5200 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5201 
5202 		if (t1->info != t2->info) {
5203 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5204 				i, fn1, btf_type_str(t1),
5205 				fn2, btf_type_str(t2));
5206 			return -EINVAL;
5207 		}
5208 		if (btf_type_has_size(t1) && t1->size != t2->size) {
5209 			bpf_log(log,
5210 				"arg%d in %s() has size %d while %s() has %d\n",
5211 				i, fn1, t1->size,
5212 				fn2, t2->size);
5213 			return -EINVAL;
5214 		}
5215 
5216 		/* global functions are validated with scalars and pointers
5217 		 * to context only. And only global functions can be replaced.
5218 		 * Hence type check only those types.
5219 		 */
5220 		if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5221 			continue;
5222 		if (!btf_type_is_ptr(t1)) {
5223 			bpf_log(log,
5224 				"arg%d in %s() has unrecognized type\n",
5225 				i, fn1);
5226 			return -EINVAL;
5227 		}
5228 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5229 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5230 		if (!btf_type_is_struct(t1)) {
5231 			bpf_log(log,
5232 				"arg%d in %s() is not a pointer to context\n",
5233 				i, fn1);
5234 			return -EINVAL;
5235 		}
5236 		if (!btf_type_is_struct(t2)) {
5237 			bpf_log(log,
5238 				"arg%d in %s() is not a pointer to context\n",
5239 				i, fn2);
5240 			return -EINVAL;
5241 		}
5242 		/* This is an optional check to make program writing easier.
5243 		 * Compare names of structs and report an error to the user.
5244 		 * btf_prepare_func_args() already checked that t2 struct
5245 		 * is a context type. btf_prepare_func_args() will check
5246 		 * later that t1 struct is a context type as well.
5247 		 */
5248 		s1 = btf_name_by_offset(btf1, t1->name_off);
5249 		s2 = btf_name_by_offset(btf2, t2->name_off);
5250 		if (strcmp(s1, s2)) {
5251 			bpf_log(log,
5252 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5253 				i, fn1, s1, fn2, s2);
5254 			return -EINVAL;
5255 		}
5256 	}
5257 	return 0;
5258 }
5259 
5260 /* Compare BTFs of given program with BTF of target program */
5261 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5262 			 struct btf *btf2, const struct btf_type *t2)
5263 {
5264 	struct btf *btf1 = prog->aux->btf;
5265 	const struct btf_type *t1;
5266 	u32 btf_id = 0;
5267 
5268 	if (!prog->aux->func_info) {
5269 		bpf_log(log, "Program extension requires BTF\n");
5270 		return -EINVAL;
5271 	}
5272 
5273 	btf_id = prog->aux->func_info[0].type_id;
5274 	if (!btf_id)
5275 		return -EFAULT;
5276 
5277 	t1 = btf_type_by_id(btf1, btf_id);
5278 	if (!t1 || !btf_type_is_func(t1))
5279 		return -EFAULT;
5280 
5281 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5282 }
5283 
5284 /* Compare BTF of a function with given bpf_reg_state.
5285  * Returns:
5286  * EFAULT - there is a verifier bug. Abort verification.
5287  * EINVAL - there is a type mismatch or BTF is not available.
5288  * 0 - BTF matches with what bpf_reg_state expects.
5289  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
5290  */
5291 int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
5292 			     struct bpf_reg_state *regs)
5293 {
5294 	struct bpf_verifier_log *log = &env->log;
5295 	struct bpf_prog *prog = env->prog;
5296 	struct btf *btf = prog->aux->btf;
5297 	const struct btf_param *args;
5298 	const struct btf_type *t, *ref_t;
5299 	u32 i, nargs, btf_id, type_size;
5300 	const char *tname;
5301 	bool is_global;
5302 
5303 	if (!prog->aux->func_info)
5304 		return -EINVAL;
5305 
5306 	btf_id = prog->aux->func_info[subprog].type_id;
5307 	if (!btf_id)
5308 		return -EFAULT;
5309 
5310 	if (prog->aux->func_info_aux[subprog].unreliable)
5311 		return -EINVAL;
5312 
5313 	t = btf_type_by_id(btf, btf_id);
5314 	if (!t || !btf_type_is_func(t)) {
5315 		/* These checks were already done by the verifier while loading
5316 		 * struct bpf_func_info
5317 		 */
5318 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5319 			subprog);
5320 		return -EFAULT;
5321 	}
5322 	tname = btf_name_by_offset(btf, t->name_off);
5323 
5324 	t = btf_type_by_id(btf, t->type);
5325 	if (!t || !btf_type_is_func_proto(t)) {
5326 		bpf_log(log, "Invalid BTF of func %s\n", tname);
5327 		return -EFAULT;
5328 	}
5329 	args = (const struct btf_param *)(t + 1);
5330 	nargs = btf_type_vlen(t);
5331 	if (nargs > 5) {
5332 		bpf_log(log, "Function %s has %d > 5 args\n", tname, nargs);
5333 		goto out;
5334 	}
5335 
5336 	is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5337 	/* check that BTF function arguments match actual types that the
5338 	 * verifier sees.
5339 	 */
5340 	for (i = 0; i < nargs; i++) {
5341 		struct bpf_reg_state *reg = &regs[i + 1];
5342 
5343 		t = btf_type_by_id(btf, args[i].type);
5344 		while (btf_type_is_modifier(t))
5345 			t = btf_type_by_id(btf, t->type);
5346 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5347 			if (reg->type == SCALAR_VALUE)
5348 				continue;
5349 			bpf_log(log, "R%d is not a scalar\n", i + 1);
5350 			goto out;
5351 		}
5352 		if (btf_type_is_ptr(t)) {
5353 			/* If function expects ctx type in BTF check that caller
5354 			 * is passing PTR_TO_CTX.
5355 			 */
5356 			if (btf_get_prog_ctx_type(log, btf, t, prog->type, i)) {
5357 				if (reg->type != PTR_TO_CTX) {
5358 					bpf_log(log,
5359 						"arg#%d expected pointer to ctx, but got %s\n",
5360 						i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5361 					goto out;
5362 				}
5363 				if (check_ctx_reg(env, reg, i + 1))
5364 					goto out;
5365 				continue;
5366 			}
5367 
5368 			if (!is_global)
5369 				goto out;
5370 
5371 			t = btf_type_skip_modifiers(btf, t->type, NULL);
5372 
5373 			ref_t = btf_resolve_size(btf, t, &type_size);
5374 			if (IS_ERR(ref_t)) {
5375 				bpf_log(log,
5376 				    "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5377 				    i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
5378 					PTR_ERR(ref_t));
5379 				goto out;
5380 			}
5381 
5382 			if (check_mem_reg(env, reg, i + 1, type_size))
5383 				goto out;
5384 
5385 			continue;
5386 		}
5387 		bpf_log(log, "Unrecognized arg#%d type %s\n",
5388 			i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5389 		goto out;
5390 	}
5391 	return 0;
5392 out:
5393 	/* Compiler optimizations can remove arguments from static functions
5394 	 * or mismatched type can be passed into a global function.
5395 	 * In such cases mark the function as unreliable from BTF point of view.
5396 	 */
5397 	prog->aux->func_info_aux[subprog].unreliable = true;
5398 	return -EINVAL;
5399 }
5400 
5401 /* Convert BTF of a function into bpf_reg_state if possible
5402  * Returns:
5403  * EFAULT - there is a verifier bug. Abort verification.
5404  * EINVAL - cannot convert BTF.
5405  * 0 - Successfully converted BTF into bpf_reg_state
5406  * (either PTR_TO_CTX or SCALAR_VALUE).
5407  */
5408 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
5409 			  struct bpf_reg_state *regs)
5410 {
5411 	struct bpf_verifier_log *log = &env->log;
5412 	struct bpf_prog *prog = env->prog;
5413 	enum bpf_prog_type prog_type = prog->type;
5414 	struct btf *btf = prog->aux->btf;
5415 	const struct btf_param *args;
5416 	const struct btf_type *t, *ref_t;
5417 	u32 i, nargs, btf_id;
5418 	const char *tname;
5419 
5420 	if (!prog->aux->func_info ||
5421 	    prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
5422 		bpf_log(log, "Verifier bug\n");
5423 		return -EFAULT;
5424 	}
5425 
5426 	btf_id = prog->aux->func_info[subprog].type_id;
5427 	if (!btf_id) {
5428 		bpf_log(log, "Global functions need valid BTF\n");
5429 		return -EFAULT;
5430 	}
5431 
5432 	t = btf_type_by_id(btf, btf_id);
5433 	if (!t || !btf_type_is_func(t)) {
5434 		/* These checks were already done by the verifier while loading
5435 		 * struct bpf_func_info
5436 		 */
5437 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5438 			subprog);
5439 		return -EFAULT;
5440 	}
5441 	tname = btf_name_by_offset(btf, t->name_off);
5442 
5443 	if (log->level & BPF_LOG_LEVEL)
5444 		bpf_log(log, "Validating %s() func#%d...\n",
5445 			tname, subprog);
5446 
5447 	if (prog->aux->func_info_aux[subprog].unreliable) {
5448 		bpf_log(log, "Verifier bug in function %s()\n", tname);
5449 		return -EFAULT;
5450 	}
5451 	if (prog_type == BPF_PROG_TYPE_EXT)
5452 		prog_type = prog->aux->dst_prog->type;
5453 
5454 	t = btf_type_by_id(btf, t->type);
5455 	if (!t || !btf_type_is_func_proto(t)) {
5456 		bpf_log(log, "Invalid type of function %s()\n", tname);
5457 		return -EFAULT;
5458 	}
5459 	args = (const struct btf_param *)(t + 1);
5460 	nargs = btf_type_vlen(t);
5461 	if (nargs > 5) {
5462 		bpf_log(log, "Global function %s() with %d > 5 args. Buggy compiler.\n",
5463 			tname, nargs);
5464 		return -EINVAL;
5465 	}
5466 	/* check that function returns int */
5467 	t = btf_type_by_id(btf, t->type);
5468 	while (btf_type_is_modifier(t))
5469 		t = btf_type_by_id(btf, t->type);
5470 	if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
5471 		bpf_log(log,
5472 			"Global function %s() doesn't return scalar. Only those are supported.\n",
5473 			tname);
5474 		return -EINVAL;
5475 	}
5476 	/* Convert BTF function arguments into verifier types.
5477 	 * Only PTR_TO_CTX and SCALAR are supported atm.
5478 	 */
5479 	for (i = 0; i < nargs; i++) {
5480 		struct bpf_reg_state *reg = &regs[i + 1];
5481 
5482 		t = btf_type_by_id(btf, args[i].type);
5483 		while (btf_type_is_modifier(t))
5484 			t = btf_type_by_id(btf, t->type);
5485 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5486 			reg->type = SCALAR_VALUE;
5487 			continue;
5488 		}
5489 		if (btf_type_is_ptr(t)) {
5490 			if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5491 				reg->type = PTR_TO_CTX;
5492 				continue;
5493 			}
5494 
5495 			t = btf_type_skip_modifiers(btf, t->type, NULL);
5496 
5497 			ref_t = btf_resolve_size(btf, t, &reg->mem_size);
5498 			if (IS_ERR(ref_t)) {
5499 				bpf_log(log,
5500 				    "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5501 				    i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
5502 					PTR_ERR(ref_t));
5503 				return -EINVAL;
5504 			}
5505 
5506 			reg->type = PTR_TO_MEM_OR_NULL;
5507 			reg->id = ++env->id_gen;
5508 
5509 			continue;
5510 		}
5511 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
5512 			i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
5513 		return -EINVAL;
5514 	}
5515 	return 0;
5516 }
5517 
5518 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
5519 			  struct btf_show *show)
5520 {
5521 	const struct btf_type *t = btf_type_by_id(btf, type_id);
5522 
5523 	show->btf = btf;
5524 	memset(&show->state, 0, sizeof(show->state));
5525 	memset(&show->obj, 0, sizeof(show->obj));
5526 
5527 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
5528 }
5529 
5530 static void btf_seq_show(struct btf_show *show, const char *fmt,
5531 			 va_list args)
5532 {
5533 	seq_vprintf((struct seq_file *)show->target, fmt, args);
5534 }
5535 
5536 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
5537 			    void *obj, struct seq_file *m, u64 flags)
5538 {
5539 	struct btf_show sseq;
5540 
5541 	sseq.target = m;
5542 	sseq.showfn = btf_seq_show;
5543 	sseq.flags = flags;
5544 
5545 	btf_type_show(btf, type_id, obj, &sseq);
5546 
5547 	return sseq.state.status;
5548 }
5549 
5550 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
5551 		       struct seq_file *m)
5552 {
5553 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
5554 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
5555 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
5556 }
5557 
5558 struct btf_show_snprintf {
5559 	struct btf_show show;
5560 	int len_left;		/* space left in string */
5561 	int len;		/* length we would have written */
5562 };
5563 
5564 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
5565 			      va_list args)
5566 {
5567 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
5568 	int len;
5569 
5570 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
5571 
5572 	if (len < 0) {
5573 		ssnprintf->len_left = 0;
5574 		ssnprintf->len = len;
5575 	} else if (len > ssnprintf->len_left) {
5576 		/* no space, drive on to get length we would have written */
5577 		ssnprintf->len_left = 0;
5578 		ssnprintf->len += len;
5579 	} else {
5580 		ssnprintf->len_left -= len;
5581 		ssnprintf->len += len;
5582 		show->target += len;
5583 	}
5584 }
5585 
5586 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
5587 			   char *buf, int len, u64 flags)
5588 {
5589 	struct btf_show_snprintf ssnprintf;
5590 
5591 	ssnprintf.show.target = buf;
5592 	ssnprintf.show.flags = flags;
5593 	ssnprintf.show.showfn = btf_snprintf_show;
5594 	ssnprintf.len_left = len;
5595 	ssnprintf.len = 0;
5596 
5597 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
5598 
5599 	/* If we encontered an error, return it. */
5600 	if (ssnprintf.show.state.status)
5601 		return ssnprintf.show.state.status;
5602 
5603 	/* Otherwise return length we would have written */
5604 	return ssnprintf.len;
5605 }
5606 
5607 #ifdef CONFIG_PROC_FS
5608 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
5609 {
5610 	const struct btf *btf = filp->private_data;
5611 
5612 	seq_printf(m, "btf_id:\t%u\n", btf->id);
5613 }
5614 #endif
5615 
5616 static int btf_release(struct inode *inode, struct file *filp)
5617 {
5618 	btf_put(filp->private_data);
5619 	return 0;
5620 }
5621 
5622 const struct file_operations btf_fops = {
5623 #ifdef CONFIG_PROC_FS
5624 	.show_fdinfo	= bpf_btf_show_fdinfo,
5625 #endif
5626 	.release	= btf_release,
5627 };
5628 
5629 static int __btf_new_fd(struct btf *btf)
5630 {
5631 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
5632 }
5633 
5634 int btf_new_fd(const union bpf_attr *attr)
5635 {
5636 	struct btf *btf;
5637 	int ret;
5638 
5639 	btf = btf_parse(u64_to_user_ptr(attr->btf),
5640 			attr->btf_size, attr->btf_log_level,
5641 			u64_to_user_ptr(attr->btf_log_buf),
5642 			attr->btf_log_size);
5643 	if (IS_ERR(btf))
5644 		return PTR_ERR(btf);
5645 
5646 	ret = btf_alloc_id(btf);
5647 	if (ret) {
5648 		btf_free(btf);
5649 		return ret;
5650 	}
5651 
5652 	/*
5653 	 * The BTF ID is published to the userspace.
5654 	 * All BTF free must go through call_rcu() from
5655 	 * now on (i.e. free by calling btf_put()).
5656 	 */
5657 
5658 	ret = __btf_new_fd(btf);
5659 	if (ret < 0)
5660 		btf_put(btf);
5661 
5662 	return ret;
5663 }
5664 
5665 struct btf *btf_get_by_fd(int fd)
5666 {
5667 	struct btf *btf;
5668 	struct fd f;
5669 
5670 	f = fdget(fd);
5671 
5672 	if (!f.file)
5673 		return ERR_PTR(-EBADF);
5674 
5675 	if (f.file->f_op != &btf_fops) {
5676 		fdput(f);
5677 		return ERR_PTR(-EINVAL);
5678 	}
5679 
5680 	btf = f.file->private_data;
5681 	refcount_inc(&btf->refcnt);
5682 	fdput(f);
5683 
5684 	return btf;
5685 }
5686 
5687 int btf_get_info_by_fd(const struct btf *btf,
5688 		       const union bpf_attr *attr,
5689 		       union bpf_attr __user *uattr)
5690 {
5691 	struct bpf_btf_info __user *uinfo;
5692 	struct bpf_btf_info info;
5693 	u32 info_copy, btf_copy;
5694 	void __user *ubtf;
5695 	char __user *uname;
5696 	u32 uinfo_len, uname_len, name_len;
5697 	int ret = 0;
5698 
5699 	uinfo = u64_to_user_ptr(attr->info.info);
5700 	uinfo_len = attr->info.info_len;
5701 
5702 	info_copy = min_t(u32, uinfo_len, sizeof(info));
5703 	memset(&info, 0, sizeof(info));
5704 	if (copy_from_user(&info, uinfo, info_copy))
5705 		return -EFAULT;
5706 
5707 	info.id = btf->id;
5708 	ubtf = u64_to_user_ptr(info.btf);
5709 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
5710 	if (copy_to_user(ubtf, btf->data, btf_copy))
5711 		return -EFAULT;
5712 	info.btf_size = btf->data_size;
5713 
5714 	info.kernel_btf = btf->kernel_btf;
5715 
5716 	uname = u64_to_user_ptr(info.name);
5717 	uname_len = info.name_len;
5718 	if (!uname ^ !uname_len)
5719 		return -EINVAL;
5720 
5721 	name_len = strlen(btf->name);
5722 	info.name_len = name_len;
5723 
5724 	if (uname) {
5725 		if (uname_len >= name_len + 1) {
5726 			if (copy_to_user(uname, btf->name, name_len + 1))
5727 				return -EFAULT;
5728 		} else {
5729 			char zero = '\0';
5730 
5731 			if (copy_to_user(uname, btf->name, uname_len - 1))
5732 				return -EFAULT;
5733 			if (put_user(zero, uname + uname_len - 1))
5734 				return -EFAULT;
5735 			/* let user-space know about too short buffer */
5736 			ret = -ENOSPC;
5737 		}
5738 	}
5739 
5740 	if (copy_to_user(uinfo, &info, info_copy) ||
5741 	    put_user(info_copy, &uattr->info.info_len))
5742 		return -EFAULT;
5743 
5744 	return ret;
5745 }
5746 
5747 int btf_get_fd_by_id(u32 id)
5748 {
5749 	struct btf *btf;
5750 	int fd;
5751 
5752 	rcu_read_lock();
5753 	btf = idr_find(&btf_idr, id);
5754 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
5755 		btf = ERR_PTR(-ENOENT);
5756 	rcu_read_unlock();
5757 
5758 	if (IS_ERR(btf))
5759 		return PTR_ERR(btf);
5760 
5761 	fd = __btf_new_fd(btf);
5762 	if (fd < 0)
5763 		btf_put(btf);
5764 
5765 	return fd;
5766 }
5767 
5768 u32 btf_obj_id(const struct btf *btf)
5769 {
5770 	return btf->id;
5771 }
5772 
5773 bool btf_is_kernel(const struct btf *btf)
5774 {
5775 	return btf->kernel_btf;
5776 }
5777 
5778 bool btf_is_module(const struct btf *btf)
5779 {
5780 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
5781 }
5782 
5783 static int btf_id_cmp_func(const void *a, const void *b)
5784 {
5785 	const int *pa = a, *pb = b;
5786 
5787 	return *pa - *pb;
5788 }
5789 
5790 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
5791 {
5792 	return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
5793 }
5794 
5795 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5796 struct btf_module {
5797 	struct list_head list;
5798 	struct module *module;
5799 	struct btf *btf;
5800 	struct bin_attribute *sysfs_attr;
5801 };
5802 
5803 static LIST_HEAD(btf_modules);
5804 static DEFINE_MUTEX(btf_module_mutex);
5805 
5806 static ssize_t
5807 btf_module_read(struct file *file, struct kobject *kobj,
5808 		struct bin_attribute *bin_attr,
5809 		char *buf, loff_t off, size_t len)
5810 {
5811 	const struct btf *btf = bin_attr->private;
5812 
5813 	memcpy(buf, btf->data + off, len);
5814 	return len;
5815 }
5816 
5817 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
5818 			     void *module)
5819 {
5820 	struct btf_module *btf_mod, *tmp;
5821 	struct module *mod = module;
5822 	struct btf *btf;
5823 	int err = 0;
5824 
5825 	if (mod->btf_data_size == 0 ||
5826 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
5827 		goto out;
5828 
5829 	switch (op) {
5830 	case MODULE_STATE_COMING:
5831 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
5832 		if (!btf_mod) {
5833 			err = -ENOMEM;
5834 			goto out;
5835 		}
5836 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
5837 		if (IS_ERR(btf)) {
5838 			pr_warn("failed to validate module [%s] BTF: %ld\n",
5839 				mod->name, PTR_ERR(btf));
5840 			kfree(btf_mod);
5841 			err = PTR_ERR(btf);
5842 			goto out;
5843 		}
5844 		err = btf_alloc_id(btf);
5845 		if (err) {
5846 			btf_free(btf);
5847 			kfree(btf_mod);
5848 			goto out;
5849 		}
5850 
5851 		mutex_lock(&btf_module_mutex);
5852 		btf_mod->module = module;
5853 		btf_mod->btf = btf;
5854 		list_add(&btf_mod->list, &btf_modules);
5855 		mutex_unlock(&btf_module_mutex);
5856 
5857 		if (IS_ENABLED(CONFIG_SYSFS)) {
5858 			struct bin_attribute *attr;
5859 
5860 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
5861 			if (!attr)
5862 				goto out;
5863 
5864 			sysfs_bin_attr_init(attr);
5865 			attr->attr.name = btf->name;
5866 			attr->attr.mode = 0444;
5867 			attr->size = btf->data_size;
5868 			attr->private = btf;
5869 			attr->read = btf_module_read;
5870 
5871 			err = sysfs_create_bin_file(btf_kobj, attr);
5872 			if (err) {
5873 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
5874 					mod->name, err);
5875 				kfree(attr);
5876 				err = 0;
5877 				goto out;
5878 			}
5879 
5880 			btf_mod->sysfs_attr = attr;
5881 		}
5882 
5883 		break;
5884 	case MODULE_STATE_GOING:
5885 		mutex_lock(&btf_module_mutex);
5886 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
5887 			if (btf_mod->module != module)
5888 				continue;
5889 
5890 			list_del(&btf_mod->list);
5891 			if (btf_mod->sysfs_attr)
5892 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
5893 			btf_put(btf_mod->btf);
5894 			kfree(btf_mod->sysfs_attr);
5895 			kfree(btf_mod);
5896 			break;
5897 		}
5898 		mutex_unlock(&btf_module_mutex);
5899 		break;
5900 	}
5901 out:
5902 	return notifier_from_errno(err);
5903 }
5904 
5905 static struct notifier_block btf_module_nb = {
5906 	.notifier_call = btf_module_notify,
5907 };
5908 
5909 static int __init btf_module_init(void)
5910 {
5911 	register_module_notifier(&btf_module_nb);
5912 	return 0;
5913 }
5914 
5915 fs_initcall(btf_module_init);
5916 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5917 
5918 struct module *btf_try_get_module(const struct btf *btf)
5919 {
5920 	struct module *res = NULL;
5921 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5922 	struct btf_module *btf_mod, *tmp;
5923 
5924 	mutex_lock(&btf_module_mutex);
5925 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
5926 		if (btf_mod->btf != btf)
5927 			continue;
5928 
5929 		if (try_module_get(btf_mod->module))
5930 			res = btf_mod->module;
5931 
5932 		break;
5933 	}
5934 	mutex_unlock(&btf_module_mutex);
5935 #endif
5936 
5937 	return res;
5938 }
5939