1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2018 Facebook */
4 #include <uapi/linux/btf.h>
5 #include <uapi/linux/bpf.h>
6 #include <uapi/linux/bpf_perf_event.h>
7 #include <uapi/linux/types.h>
8 #include <linux/seq_file.h>
9 #include <linux/compiler.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/file.h>
15 #include <linux/uaccess.h>
16 #include <linux/kernel.h>
17 #include <linux/idr.h>
18 #include <linux/sort.h>
19 #include <linux/bpf_verifier.h>
20 #include <linux/btf.h>
21 #include <linux/btf_ids.h>
22 #include <linux/skmsg.h>
23 #include <linux/perf_event.h>
24 #include <linux/bsearch.h>
25 #include <linux/kobject.h>
26 #include <linux/sysfs.h>
28 #include "../tools/lib/bpf/relo_core.h"
30 /* BTF (BPF Type Format) is the meta data format which describes
31 * the data types of BPF program/map. Hence, it basically focus
32 * on the C programming language which the modern BPF is primary
37 * The BTF data is stored under the ".BTF" ELF section
41 * Each 'struct btf_type' object describes a C data type.
42 * Depending on the type it is describing, a 'struct btf_type'
43 * object may be followed by more data. F.e.
44 * To describe an array, 'struct btf_type' is followed by
47 * 'struct btf_type' and any extra data following it are
52 * The BTF type section contains a list of 'struct btf_type' objects.
53 * Each one describes a C type. Recall from the above section
54 * that a 'struct btf_type' object could be immediately followed by extra
55 * data in order to describe some particular C types.
59 * Each btf_type object is identified by a type_id. The type_id
60 * is implicitly implied by the location of the btf_type object in
61 * the BTF type section. The first one has type_id 1. The second
62 * one has type_id 2...etc. Hence, an earlier btf_type has
65 * A btf_type object may refer to another btf_type object by using
66 * type_id (i.e. the "type" in the "struct btf_type").
68 * NOTE that we cannot assume any reference-order.
69 * A btf_type object can refer to an earlier btf_type object
70 * but it can also refer to a later btf_type object.
72 * For example, to describe "const void *". A btf_type
73 * object describing "const" may refer to another btf_type
74 * object describing "void *". This type-reference is done
75 * by specifying type_id:
77 * [1] CONST (anon) type_id=2
78 * [2] PTR (anon) type_id=0
80 * The above is the btf_verifier debug log:
81 * - Each line started with "[?]" is a btf_type object
82 * - [?] is the type_id of the btf_type object.
83 * - CONST/PTR is the BTF_KIND_XXX
84 * - "(anon)" is the name of the type. It just
85 * happens that CONST and PTR has no name.
86 * - type_id=XXX is the 'u32 type' in btf_type
88 * NOTE: "void" has type_id 0
92 * The BTF string section contains the names used by the type section.
93 * Each string is referred by an "offset" from the beginning of the
96 * Each string is '\0' terminated.
98 * The first character in the string section must be '\0'
99 * which is used to mean 'anonymous'. Some btf_type may not
105 * To verify BTF data, two passes are needed.
109 * The first pass is to collect all btf_type objects to
110 * an array: "btf->types".
112 * Depending on the C type that a btf_type is describing,
113 * a btf_type may be followed by extra data. We don't know
114 * how many btf_type is there, and more importantly we don't
115 * know where each btf_type is located in the type section.
117 * Without knowing the location of each type_id, most verifications
118 * cannot be done. e.g. an earlier btf_type may refer to a later
119 * btf_type (recall the "const void *" above), so we cannot
120 * check this type-reference in the first pass.
122 * In the first pass, it still does some verifications (e.g.
123 * checking the name is a valid offset to the string section).
127 * The main focus is to resolve a btf_type that is referring
130 * We have to ensure the referring type:
131 * 1) does exist in the BTF (i.e. in btf->types[])
132 * 2) does not cause a loop:
141 * btf_type_needs_resolve() decides if a btf_type needs
144 * The needs_resolve type implements the "resolve()" ops which
145 * essentially does a DFS and detects backedge.
147 * During resolve (or DFS), different C types have different
148 * "RESOLVED" conditions.
150 * When resolving a BTF_KIND_STRUCT, we need to resolve all its
151 * members because a member is always referring to another
152 * type. A struct's member can be treated as "RESOLVED" if
153 * it is referring to a BTF_KIND_PTR. Otherwise, the
154 * following valid C struct would be rejected:
161 * When resolving a BTF_KIND_PTR, it needs to keep resolving if
162 * it is referring to another BTF_KIND_PTR. Otherwise, we cannot
163 * detect a pointer loop, e.g.:
164 * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
166 * +-----------------------------------------+
170 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
171 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
172 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
173 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
174 #define BITS_ROUNDUP_BYTES(bits) \
175 (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
177 #define BTF_INFO_MASK 0x9f00ffff
178 #define BTF_INT_MASK 0x0fffffff
179 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
180 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
182 /* 16MB for 64k structs and each has 16 members and
183 * a few MB spaces for the string section.
184 * The hard limit is S32_MAX.
186 #define BTF_MAX_SIZE (16 * 1024 * 1024)
188 #define for_each_member_from(i, from, struct_type, member) \
189 for (i = from, member = btf_type_member(struct_type) + from; \
190 i < btf_type_vlen(struct_type); \
193 #define for_each_vsi_from(i, from, struct_type, member) \
194 for (i = from, member = btf_type_var_secinfo(struct_type) + from; \
195 i < btf_type_vlen(struct_type); \
199 DEFINE_SPINLOCK(btf_idr_lock);
203 struct btf_type **types;
208 struct btf_header hdr;
209 u32 nr_types; /* includes VOID for base BTF */
216 /* split BTF support */
217 struct btf *base_btf;
218 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
219 u32 start_str_off; /* first string offset (0 for base BTF) */
220 char name[MODULE_NAME_LEN];
224 enum verifier_phase {
229 struct resolve_vertex {
230 const struct btf_type *t;
242 RESOLVE_TBD, /* To Be Determined */
243 RESOLVE_PTR, /* Resolving for Pointer */
244 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
249 #define MAX_RESOLVE_DEPTH 32
251 struct btf_sec_info {
256 struct btf_verifier_env {
259 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
260 struct bpf_verifier_log log;
263 enum verifier_phase phase;
264 enum resolve_mode resolve_mode;
267 static const char * const btf_kind_str[NR_BTF_KINDS] = {
268 [BTF_KIND_UNKN] = "UNKNOWN",
269 [BTF_KIND_INT] = "INT",
270 [BTF_KIND_PTR] = "PTR",
271 [BTF_KIND_ARRAY] = "ARRAY",
272 [BTF_KIND_STRUCT] = "STRUCT",
273 [BTF_KIND_UNION] = "UNION",
274 [BTF_KIND_ENUM] = "ENUM",
275 [BTF_KIND_FWD] = "FWD",
276 [BTF_KIND_TYPEDEF] = "TYPEDEF",
277 [BTF_KIND_VOLATILE] = "VOLATILE",
278 [BTF_KIND_CONST] = "CONST",
279 [BTF_KIND_RESTRICT] = "RESTRICT",
280 [BTF_KIND_FUNC] = "FUNC",
281 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
282 [BTF_KIND_VAR] = "VAR",
283 [BTF_KIND_DATASEC] = "DATASEC",
284 [BTF_KIND_FLOAT] = "FLOAT",
285 [BTF_KIND_DECL_TAG] = "DECL_TAG",
286 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
289 const char *btf_type_str(const struct btf_type *t)
291 return btf_kind_str[BTF_INFO_KIND(t->info)];
294 /* Chunk size we use in safe copy of data to be shown. */
295 #define BTF_SHOW_OBJ_SAFE_SIZE 32
298 * This is the maximum size of a base type value (equivalent to a
299 * 128-bit int); if we are at the end of our safe buffer and have
300 * less than 16 bytes space we can't be assured of being able
301 * to copy the next type safely, so in such cases we will initiate
304 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
307 #define BTF_SHOW_NAME_SIZE 80
310 * Common data to all BTF show operations. Private show functions can add
311 * their own data to a structure containing a struct btf_show and consult it
312 * in the show callback. See btf_type_show() below.
314 * One challenge with showing nested data is we want to skip 0-valued
315 * data, but in order to figure out whether a nested object is all zeros
316 * we need to walk through it. As a result, we need to make two passes
317 * when handling structs, unions and arrays; the first path simply looks
318 * for nonzero data, while the second actually does the display. The first
319 * pass is signalled by show->state.depth_check being set, and if we
320 * encounter a non-zero value we set show->state.depth_to_show to
321 * the depth at which we encountered it. When we have completed the
322 * first pass, we will know if anything needs to be displayed if
323 * depth_to_show > depth. See btf_[struct,array]_show() for the
324 * implementation of this.
326 * Another problem is we want to ensure the data for display is safe to
327 * access. To support this, the anonymous "struct {} obj" tracks the data
328 * object and our safe copy of it. We copy portions of the data needed
329 * to the object "copy" buffer, but because its size is limited to
330 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
331 * traverse larger objects for display.
333 * The various data type show functions all start with a call to
334 * btf_show_start_type() which returns a pointer to the safe copy
335 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
336 * raw data itself). btf_show_obj_safe() is responsible for
337 * using copy_from_kernel_nofault() to update the safe data if necessary
338 * as we traverse the object's data. skbuff-like semantics are
341 * - obj.head points to the start of the toplevel object for display
342 * - obj.size is the size of the toplevel object
343 * - obj.data points to the current point in the original data at
344 * which our safe data starts. obj.data will advance as we copy
345 * portions of the data.
347 * In most cases a single copy will suffice, but larger data structures
348 * such as "struct task_struct" will require many copies. The logic in
349 * btf_show_obj_safe() handles the logic that determines if a new
350 * copy_from_kernel_nofault() is needed.
354 void *target; /* target of show operation (seq file, buffer) */
355 void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
356 const struct btf *btf;
357 /* below are used during iteration */
366 int status; /* non-zero for error */
367 const struct btf_type *type;
368 const struct btf_member *member;
369 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
375 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
379 struct btf_kind_operations {
380 s32 (*check_meta)(struct btf_verifier_env *env,
381 const struct btf_type *t,
383 int (*resolve)(struct btf_verifier_env *env,
384 const struct resolve_vertex *v);
385 int (*check_member)(struct btf_verifier_env *env,
386 const struct btf_type *struct_type,
387 const struct btf_member *member,
388 const struct btf_type *member_type);
389 int (*check_kflag_member)(struct btf_verifier_env *env,
390 const struct btf_type *struct_type,
391 const struct btf_member *member,
392 const struct btf_type *member_type);
393 void (*log_details)(struct btf_verifier_env *env,
394 const struct btf_type *t);
395 void (*show)(const struct btf *btf, const struct btf_type *t,
396 u32 type_id, void *data, u8 bits_offsets,
397 struct btf_show *show);
400 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
401 static struct btf_type btf_void;
403 static int btf_resolve(struct btf_verifier_env *env,
404 const struct btf_type *t, u32 type_id);
406 static bool btf_type_is_modifier(const struct btf_type *t)
408 /* Some of them is not strictly a C modifier
409 * but they are grouped into the same bucket
411 * A type (t) that refers to another
412 * type through t->type AND its size cannot
413 * be determined without following the t->type.
415 * ptr does not fall into this bucket
416 * because its size is always sizeof(void *).
418 switch (BTF_INFO_KIND(t->info)) {
419 case BTF_KIND_TYPEDEF:
420 case BTF_KIND_VOLATILE:
422 case BTF_KIND_RESTRICT:
423 case BTF_KIND_TYPE_TAG:
430 bool btf_type_is_void(const struct btf_type *t)
432 return t == &btf_void;
435 static bool btf_type_is_fwd(const struct btf_type *t)
437 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
440 static bool btf_type_nosize(const struct btf_type *t)
442 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
443 btf_type_is_func(t) || btf_type_is_func_proto(t);
446 static bool btf_type_nosize_or_null(const struct btf_type *t)
448 return !t || btf_type_nosize(t);
451 static bool __btf_type_is_struct(const struct btf_type *t)
453 return BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT;
456 static bool btf_type_is_array(const struct btf_type *t)
458 return BTF_INFO_KIND(t->info) == BTF_KIND_ARRAY;
461 static bool btf_type_is_datasec(const struct btf_type *t)
463 return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
466 static bool btf_type_is_decl_tag(const struct btf_type *t)
468 return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
471 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
473 return btf_type_is_func(t) || btf_type_is_struct(t) ||
474 btf_type_is_var(t) || btf_type_is_typedef(t);
477 u32 btf_nr_types(const struct btf *btf)
482 total += btf->nr_types;
489 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
491 const struct btf_type *t;
495 total = btf_nr_types(btf);
496 for (i = 1; i < total; i++) {
497 t = btf_type_by_id(btf, i);
498 if (BTF_INFO_KIND(t->info) != kind)
501 tname = btf_name_by_offset(btf, t->name_off);
502 if (!strcmp(tname, name))
509 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
512 const struct btf_type *t = btf_type_by_id(btf, id);
514 while (btf_type_is_modifier(t)) {
516 t = btf_type_by_id(btf, t->type);
525 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
528 const struct btf_type *t;
530 t = btf_type_skip_modifiers(btf, id, NULL);
531 if (!btf_type_is_ptr(t))
534 return btf_type_skip_modifiers(btf, t->type, res_id);
537 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
540 const struct btf_type *ptype;
542 ptype = btf_type_resolve_ptr(btf, id, res_id);
543 if (ptype && btf_type_is_func_proto(ptype))
549 /* Types that act only as a source, not sink or intermediate
550 * type when resolving.
552 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
554 return btf_type_is_var(t) ||
555 btf_type_is_decl_tag(t) ||
556 btf_type_is_datasec(t);
559 /* What types need to be resolved?
561 * btf_type_is_modifier() is an obvious one.
563 * btf_type_is_struct() because its member refers to
564 * another type (through member->type).
566 * btf_type_is_var() because the variable refers to
567 * another type. btf_type_is_datasec() holds multiple
568 * btf_type_is_var() types that need resolving.
570 * btf_type_is_array() because its element (array->type)
571 * refers to another type. Array can be thought of a
572 * special case of struct while array just has the same
573 * member-type repeated by array->nelems of times.
575 static bool btf_type_needs_resolve(const struct btf_type *t)
577 return btf_type_is_modifier(t) ||
578 btf_type_is_ptr(t) ||
579 btf_type_is_struct(t) ||
580 btf_type_is_array(t) ||
581 btf_type_is_var(t) ||
582 btf_type_is_decl_tag(t) ||
583 btf_type_is_datasec(t);
586 /* t->size can be used */
587 static bool btf_type_has_size(const struct btf_type *t)
589 switch (BTF_INFO_KIND(t->info)) {
591 case BTF_KIND_STRUCT:
594 case BTF_KIND_DATASEC:
602 static const char *btf_int_encoding_str(u8 encoding)
606 else if (encoding == BTF_INT_SIGNED)
608 else if (encoding == BTF_INT_CHAR)
610 else if (encoding == BTF_INT_BOOL)
616 static u32 btf_type_int(const struct btf_type *t)
618 return *(u32 *)(t + 1);
621 static const struct btf_array *btf_type_array(const struct btf_type *t)
623 return (const struct btf_array *)(t + 1);
626 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
628 return (const struct btf_enum *)(t + 1);
631 static const struct btf_var *btf_type_var(const struct btf_type *t)
633 return (const struct btf_var *)(t + 1);
636 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
638 return (const struct btf_decl_tag *)(t + 1);
641 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
643 return kind_ops[BTF_INFO_KIND(t->info)];
646 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
648 if (!BTF_STR_OFFSET_VALID(offset))
651 while (offset < btf->start_str_off)
654 offset -= btf->start_str_off;
655 return offset < btf->hdr.str_len;
658 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
660 if ((first ? !isalpha(c) :
663 ((c == '.' && !dot_ok) ||
669 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
671 while (offset < btf->start_str_off)
674 offset -= btf->start_str_off;
675 if (offset < btf->hdr.str_len)
676 return &btf->strings[offset];
681 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
683 /* offset must be valid */
684 const char *src = btf_str_by_offset(btf, offset);
685 const char *src_limit;
687 if (!__btf_name_char_ok(*src, true, dot_ok))
690 /* set a limit on identifier length */
691 src_limit = src + KSYM_NAME_LEN;
693 while (*src && src < src_limit) {
694 if (!__btf_name_char_ok(*src, false, dot_ok))
702 /* Only C-style identifier is permitted. This can be relaxed if
705 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
707 return __btf_name_valid(btf, offset, false);
710 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
712 return __btf_name_valid(btf, offset, true);
715 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
722 name = btf_str_by_offset(btf, offset);
723 return name ?: "(invalid-name-offset)";
726 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
728 return btf_str_by_offset(btf, offset);
731 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
733 while (type_id < btf->start_id)
736 type_id -= btf->start_id;
737 if (type_id >= btf->nr_types)
739 return btf->types[type_id];
743 * Regular int is not a bit field and it must be either
744 * u8/u16/u32/u64 or __int128.
746 static bool btf_type_int_is_regular(const struct btf_type *t)
748 u8 nr_bits, nr_bytes;
751 int_data = btf_type_int(t);
752 nr_bits = BTF_INT_BITS(int_data);
753 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
754 if (BITS_PER_BYTE_MASKED(nr_bits) ||
755 BTF_INT_OFFSET(int_data) ||
756 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
757 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
758 nr_bytes != (2 * sizeof(u64)))) {
766 * Check that given struct member is a regular int with expected
769 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
770 const struct btf_member *m,
771 u32 expected_offset, u32 expected_size)
773 const struct btf_type *t;
778 t = btf_type_id_size(btf, &id, NULL);
779 if (!t || !btf_type_is_int(t))
782 int_data = btf_type_int(t);
783 nr_bits = BTF_INT_BITS(int_data);
784 if (btf_type_kflag(s)) {
785 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
786 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
788 /* if kflag set, int should be a regular int and
789 * bit offset should be at byte boundary.
791 return !bitfield_size &&
792 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
793 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
796 if (BTF_INT_OFFSET(int_data) ||
797 BITS_PER_BYTE_MASKED(m->offset) ||
798 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
799 BITS_PER_BYTE_MASKED(nr_bits) ||
800 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
806 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
807 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
810 const struct btf_type *t = btf_type_by_id(btf, id);
812 while (btf_type_is_modifier(t) &&
813 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
814 t = btf_type_by_id(btf, t->type);
820 #define BTF_SHOW_MAX_ITER 10
822 #define BTF_KIND_BIT(kind) (1ULL << kind)
825 * Populate show->state.name with type name information.
826 * Format of type name is
828 * [.member_name = ] (type_name)
830 static const char *btf_show_name(struct btf_show *show)
832 /* BTF_MAX_ITER array suffixes "[]" */
833 const char *array_suffixes = "[][][][][][][][][][]";
834 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
835 /* BTF_MAX_ITER pointer suffixes "*" */
836 const char *ptr_suffixes = "**********";
837 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
838 const char *name = NULL, *prefix = "", *parens = "";
839 const struct btf_member *m = show->state.member;
840 const struct btf_type *t;
841 const struct btf_array *array;
842 u32 id = show->state.type_id;
843 const char *member = NULL;
844 bool show_member = false;
848 show->state.name[0] = '\0';
851 * Don't show type name if we're showing an array member;
852 * in that case we show the array type so don't need to repeat
853 * ourselves for each member.
855 if (show->state.array_member)
858 /* Retrieve member name, if any. */
860 member = btf_name_by_offset(show->btf, m->name_off);
861 show_member = strlen(member) > 0;
866 * Start with type_id, as we have resolved the struct btf_type *
867 * via btf_modifier_show() past the parent typedef to the child
868 * struct, int etc it is defined as. In such cases, the type_id
869 * still represents the starting type while the struct btf_type *
870 * in our show->state points at the resolved type of the typedef.
872 t = btf_type_by_id(show->btf, id);
877 * The goal here is to build up the right number of pointer and
878 * array suffixes while ensuring the type name for a typedef
879 * is represented. Along the way we accumulate a list of
880 * BTF kinds we have encountered, since these will inform later
881 * display; for example, pointer types will not require an
882 * opening "{" for struct, we will just display the pointer value.
884 * We also want to accumulate the right number of pointer or array
885 * indices in the format string while iterating until we get to
886 * the typedef/pointee/array member target type.
888 * We start by pointing at the end of pointer and array suffix
889 * strings; as we accumulate pointers and arrays we move the pointer
890 * or array string backwards so it will show the expected number of
891 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
892 * and/or arrays and typedefs are supported as a precaution.
894 * We also want to get typedef name while proceeding to resolve
895 * type it points to so that we can add parentheses if it is a
896 * "typedef struct" etc.
898 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
900 switch (BTF_INFO_KIND(t->info)) {
901 case BTF_KIND_TYPEDEF:
903 name = btf_name_by_offset(show->btf,
905 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
909 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
913 array = btf_type_array(t);
914 if (array_suffix > array_suffixes)
919 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
920 if (ptr_suffix > ptr_suffixes)
930 t = btf_type_skip_qualifiers(show->btf, id);
932 /* We may not be able to represent this type; bail to be safe */
933 if (i == BTF_SHOW_MAX_ITER)
937 name = btf_name_by_offset(show->btf, t->name_off);
939 switch (BTF_INFO_KIND(t->info)) {
940 case BTF_KIND_STRUCT:
942 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
944 /* if it's an array of struct/union, parens is already set */
945 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
955 /* pointer does not require parens */
956 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
958 /* typedef does not require struct/union/enum prefix */
959 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
965 /* Even if we don't want type name info, we want parentheses etc */
966 if (show->flags & BTF_SHOW_NONAME)
967 snprintf(show->state.name, sizeof(show->state.name), "%s",
970 snprintf(show->state.name, sizeof(show->state.name),
971 "%s%s%s(%s%s%s%s%s%s)%s",
972 /* first 3 strings comprise ".member = " */
973 show_member ? "." : "",
974 show_member ? member : "",
975 show_member ? " = " : "",
976 /* ...next is our prefix (struct, enum, etc) */
978 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
979 /* ...this is the type name itself */
981 /* ...suffixed by the appropriate '*', '[]' suffixes */
982 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
983 array_suffix, parens);
985 return show->state.name;
988 static const char *__btf_show_indent(struct btf_show *show)
990 const char *indents = " ";
991 const char *indent = &indents[strlen(indents)];
993 if ((indent - show->state.depth) >= indents)
994 return indent - show->state.depth;
998 static const char *btf_show_indent(struct btf_show *show)
1000 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1003 static const char *btf_show_newline(struct btf_show *show)
1005 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1008 static const char *btf_show_delim(struct btf_show *show)
1010 if (show->state.depth == 0)
1013 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1014 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1020 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1024 if (!show->state.depth_check) {
1025 va_start(args, fmt);
1026 show->showfn(show, fmt, args);
1031 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1032 * format specifiers to the format specifier passed in; these do the work of
1033 * adding indentation, delimiters etc while the caller simply has to specify
1034 * the type value(s) in the format specifier + value(s).
1036 #define btf_show_type_value(show, fmt, value) \
1038 if ((value) != 0 || (show->flags & BTF_SHOW_ZERO) || \
1039 show->state.depth == 0) { \
1040 btf_show(show, "%s%s" fmt "%s%s", \
1041 btf_show_indent(show), \
1042 btf_show_name(show), \
1043 value, btf_show_delim(show), \
1044 btf_show_newline(show)); \
1045 if (show->state.depth > show->state.depth_to_show) \
1046 show->state.depth_to_show = show->state.depth; \
1050 #define btf_show_type_values(show, fmt, ...) \
1052 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1053 btf_show_name(show), \
1054 __VA_ARGS__, btf_show_delim(show), \
1055 btf_show_newline(show)); \
1056 if (show->state.depth > show->state.depth_to_show) \
1057 show->state.depth_to_show = show->state.depth; \
1060 /* How much is left to copy to safe buffer after @data? */
1061 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1063 return show->obj.head + show->obj.size - data;
1066 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1067 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1069 return data >= show->obj.data &&
1070 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1074 * If object pointed to by @data of @size falls within our safe buffer, return
1075 * the equivalent pointer to the same safe data. Assumes
1076 * copy_from_kernel_nofault() has already happened and our safe buffer is
1079 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1081 if (btf_show_obj_is_safe(show, data, size))
1082 return show->obj.safe + (data - show->obj.data);
1087 * Return a safe-to-access version of data pointed to by @data.
1088 * We do this by copying the relevant amount of information
1089 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1091 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1092 * safe copy is needed.
1094 * Otherwise we need to determine if we have the required amount
1095 * of data (determined by the @data pointer and the size of the
1096 * largest base type we can encounter (represented by
1097 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1098 * that we will be able to print some of the current object,
1099 * and if more is needed a copy will be triggered.
1100 * Some objects such as structs will not fit into the buffer;
1101 * in such cases additional copies when we iterate over their
1102 * members may be needed.
1104 * btf_show_obj_safe() is used to return a safe buffer for
1105 * btf_show_start_type(); this ensures that as we recurse into
1106 * nested types we always have safe data for the given type.
1107 * This approach is somewhat wasteful; it's possible for example
1108 * that when iterating over a large union we'll end up copying the
1109 * same data repeatedly, but the goal is safety not performance.
1110 * We use stack data as opposed to per-CPU buffers because the
1111 * iteration over a type can take some time, and preemption handling
1112 * would greatly complicate use of the safe buffer.
1114 static void *btf_show_obj_safe(struct btf_show *show,
1115 const struct btf_type *t,
1118 const struct btf_type *rt;
1119 int size_left, size;
1122 if (show->flags & BTF_SHOW_UNSAFE)
1125 rt = btf_resolve_size(show->btf, t, &size);
1127 show->state.status = PTR_ERR(rt);
1132 * Is this toplevel object? If so, set total object size and
1133 * initialize pointers. Otherwise check if we still fall within
1134 * our safe object data.
1136 if (show->state.depth == 0) {
1137 show->obj.size = size;
1138 show->obj.head = data;
1141 * If the size of the current object is > our remaining
1142 * safe buffer we _may_ need to do a new copy. However
1143 * consider the case of a nested struct; it's size pushes
1144 * us over the safe buffer limit, but showing any individual
1145 * struct members does not. In such cases, we don't need
1146 * to initiate a fresh copy yet; however we definitely need
1147 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1148 * in our buffer, regardless of the current object size.
1149 * The logic here is that as we resolve types we will
1150 * hit a base type at some point, and we need to be sure
1151 * the next chunk of data is safely available to display
1152 * that type info safely. We cannot rely on the size of
1153 * the current object here because it may be much larger
1154 * than our current buffer (e.g. task_struct is 8k).
1155 * All we want to do here is ensure that we can print the
1156 * next basic type, which we can if either
1157 * - the current type size is within the safe buffer; or
1158 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1161 safe = __btf_show_obj_safe(show, data,
1163 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1167 * We need a new copy to our safe object, either because we haven't
1168 * yet copied and are initializing safe data, or because the data
1169 * we want falls outside the boundaries of the safe object.
1172 size_left = btf_show_obj_size_left(show, data);
1173 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1174 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1175 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1177 if (!show->state.status) {
1178 show->obj.data = data;
1179 safe = show->obj.safe;
1187 * Set the type we are starting to show and return a safe data pointer
1188 * to be used for showing the associated data.
1190 static void *btf_show_start_type(struct btf_show *show,
1191 const struct btf_type *t,
1192 u32 type_id, void *data)
1194 show->state.type = t;
1195 show->state.type_id = type_id;
1196 show->state.name[0] = '\0';
1198 return btf_show_obj_safe(show, t, data);
1201 static void btf_show_end_type(struct btf_show *show)
1203 show->state.type = NULL;
1204 show->state.type_id = 0;
1205 show->state.name[0] = '\0';
1208 static void *btf_show_start_aggr_type(struct btf_show *show,
1209 const struct btf_type *t,
1210 u32 type_id, void *data)
1212 void *safe_data = btf_show_start_type(show, t, type_id, data);
1217 btf_show(show, "%s%s%s", btf_show_indent(show),
1218 btf_show_name(show),
1219 btf_show_newline(show));
1220 show->state.depth++;
1224 static void btf_show_end_aggr_type(struct btf_show *show,
1227 show->state.depth--;
1228 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1229 btf_show_delim(show), btf_show_newline(show));
1230 btf_show_end_type(show);
1233 static void btf_show_start_member(struct btf_show *show,
1234 const struct btf_member *m)
1236 show->state.member = m;
1239 static void btf_show_start_array_member(struct btf_show *show)
1241 show->state.array_member = 1;
1242 btf_show_start_member(show, NULL);
1245 static void btf_show_end_member(struct btf_show *show)
1247 show->state.member = NULL;
1250 static void btf_show_end_array_member(struct btf_show *show)
1252 show->state.array_member = 0;
1253 btf_show_end_member(show);
1256 static void *btf_show_start_array_type(struct btf_show *show,
1257 const struct btf_type *t,
1262 show->state.array_encoding = array_encoding;
1263 show->state.array_terminated = 0;
1264 return btf_show_start_aggr_type(show, t, type_id, data);
1267 static void btf_show_end_array_type(struct btf_show *show)
1269 show->state.array_encoding = 0;
1270 show->state.array_terminated = 0;
1271 btf_show_end_aggr_type(show, "]");
1274 static void *btf_show_start_struct_type(struct btf_show *show,
1275 const struct btf_type *t,
1279 return btf_show_start_aggr_type(show, t, type_id, data);
1282 static void btf_show_end_struct_type(struct btf_show *show)
1284 btf_show_end_aggr_type(show, "}");
1287 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1288 const char *fmt, ...)
1292 va_start(args, fmt);
1293 bpf_verifier_vlog(log, fmt, args);
1297 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1298 const char *fmt, ...)
1300 struct bpf_verifier_log *log = &env->log;
1303 if (!bpf_verifier_log_needed(log))
1306 va_start(args, fmt);
1307 bpf_verifier_vlog(log, fmt, args);
1311 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1312 const struct btf_type *t,
1314 const char *fmt, ...)
1316 struct bpf_verifier_log *log = &env->log;
1317 u8 kind = BTF_INFO_KIND(t->info);
1318 struct btf *btf = env->btf;
1321 if (!bpf_verifier_log_needed(log))
1324 /* btf verifier prints all types it is processing via
1325 * btf_verifier_log_type(..., fmt = NULL).
1326 * Skip those prints for in-kernel BTF verification.
1328 if (log->level == BPF_LOG_KERNEL && !fmt)
1331 __btf_verifier_log(log, "[%u] %s %s%s",
1334 __btf_name_by_offset(btf, t->name_off),
1335 log_details ? " " : "");
1338 btf_type_ops(t)->log_details(env, t);
1341 __btf_verifier_log(log, " ");
1342 va_start(args, fmt);
1343 bpf_verifier_vlog(log, fmt, args);
1347 __btf_verifier_log(log, "\n");
1350 #define btf_verifier_log_type(env, t, ...) \
1351 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1352 #define btf_verifier_log_basic(env, t, ...) \
1353 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1356 static void btf_verifier_log_member(struct btf_verifier_env *env,
1357 const struct btf_type *struct_type,
1358 const struct btf_member *member,
1359 const char *fmt, ...)
1361 struct bpf_verifier_log *log = &env->log;
1362 struct btf *btf = env->btf;
1365 if (!bpf_verifier_log_needed(log))
1368 if (log->level == BPF_LOG_KERNEL && !fmt)
1370 /* The CHECK_META phase already did a btf dump.
1372 * If member is logged again, it must hit an error in
1373 * parsing this member. It is useful to print out which
1374 * struct this member belongs to.
1376 if (env->phase != CHECK_META)
1377 btf_verifier_log_type(env, struct_type, NULL);
1379 if (btf_type_kflag(struct_type))
1380 __btf_verifier_log(log,
1381 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1382 __btf_name_by_offset(btf, member->name_off),
1384 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1385 BTF_MEMBER_BIT_OFFSET(member->offset));
1387 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1388 __btf_name_by_offset(btf, member->name_off),
1389 member->type, member->offset);
1392 __btf_verifier_log(log, " ");
1393 va_start(args, fmt);
1394 bpf_verifier_vlog(log, fmt, args);
1398 __btf_verifier_log(log, "\n");
1402 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1403 const struct btf_type *datasec_type,
1404 const struct btf_var_secinfo *vsi,
1405 const char *fmt, ...)
1407 struct bpf_verifier_log *log = &env->log;
1410 if (!bpf_verifier_log_needed(log))
1412 if (log->level == BPF_LOG_KERNEL && !fmt)
1414 if (env->phase != CHECK_META)
1415 btf_verifier_log_type(env, datasec_type, NULL);
1417 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1418 vsi->type, vsi->offset, vsi->size);
1420 __btf_verifier_log(log, " ");
1421 va_start(args, fmt);
1422 bpf_verifier_vlog(log, fmt, args);
1426 __btf_verifier_log(log, "\n");
1429 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1432 struct bpf_verifier_log *log = &env->log;
1433 const struct btf *btf = env->btf;
1434 const struct btf_header *hdr;
1436 if (!bpf_verifier_log_needed(log))
1439 if (log->level == BPF_LOG_KERNEL)
1442 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1443 __btf_verifier_log(log, "version: %u\n", hdr->version);
1444 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1445 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1446 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1447 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1448 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1449 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1450 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1453 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1455 struct btf *btf = env->btf;
1457 if (btf->types_size == btf->nr_types) {
1458 /* Expand 'types' array */
1460 struct btf_type **new_types;
1461 u32 expand_by, new_size;
1463 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1464 btf_verifier_log(env, "Exceeded max num of types");
1468 expand_by = max_t(u32, btf->types_size >> 2, 16);
1469 new_size = min_t(u32, BTF_MAX_TYPE,
1470 btf->types_size + expand_by);
1472 new_types = kvcalloc(new_size, sizeof(*new_types),
1473 GFP_KERNEL | __GFP_NOWARN);
1477 if (btf->nr_types == 0) {
1478 if (!btf->base_btf) {
1479 /* lazily init VOID type */
1480 new_types[0] = &btf_void;
1484 memcpy(new_types, btf->types,
1485 sizeof(*btf->types) * btf->nr_types);
1489 btf->types = new_types;
1490 btf->types_size = new_size;
1493 btf->types[btf->nr_types++] = t;
1498 static int btf_alloc_id(struct btf *btf)
1502 idr_preload(GFP_KERNEL);
1503 spin_lock_bh(&btf_idr_lock);
1504 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1507 spin_unlock_bh(&btf_idr_lock);
1510 if (WARN_ON_ONCE(!id))
1513 return id > 0 ? 0 : id;
1516 static void btf_free_id(struct btf *btf)
1518 unsigned long flags;
1521 * In map-in-map, calling map_delete_elem() on outer
1522 * map will call bpf_map_put on the inner map.
1523 * It will then eventually call btf_free_id()
1524 * on the inner map. Some of the map_delete_elem()
1525 * implementation may have irq disabled, so
1526 * we need to use the _irqsave() version instead
1527 * of the _bh() version.
1529 spin_lock_irqsave(&btf_idr_lock, flags);
1530 idr_remove(&btf_idr, btf->id);
1531 spin_unlock_irqrestore(&btf_idr_lock, flags);
1534 static void btf_free(struct btf *btf)
1537 kvfree(btf->resolved_sizes);
1538 kvfree(btf->resolved_ids);
1543 static void btf_free_rcu(struct rcu_head *rcu)
1545 struct btf *btf = container_of(rcu, struct btf, rcu);
1550 void btf_get(struct btf *btf)
1552 refcount_inc(&btf->refcnt);
1555 void btf_put(struct btf *btf)
1557 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1559 call_rcu(&btf->rcu, btf_free_rcu);
1563 static int env_resolve_init(struct btf_verifier_env *env)
1565 struct btf *btf = env->btf;
1566 u32 nr_types = btf->nr_types;
1567 u32 *resolved_sizes = NULL;
1568 u32 *resolved_ids = NULL;
1569 u8 *visit_states = NULL;
1571 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1572 GFP_KERNEL | __GFP_NOWARN);
1573 if (!resolved_sizes)
1576 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1577 GFP_KERNEL | __GFP_NOWARN);
1581 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1582 GFP_KERNEL | __GFP_NOWARN);
1586 btf->resolved_sizes = resolved_sizes;
1587 btf->resolved_ids = resolved_ids;
1588 env->visit_states = visit_states;
1593 kvfree(resolved_sizes);
1594 kvfree(resolved_ids);
1595 kvfree(visit_states);
1599 static void btf_verifier_env_free(struct btf_verifier_env *env)
1601 kvfree(env->visit_states);
1605 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1606 const struct btf_type *next_type)
1608 switch (env->resolve_mode) {
1610 /* int, enum or void is a sink */
1611 return !btf_type_needs_resolve(next_type);
1613 /* int, enum, void, struct, array, func or func_proto is a sink
1616 return !btf_type_is_modifier(next_type) &&
1617 !btf_type_is_ptr(next_type);
1618 case RESOLVE_STRUCT_OR_ARRAY:
1619 /* int, enum, void, ptr, func or func_proto is a sink
1620 * for struct and array
1622 return !btf_type_is_modifier(next_type) &&
1623 !btf_type_is_array(next_type) &&
1624 !btf_type_is_struct(next_type);
1630 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1633 /* base BTF types should be resolved by now */
1634 if (type_id < env->btf->start_id)
1637 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1640 static int env_stack_push(struct btf_verifier_env *env,
1641 const struct btf_type *t, u32 type_id)
1643 const struct btf *btf = env->btf;
1644 struct resolve_vertex *v;
1646 if (env->top_stack == MAX_RESOLVE_DEPTH)
1649 if (type_id < btf->start_id
1650 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1653 env->visit_states[type_id - btf->start_id] = VISITED;
1655 v = &env->stack[env->top_stack++];
1657 v->type_id = type_id;
1660 if (env->resolve_mode == RESOLVE_TBD) {
1661 if (btf_type_is_ptr(t))
1662 env->resolve_mode = RESOLVE_PTR;
1663 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1664 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1670 static void env_stack_set_next_member(struct btf_verifier_env *env,
1673 env->stack[env->top_stack - 1].next_member = next_member;
1676 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1677 u32 resolved_type_id,
1680 u32 type_id = env->stack[--(env->top_stack)].type_id;
1681 struct btf *btf = env->btf;
1683 type_id -= btf->start_id; /* adjust to local type id */
1684 btf->resolved_sizes[type_id] = resolved_size;
1685 btf->resolved_ids[type_id] = resolved_type_id;
1686 env->visit_states[type_id] = RESOLVED;
1689 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1691 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1694 /* Resolve the size of a passed-in "type"
1696 * type: is an array (e.g. u32 array[x][y])
1697 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1698 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1699 * corresponds to the return type.
1701 * *elem_id: id of u32
1702 * *total_nelems: (x * y). Hence, individual elem size is
1703 * (*type_size / *total_nelems)
1704 * *type_id: id of type if it's changed within the function, 0 if not
1706 * type: is not an array (e.g. const struct X)
1707 * return type: type "struct X"
1708 * *type_size: sizeof(struct X)
1709 * *elem_type: same as return type ("struct X")
1712 * *type_id: id of type if it's changed within the function, 0 if not
1714 static const struct btf_type *
1715 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1716 u32 *type_size, const struct btf_type **elem_type,
1717 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1719 const struct btf_type *array_type = NULL;
1720 const struct btf_array *array = NULL;
1721 u32 i, size, nelems = 1, id = 0;
1723 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1724 switch (BTF_INFO_KIND(type->info)) {
1725 /* type->size can be used */
1727 case BTF_KIND_STRUCT:
1728 case BTF_KIND_UNION:
1730 case BTF_KIND_FLOAT:
1735 size = sizeof(void *);
1739 case BTF_KIND_TYPEDEF:
1740 case BTF_KIND_VOLATILE:
1741 case BTF_KIND_CONST:
1742 case BTF_KIND_RESTRICT:
1743 case BTF_KIND_TYPE_TAG:
1745 type = btf_type_by_id(btf, type->type);
1748 case BTF_KIND_ARRAY:
1751 array = btf_type_array(type);
1752 if (nelems && array->nelems > U32_MAX / nelems)
1753 return ERR_PTR(-EINVAL);
1754 nelems *= array->nelems;
1755 type = btf_type_by_id(btf, array->type);
1758 /* type without size */
1760 return ERR_PTR(-EINVAL);
1764 return ERR_PTR(-EINVAL);
1767 if (nelems && size > U32_MAX / nelems)
1768 return ERR_PTR(-EINVAL);
1770 *type_size = nelems * size;
1772 *total_nelems = nelems;
1776 *elem_id = array ? array->type : 0;
1780 return array_type ? : type;
1783 const struct btf_type *
1784 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1787 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1790 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1792 while (type_id < btf->start_id)
1793 btf = btf->base_btf;
1795 return btf->resolved_ids[type_id - btf->start_id];
1798 /* The input param "type_id" must point to a needs_resolve type */
1799 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1802 *type_id = btf_resolved_type_id(btf, *type_id);
1803 return btf_type_by_id(btf, *type_id);
1806 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1808 while (type_id < btf->start_id)
1809 btf = btf->base_btf;
1811 return btf->resolved_sizes[type_id - btf->start_id];
1814 const struct btf_type *btf_type_id_size(const struct btf *btf,
1815 u32 *type_id, u32 *ret_size)
1817 const struct btf_type *size_type;
1818 u32 size_type_id = *type_id;
1821 size_type = btf_type_by_id(btf, size_type_id);
1822 if (btf_type_nosize_or_null(size_type))
1825 if (btf_type_has_size(size_type)) {
1826 size = size_type->size;
1827 } else if (btf_type_is_array(size_type)) {
1828 size = btf_resolved_type_size(btf, size_type_id);
1829 } else if (btf_type_is_ptr(size_type)) {
1830 size = sizeof(void *);
1832 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1833 !btf_type_is_var(size_type)))
1836 size_type_id = btf_resolved_type_id(btf, size_type_id);
1837 size_type = btf_type_by_id(btf, size_type_id);
1838 if (btf_type_nosize_or_null(size_type))
1840 else if (btf_type_has_size(size_type))
1841 size = size_type->size;
1842 else if (btf_type_is_array(size_type))
1843 size = btf_resolved_type_size(btf, size_type_id);
1844 else if (btf_type_is_ptr(size_type))
1845 size = sizeof(void *);
1850 *type_id = size_type_id;
1857 static int btf_df_check_member(struct btf_verifier_env *env,
1858 const struct btf_type *struct_type,
1859 const struct btf_member *member,
1860 const struct btf_type *member_type)
1862 btf_verifier_log_basic(env, struct_type,
1863 "Unsupported check_member");
1867 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1868 const struct btf_type *struct_type,
1869 const struct btf_member *member,
1870 const struct btf_type *member_type)
1872 btf_verifier_log_basic(env, struct_type,
1873 "Unsupported check_kflag_member");
1877 /* Used for ptr, array struct/union and float type members.
1878 * int, enum and modifier types have their specific callback functions.
1880 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1881 const struct btf_type *struct_type,
1882 const struct btf_member *member,
1883 const struct btf_type *member_type)
1885 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1886 btf_verifier_log_member(env, struct_type, member,
1887 "Invalid member bitfield_size");
1891 /* bitfield size is 0, so member->offset represents bit offset only.
1892 * It is safe to call non kflag check_member variants.
1894 return btf_type_ops(member_type)->check_member(env, struct_type,
1899 static int btf_df_resolve(struct btf_verifier_env *env,
1900 const struct resolve_vertex *v)
1902 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
1906 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
1907 u32 type_id, void *data, u8 bits_offsets,
1908 struct btf_show *show)
1910 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
1913 static int btf_int_check_member(struct btf_verifier_env *env,
1914 const struct btf_type *struct_type,
1915 const struct btf_member *member,
1916 const struct btf_type *member_type)
1918 u32 int_data = btf_type_int(member_type);
1919 u32 struct_bits_off = member->offset;
1920 u32 struct_size = struct_type->size;
1924 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
1925 btf_verifier_log_member(env, struct_type, member,
1926 "bits_offset exceeds U32_MAX");
1930 struct_bits_off += BTF_INT_OFFSET(int_data);
1931 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1932 nr_copy_bits = BTF_INT_BITS(int_data) +
1933 BITS_PER_BYTE_MASKED(struct_bits_off);
1935 if (nr_copy_bits > BITS_PER_U128) {
1936 btf_verifier_log_member(env, struct_type, member,
1937 "nr_copy_bits exceeds 128");
1941 if (struct_size < bytes_offset ||
1942 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1943 btf_verifier_log_member(env, struct_type, member,
1944 "Member exceeds struct_size");
1951 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
1952 const struct btf_type *struct_type,
1953 const struct btf_member *member,
1954 const struct btf_type *member_type)
1956 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
1957 u32 int_data = btf_type_int(member_type);
1958 u32 struct_size = struct_type->size;
1961 /* a regular int type is required for the kflag int member */
1962 if (!btf_type_int_is_regular(member_type)) {
1963 btf_verifier_log_member(env, struct_type, member,
1964 "Invalid member base type");
1968 /* check sanity of bitfield size */
1969 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
1970 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
1971 nr_int_data_bits = BTF_INT_BITS(int_data);
1973 /* Not a bitfield member, member offset must be at byte
1976 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
1977 btf_verifier_log_member(env, struct_type, member,
1978 "Invalid member offset");
1982 nr_bits = nr_int_data_bits;
1983 } else if (nr_bits > nr_int_data_bits) {
1984 btf_verifier_log_member(env, struct_type, member,
1985 "Invalid member bitfield_size");
1989 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1990 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
1991 if (nr_copy_bits > BITS_PER_U128) {
1992 btf_verifier_log_member(env, struct_type, member,
1993 "nr_copy_bits exceeds 128");
1997 if (struct_size < bytes_offset ||
1998 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1999 btf_verifier_log_member(env, struct_type, member,
2000 "Member exceeds struct_size");
2007 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2008 const struct btf_type *t,
2011 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2014 if (meta_left < meta_needed) {
2015 btf_verifier_log_basic(env, t,
2016 "meta_left:%u meta_needed:%u",
2017 meta_left, meta_needed);
2021 if (btf_type_vlen(t)) {
2022 btf_verifier_log_type(env, t, "vlen != 0");
2026 if (btf_type_kflag(t)) {
2027 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2031 int_data = btf_type_int(t);
2032 if (int_data & ~BTF_INT_MASK) {
2033 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2038 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2040 if (nr_bits > BITS_PER_U128) {
2041 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2046 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2047 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2052 * Only one of the encoding bits is allowed and it
2053 * should be sufficient for the pretty print purpose (i.e. decoding).
2054 * Multiple bits can be allowed later if it is found
2055 * to be insufficient.
2057 encoding = BTF_INT_ENCODING(int_data);
2059 encoding != BTF_INT_SIGNED &&
2060 encoding != BTF_INT_CHAR &&
2061 encoding != BTF_INT_BOOL) {
2062 btf_verifier_log_type(env, t, "Unsupported encoding");
2066 btf_verifier_log_type(env, t, NULL);
2071 static void btf_int_log(struct btf_verifier_env *env,
2072 const struct btf_type *t)
2074 int int_data = btf_type_int(t);
2076 btf_verifier_log(env,
2077 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2078 t->size, BTF_INT_OFFSET(int_data),
2079 BTF_INT_BITS(int_data),
2080 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2083 static void btf_int128_print(struct btf_show *show, void *data)
2085 /* data points to a __int128 number.
2087 * int128_num = *(__int128 *)data;
2088 * The below formulas shows what upper_num and lower_num represents:
2089 * upper_num = int128_num >> 64;
2090 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2092 u64 upper_num, lower_num;
2094 #ifdef __BIG_ENDIAN_BITFIELD
2095 upper_num = *(u64 *)data;
2096 lower_num = *(u64 *)(data + 8);
2098 upper_num = *(u64 *)(data + 8);
2099 lower_num = *(u64 *)data;
2102 btf_show_type_value(show, "0x%llx", lower_num);
2104 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2108 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2109 u16 right_shift_bits)
2111 u64 upper_num, lower_num;
2113 #ifdef __BIG_ENDIAN_BITFIELD
2114 upper_num = print_num[0];
2115 lower_num = print_num[1];
2117 upper_num = print_num[1];
2118 lower_num = print_num[0];
2121 /* shake out un-needed bits by shift/or operations */
2122 if (left_shift_bits >= 64) {
2123 upper_num = lower_num << (left_shift_bits - 64);
2126 upper_num = (upper_num << left_shift_bits) |
2127 (lower_num >> (64 - left_shift_bits));
2128 lower_num = lower_num << left_shift_bits;
2131 if (right_shift_bits >= 64) {
2132 lower_num = upper_num >> (right_shift_bits - 64);
2135 lower_num = (lower_num >> right_shift_bits) |
2136 (upper_num << (64 - right_shift_bits));
2137 upper_num = upper_num >> right_shift_bits;
2140 #ifdef __BIG_ENDIAN_BITFIELD
2141 print_num[0] = upper_num;
2142 print_num[1] = lower_num;
2144 print_num[0] = lower_num;
2145 print_num[1] = upper_num;
2149 static void btf_bitfield_show(void *data, u8 bits_offset,
2150 u8 nr_bits, struct btf_show *show)
2152 u16 left_shift_bits, right_shift_bits;
2155 u64 print_num[2] = {};
2157 nr_copy_bits = nr_bits + bits_offset;
2158 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2160 memcpy(print_num, data, nr_copy_bytes);
2162 #ifdef __BIG_ENDIAN_BITFIELD
2163 left_shift_bits = bits_offset;
2165 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2167 right_shift_bits = BITS_PER_U128 - nr_bits;
2169 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2170 btf_int128_print(show, print_num);
2174 static void btf_int_bits_show(const struct btf *btf,
2175 const struct btf_type *t,
2176 void *data, u8 bits_offset,
2177 struct btf_show *show)
2179 u32 int_data = btf_type_int(t);
2180 u8 nr_bits = BTF_INT_BITS(int_data);
2181 u8 total_bits_offset;
2184 * bits_offset is at most 7.
2185 * BTF_INT_OFFSET() cannot exceed 128 bits.
2187 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2188 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2189 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2190 btf_bitfield_show(data, bits_offset, nr_bits, show);
2193 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2194 u32 type_id, void *data, u8 bits_offset,
2195 struct btf_show *show)
2197 u32 int_data = btf_type_int(t);
2198 u8 encoding = BTF_INT_ENCODING(int_data);
2199 bool sign = encoding & BTF_INT_SIGNED;
2200 u8 nr_bits = BTF_INT_BITS(int_data);
2203 safe_data = btf_show_start_type(show, t, type_id, data);
2207 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2208 BITS_PER_BYTE_MASKED(nr_bits)) {
2209 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2215 btf_int128_print(show, safe_data);
2219 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2221 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2225 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2227 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2231 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2233 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2236 if (show->state.array_encoding == BTF_INT_CHAR) {
2237 /* check for null terminator */
2238 if (show->state.array_terminated)
2240 if (*(char *)data == '\0') {
2241 show->state.array_terminated = 1;
2244 if (isprint(*(char *)data)) {
2245 btf_show_type_value(show, "'%c'",
2246 *(char *)safe_data);
2251 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2253 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2256 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2260 btf_show_end_type(show);
2263 static const struct btf_kind_operations int_ops = {
2264 .check_meta = btf_int_check_meta,
2265 .resolve = btf_df_resolve,
2266 .check_member = btf_int_check_member,
2267 .check_kflag_member = btf_int_check_kflag_member,
2268 .log_details = btf_int_log,
2269 .show = btf_int_show,
2272 static int btf_modifier_check_member(struct btf_verifier_env *env,
2273 const struct btf_type *struct_type,
2274 const struct btf_member *member,
2275 const struct btf_type *member_type)
2277 const struct btf_type *resolved_type;
2278 u32 resolved_type_id = member->type;
2279 struct btf_member resolved_member;
2280 struct btf *btf = env->btf;
2282 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2283 if (!resolved_type) {
2284 btf_verifier_log_member(env, struct_type, member,
2289 resolved_member = *member;
2290 resolved_member.type = resolved_type_id;
2292 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2297 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2298 const struct btf_type *struct_type,
2299 const struct btf_member *member,
2300 const struct btf_type *member_type)
2302 const struct btf_type *resolved_type;
2303 u32 resolved_type_id = member->type;
2304 struct btf_member resolved_member;
2305 struct btf *btf = env->btf;
2307 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2308 if (!resolved_type) {
2309 btf_verifier_log_member(env, struct_type, member,
2314 resolved_member = *member;
2315 resolved_member.type = resolved_type_id;
2317 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2322 static int btf_ptr_check_member(struct btf_verifier_env *env,
2323 const struct btf_type *struct_type,
2324 const struct btf_member *member,
2325 const struct btf_type *member_type)
2327 u32 struct_size, struct_bits_off, bytes_offset;
2329 struct_size = struct_type->size;
2330 struct_bits_off = member->offset;
2331 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2333 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2334 btf_verifier_log_member(env, struct_type, member,
2335 "Member is not byte aligned");
2339 if (struct_size - bytes_offset < sizeof(void *)) {
2340 btf_verifier_log_member(env, struct_type, member,
2341 "Member exceeds struct_size");
2348 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2349 const struct btf_type *t,
2354 if (btf_type_vlen(t)) {
2355 btf_verifier_log_type(env, t, "vlen != 0");
2359 if (btf_type_kflag(t)) {
2360 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2364 if (!BTF_TYPE_ID_VALID(t->type)) {
2365 btf_verifier_log_type(env, t, "Invalid type_id");
2369 /* typedef/type_tag type must have a valid name, and other ref types,
2370 * volatile, const, restrict, should have a null name.
2372 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2374 !btf_name_valid_identifier(env->btf, t->name_off)) {
2375 btf_verifier_log_type(env, t, "Invalid name");
2378 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2379 value = btf_name_by_offset(env->btf, t->name_off);
2380 if (!value || !value[0]) {
2381 btf_verifier_log_type(env, t, "Invalid name");
2386 btf_verifier_log_type(env, t, "Invalid name");
2391 btf_verifier_log_type(env, t, NULL);
2396 static int btf_modifier_resolve(struct btf_verifier_env *env,
2397 const struct resolve_vertex *v)
2399 const struct btf_type *t = v->t;
2400 const struct btf_type *next_type;
2401 u32 next_type_id = t->type;
2402 struct btf *btf = env->btf;
2404 next_type = btf_type_by_id(btf, next_type_id);
2405 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2406 btf_verifier_log_type(env, v->t, "Invalid type_id");
2410 if (!env_type_is_resolve_sink(env, next_type) &&
2411 !env_type_is_resolved(env, next_type_id))
2412 return env_stack_push(env, next_type, next_type_id);
2414 /* Figure out the resolved next_type_id with size.
2415 * They will be stored in the current modifier's
2416 * resolved_ids and resolved_sizes such that it can
2417 * save us a few type-following when we use it later (e.g. in
2420 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2421 if (env_type_is_resolved(env, next_type_id))
2422 next_type = btf_type_id_resolve(btf, &next_type_id);
2424 /* "typedef void new_void", "const void"...etc */
2425 if (!btf_type_is_void(next_type) &&
2426 !btf_type_is_fwd(next_type) &&
2427 !btf_type_is_func_proto(next_type)) {
2428 btf_verifier_log_type(env, v->t, "Invalid type_id");
2433 env_stack_pop_resolved(env, next_type_id, 0);
2438 static int btf_var_resolve(struct btf_verifier_env *env,
2439 const struct resolve_vertex *v)
2441 const struct btf_type *next_type;
2442 const struct btf_type *t = v->t;
2443 u32 next_type_id = t->type;
2444 struct btf *btf = env->btf;
2446 next_type = btf_type_by_id(btf, next_type_id);
2447 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2448 btf_verifier_log_type(env, v->t, "Invalid type_id");
2452 if (!env_type_is_resolve_sink(env, next_type) &&
2453 !env_type_is_resolved(env, next_type_id))
2454 return env_stack_push(env, next_type, next_type_id);
2456 if (btf_type_is_modifier(next_type)) {
2457 const struct btf_type *resolved_type;
2458 u32 resolved_type_id;
2460 resolved_type_id = next_type_id;
2461 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2463 if (btf_type_is_ptr(resolved_type) &&
2464 !env_type_is_resolve_sink(env, resolved_type) &&
2465 !env_type_is_resolved(env, resolved_type_id))
2466 return env_stack_push(env, resolved_type,
2470 /* We must resolve to something concrete at this point, no
2471 * forward types or similar that would resolve to size of
2474 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2475 btf_verifier_log_type(env, v->t, "Invalid type_id");
2479 env_stack_pop_resolved(env, next_type_id, 0);
2484 static int btf_ptr_resolve(struct btf_verifier_env *env,
2485 const struct resolve_vertex *v)
2487 const struct btf_type *next_type;
2488 const struct btf_type *t = v->t;
2489 u32 next_type_id = t->type;
2490 struct btf *btf = env->btf;
2492 next_type = btf_type_by_id(btf, next_type_id);
2493 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2494 btf_verifier_log_type(env, v->t, "Invalid type_id");
2498 if (!env_type_is_resolve_sink(env, next_type) &&
2499 !env_type_is_resolved(env, next_type_id))
2500 return env_stack_push(env, next_type, next_type_id);
2502 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2503 * the modifier may have stopped resolving when it was resolved
2504 * to a ptr (last-resolved-ptr).
2506 * We now need to continue from the last-resolved-ptr to
2507 * ensure the last-resolved-ptr will not referring back to
2508 * the currenct ptr (t).
2510 if (btf_type_is_modifier(next_type)) {
2511 const struct btf_type *resolved_type;
2512 u32 resolved_type_id;
2514 resolved_type_id = next_type_id;
2515 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2517 if (btf_type_is_ptr(resolved_type) &&
2518 !env_type_is_resolve_sink(env, resolved_type) &&
2519 !env_type_is_resolved(env, resolved_type_id))
2520 return env_stack_push(env, resolved_type,
2524 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2525 if (env_type_is_resolved(env, next_type_id))
2526 next_type = btf_type_id_resolve(btf, &next_type_id);
2528 if (!btf_type_is_void(next_type) &&
2529 !btf_type_is_fwd(next_type) &&
2530 !btf_type_is_func_proto(next_type)) {
2531 btf_verifier_log_type(env, v->t, "Invalid type_id");
2536 env_stack_pop_resolved(env, next_type_id, 0);
2541 static void btf_modifier_show(const struct btf *btf,
2542 const struct btf_type *t,
2543 u32 type_id, void *data,
2544 u8 bits_offset, struct btf_show *show)
2546 if (btf->resolved_ids)
2547 t = btf_type_id_resolve(btf, &type_id);
2549 t = btf_type_skip_modifiers(btf, type_id, NULL);
2551 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2554 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2555 u32 type_id, void *data, u8 bits_offset,
2556 struct btf_show *show)
2558 t = btf_type_id_resolve(btf, &type_id);
2560 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2563 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2564 u32 type_id, void *data, u8 bits_offset,
2565 struct btf_show *show)
2569 safe_data = btf_show_start_type(show, t, type_id, data);
2573 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2574 if (show->flags & BTF_SHOW_PTR_RAW)
2575 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2577 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2578 btf_show_end_type(show);
2581 static void btf_ref_type_log(struct btf_verifier_env *env,
2582 const struct btf_type *t)
2584 btf_verifier_log(env, "type_id=%u", t->type);
2587 static struct btf_kind_operations modifier_ops = {
2588 .check_meta = btf_ref_type_check_meta,
2589 .resolve = btf_modifier_resolve,
2590 .check_member = btf_modifier_check_member,
2591 .check_kflag_member = btf_modifier_check_kflag_member,
2592 .log_details = btf_ref_type_log,
2593 .show = btf_modifier_show,
2596 static struct btf_kind_operations ptr_ops = {
2597 .check_meta = btf_ref_type_check_meta,
2598 .resolve = btf_ptr_resolve,
2599 .check_member = btf_ptr_check_member,
2600 .check_kflag_member = btf_generic_check_kflag_member,
2601 .log_details = btf_ref_type_log,
2602 .show = btf_ptr_show,
2605 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2606 const struct btf_type *t,
2609 if (btf_type_vlen(t)) {
2610 btf_verifier_log_type(env, t, "vlen != 0");
2615 btf_verifier_log_type(env, t, "type != 0");
2619 /* fwd type must have a valid name */
2621 !btf_name_valid_identifier(env->btf, t->name_off)) {
2622 btf_verifier_log_type(env, t, "Invalid name");
2626 btf_verifier_log_type(env, t, NULL);
2631 static void btf_fwd_type_log(struct btf_verifier_env *env,
2632 const struct btf_type *t)
2634 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2637 static struct btf_kind_operations fwd_ops = {
2638 .check_meta = btf_fwd_check_meta,
2639 .resolve = btf_df_resolve,
2640 .check_member = btf_df_check_member,
2641 .check_kflag_member = btf_df_check_kflag_member,
2642 .log_details = btf_fwd_type_log,
2643 .show = btf_df_show,
2646 static int btf_array_check_member(struct btf_verifier_env *env,
2647 const struct btf_type *struct_type,
2648 const struct btf_member *member,
2649 const struct btf_type *member_type)
2651 u32 struct_bits_off = member->offset;
2652 u32 struct_size, bytes_offset;
2653 u32 array_type_id, array_size;
2654 struct btf *btf = env->btf;
2656 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2657 btf_verifier_log_member(env, struct_type, member,
2658 "Member is not byte aligned");
2662 array_type_id = member->type;
2663 btf_type_id_size(btf, &array_type_id, &array_size);
2664 struct_size = struct_type->size;
2665 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2666 if (struct_size - bytes_offset < array_size) {
2667 btf_verifier_log_member(env, struct_type, member,
2668 "Member exceeds struct_size");
2675 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2676 const struct btf_type *t,
2679 const struct btf_array *array = btf_type_array(t);
2680 u32 meta_needed = sizeof(*array);
2682 if (meta_left < meta_needed) {
2683 btf_verifier_log_basic(env, t,
2684 "meta_left:%u meta_needed:%u",
2685 meta_left, meta_needed);
2689 /* array type should not have a name */
2691 btf_verifier_log_type(env, t, "Invalid name");
2695 if (btf_type_vlen(t)) {
2696 btf_verifier_log_type(env, t, "vlen != 0");
2700 if (btf_type_kflag(t)) {
2701 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2706 btf_verifier_log_type(env, t, "size != 0");
2710 /* Array elem type and index type cannot be in type void,
2711 * so !array->type and !array->index_type are not allowed.
2713 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2714 btf_verifier_log_type(env, t, "Invalid elem");
2718 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2719 btf_verifier_log_type(env, t, "Invalid index");
2723 btf_verifier_log_type(env, t, NULL);
2728 static int btf_array_resolve(struct btf_verifier_env *env,
2729 const struct resolve_vertex *v)
2731 const struct btf_array *array = btf_type_array(v->t);
2732 const struct btf_type *elem_type, *index_type;
2733 u32 elem_type_id, index_type_id;
2734 struct btf *btf = env->btf;
2737 /* Check array->index_type */
2738 index_type_id = array->index_type;
2739 index_type = btf_type_by_id(btf, index_type_id);
2740 if (btf_type_nosize_or_null(index_type) ||
2741 btf_type_is_resolve_source_only(index_type)) {
2742 btf_verifier_log_type(env, v->t, "Invalid index");
2746 if (!env_type_is_resolve_sink(env, index_type) &&
2747 !env_type_is_resolved(env, index_type_id))
2748 return env_stack_push(env, index_type, index_type_id);
2750 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2751 if (!index_type || !btf_type_is_int(index_type) ||
2752 !btf_type_int_is_regular(index_type)) {
2753 btf_verifier_log_type(env, v->t, "Invalid index");
2757 /* Check array->type */
2758 elem_type_id = array->type;
2759 elem_type = btf_type_by_id(btf, elem_type_id);
2760 if (btf_type_nosize_or_null(elem_type) ||
2761 btf_type_is_resolve_source_only(elem_type)) {
2762 btf_verifier_log_type(env, v->t,
2767 if (!env_type_is_resolve_sink(env, elem_type) &&
2768 !env_type_is_resolved(env, elem_type_id))
2769 return env_stack_push(env, elem_type, elem_type_id);
2771 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2773 btf_verifier_log_type(env, v->t, "Invalid elem");
2777 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2778 btf_verifier_log_type(env, v->t, "Invalid array of int");
2782 if (array->nelems && elem_size > U32_MAX / array->nelems) {
2783 btf_verifier_log_type(env, v->t,
2784 "Array size overflows U32_MAX");
2788 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2793 static void btf_array_log(struct btf_verifier_env *env,
2794 const struct btf_type *t)
2796 const struct btf_array *array = btf_type_array(t);
2798 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2799 array->type, array->index_type, array->nelems);
2802 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2803 u32 type_id, void *data, u8 bits_offset,
2804 struct btf_show *show)
2806 const struct btf_array *array = btf_type_array(t);
2807 const struct btf_kind_operations *elem_ops;
2808 const struct btf_type *elem_type;
2809 u32 i, elem_size = 0, elem_type_id;
2812 elem_type_id = array->type;
2813 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2814 if (elem_type && btf_type_has_size(elem_type))
2815 elem_size = elem_type->size;
2817 if (elem_type && btf_type_is_int(elem_type)) {
2818 u32 int_type = btf_type_int(elem_type);
2820 encoding = BTF_INT_ENCODING(int_type);
2823 * BTF_INT_CHAR encoding never seems to be set for
2824 * char arrays, so if size is 1 and element is
2825 * printable as a char, we'll do that.
2828 encoding = BTF_INT_CHAR;
2831 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2836 elem_ops = btf_type_ops(elem_type);
2838 for (i = 0; i < array->nelems; i++) {
2840 btf_show_start_array_member(show);
2842 elem_ops->show(btf, elem_type, elem_type_id, data,
2846 btf_show_end_array_member(show);
2848 if (show->state.array_terminated)
2852 btf_show_end_array_type(show);
2855 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2856 u32 type_id, void *data, u8 bits_offset,
2857 struct btf_show *show)
2859 const struct btf_member *m = show->state.member;
2862 * First check if any members would be shown (are non-zero).
2863 * See comments above "struct btf_show" definition for more
2864 * details on how this works at a high-level.
2866 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2867 if (!show->state.depth_check) {
2868 show->state.depth_check = show->state.depth + 1;
2869 show->state.depth_to_show = 0;
2871 __btf_array_show(btf, t, type_id, data, bits_offset, show);
2872 show->state.member = m;
2874 if (show->state.depth_check != show->state.depth + 1)
2876 show->state.depth_check = 0;
2878 if (show->state.depth_to_show <= show->state.depth)
2881 * Reaching here indicates we have recursed and found
2882 * non-zero array member(s).
2885 __btf_array_show(btf, t, type_id, data, bits_offset, show);
2888 static struct btf_kind_operations array_ops = {
2889 .check_meta = btf_array_check_meta,
2890 .resolve = btf_array_resolve,
2891 .check_member = btf_array_check_member,
2892 .check_kflag_member = btf_generic_check_kflag_member,
2893 .log_details = btf_array_log,
2894 .show = btf_array_show,
2897 static int btf_struct_check_member(struct btf_verifier_env *env,
2898 const struct btf_type *struct_type,
2899 const struct btf_member *member,
2900 const struct btf_type *member_type)
2902 u32 struct_bits_off = member->offset;
2903 u32 struct_size, bytes_offset;
2905 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2906 btf_verifier_log_member(env, struct_type, member,
2907 "Member is not byte aligned");
2911 struct_size = struct_type->size;
2912 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2913 if (struct_size - bytes_offset < member_type->size) {
2914 btf_verifier_log_member(env, struct_type, member,
2915 "Member exceeds struct_size");
2922 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
2923 const struct btf_type *t,
2926 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
2927 const struct btf_member *member;
2928 u32 meta_needed, last_offset;
2929 struct btf *btf = env->btf;
2930 u32 struct_size = t->size;
2934 meta_needed = btf_type_vlen(t) * sizeof(*member);
2935 if (meta_left < meta_needed) {
2936 btf_verifier_log_basic(env, t,
2937 "meta_left:%u meta_needed:%u",
2938 meta_left, meta_needed);
2942 /* struct type either no name or a valid one */
2944 !btf_name_valid_identifier(env->btf, t->name_off)) {
2945 btf_verifier_log_type(env, t, "Invalid name");
2949 btf_verifier_log_type(env, t, NULL);
2952 for_each_member(i, t, member) {
2953 if (!btf_name_offset_valid(btf, member->name_off)) {
2954 btf_verifier_log_member(env, t, member,
2955 "Invalid member name_offset:%u",
2960 /* struct member either no name or a valid one */
2961 if (member->name_off &&
2962 !btf_name_valid_identifier(btf, member->name_off)) {
2963 btf_verifier_log_member(env, t, member, "Invalid name");
2966 /* A member cannot be in type void */
2967 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
2968 btf_verifier_log_member(env, t, member,
2973 offset = __btf_member_bit_offset(t, member);
2974 if (is_union && offset) {
2975 btf_verifier_log_member(env, t, member,
2976 "Invalid member bits_offset");
2981 * ">" instead of ">=" because the last member could be
2984 if (last_offset > offset) {
2985 btf_verifier_log_member(env, t, member,
2986 "Invalid member bits_offset");
2990 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
2991 btf_verifier_log_member(env, t, member,
2992 "Member bits_offset exceeds its struct size");
2996 btf_verifier_log_member(env, t, member, NULL);
2997 last_offset = offset;
3003 static int btf_struct_resolve(struct btf_verifier_env *env,
3004 const struct resolve_vertex *v)
3006 const struct btf_member *member;
3010 /* Before continue resolving the next_member,
3011 * ensure the last member is indeed resolved to a
3012 * type with size info.
3014 if (v->next_member) {
3015 const struct btf_type *last_member_type;
3016 const struct btf_member *last_member;
3017 u16 last_member_type_id;
3019 last_member = btf_type_member(v->t) + v->next_member - 1;
3020 last_member_type_id = last_member->type;
3021 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3022 last_member_type_id)))
3025 last_member_type = btf_type_by_id(env->btf,
3026 last_member_type_id);
3027 if (btf_type_kflag(v->t))
3028 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3032 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3039 for_each_member_from(i, v->next_member, v->t, member) {
3040 u32 member_type_id = member->type;
3041 const struct btf_type *member_type = btf_type_by_id(env->btf,
3044 if (btf_type_nosize_or_null(member_type) ||
3045 btf_type_is_resolve_source_only(member_type)) {
3046 btf_verifier_log_member(env, v->t, member,
3051 if (!env_type_is_resolve_sink(env, member_type) &&
3052 !env_type_is_resolved(env, member_type_id)) {
3053 env_stack_set_next_member(env, i + 1);
3054 return env_stack_push(env, member_type, member_type_id);
3057 if (btf_type_kflag(v->t))
3058 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3062 err = btf_type_ops(member_type)->check_member(env, v->t,
3069 env_stack_pop_resolved(env, 0, 0);
3074 static void btf_struct_log(struct btf_verifier_env *env,
3075 const struct btf_type *t)
3077 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3080 static int btf_find_struct_field(const struct btf *btf, const struct btf_type *t,
3081 const char *name, int sz, int align)
3083 const struct btf_member *member;
3084 u32 i, off = -ENOENT;
3086 for_each_member(i, t, member) {
3087 const struct btf_type *member_type = btf_type_by_id(btf,
3089 if (!__btf_type_is_struct(member_type))
3091 if (member_type->size != sz)
3093 if (strcmp(__btf_name_by_offset(btf, member_type->name_off), name))
3096 /* only one such field is allowed */
3098 off = __btf_member_bit_offset(t, member);
3100 /* valid C code cannot generate such BTF */
3109 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3110 const char *name, int sz, int align)
3112 const struct btf_var_secinfo *vsi;
3113 u32 i, off = -ENOENT;
3115 for_each_vsi(i, t, vsi) {
3116 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3117 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3119 if (!__btf_type_is_struct(var_type))
3121 if (var_type->size != sz)
3123 if (vsi->size != sz)
3125 if (strcmp(__btf_name_by_offset(btf, var_type->name_off), name))
3128 /* only one such field is allowed */
3137 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3138 const char *name, int sz, int align)
3141 if (__btf_type_is_struct(t))
3142 return btf_find_struct_field(btf, t, name, sz, align);
3143 else if (btf_type_is_datasec(t))
3144 return btf_find_datasec_var(btf, t, name, sz, align);
3148 /* find 'struct bpf_spin_lock' in map value.
3149 * return >= 0 offset if found
3150 * and < 0 in case of error
3152 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3154 return btf_find_field(btf, t, "bpf_spin_lock",
3155 sizeof(struct bpf_spin_lock),
3156 __alignof__(struct bpf_spin_lock));
3159 int btf_find_timer(const struct btf *btf, const struct btf_type *t)
3161 return btf_find_field(btf, t, "bpf_timer",
3162 sizeof(struct bpf_timer),
3163 __alignof__(struct bpf_timer));
3166 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3167 u32 type_id, void *data, u8 bits_offset,
3168 struct btf_show *show)
3170 const struct btf_member *member;
3174 safe_data = btf_show_start_struct_type(show, t, type_id, data);
3178 for_each_member(i, t, member) {
3179 const struct btf_type *member_type = btf_type_by_id(btf,
3181 const struct btf_kind_operations *ops;
3182 u32 member_offset, bitfield_size;
3186 btf_show_start_member(show, member);
3188 member_offset = __btf_member_bit_offset(t, member);
3189 bitfield_size = __btf_member_bitfield_size(t, member);
3190 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3191 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3192 if (bitfield_size) {
3193 safe_data = btf_show_start_type(show, member_type,
3195 data + bytes_offset);
3197 btf_bitfield_show(safe_data,
3199 bitfield_size, show);
3200 btf_show_end_type(show);
3202 ops = btf_type_ops(member_type);
3203 ops->show(btf, member_type, member->type,
3204 data + bytes_offset, bits8_offset, show);
3207 btf_show_end_member(show);
3210 btf_show_end_struct_type(show);
3213 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3214 u32 type_id, void *data, u8 bits_offset,
3215 struct btf_show *show)
3217 const struct btf_member *m = show->state.member;
3220 * First check if any members would be shown (are non-zero).
3221 * See comments above "struct btf_show" definition for more
3222 * details on how this works at a high-level.
3224 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3225 if (!show->state.depth_check) {
3226 show->state.depth_check = show->state.depth + 1;
3227 show->state.depth_to_show = 0;
3229 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3230 /* Restore saved member data here */
3231 show->state.member = m;
3232 if (show->state.depth_check != show->state.depth + 1)
3234 show->state.depth_check = 0;
3236 if (show->state.depth_to_show <= show->state.depth)
3239 * Reaching here indicates we have recursed and found
3240 * non-zero child values.
3244 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3247 static struct btf_kind_operations struct_ops = {
3248 .check_meta = btf_struct_check_meta,
3249 .resolve = btf_struct_resolve,
3250 .check_member = btf_struct_check_member,
3251 .check_kflag_member = btf_generic_check_kflag_member,
3252 .log_details = btf_struct_log,
3253 .show = btf_struct_show,
3256 static int btf_enum_check_member(struct btf_verifier_env *env,
3257 const struct btf_type *struct_type,
3258 const struct btf_member *member,
3259 const struct btf_type *member_type)
3261 u32 struct_bits_off = member->offset;
3262 u32 struct_size, bytes_offset;
3264 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3265 btf_verifier_log_member(env, struct_type, member,
3266 "Member is not byte aligned");
3270 struct_size = struct_type->size;
3271 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3272 if (struct_size - bytes_offset < member_type->size) {
3273 btf_verifier_log_member(env, struct_type, member,
3274 "Member exceeds struct_size");
3281 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3282 const struct btf_type *struct_type,
3283 const struct btf_member *member,
3284 const struct btf_type *member_type)
3286 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3287 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3289 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3290 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3292 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3293 btf_verifier_log_member(env, struct_type, member,
3294 "Member is not byte aligned");
3298 nr_bits = int_bitsize;
3299 } else if (nr_bits > int_bitsize) {
3300 btf_verifier_log_member(env, struct_type, member,
3301 "Invalid member bitfield_size");
3305 struct_size = struct_type->size;
3306 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3307 if (struct_size < bytes_end) {
3308 btf_verifier_log_member(env, struct_type, member,
3309 "Member exceeds struct_size");
3316 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3317 const struct btf_type *t,
3320 const struct btf_enum *enums = btf_type_enum(t);
3321 struct btf *btf = env->btf;
3325 nr_enums = btf_type_vlen(t);
3326 meta_needed = nr_enums * sizeof(*enums);
3328 if (meta_left < meta_needed) {
3329 btf_verifier_log_basic(env, t,
3330 "meta_left:%u meta_needed:%u",
3331 meta_left, meta_needed);
3335 if (btf_type_kflag(t)) {
3336 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3340 if (t->size > 8 || !is_power_of_2(t->size)) {
3341 btf_verifier_log_type(env, t, "Unexpected size");
3345 /* enum type either no name or a valid one */
3347 !btf_name_valid_identifier(env->btf, t->name_off)) {
3348 btf_verifier_log_type(env, t, "Invalid name");
3352 btf_verifier_log_type(env, t, NULL);
3354 for (i = 0; i < nr_enums; i++) {
3355 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3356 btf_verifier_log(env, "\tInvalid name_offset:%u",
3361 /* enum member must have a valid name */
3362 if (!enums[i].name_off ||
3363 !btf_name_valid_identifier(btf, enums[i].name_off)) {
3364 btf_verifier_log_type(env, t, "Invalid name");
3368 if (env->log.level == BPF_LOG_KERNEL)
3370 btf_verifier_log(env, "\t%s val=%d\n",
3371 __btf_name_by_offset(btf, enums[i].name_off),
3378 static void btf_enum_log(struct btf_verifier_env *env,
3379 const struct btf_type *t)
3381 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3384 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3385 u32 type_id, void *data, u8 bits_offset,
3386 struct btf_show *show)
3388 const struct btf_enum *enums = btf_type_enum(t);
3389 u32 i, nr_enums = btf_type_vlen(t);
3393 safe_data = btf_show_start_type(show, t, type_id, data);
3397 v = *(int *)safe_data;
3399 for (i = 0; i < nr_enums; i++) {
3400 if (v != enums[i].val)
3403 btf_show_type_value(show, "%s",
3404 __btf_name_by_offset(btf,
3405 enums[i].name_off));
3407 btf_show_end_type(show);
3411 btf_show_type_value(show, "%d", v);
3412 btf_show_end_type(show);
3415 static struct btf_kind_operations enum_ops = {
3416 .check_meta = btf_enum_check_meta,
3417 .resolve = btf_df_resolve,
3418 .check_member = btf_enum_check_member,
3419 .check_kflag_member = btf_enum_check_kflag_member,
3420 .log_details = btf_enum_log,
3421 .show = btf_enum_show,
3424 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3425 const struct btf_type *t,
3428 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3430 if (meta_left < meta_needed) {
3431 btf_verifier_log_basic(env, t,
3432 "meta_left:%u meta_needed:%u",
3433 meta_left, meta_needed);
3438 btf_verifier_log_type(env, t, "Invalid name");
3442 if (btf_type_kflag(t)) {
3443 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3447 btf_verifier_log_type(env, t, NULL);
3452 static void btf_func_proto_log(struct btf_verifier_env *env,
3453 const struct btf_type *t)
3455 const struct btf_param *args = (const struct btf_param *)(t + 1);
3456 u16 nr_args = btf_type_vlen(t), i;
3458 btf_verifier_log(env, "return=%u args=(", t->type);
3460 btf_verifier_log(env, "void");
3464 if (nr_args == 1 && !args[0].type) {
3465 /* Only one vararg */
3466 btf_verifier_log(env, "vararg");
3470 btf_verifier_log(env, "%u %s", args[0].type,
3471 __btf_name_by_offset(env->btf,
3473 for (i = 1; i < nr_args - 1; i++)
3474 btf_verifier_log(env, ", %u %s", args[i].type,
3475 __btf_name_by_offset(env->btf,
3479 const struct btf_param *last_arg = &args[nr_args - 1];
3482 btf_verifier_log(env, ", %u %s", last_arg->type,
3483 __btf_name_by_offset(env->btf,
3484 last_arg->name_off));
3486 btf_verifier_log(env, ", vararg");
3490 btf_verifier_log(env, ")");
3493 static struct btf_kind_operations func_proto_ops = {
3494 .check_meta = btf_func_proto_check_meta,
3495 .resolve = btf_df_resolve,
3497 * BTF_KIND_FUNC_PROTO cannot be directly referred by
3498 * a struct's member.
3500 * It should be a function pointer instead.
3501 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3503 * Hence, there is no btf_func_check_member().
3505 .check_member = btf_df_check_member,
3506 .check_kflag_member = btf_df_check_kflag_member,
3507 .log_details = btf_func_proto_log,
3508 .show = btf_df_show,
3511 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3512 const struct btf_type *t,
3516 !btf_name_valid_identifier(env->btf, t->name_off)) {
3517 btf_verifier_log_type(env, t, "Invalid name");
3521 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3522 btf_verifier_log_type(env, t, "Invalid func linkage");
3526 if (btf_type_kflag(t)) {
3527 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3531 btf_verifier_log_type(env, t, NULL);
3536 static struct btf_kind_operations func_ops = {
3537 .check_meta = btf_func_check_meta,
3538 .resolve = btf_df_resolve,
3539 .check_member = btf_df_check_member,
3540 .check_kflag_member = btf_df_check_kflag_member,
3541 .log_details = btf_ref_type_log,
3542 .show = btf_df_show,
3545 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3546 const struct btf_type *t,
3549 const struct btf_var *var;
3550 u32 meta_needed = sizeof(*var);
3552 if (meta_left < meta_needed) {
3553 btf_verifier_log_basic(env, t,
3554 "meta_left:%u meta_needed:%u",
3555 meta_left, meta_needed);
3559 if (btf_type_vlen(t)) {
3560 btf_verifier_log_type(env, t, "vlen != 0");
3564 if (btf_type_kflag(t)) {
3565 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3570 !__btf_name_valid(env->btf, t->name_off, true)) {
3571 btf_verifier_log_type(env, t, "Invalid name");
3575 /* A var cannot be in type void */
3576 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3577 btf_verifier_log_type(env, t, "Invalid type_id");
3581 var = btf_type_var(t);
3582 if (var->linkage != BTF_VAR_STATIC &&
3583 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3584 btf_verifier_log_type(env, t, "Linkage not supported");
3588 btf_verifier_log_type(env, t, NULL);
3593 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3595 const struct btf_var *var = btf_type_var(t);
3597 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3600 static const struct btf_kind_operations var_ops = {
3601 .check_meta = btf_var_check_meta,
3602 .resolve = btf_var_resolve,
3603 .check_member = btf_df_check_member,
3604 .check_kflag_member = btf_df_check_kflag_member,
3605 .log_details = btf_var_log,
3606 .show = btf_var_show,
3609 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3610 const struct btf_type *t,
3613 const struct btf_var_secinfo *vsi;
3614 u64 last_vsi_end_off = 0, sum = 0;
3617 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3618 if (meta_left < meta_needed) {
3619 btf_verifier_log_basic(env, t,
3620 "meta_left:%u meta_needed:%u",
3621 meta_left, meta_needed);
3626 btf_verifier_log_type(env, t, "size == 0");
3630 if (btf_type_kflag(t)) {
3631 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3636 !btf_name_valid_section(env->btf, t->name_off)) {
3637 btf_verifier_log_type(env, t, "Invalid name");
3641 btf_verifier_log_type(env, t, NULL);
3643 for_each_vsi(i, t, vsi) {
3644 /* A var cannot be in type void */
3645 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
3646 btf_verifier_log_vsi(env, t, vsi,
3651 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
3652 btf_verifier_log_vsi(env, t, vsi,
3657 if (!vsi->size || vsi->size > t->size) {
3658 btf_verifier_log_vsi(env, t, vsi,
3663 last_vsi_end_off = vsi->offset + vsi->size;
3664 if (last_vsi_end_off > t->size) {
3665 btf_verifier_log_vsi(env, t, vsi,
3666 "Invalid offset+size");
3670 btf_verifier_log_vsi(env, t, vsi, NULL);
3674 if (t->size < sum) {
3675 btf_verifier_log_type(env, t, "Invalid btf_info size");
3682 static int btf_datasec_resolve(struct btf_verifier_env *env,
3683 const struct resolve_vertex *v)
3685 const struct btf_var_secinfo *vsi;
3686 struct btf *btf = env->btf;
3689 for_each_vsi_from(i, v->next_member, v->t, vsi) {
3690 u32 var_type_id = vsi->type, type_id, type_size = 0;
3691 const struct btf_type *var_type = btf_type_by_id(env->btf,
3693 if (!var_type || !btf_type_is_var(var_type)) {
3694 btf_verifier_log_vsi(env, v->t, vsi,
3695 "Not a VAR kind member");
3699 if (!env_type_is_resolve_sink(env, var_type) &&
3700 !env_type_is_resolved(env, var_type_id)) {
3701 env_stack_set_next_member(env, i + 1);
3702 return env_stack_push(env, var_type, var_type_id);
3705 type_id = var_type->type;
3706 if (!btf_type_id_size(btf, &type_id, &type_size)) {
3707 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
3711 if (vsi->size < type_size) {
3712 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
3717 env_stack_pop_resolved(env, 0, 0);
3721 static void btf_datasec_log(struct btf_verifier_env *env,
3722 const struct btf_type *t)
3724 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3727 static void btf_datasec_show(const struct btf *btf,
3728 const struct btf_type *t, u32 type_id,
3729 void *data, u8 bits_offset,
3730 struct btf_show *show)
3732 const struct btf_var_secinfo *vsi;
3733 const struct btf_type *var;
3736 if (!btf_show_start_type(show, t, type_id, data))
3739 btf_show_type_value(show, "section (\"%s\") = {",
3740 __btf_name_by_offset(btf, t->name_off));
3741 for_each_vsi(i, t, vsi) {
3742 var = btf_type_by_id(btf, vsi->type);
3744 btf_show(show, ",");
3745 btf_type_ops(var)->show(btf, var, vsi->type,
3746 data + vsi->offset, bits_offset, show);
3748 btf_show_end_type(show);
3751 static const struct btf_kind_operations datasec_ops = {
3752 .check_meta = btf_datasec_check_meta,
3753 .resolve = btf_datasec_resolve,
3754 .check_member = btf_df_check_member,
3755 .check_kflag_member = btf_df_check_kflag_member,
3756 .log_details = btf_datasec_log,
3757 .show = btf_datasec_show,
3760 static s32 btf_float_check_meta(struct btf_verifier_env *env,
3761 const struct btf_type *t,
3764 if (btf_type_vlen(t)) {
3765 btf_verifier_log_type(env, t, "vlen != 0");
3769 if (btf_type_kflag(t)) {
3770 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3774 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
3776 btf_verifier_log_type(env, t, "Invalid type_size");
3780 btf_verifier_log_type(env, t, NULL);
3785 static int btf_float_check_member(struct btf_verifier_env *env,
3786 const struct btf_type *struct_type,
3787 const struct btf_member *member,
3788 const struct btf_type *member_type)
3790 u64 start_offset_bytes;
3791 u64 end_offset_bytes;
3796 /* Different architectures have different alignment requirements, so
3797 * here we check only for the reasonable minimum. This way we ensure
3798 * that types after CO-RE can pass the kernel BTF verifier.
3800 align_bytes = min_t(u64, sizeof(void *), member_type->size);
3801 align_bits = align_bytes * BITS_PER_BYTE;
3802 div64_u64_rem(member->offset, align_bits, &misalign_bits);
3803 if (misalign_bits) {
3804 btf_verifier_log_member(env, struct_type, member,
3805 "Member is not properly aligned");
3809 start_offset_bytes = member->offset / BITS_PER_BYTE;
3810 end_offset_bytes = start_offset_bytes + member_type->size;
3811 if (end_offset_bytes > struct_type->size) {
3812 btf_verifier_log_member(env, struct_type, member,
3813 "Member exceeds struct_size");
3820 static void btf_float_log(struct btf_verifier_env *env,
3821 const struct btf_type *t)
3823 btf_verifier_log(env, "size=%u", t->size);
3826 static const struct btf_kind_operations float_ops = {
3827 .check_meta = btf_float_check_meta,
3828 .resolve = btf_df_resolve,
3829 .check_member = btf_float_check_member,
3830 .check_kflag_member = btf_generic_check_kflag_member,
3831 .log_details = btf_float_log,
3832 .show = btf_df_show,
3835 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
3836 const struct btf_type *t,
3839 const struct btf_decl_tag *tag;
3840 u32 meta_needed = sizeof(*tag);
3844 if (meta_left < meta_needed) {
3845 btf_verifier_log_basic(env, t,
3846 "meta_left:%u meta_needed:%u",
3847 meta_left, meta_needed);
3851 value = btf_name_by_offset(env->btf, t->name_off);
3852 if (!value || !value[0]) {
3853 btf_verifier_log_type(env, t, "Invalid value");
3857 if (btf_type_vlen(t)) {
3858 btf_verifier_log_type(env, t, "vlen != 0");
3862 if (btf_type_kflag(t)) {
3863 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3867 component_idx = btf_type_decl_tag(t)->component_idx;
3868 if (component_idx < -1) {
3869 btf_verifier_log_type(env, t, "Invalid component_idx");
3873 btf_verifier_log_type(env, t, NULL);
3878 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
3879 const struct resolve_vertex *v)
3881 const struct btf_type *next_type;
3882 const struct btf_type *t = v->t;
3883 u32 next_type_id = t->type;
3884 struct btf *btf = env->btf;
3888 next_type = btf_type_by_id(btf, next_type_id);
3889 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
3890 btf_verifier_log_type(env, v->t, "Invalid type_id");
3894 if (!env_type_is_resolve_sink(env, next_type) &&
3895 !env_type_is_resolved(env, next_type_id))
3896 return env_stack_push(env, next_type, next_type_id);
3898 component_idx = btf_type_decl_tag(t)->component_idx;
3899 if (component_idx != -1) {
3900 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
3901 btf_verifier_log_type(env, v->t, "Invalid component_idx");
3905 if (btf_type_is_struct(next_type)) {
3906 vlen = btf_type_vlen(next_type);
3908 /* next_type should be a function */
3909 next_type = btf_type_by_id(btf, next_type->type);
3910 vlen = btf_type_vlen(next_type);
3913 if ((u32)component_idx >= vlen) {
3914 btf_verifier_log_type(env, v->t, "Invalid component_idx");
3919 env_stack_pop_resolved(env, next_type_id, 0);
3924 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
3926 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
3927 btf_type_decl_tag(t)->component_idx);
3930 static const struct btf_kind_operations decl_tag_ops = {
3931 .check_meta = btf_decl_tag_check_meta,
3932 .resolve = btf_decl_tag_resolve,
3933 .check_member = btf_df_check_member,
3934 .check_kflag_member = btf_df_check_kflag_member,
3935 .log_details = btf_decl_tag_log,
3936 .show = btf_df_show,
3939 static int btf_func_proto_check(struct btf_verifier_env *env,
3940 const struct btf_type *t)
3942 const struct btf_type *ret_type;
3943 const struct btf_param *args;
3944 const struct btf *btf;
3949 args = (const struct btf_param *)(t + 1);
3950 nr_args = btf_type_vlen(t);
3952 /* Check func return type which could be "void" (t->type == 0) */
3954 u32 ret_type_id = t->type;
3956 ret_type = btf_type_by_id(btf, ret_type_id);
3958 btf_verifier_log_type(env, t, "Invalid return type");
3962 if (btf_type_needs_resolve(ret_type) &&
3963 !env_type_is_resolved(env, ret_type_id)) {
3964 err = btf_resolve(env, ret_type, ret_type_id);
3969 /* Ensure the return type is a type that has a size */
3970 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
3971 btf_verifier_log_type(env, t, "Invalid return type");
3979 /* Last func arg type_id could be 0 if it is a vararg */
3980 if (!args[nr_args - 1].type) {
3981 if (args[nr_args - 1].name_off) {
3982 btf_verifier_log_type(env, t, "Invalid arg#%u",
3990 for (i = 0; i < nr_args; i++) {
3991 const struct btf_type *arg_type;
3994 arg_type_id = args[i].type;
3995 arg_type = btf_type_by_id(btf, arg_type_id);
3997 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4002 if (args[i].name_off &&
4003 (!btf_name_offset_valid(btf, args[i].name_off) ||
4004 !btf_name_valid_identifier(btf, args[i].name_off))) {
4005 btf_verifier_log_type(env, t,
4006 "Invalid arg#%u", i + 1);
4011 if (btf_type_needs_resolve(arg_type) &&
4012 !env_type_is_resolved(env, arg_type_id)) {
4013 err = btf_resolve(env, arg_type, arg_type_id);
4018 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4019 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4028 static int btf_func_check(struct btf_verifier_env *env,
4029 const struct btf_type *t)
4031 const struct btf_type *proto_type;
4032 const struct btf_param *args;
4033 const struct btf *btf;
4037 proto_type = btf_type_by_id(btf, t->type);
4039 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4040 btf_verifier_log_type(env, t, "Invalid type_id");
4044 args = (const struct btf_param *)(proto_type + 1);
4045 nr_args = btf_type_vlen(proto_type);
4046 for (i = 0; i < nr_args; i++) {
4047 if (!args[i].name_off && args[i].type) {
4048 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4056 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4057 [BTF_KIND_INT] = &int_ops,
4058 [BTF_KIND_PTR] = &ptr_ops,
4059 [BTF_KIND_ARRAY] = &array_ops,
4060 [BTF_KIND_STRUCT] = &struct_ops,
4061 [BTF_KIND_UNION] = &struct_ops,
4062 [BTF_KIND_ENUM] = &enum_ops,
4063 [BTF_KIND_FWD] = &fwd_ops,
4064 [BTF_KIND_TYPEDEF] = &modifier_ops,
4065 [BTF_KIND_VOLATILE] = &modifier_ops,
4066 [BTF_KIND_CONST] = &modifier_ops,
4067 [BTF_KIND_RESTRICT] = &modifier_ops,
4068 [BTF_KIND_FUNC] = &func_ops,
4069 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4070 [BTF_KIND_VAR] = &var_ops,
4071 [BTF_KIND_DATASEC] = &datasec_ops,
4072 [BTF_KIND_FLOAT] = &float_ops,
4073 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
4074 [BTF_KIND_TYPE_TAG] = &modifier_ops,
4077 static s32 btf_check_meta(struct btf_verifier_env *env,
4078 const struct btf_type *t,
4081 u32 saved_meta_left = meta_left;
4084 if (meta_left < sizeof(*t)) {
4085 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4086 env->log_type_id, meta_left, sizeof(*t));
4089 meta_left -= sizeof(*t);
4091 if (t->info & ~BTF_INFO_MASK) {
4092 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4093 env->log_type_id, t->info);
4097 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4098 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4099 btf_verifier_log(env, "[%u] Invalid kind:%u",
4100 env->log_type_id, BTF_INFO_KIND(t->info));
4104 if (!btf_name_offset_valid(env->btf, t->name_off)) {
4105 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4106 env->log_type_id, t->name_off);
4110 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4111 if (var_meta_size < 0)
4112 return var_meta_size;
4114 meta_left -= var_meta_size;
4116 return saved_meta_left - meta_left;
4119 static int btf_check_all_metas(struct btf_verifier_env *env)
4121 struct btf *btf = env->btf;
4122 struct btf_header *hdr;
4126 cur = btf->nohdr_data + hdr->type_off;
4127 end = cur + hdr->type_len;
4129 env->log_type_id = btf->base_btf ? btf->start_id : 1;
4131 struct btf_type *t = cur;
4134 meta_size = btf_check_meta(env, t, end - cur);
4138 btf_add_type(env, t);
4146 static bool btf_resolve_valid(struct btf_verifier_env *env,
4147 const struct btf_type *t,
4150 struct btf *btf = env->btf;
4152 if (!env_type_is_resolved(env, type_id))
4155 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
4156 return !btf_resolved_type_id(btf, type_id) &&
4157 !btf_resolved_type_size(btf, type_id);
4159 if (btf_type_is_decl_tag(t))
4160 return btf_resolved_type_id(btf, type_id) &&
4161 !btf_resolved_type_size(btf, type_id);
4163 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
4164 btf_type_is_var(t)) {
4165 t = btf_type_id_resolve(btf, &type_id);
4167 !btf_type_is_modifier(t) &&
4168 !btf_type_is_var(t) &&
4169 !btf_type_is_datasec(t);
4172 if (btf_type_is_array(t)) {
4173 const struct btf_array *array = btf_type_array(t);
4174 const struct btf_type *elem_type;
4175 u32 elem_type_id = array->type;
4178 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
4179 return elem_type && !btf_type_is_modifier(elem_type) &&
4180 (array->nelems * elem_size ==
4181 btf_resolved_type_size(btf, type_id));
4187 static int btf_resolve(struct btf_verifier_env *env,
4188 const struct btf_type *t, u32 type_id)
4190 u32 save_log_type_id = env->log_type_id;
4191 const struct resolve_vertex *v;
4194 env->resolve_mode = RESOLVE_TBD;
4195 env_stack_push(env, t, type_id);
4196 while (!err && (v = env_stack_peak(env))) {
4197 env->log_type_id = v->type_id;
4198 err = btf_type_ops(v->t)->resolve(env, v);
4201 env->log_type_id = type_id;
4202 if (err == -E2BIG) {
4203 btf_verifier_log_type(env, t,
4204 "Exceeded max resolving depth:%u",
4206 } else if (err == -EEXIST) {
4207 btf_verifier_log_type(env, t, "Loop detected");
4210 /* Final sanity check */
4211 if (!err && !btf_resolve_valid(env, t, type_id)) {
4212 btf_verifier_log_type(env, t, "Invalid resolve state");
4216 env->log_type_id = save_log_type_id;
4220 static int btf_check_all_types(struct btf_verifier_env *env)
4222 struct btf *btf = env->btf;
4223 const struct btf_type *t;
4227 err = env_resolve_init(env);
4232 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
4233 type_id = btf->start_id + i;
4234 t = btf_type_by_id(btf, type_id);
4236 env->log_type_id = type_id;
4237 if (btf_type_needs_resolve(t) &&
4238 !env_type_is_resolved(env, type_id)) {
4239 err = btf_resolve(env, t, type_id);
4244 if (btf_type_is_func_proto(t)) {
4245 err = btf_func_proto_check(env, t);
4250 if (btf_type_is_func(t)) {
4251 err = btf_func_check(env, t);
4260 static int btf_parse_type_sec(struct btf_verifier_env *env)
4262 const struct btf_header *hdr = &env->btf->hdr;
4265 /* Type section must align to 4 bytes */
4266 if (hdr->type_off & (sizeof(u32) - 1)) {
4267 btf_verifier_log(env, "Unaligned type_off");
4271 if (!env->btf->base_btf && !hdr->type_len) {
4272 btf_verifier_log(env, "No type found");
4276 err = btf_check_all_metas(env);
4280 return btf_check_all_types(env);
4283 static int btf_parse_str_sec(struct btf_verifier_env *env)
4285 const struct btf_header *hdr;
4286 struct btf *btf = env->btf;
4287 const char *start, *end;
4290 start = btf->nohdr_data + hdr->str_off;
4291 end = start + hdr->str_len;
4293 if (end != btf->data + btf->data_size) {
4294 btf_verifier_log(env, "String section is not at the end");
4298 btf->strings = start;
4300 if (btf->base_btf && !hdr->str_len)
4302 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
4303 btf_verifier_log(env, "Invalid string section");
4306 if (!btf->base_btf && start[0]) {
4307 btf_verifier_log(env, "Invalid string section");
4314 static const size_t btf_sec_info_offset[] = {
4315 offsetof(struct btf_header, type_off),
4316 offsetof(struct btf_header, str_off),
4319 static int btf_sec_info_cmp(const void *a, const void *b)
4321 const struct btf_sec_info *x = a;
4322 const struct btf_sec_info *y = b;
4324 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
4327 static int btf_check_sec_info(struct btf_verifier_env *env,
4330 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
4331 u32 total, expected_total, i;
4332 const struct btf_header *hdr;
4333 const struct btf *btf;
4338 /* Populate the secs from hdr */
4339 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
4340 secs[i] = *(struct btf_sec_info *)((void *)hdr +
4341 btf_sec_info_offset[i]);
4343 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
4344 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
4346 /* Check for gaps and overlap among sections */
4348 expected_total = btf_data_size - hdr->hdr_len;
4349 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
4350 if (expected_total < secs[i].off) {
4351 btf_verifier_log(env, "Invalid section offset");
4354 if (total < secs[i].off) {
4356 btf_verifier_log(env, "Unsupported section found");
4359 if (total > secs[i].off) {
4360 btf_verifier_log(env, "Section overlap found");
4363 if (expected_total - total < secs[i].len) {
4364 btf_verifier_log(env,
4365 "Total section length too long");
4368 total += secs[i].len;
4371 /* There is data other than hdr and known sections */
4372 if (expected_total != total) {
4373 btf_verifier_log(env, "Unsupported section found");
4380 static int btf_parse_hdr(struct btf_verifier_env *env)
4382 u32 hdr_len, hdr_copy, btf_data_size;
4383 const struct btf_header *hdr;
4388 btf_data_size = btf->data_size;
4391 offsetof(struct btf_header, hdr_len) + sizeof(hdr->hdr_len)) {
4392 btf_verifier_log(env, "hdr_len not found");
4397 hdr_len = hdr->hdr_len;
4398 if (btf_data_size < hdr_len) {
4399 btf_verifier_log(env, "btf_header not found");
4403 /* Ensure the unsupported header fields are zero */
4404 if (hdr_len > sizeof(btf->hdr)) {
4405 u8 *expected_zero = btf->data + sizeof(btf->hdr);
4406 u8 *end = btf->data + hdr_len;
4408 for (; expected_zero < end; expected_zero++) {
4409 if (*expected_zero) {
4410 btf_verifier_log(env, "Unsupported btf_header");
4416 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4417 memcpy(&btf->hdr, btf->data, hdr_copy);
4421 btf_verifier_log_hdr(env, btf_data_size);
4423 if (hdr->magic != BTF_MAGIC) {
4424 btf_verifier_log(env, "Invalid magic");
4428 if (hdr->version != BTF_VERSION) {
4429 btf_verifier_log(env, "Unsupported version");
4434 btf_verifier_log(env, "Unsupported flags");
4438 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
4439 btf_verifier_log(env, "No data");
4443 err = btf_check_sec_info(env, btf_data_size);
4450 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
4451 u32 log_level, char __user *log_ubuf, u32 log_size)
4453 struct btf_verifier_env *env = NULL;
4454 struct bpf_verifier_log *log;
4455 struct btf *btf = NULL;
4459 if (btf_data_size > BTF_MAX_SIZE)
4460 return ERR_PTR(-E2BIG);
4462 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4464 return ERR_PTR(-ENOMEM);
4467 if (log_level || log_ubuf || log_size) {
4468 /* user requested verbose verifier output
4469 * and supplied buffer to store the verification trace
4471 log->level = log_level;
4472 log->ubuf = log_ubuf;
4473 log->len_total = log_size;
4475 /* log attributes have to be sane */
4476 if (!bpf_verifier_log_attr_valid(log)) {
4482 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4489 data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4496 btf->data_size = btf_data_size;
4498 if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
4503 err = btf_parse_hdr(env);
4507 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4509 err = btf_parse_str_sec(env);
4513 err = btf_parse_type_sec(env);
4517 if (log->level && bpf_verifier_log_full(log)) {
4522 btf_verifier_env_free(env);
4523 refcount_set(&btf->refcnt, 1);
4527 btf_verifier_env_free(env);
4530 return ERR_PTR(err);
4533 extern char __weak __start_BTF[];
4534 extern char __weak __stop_BTF[];
4535 extern struct btf *btf_vmlinux;
4537 #define BPF_MAP_TYPE(_id, _ops)
4538 #define BPF_LINK_TYPE(_id, _name)
4540 struct bpf_ctx_convert {
4541 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4542 prog_ctx_type _id##_prog; \
4543 kern_ctx_type _id##_kern;
4544 #include <linux/bpf_types.h>
4545 #undef BPF_PROG_TYPE
4547 /* 't' is written once under lock. Read many times. */
4548 const struct btf_type *t;
4551 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4553 #include <linux/bpf_types.h>
4554 #undef BPF_PROG_TYPE
4555 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
4557 static u8 bpf_ctx_convert_map[] = {
4558 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4559 [_id] = __ctx_convert##_id,
4560 #include <linux/bpf_types.h>
4561 #undef BPF_PROG_TYPE
4562 0, /* avoid empty array */
4565 #undef BPF_LINK_TYPE
4567 static const struct btf_member *
4568 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
4569 const struct btf_type *t, enum bpf_prog_type prog_type,
4572 const struct btf_type *conv_struct;
4573 const struct btf_type *ctx_struct;
4574 const struct btf_member *ctx_type;
4575 const char *tname, *ctx_tname;
4577 conv_struct = bpf_ctx_convert.t;
4579 bpf_log(log, "btf_vmlinux is malformed\n");
4582 t = btf_type_by_id(btf, t->type);
4583 while (btf_type_is_modifier(t))
4584 t = btf_type_by_id(btf, t->type);
4585 if (!btf_type_is_struct(t)) {
4586 /* Only pointer to struct is supported for now.
4587 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4588 * is not supported yet.
4589 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
4593 tname = btf_name_by_offset(btf, t->name_off);
4595 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
4598 /* prog_type is valid bpf program type. No need for bounds check. */
4599 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
4600 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
4601 * Like 'struct __sk_buff'
4603 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
4605 /* should not happen */
4607 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
4609 /* should not happen */
4610 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
4613 /* only compare that prog's ctx type name is the same as
4614 * kernel expects. No need to compare field by field.
4615 * It's ok for bpf prog to do:
4616 * struct __sk_buff {};
4617 * int socket_filter_bpf_prog(struct __sk_buff *skb)
4618 * { // no fields of skb are ever used }
4620 if (strcmp(ctx_tname, tname))
4625 static const struct bpf_map_ops * const btf_vmlinux_map_ops[] = {
4626 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
4627 #define BPF_LINK_TYPE(_id, _name)
4628 #define BPF_MAP_TYPE(_id, _ops) \
4630 #include <linux/bpf_types.h>
4631 #undef BPF_PROG_TYPE
4632 #undef BPF_LINK_TYPE
4636 static int btf_vmlinux_map_ids_init(const struct btf *btf,
4637 struct bpf_verifier_log *log)
4639 const struct bpf_map_ops *ops;
4642 for (i = 0; i < ARRAY_SIZE(btf_vmlinux_map_ops); ++i) {
4643 ops = btf_vmlinux_map_ops[i];
4644 if (!ops || (!ops->map_btf_name && !ops->map_btf_id))
4646 if (!ops->map_btf_name || !ops->map_btf_id) {
4647 bpf_log(log, "map type %d is misconfigured\n", i);
4650 btf_id = btf_find_by_name_kind(btf, ops->map_btf_name,
4654 *ops->map_btf_id = btf_id;
4660 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
4662 const struct btf_type *t,
4663 enum bpf_prog_type prog_type,
4666 const struct btf_member *prog_ctx_type, *kern_ctx_type;
4668 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
4671 kern_ctx_type = prog_ctx_type + 1;
4672 return kern_ctx_type->type;
4675 BTF_ID_LIST(bpf_ctx_convert_btf_id)
4676 BTF_ID(struct, bpf_ctx_convert)
4678 struct btf *btf_parse_vmlinux(void)
4680 struct btf_verifier_env *env = NULL;
4681 struct bpf_verifier_log *log;
4682 struct btf *btf = NULL;
4685 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4687 return ERR_PTR(-ENOMEM);
4690 log->level = BPF_LOG_KERNEL;
4692 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4699 btf->data = __start_BTF;
4700 btf->data_size = __stop_BTF - __start_BTF;
4701 btf->kernel_btf = true;
4702 snprintf(btf->name, sizeof(btf->name), "vmlinux");
4704 err = btf_parse_hdr(env);
4708 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4710 err = btf_parse_str_sec(env);
4714 err = btf_check_all_metas(env);
4718 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
4719 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
4721 /* find bpf map structs for map_ptr access checking */
4722 err = btf_vmlinux_map_ids_init(btf, log);
4726 bpf_struct_ops_init(btf, log);
4728 refcount_set(&btf->refcnt, 1);
4730 err = btf_alloc_id(btf);
4734 btf_verifier_env_free(env);
4738 btf_verifier_env_free(env);
4743 return ERR_PTR(err);
4746 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
4748 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
4750 struct btf_verifier_env *env = NULL;
4751 struct bpf_verifier_log *log;
4752 struct btf *btf = NULL, *base_btf;
4755 base_btf = bpf_get_btf_vmlinux();
4756 if (IS_ERR(base_btf))
4759 return ERR_PTR(-EINVAL);
4761 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4763 return ERR_PTR(-ENOMEM);
4766 log->level = BPF_LOG_KERNEL;
4768 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4775 btf->base_btf = base_btf;
4776 btf->start_id = base_btf->nr_types;
4777 btf->start_str_off = base_btf->hdr.str_len;
4778 btf->kernel_btf = true;
4779 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
4781 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
4786 memcpy(btf->data, data, data_size);
4787 btf->data_size = data_size;
4789 err = btf_parse_hdr(env);
4793 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4795 err = btf_parse_str_sec(env);
4799 err = btf_check_all_metas(env);
4803 btf_verifier_env_free(env);
4804 refcount_set(&btf->refcnt, 1);
4808 btf_verifier_env_free(env);
4814 return ERR_PTR(err);
4817 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
4819 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
4821 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4824 return tgt_prog->aux->btf;
4826 return prog->aux->attach_btf;
4829 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
4831 /* t comes in already as a pointer */
4832 t = btf_type_by_id(btf, t->type);
4835 if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
4836 t = btf_type_by_id(btf, t->type);
4838 return btf_type_is_int(t);
4841 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
4842 const struct bpf_prog *prog,
4843 struct bpf_insn_access_aux *info)
4845 const struct btf_type *t = prog->aux->attach_func_proto;
4846 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4847 struct btf *btf = bpf_prog_get_target_btf(prog);
4848 const char *tname = prog->aux->attach_func_name;
4849 struct bpf_verifier_log *log = info->log;
4850 const struct btf_param *args;
4855 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
4860 args = (const struct btf_param *)(t + 1);
4861 /* if (t == NULL) Fall back to default BPF prog with
4862 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
4864 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
4865 if (prog->aux->attach_btf_trace) {
4866 /* skip first 'void *__data' argument in btf_trace_##name typedef */
4871 if (arg > nr_args) {
4872 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4877 if (arg == nr_args) {
4878 switch (prog->expected_attach_type) {
4880 case BPF_TRACE_FEXIT:
4881 /* When LSM programs are attached to void LSM hooks
4882 * they use FEXIT trampolines and when attached to
4883 * int LSM hooks, they use MODIFY_RETURN trampolines.
4885 * While the LSM programs are BPF_MODIFY_RETURN-like
4888 * if (ret_type != 'int')
4891 * is _not_ done here. This is still safe as LSM hooks
4892 * have only void and int return types.
4896 t = btf_type_by_id(btf, t->type);
4898 case BPF_MODIFY_RETURN:
4899 /* For now the BPF_MODIFY_RETURN can only be attached to
4900 * functions that return an int.
4905 t = btf_type_skip_modifiers(btf, t->type, NULL);
4906 if (!btf_type_is_small_int(t)) {
4908 "ret type %s not allowed for fmod_ret\n",
4909 btf_kind_str[BTF_INFO_KIND(t->info)]);
4914 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4920 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
4922 t = btf_type_by_id(btf, args[arg].type);
4925 /* skip modifiers */
4926 while (btf_type_is_modifier(t))
4927 t = btf_type_by_id(btf, t->type);
4928 if (btf_type_is_small_int(t) || btf_type_is_enum(t))
4929 /* accessing a scalar */
4931 if (!btf_type_is_ptr(t)) {
4933 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
4935 __btf_name_by_offset(btf, t->name_off),
4936 btf_kind_str[BTF_INFO_KIND(t->info)]);
4940 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
4941 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4942 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4945 type = base_type(ctx_arg_info->reg_type);
4946 flag = type_flag(ctx_arg_info->reg_type);
4947 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
4948 (flag & PTR_MAYBE_NULL)) {
4949 info->reg_type = ctx_arg_info->reg_type;
4955 /* This is a pointer to void.
4956 * It is the same as scalar from the verifier safety pov.
4957 * No further pointer walking is allowed.
4961 if (is_int_ptr(btf, t))
4964 /* this is a pointer to another type */
4965 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4966 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4968 if (ctx_arg_info->offset == off) {
4969 if (!ctx_arg_info->btf_id) {
4970 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
4974 info->reg_type = ctx_arg_info->reg_type;
4975 info->btf = btf_vmlinux;
4976 info->btf_id = ctx_arg_info->btf_id;
4981 info->reg_type = PTR_TO_BTF_ID;
4983 enum bpf_prog_type tgt_type;
4985 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
4986 tgt_type = tgt_prog->aux->saved_dst_prog_type;
4988 tgt_type = tgt_prog->type;
4990 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
4992 info->btf = btf_vmlinux;
5001 info->btf_id = t->type;
5002 t = btf_type_by_id(btf, t->type);
5003 /* skip modifiers */
5004 while (btf_type_is_modifier(t)) {
5005 info->btf_id = t->type;
5006 t = btf_type_by_id(btf, t->type);
5008 if (!btf_type_is_struct(t)) {
5010 "func '%s' arg%d type %s is not a struct\n",
5011 tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
5014 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
5015 tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
5016 __btf_name_by_offset(btf, t->name_off));
5020 enum bpf_struct_walk_result {
5027 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
5028 const struct btf_type *t, int off, int size,
5031 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
5032 const struct btf_type *mtype, *elem_type = NULL;
5033 const struct btf_member *member;
5034 const char *tname, *mname;
5035 u32 vlen, elem_id, mid;
5038 tname = __btf_name_by_offset(btf, t->name_off);
5039 if (!btf_type_is_struct(t)) {
5040 bpf_log(log, "Type '%s' is not a struct\n", tname);
5044 vlen = btf_type_vlen(t);
5045 if (off + size > t->size) {
5046 /* If the last element is a variable size array, we may
5047 * need to relax the rule.
5049 struct btf_array *array_elem;
5054 member = btf_type_member(t) + vlen - 1;
5055 mtype = btf_type_skip_modifiers(btf, member->type,
5057 if (!btf_type_is_array(mtype))
5060 array_elem = (struct btf_array *)(mtype + 1);
5061 if (array_elem->nelems != 0)
5064 moff = __btf_member_bit_offset(t, member) / 8;
5068 /* Only allow structure for now, can be relaxed for
5069 * other types later.
5071 t = btf_type_skip_modifiers(btf, array_elem->type,
5073 if (!btf_type_is_struct(t))
5076 off = (off - moff) % t->size;
5080 bpf_log(log, "access beyond struct %s at off %u size %u\n",
5085 for_each_member(i, t, member) {
5086 /* offset of the field in bytes */
5087 moff = __btf_member_bit_offset(t, member) / 8;
5088 if (off + size <= moff)
5089 /* won't find anything, field is already too far */
5092 if (__btf_member_bitfield_size(t, member)) {
5093 u32 end_bit = __btf_member_bit_offset(t, member) +
5094 __btf_member_bitfield_size(t, member);
5096 /* off <= moff instead of off == moff because clang
5097 * does not generate a BTF member for anonymous
5098 * bitfield like the ":16" here:
5105 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
5108 /* off may be accessing a following member
5112 * Doing partial access at either end of this
5113 * bitfield. Continue on this case also to
5114 * treat it as not accessing this bitfield
5115 * and eventually error out as field not
5116 * found to keep it simple.
5117 * It could be relaxed if there was a legit
5118 * partial access case later.
5123 /* In case of "off" is pointing to holes of a struct */
5127 /* type of the field */
5129 mtype = btf_type_by_id(btf, member->type);
5130 mname = __btf_name_by_offset(btf, member->name_off);
5132 mtype = __btf_resolve_size(btf, mtype, &msize,
5133 &elem_type, &elem_id, &total_nelems,
5135 if (IS_ERR(mtype)) {
5136 bpf_log(log, "field %s doesn't have size\n", mname);
5140 mtrue_end = moff + msize;
5141 if (off >= mtrue_end)
5142 /* no overlap with member, keep iterating */
5145 if (btf_type_is_array(mtype)) {
5148 /* __btf_resolve_size() above helps to
5149 * linearize a multi-dimensional array.
5151 * The logic here is treating an array
5152 * in a struct as the following way:
5155 * struct inner array[2][2];
5161 * struct inner array_elem0;
5162 * struct inner array_elem1;
5163 * struct inner array_elem2;
5164 * struct inner array_elem3;
5167 * When accessing outer->array[1][0], it moves
5168 * moff to "array_elem2", set mtype to
5169 * "struct inner", and msize also becomes
5170 * sizeof(struct inner). Then most of the
5171 * remaining logic will fall through without
5172 * caring the current member is an array or
5175 * Unlike mtype/msize/moff, mtrue_end does not
5176 * change. The naming difference ("_true") tells
5177 * that it is not always corresponding to
5178 * the current mtype/msize/moff.
5179 * It is the true end of the current
5180 * member (i.e. array in this case). That
5181 * will allow an int array to be accessed like
5183 * i.e. allow access beyond the size of
5184 * the array's element as long as it is
5185 * within the mtrue_end boundary.
5188 /* skip empty array */
5189 if (moff == mtrue_end)
5192 msize /= total_nelems;
5193 elem_idx = (off - moff) / msize;
5194 moff += elem_idx * msize;
5199 /* the 'off' we're looking for is either equal to start
5200 * of this field or inside of this struct
5202 if (btf_type_is_struct(mtype)) {
5203 /* our field must be inside that union or struct */
5206 /* return if the offset matches the member offset */
5212 /* adjust offset we're looking for */
5217 if (btf_type_is_ptr(mtype)) {
5218 const struct btf_type *stype;
5221 if (msize != size || off != moff) {
5223 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
5224 mname, moff, tname, off, size);
5227 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
5228 if (btf_type_is_struct(stype)) {
5234 /* Allow more flexible access within an int as long as
5235 * it is within mtrue_end.
5236 * Since mtrue_end could be the end of an array,
5237 * that also allows using an array of int as a scratch
5238 * space. e.g. skb->cb[].
5240 if (off + size > mtrue_end) {
5242 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
5243 mname, mtrue_end, tname, off, size);
5249 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
5253 int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
5254 const struct btf_type *t, int off, int size,
5255 enum bpf_access_type atype __maybe_unused,
5262 err = btf_struct_walk(log, btf, t, off, size, &id);
5266 /* If we found the pointer or scalar on t+off,
5270 return PTR_TO_BTF_ID;
5272 return SCALAR_VALUE;
5274 /* We found nested struct, so continue the search
5275 * by diving in it. At this point the offset is
5276 * aligned with the new type, so set it to 0.
5278 t = btf_type_by_id(btf, id);
5282 /* It's either error or unknown return value..
5285 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5294 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5295 * the same. Trivial ID check is not enough due to module BTFs, because we can
5296 * end up with two different module BTFs, but IDs point to the common type in
5299 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5300 const struct btf *btf2, u32 id2)
5306 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5309 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5310 const struct btf *btf, u32 id, int off,
5311 const struct btf *need_btf, u32 need_type_id)
5313 const struct btf_type *type;
5316 /* Are we already done? */
5317 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5321 type = btf_type_by_id(btf, id);
5324 err = btf_struct_walk(log, btf, type, off, 1, &id);
5325 if (err != WALK_STRUCT)
5328 /* We found nested struct object. If it matches
5329 * the requested ID, we're done. Otherwise let's
5330 * continue the search with offset 0 in the new
5333 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5341 static int __get_type_size(struct btf *btf, u32 btf_id,
5342 const struct btf_type **bad_type)
5344 const struct btf_type *t;
5349 t = btf_type_by_id(btf, btf_id);
5350 while (t && btf_type_is_modifier(t))
5351 t = btf_type_by_id(btf, t->type);
5353 *bad_type = btf_type_by_id(btf, 0);
5356 if (btf_type_is_ptr(t))
5357 /* kernel size of pointer. Not BPF's size of pointer*/
5358 return sizeof(void *);
5359 if (btf_type_is_int(t) || btf_type_is_enum(t))
5365 int btf_distill_func_proto(struct bpf_verifier_log *log,
5367 const struct btf_type *func,
5369 struct btf_func_model *m)
5371 const struct btf_param *args;
5372 const struct btf_type *t;
5377 /* BTF function prototype doesn't match the verifier types.
5378 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
5380 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
5383 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
5386 args = (const struct btf_param *)(func + 1);
5387 nargs = btf_type_vlen(func);
5388 if (nargs >= MAX_BPF_FUNC_ARGS) {
5390 "The function %s has %d arguments. Too many.\n",
5394 ret = __get_type_size(btf, func->type, &t);
5397 "The function %s return type %s is unsupported.\n",
5398 tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5403 for (i = 0; i < nargs; i++) {
5404 if (i == nargs - 1 && args[i].type == 0) {
5406 "The function %s with variable args is unsupported.\n",
5410 ret = __get_type_size(btf, args[i].type, &t);
5413 "The function %s arg%d type %s is unsupported.\n",
5414 tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5419 "The function %s has malformed void argument.\n",
5423 m->arg_size[i] = ret;
5429 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5430 * t1 points to BTF_KIND_FUNC in btf1
5431 * t2 points to BTF_KIND_FUNC in btf2
5433 * EINVAL - function prototype mismatch
5434 * EFAULT - verifier bug
5435 * 0 - 99% match. The last 1% is validated by the verifier.
5437 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5438 struct btf *btf1, const struct btf_type *t1,
5439 struct btf *btf2, const struct btf_type *t2)
5441 const struct btf_param *args1, *args2;
5442 const char *fn1, *fn2, *s1, *s2;
5443 u32 nargs1, nargs2, i;
5445 fn1 = btf_name_by_offset(btf1, t1->name_off);
5446 fn2 = btf_name_by_offset(btf2, t2->name_off);
5448 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5449 bpf_log(log, "%s() is not a global function\n", fn1);
5452 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5453 bpf_log(log, "%s() is not a global function\n", fn2);
5457 t1 = btf_type_by_id(btf1, t1->type);
5458 if (!t1 || !btf_type_is_func_proto(t1))
5460 t2 = btf_type_by_id(btf2, t2->type);
5461 if (!t2 || !btf_type_is_func_proto(t2))
5464 args1 = (const struct btf_param *)(t1 + 1);
5465 nargs1 = btf_type_vlen(t1);
5466 args2 = (const struct btf_param *)(t2 + 1);
5467 nargs2 = btf_type_vlen(t2);
5469 if (nargs1 != nargs2) {
5470 bpf_log(log, "%s() has %d args while %s() has %d args\n",
5471 fn1, nargs1, fn2, nargs2);
5475 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5476 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5477 if (t1->info != t2->info) {
5479 "Return type %s of %s() doesn't match type %s of %s()\n",
5480 btf_type_str(t1), fn1,
5481 btf_type_str(t2), fn2);
5485 for (i = 0; i < nargs1; i++) {
5486 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5487 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5489 if (t1->info != t2->info) {
5490 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5491 i, fn1, btf_type_str(t1),
5492 fn2, btf_type_str(t2));
5495 if (btf_type_has_size(t1) && t1->size != t2->size) {
5497 "arg%d in %s() has size %d while %s() has %d\n",
5503 /* global functions are validated with scalars and pointers
5504 * to context only. And only global functions can be replaced.
5505 * Hence type check only those types.
5507 if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5509 if (!btf_type_is_ptr(t1)) {
5511 "arg%d in %s() has unrecognized type\n",
5515 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5516 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5517 if (!btf_type_is_struct(t1)) {
5519 "arg%d in %s() is not a pointer to context\n",
5523 if (!btf_type_is_struct(t2)) {
5525 "arg%d in %s() is not a pointer to context\n",
5529 /* This is an optional check to make program writing easier.
5530 * Compare names of structs and report an error to the user.
5531 * btf_prepare_func_args() already checked that t2 struct
5532 * is a context type. btf_prepare_func_args() will check
5533 * later that t1 struct is a context type as well.
5535 s1 = btf_name_by_offset(btf1, t1->name_off);
5536 s2 = btf_name_by_offset(btf2, t2->name_off);
5537 if (strcmp(s1, s2)) {
5539 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5540 i, fn1, s1, fn2, s2);
5547 /* Compare BTFs of given program with BTF of target program */
5548 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5549 struct btf *btf2, const struct btf_type *t2)
5551 struct btf *btf1 = prog->aux->btf;
5552 const struct btf_type *t1;
5555 if (!prog->aux->func_info) {
5556 bpf_log(log, "Program extension requires BTF\n");
5560 btf_id = prog->aux->func_info[0].type_id;
5564 t1 = btf_type_by_id(btf1, btf_id);
5565 if (!t1 || !btf_type_is_func(t1))
5568 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5571 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5573 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5574 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5575 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5579 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
5580 static bool __btf_type_is_scalar_struct(struct bpf_verifier_log *log,
5581 const struct btf *btf,
5582 const struct btf_type *t, int rec)
5584 const struct btf_type *member_type;
5585 const struct btf_member *member;
5588 if (!btf_type_is_struct(t))
5591 for_each_member(i, t, member) {
5592 const struct btf_array *array;
5594 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
5595 if (btf_type_is_struct(member_type)) {
5597 bpf_log(log, "max struct nesting depth exceeded\n");
5600 if (!__btf_type_is_scalar_struct(log, btf, member_type, rec + 1))
5604 if (btf_type_is_array(member_type)) {
5605 array = btf_type_array(member_type);
5608 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
5609 if (!btf_type_is_scalar(member_type))
5613 if (!btf_type_is_scalar(member_type))
5619 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
5620 const struct btf *btf, u32 func_id,
5621 struct bpf_reg_state *regs,
5624 struct bpf_verifier_log *log = &env->log;
5625 bool is_kfunc = btf_is_kernel(btf);
5626 const char *func_name, *ref_tname;
5627 const struct btf_type *t, *ref_t;
5628 const struct btf_param *args;
5629 u32 i, nargs, ref_id;
5631 t = btf_type_by_id(btf, func_id);
5632 if (!t || !btf_type_is_func(t)) {
5633 /* These checks were already done by the verifier while loading
5634 * struct bpf_func_info or in add_kfunc_call().
5636 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
5640 func_name = btf_name_by_offset(btf, t->name_off);
5642 t = btf_type_by_id(btf, t->type);
5643 if (!t || !btf_type_is_func_proto(t)) {
5644 bpf_log(log, "Invalid BTF of func %s\n", func_name);
5647 args = (const struct btf_param *)(t + 1);
5648 nargs = btf_type_vlen(t);
5649 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
5650 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
5651 MAX_BPF_FUNC_REG_ARGS);
5655 /* check that BTF function arguments match actual types that the
5658 for (i = 0; i < nargs; i++) {
5660 struct bpf_reg_state *reg = ®s[regno];
5662 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5663 if (btf_type_is_scalar(t)) {
5664 if (reg->type == SCALAR_VALUE)
5666 bpf_log(log, "R%d is not a scalar\n", regno);
5670 if (!btf_type_is_ptr(t)) {
5671 bpf_log(log, "Unrecognized arg#%d type %s\n",
5672 i, btf_type_str(t));
5676 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
5677 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
5678 if (btf_get_prog_ctx_type(log, btf, t,
5679 env->prog->type, i)) {
5680 /* If function expects ctx type in BTF check that caller
5681 * is passing PTR_TO_CTX.
5683 if (reg->type != PTR_TO_CTX) {
5685 "arg#%d expected pointer to ctx, but got %s\n",
5686 i, btf_type_str(t));
5689 if (check_ctx_reg(env, reg, regno))
5691 } else if (is_kfunc && (reg->type == PTR_TO_BTF_ID || reg2btf_ids[reg->type])) {
5692 const struct btf_type *reg_ref_t;
5693 const struct btf *reg_btf;
5694 const char *reg_ref_tname;
5697 if (!btf_type_is_struct(ref_t)) {
5698 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
5699 func_name, i, btf_type_str(ref_t),
5704 if (reg->type == PTR_TO_BTF_ID) {
5706 reg_ref_id = reg->btf_id;
5708 reg_btf = btf_vmlinux;
5709 reg_ref_id = *reg2btf_ids[reg->type];
5712 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id,
5714 reg_ref_tname = btf_name_by_offset(reg_btf,
5715 reg_ref_t->name_off);
5716 if (!btf_struct_ids_match(log, reg_btf, reg_ref_id,
5717 reg->off, btf, ref_id)) {
5718 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
5720 btf_type_str(ref_t), ref_tname,
5721 regno, btf_type_str(reg_ref_t),
5725 } else if (ptr_to_mem_ok) {
5726 const struct btf_type *resolve_ret;
5730 /* Permit pointer to mem, but only when argument
5731 * type is pointer to scalar, or struct composed
5732 * (recursively) of scalars.
5734 if (!btf_type_is_scalar(ref_t) &&
5735 !__btf_type_is_scalar_struct(log, btf, ref_t, 0)) {
5737 "arg#%d pointer type %s %s must point to scalar or struct with scalar\n",
5738 i, btf_type_str(ref_t), ref_tname);
5743 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
5744 if (IS_ERR(resolve_ret)) {
5746 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5747 i, btf_type_str(ref_t), ref_tname,
5748 PTR_ERR(resolve_ret));
5752 if (check_mem_reg(env, reg, regno, type_size))
5755 bpf_log(log, "reg type unsupported for arg#%d %sfunction %s#%d\n", i,
5756 is_kfunc ? "kernel " : "", func_name, func_id);
5764 /* Compare BTF of a function with given bpf_reg_state.
5766 * EFAULT - there is a verifier bug. Abort verification.
5767 * EINVAL - there is a type mismatch or BTF is not available.
5768 * 0 - BTF matches with what bpf_reg_state expects.
5769 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
5771 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
5772 struct bpf_reg_state *regs)
5774 struct bpf_prog *prog = env->prog;
5775 struct btf *btf = prog->aux->btf;
5780 if (!prog->aux->func_info)
5783 btf_id = prog->aux->func_info[subprog].type_id;
5787 if (prog->aux->func_info_aux[subprog].unreliable)
5790 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5791 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global);
5793 /* Compiler optimizations can remove arguments from static functions
5794 * or mismatched type can be passed into a global function.
5795 * In such cases mark the function as unreliable from BTF point of view.
5798 prog->aux->func_info_aux[subprog].unreliable = true;
5802 int btf_check_kfunc_arg_match(struct bpf_verifier_env *env,
5803 const struct btf *btf, u32 func_id,
5804 struct bpf_reg_state *regs)
5806 return btf_check_func_arg_match(env, btf, func_id, regs, true);
5809 /* Convert BTF of a function into bpf_reg_state if possible
5811 * EFAULT - there is a verifier bug. Abort verification.
5812 * EINVAL - cannot convert BTF.
5813 * 0 - Successfully converted BTF into bpf_reg_state
5814 * (either PTR_TO_CTX or SCALAR_VALUE).
5816 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
5817 struct bpf_reg_state *regs)
5819 struct bpf_verifier_log *log = &env->log;
5820 struct bpf_prog *prog = env->prog;
5821 enum bpf_prog_type prog_type = prog->type;
5822 struct btf *btf = prog->aux->btf;
5823 const struct btf_param *args;
5824 const struct btf_type *t, *ref_t;
5825 u32 i, nargs, btf_id;
5828 if (!prog->aux->func_info ||
5829 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
5830 bpf_log(log, "Verifier bug\n");
5834 btf_id = prog->aux->func_info[subprog].type_id;
5836 bpf_log(log, "Global functions need valid BTF\n");
5840 t = btf_type_by_id(btf, btf_id);
5841 if (!t || !btf_type_is_func(t)) {
5842 /* These checks were already done by the verifier while loading
5843 * struct bpf_func_info
5845 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5849 tname = btf_name_by_offset(btf, t->name_off);
5851 if (log->level & BPF_LOG_LEVEL)
5852 bpf_log(log, "Validating %s() func#%d...\n",
5855 if (prog->aux->func_info_aux[subprog].unreliable) {
5856 bpf_log(log, "Verifier bug in function %s()\n", tname);
5859 if (prog_type == BPF_PROG_TYPE_EXT)
5860 prog_type = prog->aux->dst_prog->type;
5862 t = btf_type_by_id(btf, t->type);
5863 if (!t || !btf_type_is_func_proto(t)) {
5864 bpf_log(log, "Invalid type of function %s()\n", tname);
5867 args = (const struct btf_param *)(t + 1);
5868 nargs = btf_type_vlen(t);
5869 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
5870 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
5871 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
5874 /* check that function returns int */
5875 t = btf_type_by_id(btf, t->type);
5876 while (btf_type_is_modifier(t))
5877 t = btf_type_by_id(btf, t->type);
5878 if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
5880 "Global function %s() doesn't return scalar. Only those are supported.\n",
5884 /* Convert BTF function arguments into verifier types.
5885 * Only PTR_TO_CTX and SCALAR are supported atm.
5887 for (i = 0; i < nargs; i++) {
5888 struct bpf_reg_state *reg = ®s[i + 1];
5890 t = btf_type_by_id(btf, args[i].type);
5891 while (btf_type_is_modifier(t))
5892 t = btf_type_by_id(btf, t->type);
5893 if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5894 reg->type = SCALAR_VALUE;
5897 if (btf_type_is_ptr(t)) {
5898 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5899 reg->type = PTR_TO_CTX;
5903 t = btf_type_skip_modifiers(btf, t->type, NULL);
5905 ref_t = btf_resolve_size(btf, t, ®->mem_size);
5906 if (IS_ERR(ref_t)) {
5908 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5909 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
5914 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5915 reg->id = ++env->id_gen;
5919 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
5920 i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
5926 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
5927 struct btf_show *show)
5929 const struct btf_type *t = btf_type_by_id(btf, type_id);
5932 memset(&show->state, 0, sizeof(show->state));
5933 memset(&show->obj, 0, sizeof(show->obj));
5935 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
5938 static void btf_seq_show(struct btf_show *show, const char *fmt,
5941 seq_vprintf((struct seq_file *)show->target, fmt, args);
5944 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
5945 void *obj, struct seq_file *m, u64 flags)
5947 struct btf_show sseq;
5950 sseq.showfn = btf_seq_show;
5953 btf_type_show(btf, type_id, obj, &sseq);
5955 return sseq.state.status;
5958 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
5961 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
5962 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
5963 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
5966 struct btf_show_snprintf {
5967 struct btf_show show;
5968 int len_left; /* space left in string */
5969 int len; /* length we would have written */
5972 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
5975 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
5978 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
5981 ssnprintf->len_left = 0;
5982 ssnprintf->len = len;
5983 } else if (len > ssnprintf->len_left) {
5984 /* no space, drive on to get length we would have written */
5985 ssnprintf->len_left = 0;
5986 ssnprintf->len += len;
5988 ssnprintf->len_left -= len;
5989 ssnprintf->len += len;
5990 show->target += len;
5994 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
5995 char *buf, int len, u64 flags)
5997 struct btf_show_snprintf ssnprintf;
5999 ssnprintf.show.target = buf;
6000 ssnprintf.show.flags = flags;
6001 ssnprintf.show.showfn = btf_snprintf_show;
6002 ssnprintf.len_left = len;
6005 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
6007 /* If we encontered an error, return it. */
6008 if (ssnprintf.show.state.status)
6009 return ssnprintf.show.state.status;
6011 /* Otherwise return length we would have written */
6012 return ssnprintf.len;
6015 #ifdef CONFIG_PROC_FS
6016 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
6018 const struct btf *btf = filp->private_data;
6020 seq_printf(m, "btf_id:\t%u\n", btf->id);
6024 static int btf_release(struct inode *inode, struct file *filp)
6026 btf_put(filp->private_data);
6030 const struct file_operations btf_fops = {
6031 #ifdef CONFIG_PROC_FS
6032 .show_fdinfo = bpf_btf_show_fdinfo,
6034 .release = btf_release,
6037 static int __btf_new_fd(struct btf *btf)
6039 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
6042 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
6047 btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
6048 attr->btf_size, attr->btf_log_level,
6049 u64_to_user_ptr(attr->btf_log_buf),
6050 attr->btf_log_size);
6052 return PTR_ERR(btf);
6054 ret = btf_alloc_id(btf);
6061 * The BTF ID is published to the userspace.
6062 * All BTF free must go through call_rcu() from
6063 * now on (i.e. free by calling btf_put()).
6066 ret = __btf_new_fd(btf);
6073 struct btf *btf_get_by_fd(int fd)
6081 return ERR_PTR(-EBADF);
6083 if (f.file->f_op != &btf_fops) {
6085 return ERR_PTR(-EINVAL);
6088 btf = f.file->private_data;
6089 refcount_inc(&btf->refcnt);
6095 int btf_get_info_by_fd(const struct btf *btf,
6096 const union bpf_attr *attr,
6097 union bpf_attr __user *uattr)
6099 struct bpf_btf_info __user *uinfo;
6100 struct bpf_btf_info info;
6101 u32 info_copy, btf_copy;
6104 u32 uinfo_len, uname_len, name_len;
6107 uinfo = u64_to_user_ptr(attr->info.info);
6108 uinfo_len = attr->info.info_len;
6110 info_copy = min_t(u32, uinfo_len, sizeof(info));
6111 memset(&info, 0, sizeof(info));
6112 if (copy_from_user(&info, uinfo, info_copy))
6116 ubtf = u64_to_user_ptr(info.btf);
6117 btf_copy = min_t(u32, btf->data_size, info.btf_size);
6118 if (copy_to_user(ubtf, btf->data, btf_copy))
6120 info.btf_size = btf->data_size;
6122 info.kernel_btf = btf->kernel_btf;
6124 uname = u64_to_user_ptr(info.name);
6125 uname_len = info.name_len;
6126 if (!uname ^ !uname_len)
6129 name_len = strlen(btf->name);
6130 info.name_len = name_len;
6133 if (uname_len >= name_len + 1) {
6134 if (copy_to_user(uname, btf->name, name_len + 1))
6139 if (copy_to_user(uname, btf->name, uname_len - 1))
6141 if (put_user(zero, uname + uname_len - 1))
6143 /* let user-space know about too short buffer */
6148 if (copy_to_user(uinfo, &info, info_copy) ||
6149 put_user(info_copy, &uattr->info.info_len))
6155 int btf_get_fd_by_id(u32 id)
6161 btf = idr_find(&btf_idr, id);
6162 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
6163 btf = ERR_PTR(-ENOENT);
6167 return PTR_ERR(btf);
6169 fd = __btf_new_fd(btf);
6176 u32 btf_obj_id(const struct btf *btf)
6181 bool btf_is_kernel(const struct btf *btf)
6183 return btf->kernel_btf;
6186 bool btf_is_module(const struct btf *btf)
6188 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
6191 static int btf_id_cmp_func(const void *a, const void *b)
6193 const int *pa = a, *pb = b;
6198 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
6200 return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
6203 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6205 struct list_head list;
6206 struct module *module;
6208 struct bin_attribute *sysfs_attr;
6211 static LIST_HEAD(btf_modules);
6212 static DEFINE_MUTEX(btf_module_mutex);
6215 btf_module_read(struct file *file, struct kobject *kobj,
6216 struct bin_attribute *bin_attr,
6217 char *buf, loff_t off, size_t len)
6219 const struct btf *btf = bin_attr->private;
6221 memcpy(buf, btf->data + off, len);
6225 static void purge_cand_cache(struct btf *btf);
6227 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
6230 struct btf_module *btf_mod, *tmp;
6231 struct module *mod = module;
6235 if (mod->btf_data_size == 0 ||
6236 (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
6240 case MODULE_STATE_COMING:
6241 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
6246 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
6248 pr_warn("failed to validate module [%s] BTF: %ld\n",
6249 mod->name, PTR_ERR(btf));
6254 err = btf_alloc_id(btf);
6261 purge_cand_cache(NULL);
6262 mutex_lock(&btf_module_mutex);
6263 btf_mod->module = module;
6265 list_add(&btf_mod->list, &btf_modules);
6266 mutex_unlock(&btf_module_mutex);
6268 if (IS_ENABLED(CONFIG_SYSFS)) {
6269 struct bin_attribute *attr;
6271 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
6275 sysfs_bin_attr_init(attr);
6276 attr->attr.name = btf->name;
6277 attr->attr.mode = 0444;
6278 attr->size = btf->data_size;
6279 attr->private = btf;
6280 attr->read = btf_module_read;
6282 err = sysfs_create_bin_file(btf_kobj, attr);
6284 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
6291 btf_mod->sysfs_attr = attr;
6295 case MODULE_STATE_GOING:
6296 mutex_lock(&btf_module_mutex);
6297 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6298 if (btf_mod->module != module)
6301 list_del(&btf_mod->list);
6302 if (btf_mod->sysfs_attr)
6303 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
6304 purge_cand_cache(btf_mod->btf);
6305 btf_put(btf_mod->btf);
6306 kfree(btf_mod->sysfs_attr);
6310 mutex_unlock(&btf_module_mutex);
6314 return notifier_from_errno(err);
6317 static struct notifier_block btf_module_nb = {
6318 .notifier_call = btf_module_notify,
6321 static int __init btf_module_init(void)
6323 register_module_notifier(&btf_module_nb);
6327 fs_initcall(btf_module_init);
6328 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6330 struct module *btf_try_get_module(const struct btf *btf)
6332 struct module *res = NULL;
6333 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6334 struct btf_module *btf_mod, *tmp;
6336 mutex_lock(&btf_module_mutex);
6337 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6338 if (btf_mod->btf != btf)
6341 if (try_module_get(btf_mod->module))
6342 res = btf_mod->module;
6346 mutex_unlock(&btf_module_mutex);
6352 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
6360 if (name_sz <= 1 || name[name_sz - 1])
6363 btf = bpf_get_btf_vmlinux();
6365 return PTR_ERR(btf);
6367 ret = btf_find_by_name_kind(btf, name, kind);
6368 /* ret is never zero, since btf_find_by_name_kind returns
6369 * positive btf_id or negative error.
6372 struct btf *mod_btf;
6375 /* If name is not found in vmlinux's BTF then search in module's BTFs */
6376 spin_lock_bh(&btf_idr_lock);
6377 idr_for_each_entry(&btf_idr, mod_btf, id) {
6378 if (!btf_is_module(mod_btf))
6380 /* linear search could be slow hence unlock/lock
6381 * the IDR to avoiding holding it for too long
6384 spin_unlock_bh(&btf_idr_lock);
6385 ret = btf_find_by_name_kind(mod_btf, name, kind);
6389 btf_obj_fd = __btf_new_fd(mod_btf);
6390 if (btf_obj_fd < 0) {
6394 return ret | (((u64)btf_obj_fd) << 32);
6396 spin_lock_bh(&btf_idr_lock);
6399 spin_unlock_bh(&btf_idr_lock);
6404 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
6405 .func = bpf_btf_find_by_name_kind,
6407 .ret_type = RET_INTEGER,
6408 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
6409 .arg2_type = ARG_CONST_SIZE,
6410 .arg3_type = ARG_ANYTHING,
6411 .arg4_type = ARG_ANYTHING,
6414 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
6415 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
6416 BTF_TRACING_TYPE_xxx
6417 #undef BTF_TRACING_TYPE
6419 /* BTF ID set registration API for modules */
6421 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6423 void register_kfunc_btf_id_set(struct kfunc_btf_id_list *l,
6424 struct kfunc_btf_id_set *s)
6426 mutex_lock(&l->mutex);
6427 list_add(&s->list, &l->list);
6428 mutex_unlock(&l->mutex);
6430 EXPORT_SYMBOL_GPL(register_kfunc_btf_id_set);
6432 void unregister_kfunc_btf_id_set(struct kfunc_btf_id_list *l,
6433 struct kfunc_btf_id_set *s)
6435 mutex_lock(&l->mutex);
6436 list_del_init(&s->list);
6437 mutex_unlock(&l->mutex);
6439 EXPORT_SYMBOL_GPL(unregister_kfunc_btf_id_set);
6441 bool bpf_check_mod_kfunc_call(struct kfunc_btf_id_list *klist, u32 kfunc_id,
6442 struct module *owner)
6444 struct kfunc_btf_id_set *s;
6446 mutex_lock(&klist->mutex);
6447 list_for_each_entry(s, &klist->list, list) {
6448 if (s->owner == owner && btf_id_set_contains(s->set, kfunc_id)) {
6449 mutex_unlock(&klist->mutex);
6453 mutex_unlock(&klist->mutex);
6457 #define DEFINE_KFUNC_BTF_ID_LIST(name) \
6458 struct kfunc_btf_id_list name = { LIST_HEAD_INIT(name.list), \
6459 __MUTEX_INITIALIZER(name.mutex) }; \
6460 EXPORT_SYMBOL_GPL(name)
6462 DEFINE_KFUNC_BTF_ID_LIST(bpf_tcp_ca_kfunc_list);
6463 DEFINE_KFUNC_BTF_ID_LIST(prog_test_kfunc_list);
6467 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6468 const struct btf *targ_btf, __u32 targ_id)
6473 static bool bpf_core_is_flavor_sep(const char *s)
6475 /* check X___Y name pattern, where X and Y are not underscores */
6476 return s[0] != '_' && /* X */
6477 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
6478 s[4] != '_'; /* Y */
6481 size_t bpf_core_essential_name_len(const char *name)
6483 size_t n = strlen(name);
6486 for (i = n - 5; i >= 0; i--) {
6487 if (bpf_core_is_flavor_sep(name + i))
6493 struct bpf_cand_cache {
6499 const struct btf *btf;
6504 static void bpf_free_cands(struct bpf_cand_cache *cands)
6507 /* empty candidate array was allocated on stack */
6512 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
6518 #define VMLINUX_CAND_CACHE_SIZE 31
6519 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
6521 #define MODULE_CAND_CACHE_SIZE 31
6522 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
6524 static DEFINE_MUTEX(cand_cache_mutex);
6526 static void __print_cand_cache(struct bpf_verifier_log *log,
6527 struct bpf_cand_cache **cache,
6530 struct bpf_cand_cache *cc;
6533 for (i = 0; i < cache_size; i++) {
6537 bpf_log(log, "[%d]%s(", i, cc->name);
6538 for (j = 0; j < cc->cnt; j++) {
6539 bpf_log(log, "%d", cc->cands[j].id);
6540 if (j < cc->cnt - 1)
6543 bpf_log(log, "), ");
6547 static void print_cand_cache(struct bpf_verifier_log *log)
6549 mutex_lock(&cand_cache_mutex);
6550 bpf_log(log, "vmlinux_cand_cache:");
6551 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
6552 bpf_log(log, "\nmodule_cand_cache:");
6553 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
6555 mutex_unlock(&cand_cache_mutex);
6558 static u32 hash_cands(struct bpf_cand_cache *cands)
6560 return jhash(cands->name, cands->name_len, 0);
6563 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
6564 struct bpf_cand_cache **cache,
6567 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
6569 if (cc && cc->name_len == cands->name_len &&
6570 !strncmp(cc->name, cands->name, cands->name_len))
6575 static size_t sizeof_cands(int cnt)
6577 return offsetof(struct bpf_cand_cache, cands[cnt]);
6580 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
6581 struct bpf_cand_cache **cache,
6584 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
6587 bpf_free_cands_from_cache(*cc);
6590 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
6592 bpf_free_cands(cands);
6593 return ERR_PTR(-ENOMEM);
6595 /* strdup the name, since it will stay in cache.
6596 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
6598 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
6599 bpf_free_cands(cands);
6600 if (!new_cands->name) {
6602 return ERR_PTR(-ENOMEM);
6608 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6609 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
6612 struct bpf_cand_cache *cc;
6615 for (i = 0; i < cache_size; i++) {
6620 /* when new module is loaded purge all of module_cand_cache,
6621 * since new module might have candidates with the name
6622 * that matches cached cands.
6624 bpf_free_cands_from_cache(cc);
6628 /* when module is unloaded purge cache entries
6629 * that match module's btf
6631 for (j = 0; j < cc->cnt; j++)
6632 if (cc->cands[j].btf == btf) {
6633 bpf_free_cands_from_cache(cc);
6641 static void purge_cand_cache(struct btf *btf)
6643 mutex_lock(&cand_cache_mutex);
6644 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
6645 mutex_unlock(&cand_cache_mutex);
6649 static struct bpf_cand_cache *
6650 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
6653 struct bpf_cand_cache *new_cands;
6654 const struct btf_type *t;
6655 const char *targ_name;
6656 size_t targ_essent_len;
6659 n = btf_nr_types(targ_btf);
6660 for (i = targ_start_id; i < n; i++) {
6661 t = btf_type_by_id(targ_btf, i);
6662 if (btf_kind(t) != cands->kind)
6665 targ_name = btf_name_by_offset(targ_btf, t->name_off);
6669 /* the resched point is before strncmp to make sure that search
6670 * for non-existing name will have a chance to schedule().
6674 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
6677 targ_essent_len = bpf_core_essential_name_len(targ_name);
6678 if (targ_essent_len != cands->name_len)
6681 /* most of the time there is only one candidate for a given kind+name pair */
6682 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
6684 bpf_free_cands(cands);
6685 return ERR_PTR(-ENOMEM);
6688 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
6689 bpf_free_cands(cands);
6691 cands->cands[cands->cnt].btf = targ_btf;
6692 cands->cands[cands->cnt].id = i;
6698 static struct bpf_cand_cache *
6699 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
6701 struct bpf_cand_cache *cands, *cc, local_cand = {};
6702 const struct btf *local_btf = ctx->btf;
6703 const struct btf_type *local_type;
6704 const struct btf *main_btf;
6705 size_t local_essent_len;
6706 struct btf *mod_btf;
6710 main_btf = bpf_get_btf_vmlinux();
6711 if (IS_ERR(main_btf))
6712 return ERR_CAST(main_btf);
6714 local_type = btf_type_by_id(local_btf, local_type_id);
6716 return ERR_PTR(-EINVAL);
6718 name = btf_name_by_offset(local_btf, local_type->name_off);
6719 if (str_is_empty(name))
6720 return ERR_PTR(-EINVAL);
6721 local_essent_len = bpf_core_essential_name_len(name);
6723 cands = &local_cand;
6725 cands->kind = btf_kind(local_type);
6726 cands->name_len = local_essent_len;
6728 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
6729 /* cands is a pointer to stack here */
6736 /* Attempt to find target candidates in vmlinux BTF first */
6737 cands = bpf_core_add_cands(cands, main_btf, 1);
6739 return ERR_CAST(cands);
6741 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
6743 /* populate cache even when cands->cnt == 0 */
6744 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
6746 return ERR_CAST(cc);
6748 /* if vmlinux BTF has any candidate, don't go for module BTFs */
6753 /* cands is a pointer to stack here and cands->cnt == 0 */
6754 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
6756 /* if cache has it return it even if cc->cnt == 0 */
6759 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
6760 spin_lock_bh(&btf_idr_lock);
6761 idr_for_each_entry(&btf_idr, mod_btf, id) {
6762 if (!btf_is_module(mod_btf))
6764 /* linear search could be slow hence unlock/lock
6765 * the IDR to avoiding holding it for too long
6768 spin_unlock_bh(&btf_idr_lock);
6769 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
6770 if (IS_ERR(cands)) {
6772 return ERR_CAST(cands);
6774 spin_lock_bh(&btf_idr_lock);
6777 spin_unlock_bh(&btf_idr_lock);
6778 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
6779 * or pointer to stack if cands->cnd == 0.
6780 * Copy it into the cache even when cands->cnt == 0 and
6781 * return the result.
6783 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
6786 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
6787 int relo_idx, void *insn)
6789 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
6790 struct bpf_core_cand_list cands = {};
6791 struct bpf_core_spec *specs;
6794 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
6795 * into arrays of btf_ids of struct fields and array indices.
6797 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
6802 struct bpf_cand_cache *cc;
6805 mutex_lock(&cand_cache_mutex);
6806 cc = bpf_core_find_cands(ctx, relo->type_id);
6808 bpf_log(ctx->log, "target candidate search failed for %d\n",
6814 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
6820 for (i = 0; i < cc->cnt; i++) {
6822 "CO-RE relocating %s %s: found target candidate [%d]\n",
6823 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
6824 cands.cands[i].btf = cc->cands[i].btf;
6825 cands.cands[i].id = cc->cands[i].id;
6827 cands.len = cc->cnt;
6828 /* cand_cache_mutex needs to span the cache lookup and
6829 * copy of btf pointer into bpf_core_cand_list,
6830 * since module can be unloaded while bpf_core_apply_relo_insn
6831 * is working with module's btf.
6835 err = bpf_core_apply_relo_insn((void *)ctx->log, insn, relo->insn_off / 8,
6836 relo, relo_idx, ctx->btf, &cands, specs);
6841 mutex_unlock(&cand_cache_mutex);
6842 if (ctx->log->level & BPF_LOG_LEVEL2)
6843 print_cand_cache(ctx->log);