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