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