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