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);
201 enum btf_kfunc_hook {
204 BTF_KFUNC_HOOK_STRUCT_OPS,
205 BTF_KFUNC_HOOK_TRACING,
206 BTF_KFUNC_HOOK_SYSCALL,
211 BTF_KFUNC_SET_MAX_CNT = 32,
212 BTF_DTOR_KFUNC_MAX_CNT = 256,
215 struct btf_kfunc_set_tab {
216 struct btf_id_set *sets[BTF_KFUNC_HOOK_MAX][BTF_KFUNC_TYPE_MAX];
219 struct btf_id_dtor_kfunc_tab {
221 struct btf_id_dtor_kfunc dtors[];
226 struct btf_type **types;
231 struct btf_header hdr;
232 u32 nr_types; /* includes VOID for base BTF */
238 struct btf_kfunc_set_tab *kfunc_set_tab;
239 struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
241 /* split BTF support */
242 struct btf *base_btf;
243 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
244 u32 start_str_off; /* first string offset (0 for base BTF) */
245 char name[MODULE_NAME_LEN];
249 enum verifier_phase {
254 struct resolve_vertex {
255 const struct btf_type *t;
267 RESOLVE_TBD, /* To Be Determined */
268 RESOLVE_PTR, /* Resolving for Pointer */
269 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
274 #define MAX_RESOLVE_DEPTH 32
276 struct btf_sec_info {
281 struct btf_verifier_env {
284 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
285 struct bpf_verifier_log log;
288 enum verifier_phase phase;
289 enum resolve_mode resolve_mode;
292 static const char * const btf_kind_str[NR_BTF_KINDS] = {
293 [BTF_KIND_UNKN] = "UNKNOWN",
294 [BTF_KIND_INT] = "INT",
295 [BTF_KIND_PTR] = "PTR",
296 [BTF_KIND_ARRAY] = "ARRAY",
297 [BTF_KIND_STRUCT] = "STRUCT",
298 [BTF_KIND_UNION] = "UNION",
299 [BTF_KIND_ENUM] = "ENUM",
300 [BTF_KIND_FWD] = "FWD",
301 [BTF_KIND_TYPEDEF] = "TYPEDEF",
302 [BTF_KIND_VOLATILE] = "VOLATILE",
303 [BTF_KIND_CONST] = "CONST",
304 [BTF_KIND_RESTRICT] = "RESTRICT",
305 [BTF_KIND_FUNC] = "FUNC",
306 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
307 [BTF_KIND_VAR] = "VAR",
308 [BTF_KIND_DATASEC] = "DATASEC",
309 [BTF_KIND_FLOAT] = "FLOAT",
310 [BTF_KIND_DECL_TAG] = "DECL_TAG",
311 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
314 const char *btf_type_str(const struct btf_type *t)
316 return btf_kind_str[BTF_INFO_KIND(t->info)];
319 /* Chunk size we use in safe copy of data to be shown. */
320 #define BTF_SHOW_OBJ_SAFE_SIZE 32
323 * This is the maximum size of a base type value (equivalent to a
324 * 128-bit int); if we are at the end of our safe buffer and have
325 * less than 16 bytes space we can't be assured of being able
326 * to copy the next type safely, so in such cases we will initiate
329 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
332 #define BTF_SHOW_NAME_SIZE 80
335 * Common data to all BTF show operations. Private show functions can add
336 * their own data to a structure containing a struct btf_show and consult it
337 * in the show callback. See btf_type_show() below.
339 * One challenge with showing nested data is we want to skip 0-valued
340 * data, but in order to figure out whether a nested object is all zeros
341 * we need to walk through it. As a result, we need to make two passes
342 * when handling structs, unions and arrays; the first path simply looks
343 * for nonzero data, while the second actually does the display. The first
344 * pass is signalled by show->state.depth_check being set, and if we
345 * encounter a non-zero value we set show->state.depth_to_show to
346 * the depth at which we encountered it. When we have completed the
347 * first pass, we will know if anything needs to be displayed if
348 * depth_to_show > depth. See btf_[struct,array]_show() for the
349 * implementation of this.
351 * Another problem is we want to ensure the data for display is safe to
352 * access. To support this, the anonymous "struct {} obj" tracks the data
353 * object and our safe copy of it. We copy portions of the data needed
354 * to the object "copy" buffer, but because its size is limited to
355 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
356 * traverse larger objects for display.
358 * The various data type show functions all start with a call to
359 * btf_show_start_type() which returns a pointer to the safe copy
360 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
361 * raw data itself). btf_show_obj_safe() is responsible for
362 * using copy_from_kernel_nofault() to update the safe data if necessary
363 * as we traverse the object's data. skbuff-like semantics are
366 * - obj.head points to the start of the toplevel object for display
367 * - obj.size is the size of the toplevel object
368 * - obj.data points to the current point in the original data at
369 * which our safe data starts. obj.data will advance as we copy
370 * portions of the data.
372 * In most cases a single copy will suffice, but larger data structures
373 * such as "struct task_struct" will require many copies. The logic in
374 * btf_show_obj_safe() handles the logic that determines if a new
375 * copy_from_kernel_nofault() is needed.
379 void *target; /* target of show operation (seq file, buffer) */
380 void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
381 const struct btf *btf;
382 /* below are used during iteration */
391 int status; /* non-zero for error */
392 const struct btf_type *type;
393 const struct btf_member *member;
394 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
400 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
404 struct btf_kind_operations {
405 s32 (*check_meta)(struct btf_verifier_env *env,
406 const struct btf_type *t,
408 int (*resolve)(struct btf_verifier_env *env,
409 const struct resolve_vertex *v);
410 int (*check_member)(struct btf_verifier_env *env,
411 const struct btf_type *struct_type,
412 const struct btf_member *member,
413 const struct btf_type *member_type);
414 int (*check_kflag_member)(struct btf_verifier_env *env,
415 const struct btf_type *struct_type,
416 const struct btf_member *member,
417 const struct btf_type *member_type);
418 void (*log_details)(struct btf_verifier_env *env,
419 const struct btf_type *t);
420 void (*show)(const struct btf *btf, const struct btf_type *t,
421 u32 type_id, void *data, u8 bits_offsets,
422 struct btf_show *show);
425 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
426 static struct btf_type btf_void;
428 static int btf_resolve(struct btf_verifier_env *env,
429 const struct btf_type *t, u32 type_id);
431 static int btf_func_check(struct btf_verifier_env *env,
432 const struct btf_type *t);
434 static bool btf_type_is_modifier(const struct btf_type *t)
436 /* Some of them is not strictly a C modifier
437 * but they are grouped into the same bucket
439 * A type (t) that refers to another
440 * type through t->type AND its size cannot
441 * be determined without following the t->type.
443 * ptr does not fall into this bucket
444 * because its size is always sizeof(void *).
446 switch (BTF_INFO_KIND(t->info)) {
447 case BTF_KIND_TYPEDEF:
448 case BTF_KIND_VOLATILE:
450 case BTF_KIND_RESTRICT:
451 case BTF_KIND_TYPE_TAG:
458 bool btf_type_is_void(const struct btf_type *t)
460 return t == &btf_void;
463 static bool btf_type_is_fwd(const struct btf_type *t)
465 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
468 static bool btf_type_nosize(const struct btf_type *t)
470 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
471 btf_type_is_func(t) || btf_type_is_func_proto(t);
474 static bool btf_type_nosize_or_null(const struct btf_type *t)
476 return !t || btf_type_nosize(t);
479 static bool __btf_type_is_struct(const struct btf_type *t)
481 return BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT;
484 static bool btf_type_is_array(const struct btf_type *t)
486 return BTF_INFO_KIND(t->info) == BTF_KIND_ARRAY;
489 static bool btf_type_is_datasec(const struct btf_type *t)
491 return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
494 static bool btf_type_is_decl_tag(const struct btf_type *t)
496 return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
499 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
501 return btf_type_is_func(t) || btf_type_is_struct(t) ||
502 btf_type_is_var(t) || btf_type_is_typedef(t);
505 u32 btf_nr_types(const struct btf *btf)
510 total += btf->nr_types;
517 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
519 const struct btf_type *t;
523 total = btf_nr_types(btf);
524 for (i = 1; i < total; i++) {
525 t = btf_type_by_id(btf, i);
526 if (BTF_INFO_KIND(t->info) != kind)
529 tname = btf_name_by_offset(btf, t->name_off);
530 if (!strcmp(tname, name))
537 static s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
543 btf = bpf_get_btf_vmlinux();
549 ret = btf_find_by_name_kind(btf, name, kind);
550 /* ret is never zero, since btf_find_by_name_kind returns
551 * positive btf_id or negative error.
559 /* If name is not found in vmlinux's BTF then search in module's BTFs */
560 spin_lock_bh(&btf_idr_lock);
561 idr_for_each_entry(&btf_idr, btf, id) {
562 if (!btf_is_module(btf))
564 /* linear search could be slow hence unlock/lock
565 * the IDR to avoiding holding it for too long
568 spin_unlock_bh(&btf_idr_lock);
569 ret = btf_find_by_name_kind(btf, name, kind);
574 spin_lock_bh(&btf_idr_lock);
577 spin_unlock_bh(&btf_idr_lock);
581 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
584 const struct btf_type *t = btf_type_by_id(btf, id);
586 while (btf_type_is_modifier(t)) {
588 t = btf_type_by_id(btf, t->type);
597 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
600 const struct btf_type *t;
602 t = btf_type_skip_modifiers(btf, id, NULL);
603 if (!btf_type_is_ptr(t))
606 return btf_type_skip_modifiers(btf, t->type, res_id);
609 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
612 const struct btf_type *ptype;
614 ptype = btf_type_resolve_ptr(btf, id, res_id);
615 if (ptype && btf_type_is_func_proto(ptype))
621 /* Types that act only as a source, not sink or intermediate
622 * type when resolving.
624 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
626 return btf_type_is_var(t) ||
627 btf_type_is_decl_tag(t) ||
628 btf_type_is_datasec(t);
631 /* What types need to be resolved?
633 * btf_type_is_modifier() is an obvious one.
635 * btf_type_is_struct() because its member refers to
636 * another type (through member->type).
638 * btf_type_is_var() because the variable refers to
639 * another type. btf_type_is_datasec() holds multiple
640 * btf_type_is_var() types that need resolving.
642 * btf_type_is_array() because its element (array->type)
643 * refers to another type. Array can be thought of a
644 * special case of struct while array just has the same
645 * member-type repeated by array->nelems of times.
647 static bool btf_type_needs_resolve(const struct btf_type *t)
649 return btf_type_is_modifier(t) ||
650 btf_type_is_ptr(t) ||
651 btf_type_is_struct(t) ||
652 btf_type_is_array(t) ||
653 btf_type_is_var(t) ||
654 btf_type_is_func(t) ||
655 btf_type_is_decl_tag(t) ||
656 btf_type_is_datasec(t);
659 /* t->size can be used */
660 static bool btf_type_has_size(const struct btf_type *t)
662 switch (BTF_INFO_KIND(t->info)) {
664 case BTF_KIND_STRUCT:
667 case BTF_KIND_DATASEC:
675 static const char *btf_int_encoding_str(u8 encoding)
679 else if (encoding == BTF_INT_SIGNED)
681 else if (encoding == BTF_INT_CHAR)
683 else if (encoding == BTF_INT_BOOL)
689 static u32 btf_type_int(const struct btf_type *t)
691 return *(u32 *)(t + 1);
694 static const struct btf_array *btf_type_array(const struct btf_type *t)
696 return (const struct btf_array *)(t + 1);
699 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
701 return (const struct btf_enum *)(t + 1);
704 static const struct btf_var *btf_type_var(const struct btf_type *t)
706 return (const struct btf_var *)(t + 1);
709 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
711 return (const struct btf_decl_tag *)(t + 1);
714 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
716 return kind_ops[BTF_INFO_KIND(t->info)];
719 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
721 if (!BTF_STR_OFFSET_VALID(offset))
724 while (offset < btf->start_str_off)
727 offset -= btf->start_str_off;
728 return offset < btf->hdr.str_len;
731 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
733 if ((first ? !isalpha(c) :
736 ((c == '.' && !dot_ok) ||
742 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
744 while (offset < btf->start_str_off)
747 offset -= btf->start_str_off;
748 if (offset < btf->hdr.str_len)
749 return &btf->strings[offset];
754 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
756 /* offset must be valid */
757 const char *src = btf_str_by_offset(btf, offset);
758 const char *src_limit;
760 if (!__btf_name_char_ok(*src, true, dot_ok))
763 /* set a limit on identifier length */
764 src_limit = src + KSYM_NAME_LEN;
766 while (*src && src < src_limit) {
767 if (!__btf_name_char_ok(*src, false, dot_ok))
775 /* Only C-style identifier is permitted. This can be relaxed if
778 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
780 return __btf_name_valid(btf, offset, false);
783 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
785 return __btf_name_valid(btf, offset, true);
788 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
795 name = btf_str_by_offset(btf, offset);
796 return name ?: "(invalid-name-offset)";
799 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
801 return btf_str_by_offset(btf, offset);
804 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
806 while (type_id < btf->start_id)
809 type_id -= btf->start_id;
810 if (type_id >= btf->nr_types)
812 return btf->types[type_id];
816 * Regular int is not a bit field and it must be either
817 * u8/u16/u32/u64 or __int128.
819 static bool btf_type_int_is_regular(const struct btf_type *t)
821 u8 nr_bits, nr_bytes;
824 int_data = btf_type_int(t);
825 nr_bits = BTF_INT_BITS(int_data);
826 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
827 if (BITS_PER_BYTE_MASKED(nr_bits) ||
828 BTF_INT_OFFSET(int_data) ||
829 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
830 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
831 nr_bytes != (2 * sizeof(u64)))) {
839 * Check that given struct member is a regular int with expected
842 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
843 const struct btf_member *m,
844 u32 expected_offset, u32 expected_size)
846 const struct btf_type *t;
851 t = btf_type_id_size(btf, &id, NULL);
852 if (!t || !btf_type_is_int(t))
855 int_data = btf_type_int(t);
856 nr_bits = BTF_INT_BITS(int_data);
857 if (btf_type_kflag(s)) {
858 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
859 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
861 /* if kflag set, int should be a regular int and
862 * bit offset should be at byte boundary.
864 return !bitfield_size &&
865 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
866 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
869 if (BTF_INT_OFFSET(int_data) ||
870 BITS_PER_BYTE_MASKED(m->offset) ||
871 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
872 BITS_PER_BYTE_MASKED(nr_bits) ||
873 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
879 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
880 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
883 const struct btf_type *t = btf_type_by_id(btf, id);
885 while (btf_type_is_modifier(t) &&
886 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
887 t = btf_type_by_id(btf, t->type);
893 #define BTF_SHOW_MAX_ITER 10
895 #define BTF_KIND_BIT(kind) (1ULL << kind)
898 * Populate show->state.name with type name information.
899 * Format of type name is
901 * [.member_name = ] (type_name)
903 static const char *btf_show_name(struct btf_show *show)
905 /* BTF_MAX_ITER array suffixes "[]" */
906 const char *array_suffixes = "[][][][][][][][][][]";
907 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
908 /* BTF_MAX_ITER pointer suffixes "*" */
909 const char *ptr_suffixes = "**********";
910 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
911 const char *name = NULL, *prefix = "", *parens = "";
912 const struct btf_member *m = show->state.member;
913 const struct btf_type *t;
914 const struct btf_array *array;
915 u32 id = show->state.type_id;
916 const char *member = NULL;
917 bool show_member = false;
921 show->state.name[0] = '\0';
924 * Don't show type name if we're showing an array member;
925 * in that case we show the array type so don't need to repeat
926 * ourselves for each member.
928 if (show->state.array_member)
931 /* Retrieve member name, if any. */
933 member = btf_name_by_offset(show->btf, m->name_off);
934 show_member = strlen(member) > 0;
939 * Start with type_id, as we have resolved the struct btf_type *
940 * via btf_modifier_show() past the parent typedef to the child
941 * struct, int etc it is defined as. In such cases, the type_id
942 * still represents the starting type while the struct btf_type *
943 * in our show->state points at the resolved type of the typedef.
945 t = btf_type_by_id(show->btf, id);
950 * The goal here is to build up the right number of pointer and
951 * array suffixes while ensuring the type name for a typedef
952 * is represented. Along the way we accumulate a list of
953 * BTF kinds we have encountered, since these will inform later
954 * display; for example, pointer types will not require an
955 * opening "{" for struct, we will just display the pointer value.
957 * We also want to accumulate the right number of pointer or array
958 * indices in the format string while iterating until we get to
959 * the typedef/pointee/array member target type.
961 * We start by pointing at the end of pointer and array suffix
962 * strings; as we accumulate pointers and arrays we move the pointer
963 * or array string backwards so it will show the expected number of
964 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
965 * and/or arrays and typedefs are supported as a precaution.
967 * We also want to get typedef name while proceeding to resolve
968 * type it points to so that we can add parentheses if it is a
969 * "typedef struct" etc.
971 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
973 switch (BTF_INFO_KIND(t->info)) {
974 case BTF_KIND_TYPEDEF:
976 name = btf_name_by_offset(show->btf,
978 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
982 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
986 array = btf_type_array(t);
987 if (array_suffix > array_suffixes)
992 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
993 if (ptr_suffix > ptr_suffixes)
1003 t = btf_type_skip_qualifiers(show->btf, id);
1005 /* We may not be able to represent this type; bail to be safe */
1006 if (i == BTF_SHOW_MAX_ITER)
1010 name = btf_name_by_offset(show->btf, t->name_off);
1012 switch (BTF_INFO_KIND(t->info)) {
1013 case BTF_KIND_STRUCT:
1014 case BTF_KIND_UNION:
1015 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1017 /* if it's an array of struct/union, parens is already set */
1018 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1028 /* pointer does not require parens */
1029 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1031 /* typedef does not require struct/union/enum prefix */
1032 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1038 /* Even if we don't want type name info, we want parentheses etc */
1039 if (show->flags & BTF_SHOW_NONAME)
1040 snprintf(show->state.name, sizeof(show->state.name), "%s",
1043 snprintf(show->state.name, sizeof(show->state.name),
1044 "%s%s%s(%s%s%s%s%s%s)%s",
1045 /* first 3 strings comprise ".member = " */
1046 show_member ? "." : "",
1047 show_member ? member : "",
1048 show_member ? " = " : "",
1049 /* ...next is our prefix (struct, enum, etc) */
1051 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1052 /* ...this is the type name itself */
1054 /* ...suffixed by the appropriate '*', '[]' suffixes */
1055 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1056 array_suffix, parens);
1058 return show->state.name;
1061 static const char *__btf_show_indent(struct btf_show *show)
1063 const char *indents = " ";
1064 const char *indent = &indents[strlen(indents)];
1066 if ((indent - show->state.depth) >= indents)
1067 return indent - show->state.depth;
1071 static const char *btf_show_indent(struct btf_show *show)
1073 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1076 static const char *btf_show_newline(struct btf_show *show)
1078 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1081 static const char *btf_show_delim(struct btf_show *show)
1083 if (show->state.depth == 0)
1086 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1087 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1093 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1097 if (!show->state.depth_check) {
1098 va_start(args, fmt);
1099 show->showfn(show, fmt, args);
1104 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1105 * format specifiers to the format specifier passed in; these do the work of
1106 * adding indentation, delimiters etc while the caller simply has to specify
1107 * the type value(s) in the format specifier + value(s).
1109 #define btf_show_type_value(show, fmt, value) \
1111 if ((value) != 0 || (show->flags & BTF_SHOW_ZERO) || \
1112 show->state.depth == 0) { \
1113 btf_show(show, "%s%s" fmt "%s%s", \
1114 btf_show_indent(show), \
1115 btf_show_name(show), \
1116 value, btf_show_delim(show), \
1117 btf_show_newline(show)); \
1118 if (show->state.depth > show->state.depth_to_show) \
1119 show->state.depth_to_show = show->state.depth; \
1123 #define btf_show_type_values(show, fmt, ...) \
1125 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1126 btf_show_name(show), \
1127 __VA_ARGS__, btf_show_delim(show), \
1128 btf_show_newline(show)); \
1129 if (show->state.depth > show->state.depth_to_show) \
1130 show->state.depth_to_show = show->state.depth; \
1133 /* How much is left to copy to safe buffer after @data? */
1134 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1136 return show->obj.head + show->obj.size - data;
1139 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1140 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1142 return data >= show->obj.data &&
1143 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1147 * If object pointed to by @data of @size falls within our safe buffer, return
1148 * the equivalent pointer to the same safe data. Assumes
1149 * copy_from_kernel_nofault() has already happened and our safe buffer is
1152 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1154 if (btf_show_obj_is_safe(show, data, size))
1155 return show->obj.safe + (data - show->obj.data);
1160 * Return a safe-to-access version of data pointed to by @data.
1161 * We do this by copying the relevant amount of information
1162 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1164 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1165 * safe copy is needed.
1167 * Otherwise we need to determine if we have the required amount
1168 * of data (determined by the @data pointer and the size of the
1169 * largest base type we can encounter (represented by
1170 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1171 * that we will be able to print some of the current object,
1172 * and if more is needed a copy will be triggered.
1173 * Some objects such as structs will not fit into the buffer;
1174 * in such cases additional copies when we iterate over their
1175 * members may be needed.
1177 * btf_show_obj_safe() is used to return a safe buffer for
1178 * btf_show_start_type(); this ensures that as we recurse into
1179 * nested types we always have safe data for the given type.
1180 * This approach is somewhat wasteful; it's possible for example
1181 * that when iterating over a large union we'll end up copying the
1182 * same data repeatedly, but the goal is safety not performance.
1183 * We use stack data as opposed to per-CPU buffers because the
1184 * iteration over a type can take some time, and preemption handling
1185 * would greatly complicate use of the safe buffer.
1187 static void *btf_show_obj_safe(struct btf_show *show,
1188 const struct btf_type *t,
1191 const struct btf_type *rt;
1192 int size_left, size;
1195 if (show->flags & BTF_SHOW_UNSAFE)
1198 rt = btf_resolve_size(show->btf, t, &size);
1200 show->state.status = PTR_ERR(rt);
1205 * Is this toplevel object? If so, set total object size and
1206 * initialize pointers. Otherwise check if we still fall within
1207 * our safe object data.
1209 if (show->state.depth == 0) {
1210 show->obj.size = size;
1211 show->obj.head = data;
1214 * If the size of the current object is > our remaining
1215 * safe buffer we _may_ need to do a new copy. However
1216 * consider the case of a nested struct; it's size pushes
1217 * us over the safe buffer limit, but showing any individual
1218 * struct members does not. In such cases, we don't need
1219 * to initiate a fresh copy yet; however we definitely need
1220 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1221 * in our buffer, regardless of the current object size.
1222 * The logic here is that as we resolve types we will
1223 * hit a base type at some point, and we need to be sure
1224 * the next chunk of data is safely available to display
1225 * that type info safely. We cannot rely on the size of
1226 * the current object here because it may be much larger
1227 * than our current buffer (e.g. task_struct is 8k).
1228 * All we want to do here is ensure that we can print the
1229 * next basic type, which we can if either
1230 * - the current type size is within the safe buffer; or
1231 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1234 safe = __btf_show_obj_safe(show, data,
1236 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1240 * We need a new copy to our safe object, either because we haven't
1241 * yet copied and are initializing safe data, or because the data
1242 * we want falls outside the boundaries of the safe object.
1245 size_left = btf_show_obj_size_left(show, data);
1246 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1247 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1248 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1250 if (!show->state.status) {
1251 show->obj.data = data;
1252 safe = show->obj.safe;
1260 * Set the type we are starting to show and return a safe data pointer
1261 * to be used for showing the associated data.
1263 static void *btf_show_start_type(struct btf_show *show,
1264 const struct btf_type *t,
1265 u32 type_id, void *data)
1267 show->state.type = t;
1268 show->state.type_id = type_id;
1269 show->state.name[0] = '\0';
1271 return btf_show_obj_safe(show, t, data);
1274 static void btf_show_end_type(struct btf_show *show)
1276 show->state.type = NULL;
1277 show->state.type_id = 0;
1278 show->state.name[0] = '\0';
1281 static void *btf_show_start_aggr_type(struct btf_show *show,
1282 const struct btf_type *t,
1283 u32 type_id, void *data)
1285 void *safe_data = btf_show_start_type(show, t, type_id, data);
1290 btf_show(show, "%s%s%s", btf_show_indent(show),
1291 btf_show_name(show),
1292 btf_show_newline(show));
1293 show->state.depth++;
1297 static void btf_show_end_aggr_type(struct btf_show *show,
1300 show->state.depth--;
1301 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1302 btf_show_delim(show), btf_show_newline(show));
1303 btf_show_end_type(show);
1306 static void btf_show_start_member(struct btf_show *show,
1307 const struct btf_member *m)
1309 show->state.member = m;
1312 static void btf_show_start_array_member(struct btf_show *show)
1314 show->state.array_member = 1;
1315 btf_show_start_member(show, NULL);
1318 static void btf_show_end_member(struct btf_show *show)
1320 show->state.member = NULL;
1323 static void btf_show_end_array_member(struct btf_show *show)
1325 show->state.array_member = 0;
1326 btf_show_end_member(show);
1329 static void *btf_show_start_array_type(struct btf_show *show,
1330 const struct btf_type *t,
1335 show->state.array_encoding = array_encoding;
1336 show->state.array_terminated = 0;
1337 return btf_show_start_aggr_type(show, t, type_id, data);
1340 static void btf_show_end_array_type(struct btf_show *show)
1342 show->state.array_encoding = 0;
1343 show->state.array_terminated = 0;
1344 btf_show_end_aggr_type(show, "]");
1347 static void *btf_show_start_struct_type(struct btf_show *show,
1348 const struct btf_type *t,
1352 return btf_show_start_aggr_type(show, t, type_id, data);
1355 static void btf_show_end_struct_type(struct btf_show *show)
1357 btf_show_end_aggr_type(show, "}");
1360 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1361 const char *fmt, ...)
1365 va_start(args, fmt);
1366 bpf_verifier_vlog(log, fmt, args);
1370 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1371 const char *fmt, ...)
1373 struct bpf_verifier_log *log = &env->log;
1376 if (!bpf_verifier_log_needed(log))
1379 va_start(args, fmt);
1380 bpf_verifier_vlog(log, fmt, args);
1384 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1385 const struct btf_type *t,
1387 const char *fmt, ...)
1389 struct bpf_verifier_log *log = &env->log;
1390 u8 kind = BTF_INFO_KIND(t->info);
1391 struct btf *btf = env->btf;
1394 if (!bpf_verifier_log_needed(log))
1397 /* btf verifier prints all types it is processing via
1398 * btf_verifier_log_type(..., fmt = NULL).
1399 * Skip those prints for in-kernel BTF verification.
1401 if (log->level == BPF_LOG_KERNEL && !fmt)
1404 __btf_verifier_log(log, "[%u] %s %s%s",
1407 __btf_name_by_offset(btf, t->name_off),
1408 log_details ? " " : "");
1411 btf_type_ops(t)->log_details(env, t);
1414 __btf_verifier_log(log, " ");
1415 va_start(args, fmt);
1416 bpf_verifier_vlog(log, fmt, args);
1420 __btf_verifier_log(log, "\n");
1423 #define btf_verifier_log_type(env, t, ...) \
1424 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1425 #define btf_verifier_log_basic(env, t, ...) \
1426 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1429 static void btf_verifier_log_member(struct btf_verifier_env *env,
1430 const struct btf_type *struct_type,
1431 const struct btf_member *member,
1432 const char *fmt, ...)
1434 struct bpf_verifier_log *log = &env->log;
1435 struct btf *btf = env->btf;
1438 if (!bpf_verifier_log_needed(log))
1441 if (log->level == BPF_LOG_KERNEL && !fmt)
1443 /* The CHECK_META phase already did a btf dump.
1445 * If member is logged again, it must hit an error in
1446 * parsing this member. It is useful to print out which
1447 * struct this member belongs to.
1449 if (env->phase != CHECK_META)
1450 btf_verifier_log_type(env, struct_type, NULL);
1452 if (btf_type_kflag(struct_type))
1453 __btf_verifier_log(log,
1454 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1455 __btf_name_by_offset(btf, member->name_off),
1457 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1458 BTF_MEMBER_BIT_OFFSET(member->offset));
1460 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1461 __btf_name_by_offset(btf, member->name_off),
1462 member->type, member->offset);
1465 __btf_verifier_log(log, " ");
1466 va_start(args, fmt);
1467 bpf_verifier_vlog(log, fmt, args);
1471 __btf_verifier_log(log, "\n");
1475 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1476 const struct btf_type *datasec_type,
1477 const struct btf_var_secinfo *vsi,
1478 const char *fmt, ...)
1480 struct bpf_verifier_log *log = &env->log;
1483 if (!bpf_verifier_log_needed(log))
1485 if (log->level == BPF_LOG_KERNEL && !fmt)
1487 if (env->phase != CHECK_META)
1488 btf_verifier_log_type(env, datasec_type, NULL);
1490 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1491 vsi->type, vsi->offset, vsi->size);
1493 __btf_verifier_log(log, " ");
1494 va_start(args, fmt);
1495 bpf_verifier_vlog(log, fmt, args);
1499 __btf_verifier_log(log, "\n");
1502 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1505 struct bpf_verifier_log *log = &env->log;
1506 const struct btf *btf = env->btf;
1507 const struct btf_header *hdr;
1509 if (!bpf_verifier_log_needed(log))
1512 if (log->level == BPF_LOG_KERNEL)
1515 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1516 __btf_verifier_log(log, "version: %u\n", hdr->version);
1517 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1518 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1519 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1520 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1521 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1522 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1523 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1526 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1528 struct btf *btf = env->btf;
1530 if (btf->types_size == btf->nr_types) {
1531 /* Expand 'types' array */
1533 struct btf_type **new_types;
1534 u32 expand_by, new_size;
1536 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1537 btf_verifier_log(env, "Exceeded max num of types");
1541 expand_by = max_t(u32, btf->types_size >> 2, 16);
1542 new_size = min_t(u32, BTF_MAX_TYPE,
1543 btf->types_size + expand_by);
1545 new_types = kvcalloc(new_size, sizeof(*new_types),
1546 GFP_KERNEL | __GFP_NOWARN);
1550 if (btf->nr_types == 0) {
1551 if (!btf->base_btf) {
1552 /* lazily init VOID type */
1553 new_types[0] = &btf_void;
1557 memcpy(new_types, btf->types,
1558 sizeof(*btf->types) * btf->nr_types);
1562 btf->types = new_types;
1563 btf->types_size = new_size;
1566 btf->types[btf->nr_types++] = t;
1571 static int btf_alloc_id(struct btf *btf)
1575 idr_preload(GFP_KERNEL);
1576 spin_lock_bh(&btf_idr_lock);
1577 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1580 spin_unlock_bh(&btf_idr_lock);
1583 if (WARN_ON_ONCE(!id))
1586 return id > 0 ? 0 : id;
1589 static void btf_free_id(struct btf *btf)
1591 unsigned long flags;
1594 * In map-in-map, calling map_delete_elem() on outer
1595 * map will call bpf_map_put on the inner map.
1596 * It will then eventually call btf_free_id()
1597 * on the inner map. Some of the map_delete_elem()
1598 * implementation may have irq disabled, so
1599 * we need to use the _irqsave() version instead
1600 * of the _bh() version.
1602 spin_lock_irqsave(&btf_idr_lock, flags);
1603 idr_remove(&btf_idr, btf->id);
1604 spin_unlock_irqrestore(&btf_idr_lock, flags);
1607 static void btf_free_kfunc_set_tab(struct btf *btf)
1609 struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1614 /* For module BTF, we directly assign the sets being registered, so
1615 * there is nothing to free except kfunc_set_tab.
1617 if (btf_is_module(btf))
1619 for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++) {
1620 for (type = 0; type < ARRAY_SIZE(tab->sets[0]); type++)
1621 kfree(tab->sets[hook][type]);
1625 btf->kfunc_set_tab = NULL;
1628 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1630 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1635 btf->dtor_kfunc_tab = NULL;
1638 static void btf_free(struct btf *btf)
1640 btf_free_dtor_kfunc_tab(btf);
1641 btf_free_kfunc_set_tab(btf);
1643 kvfree(btf->resolved_sizes);
1644 kvfree(btf->resolved_ids);
1649 static void btf_free_rcu(struct rcu_head *rcu)
1651 struct btf *btf = container_of(rcu, struct btf, rcu);
1656 void btf_get(struct btf *btf)
1658 refcount_inc(&btf->refcnt);
1661 void btf_put(struct btf *btf)
1663 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1665 call_rcu(&btf->rcu, btf_free_rcu);
1669 static int env_resolve_init(struct btf_verifier_env *env)
1671 struct btf *btf = env->btf;
1672 u32 nr_types = btf->nr_types;
1673 u32 *resolved_sizes = NULL;
1674 u32 *resolved_ids = NULL;
1675 u8 *visit_states = NULL;
1677 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1678 GFP_KERNEL | __GFP_NOWARN);
1679 if (!resolved_sizes)
1682 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1683 GFP_KERNEL | __GFP_NOWARN);
1687 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1688 GFP_KERNEL | __GFP_NOWARN);
1692 btf->resolved_sizes = resolved_sizes;
1693 btf->resolved_ids = resolved_ids;
1694 env->visit_states = visit_states;
1699 kvfree(resolved_sizes);
1700 kvfree(resolved_ids);
1701 kvfree(visit_states);
1705 static void btf_verifier_env_free(struct btf_verifier_env *env)
1707 kvfree(env->visit_states);
1711 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1712 const struct btf_type *next_type)
1714 switch (env->resolve_mode) {
1716 /* int, enum or void is a sink */
1717 return !btf_type_needs_resolve(next_type);
1719 /* int, enum, void, struct, array, func or func_proto is a sink
1722 return !btf_type_is_modifier(next_type) &&
1723 !btf_type_is_ptr(next_type);
1724 case RESOLVE_STRUCT_OR_ARRAY:
1725 /* int, enum, void, ptr, func or func_proto is a sink
1726 * for struct and array
1728 return !btf_type_is_modifier(next_type) &&
1729 !btf_type_is_array(next_type) &&
1730 !btf_type_is_struct(next_type);
1736 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1739 /* base BTF types should be resolved by now */
1740 if (type_id < env->btf->start_id)
1743 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1746 static int env_stack_push(struct btf_verifier_env *env,
1747 const struct btf_type *t, u32 type_id)
1749 const struct btf *btf = env->btf;
1750 struct resolve_vertex *v;
1752 if (env->top_stack == MAX_RESOLVE_DEPTH)
1755 if (type_id < btf->start_id
1756 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1759 env->visit_states[type_id - btf->start_id] = VISITED;
1761 v = &env->stack[env->top_stack++];
1763 v->type_id = type_id;
1766 if (env->resolve_mode == RESOLVE_TBD) {
1767 if (btf_type_is_ptr(t))
1768 env->resolve_mode = RESOLVE_PTR;
1769 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1770 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1776 static void env_stack_set_next_member(struct btf_verifier_env *env,
1779 env->stack[env->top_stack - 1].next_member = next_member;
1782 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1783 u32 resolved_type_id,
1786 u32 type_id = env->stack[--(env->top_stack)].type_id;
1787 struct btf *btf = env->btf;
1789 type_id -= btf->start_id; /* adjust to local type id */
1790 btf->resolved_sizes[type_id] = resolved_size;
1791 btf->resolved_ids[type_id] = resolved_type_id;
1792 env->visit_states[type_id] = RESOLVED;
1795 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1797 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1800 /* Resolve the size of a passed-in "type"
1802 * type: is an array (e.g. u32 array[x][y])
1803 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1804 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1805 * corresponds to the return type.
1807 * *elem_id: id of u32
1808 * *total_nelems: (x * y). Hence, individual elem size is
1809 * (*type_size / *total_nelems)
1810 * *type_id: id of type if it's changed within the function, 0 if not
1812 * type: is not an array (e.g. const struct X)
1813 * return type: type "struct X"
1814 * *type_size: sizeof(struct X)
1815 * *elem_type: same as return type ("struct X")
1818 * *type_id: id of type if it's changed within the function, 0 if not
1820 static const struct btf_type *
1821 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1822 u32 *type_size, const struct btf_type **elem_type,
1823 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1825 const struct btf_type *array_type = NULL;
1826 const struct btf_array *array = NULL;
1827 u32 i, size, nelems = 1, id = 0;
1829 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1830 switch (BTF_INFO_KIND(type->info)) {
1831 /* type->size can be used */
1833 case BTF_KIND_STRUCT:
1834 case BTF_KIND_UNION:
1836 case BTF_KIND_FLOAT:
1841 size = sizeof(void *);
1845 case BTF_KIND_TYPEDEF:
1846 case BTF_KIND_VOLATILE:
1847 case BTF_KIND_CONST:
1848 case BTF_KIND_RESTRICT:
1849 case BTF_KIND_TYPE_TAG:
1851 type = btf_type_by_id(btf, type->type);
1854 case BTF_KIND_ARRAY:
1857 array = btf_type_array(type);
1858 if (nelems && array->nelems > U32_MAX / nelems)
1859 return ERR_PTR(-EINVAL);
1860 nelems *= array->nelems;
1861 type = btf_type_by_id(btf, array->type);
1864 /* type without size */
1866 return ERR_PTR(-EINVAL);
1870 return ERR_PTR(-EINVAL);
1873 if (nelems && size > U32_MAX / nelems)
1874 return ERR_PTR(-EINVAL);
1876 *type_size = nelems * size;
1878 *total_nelems = nelems;
1882 *elem_id = array ? array->type : 0;
1886 return array_type ? : type;
1889 const struct btf_type *
1890 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1893 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1896 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1898 while (type_id < btf->start_id)
1899 btf = btf->base_btf;
1901 return btf->resolved_ids[type_id - btf->start_id];
1904 /* The input param "type_id" must point to a needs_resolve type */
1905 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1908 *type_id = btf_resolved_type_id(btf, *type_id);
1909 return btf_type_by_id(btf, *type_id);
1912 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1914 while (type_id < btf->start_id)
1915 btf = btf->base_btf;
1917 return btf->resolved_sizes[type_id - btf->start_id];
1920 const struct btf_type *btf_type_id_size(const struct btf *btf,
1921 u32 *type_id, u32 *ret_size)
1923 const struct btf_type *size_type;
1924 u32 size_type_id = *type_id;
1927 size_type = btf_type_by_id(btf, size_type_id);
1928 if (btf_type_nosize_or_null(size_type))
1931 if (btf_type_has_size(size_type)) {
1932 size = size_type->size;
1933 } else if (btf_type_is_array(size_type)) {
1934 size = btf_resolved_type_size(btf, size_type_id);
1935 } else if (btf_type_is_ptr(size_type)) {
1936 size = sizeof(void *);
1938 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1939 !btf_type_is_var(size_type)))
1942 size_type_id = btf_resolved_type_id(btf, size_type_id);
1943 size_type = btf_type_by_id(btf, size_type_id);
1944 if (btf_type_nosize_or_null(size_type))
1946 else if (btf_type_has_size(size_type))
1947 size = size_type->size;
1948 else if (btf_type_is_array(size_type))
1949 size = btf_resolved_type_size(btf, size_type_id);
1950 else if (btf_type_is_ptr(size_type))
1951 size = sizeof(void *);
1956 *type_id = size_type_id;
1963 static int btf_df_check_member(struct btf_verifier_env *env,
1964 const struct btf_type *struct_type,
1965 const struct btf_member *member,
1966 const struct btf_type *member_type)
1968 btf_verifier_log_basic(env, struct_type,
1969 "Unsupported check_member");
1973 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1974 const struct btf_type *struct_type,
1975 const struct btf_member *member,
1976 const struct btf_type *member_type)
1978 btf_verifier_log_basic(env, struct_type,
1979 "Unsupported check_kflag_member");
1983 /* Used for ptr, array struct/union and float type members.
1984 * int, enum and modifier types have their specific callback functions.
1986 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1987 const struct btf_type *struct_type,
1988 const struct btf_member *member,
1989 const struct btf_type *member_type)
1991 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1992 btf_verifier_log_member(env, struct_type, member,
1993 "Invalid member bitfield_size");
1997 /* bitfield size is 0, so member->offset represents bit offset only.
1998 * It is safe to call non kflag check_member variants.
2000 return btf_type_ops(member_type)->check_member(env, struct_type,
2005 static int btf_df_resolve(struct btf_verifier_env *env,
2006 const struct resolve_vertex *v)
2008 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2012 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2013 u32 type_id, void *data, u8 bits_offsets,
2014 struct btf_show *show)
2016 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2019 static int btf_int_check_member(struct btf_verifier_env *env,
2020 const struct btf_type *struct_type,
2021 const struct btf_member *member,
2022 const struct btf_type *member_type)
2024 u32 int_data = btf_type_int(member_type);
2025 u32 struct_bits_off = member->offset;
2026 u32 struct_size = struct_type->size;
2030 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2031 btf_verifier_log_member(env, struct_type, member,
2032 "bits_offset exceeds U32_MAX");
2036 struct_bits_off += BTF_INT_OFFSET(int_data);
2037 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2038 nr_copy_bits = BTF_INT_BITS(int_data) +
2039 BITS_PER_BYTE_MASKED(struct_bits_off);
2041 if (nr_copy_bits > BITS_PER_U128) {
2042 btf_verifier_log_member(env, struct_type, member,
2043 "nr_copy_bits exceeds 128");
2047 if (struct_size < bytes_offset ||
2048 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2049 btf_verifier_log_member(env, struct_type, member,
2050 "Member exceeds struct_size");
2057 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2058 const struct btf_type *struct_type,
2059 const struct btf_member *member,
2060 const struct btf_type *member_type)
2062 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2063 u32 int_data = btf_type_int(member_type);
2064 u32 struct_size = struct_type->size;
2067 /* a regular int type is required for the kflag int member */
2068 if (!btf_type_int_is_regular(member_type)) {
2069 btf_verifier_log_member(env, struct_type, member,
2070 "Invalid member base type");
2074 /* check sanity of bitfield size */
2075 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2076 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2077 nr_int_data_bits = BTF_INT_BITS(int_data);
2079 /* Not a bitfield member, member offset must be at byte
2082 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2083 btf_verifier_log_member(env, struct_type, member,
2084 "Invalid member offset");
2088 nr_bits = nr_int_data_bits;
2089 } else if (nr_bits > nr_int_data_bits) {
2090 btf_verifier_log_member(env, struct_type, member,
2091 "Invalid member bitfield_size");
2095 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2096 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2097 if (nr_copy_bits > BITS_PER_U128) {
2098 btf_verifier_log_member(env, struct_type, member,
2099 "nr_copy_bits exceeds 128");
2103 if (struct_size < bytes_offset ||
2104 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2105 btf_verifier_log_member(env, struct_type, member,
2106 "Member exceeds struct_size");
2113 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2114 const struct btf_type *t,
2117 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2120 if (meta_left < meta_needed) {
2121 btf_verifier_log_basic(env, t,
2122 "meta_left:%u meta_needed:%u",
2123 meta_left, meta_needed);
2127 if (btf_type_vlen(t)) {
2128 btf_verifier_log_type(env, t, "vlen != 0");
2132 if (btf_type_kflag(t)) {
2133 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2137 int_data = btf_type_int(t);
2138 if (int_data & ~BTF_INT_MASK) {
2139 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2144 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2146 if (nr_bits > BITS_PER_U128) {
2147 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2152 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2153 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2158 * Only one of the encoding bits is allowed and it
2159 * should be sufficient for the pretty print purpose (i.e. decoding).
2160 * Multiple bits can be allowed later if it is found
2161 * to be insufficient.
2163 encoding = BTF_INT_ENCODING(int_data);
2165 encoding != BTF_INT_SIGNED &&
2166 encoding != BTF_INT_CHAR &&
2167 encoding != BTF_INT_BOOL) {
2168 btf_verifier_log_type(env, t, "Unsupported encoding");
2172 btf_verifier_log_type(env, t, NULL);
2177 static void btf_int_log(struct btf_verifier_env *env,
2178 const struct btf_type *t)
2180 int int_data = btf_type_int(t);
2182 btf_verifier_log(env,
2183 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2184 t->size, BTF_INT_OFFSET(int_data),
2185 BTF_INT_BITS(int_data),
2186 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2189 static void btf_int128_print(struct btf_show *show, void *data)
2191 /* data points to a __int128 number.
2193 * int128_num = *(__int128 *)data;
2194 * The below formulas shows what upper_num and lower_num represents:
2195 * upper_num = int128_num >> 64;
2196 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2198 u64 upper_num, lower_num;
2200 #ifdef __BIG_ENDIAN_BITFIELD
2201 upper_num = *(u64 *)data;
2202 lower_num = *(u64 *)(data + 8);
2204 upper_num = *(u64 *)(data + 8);
2205 lower_num = *(u64 *)data;
2208 btf_show_type_value(show, "0x%llx", lower_num);
2210 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2214 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2215 u16 right_shift_bits)
2217 u64 upper_num, lower_num;
2219 #ifdef __BIG_ENDIAN_BITFIELD
2220 upper_num = print_num[0];
2221 lower_num = print_num[1];
2223 upper_num = print_num[1];
2224 lower_num = print_num[0];
2227 /* shake out un-needed bits by shift/or operations */
2228 if (left_shift_bits >= 64) {
2229 upper_num = lower_num << (left_shift_bits - 64);
2232 upper_num = (upper_num << left_shift_bits) |
2233 (lower_num >> (64 - left_shift_bits));
2234 lower_num = lower_num << left_shift_bits;
2237 if (right_shift_bits >= 64) {
2238 lower_num = upper_num >> (right_shift_bits - 64);
2241 lower_num = (lower_num >> right_shift_bits) |
2242 (upper_num << (64 - right_shift_bits));
2243 upper_num = upper_num >> right_shift_bits;
2246 #ifdef __BIG_ENDIAN_BITFIELD
2247 print_num[0] = upper_num;
2248 print_num[1] = lower_num;
2250 print_num[0] = lower_num;
2251 print_num[1] = upper_num;
2255 static void btf_bitfield_show(void *data, u8 bits_offset,
2256 u8 nr_bits, struct btf_show *show)
2258 u16 left_shift_bits, right_shift_bits;
2261 u64 print_num[2] = {};
2263 nr_copy_bits = nr_bits + bits_offset;
2264 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2266 memcpy(print_num, data, nr_copy_bytes);
2268 #ifdef __BIG_ENDIAN_BITFIELD
2269 left_shift_bits = bits_offset;
2271 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2273 right_shift_bits = BITS_PER_U128 - nr_bits;
2275 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2276 btf_int128_print(show, print_num);
2280 static void btf_int_bits_show(const struct btf *btf,
2281 const struct btf_type *t,
2282 void *data, u8 bits_offset,
2283 struct btf_show *show)
2285 u32 int_data = btf_type_int(t);
2286 u8 nr_bits = BTF_INT_BITS(int_data);
2287 u8 total_bits_offset;
2290 * bits_offset is at most 7.
2291 * BTF_INT_OFFSET() cannot exceed 128 bits.
2293 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2294 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2295 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2296 btf_bitfield_show(data, bits_offset, nr_bits, show);
2299 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2300 u32 type_id, void *data, u8 bits_offset,
2301 struct btf_show *show)
2303 u32 int_data = btf_type_int(t);
2304 u8 encoding = BTF_INT_ENCODING(int_data);
2305 bool sign = encoding & BTF_INT_SIGNED;
2306 u8 nr_bits = BTF_INT_BITS(int_data);
2309 safe_data = btf_show_start_type(show, t, type_id, data);
2313 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2314 BITS_PER_BYTE_MASKED(nr_bits)) {
2315 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2321 btf_int128_print(show, safe_data);
2325 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2327 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2331 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2333 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2337 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2339 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2342 if (show->state.array_encoding == BTF_INT_CHAR) {
2343 /* check for null terminator */
2344 if (show->state.array_terminated)
2346 if (*(char *)data == '\0') {
2347 show->state.array_terminated = 1;
2350 if (isprint(*(char *)data)) {
2351 btf_show_type_value(show, "'%c'",
2352 *(char *)safe_data);
2357 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2359 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2362 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2366 btf_show_end_type(show);
2369 static const struct btf_kind_operations int_ops = {
2370 .check_meta = btf_int_check_meta,
2371 .resolve = btf_df_resolve,
2372 .check_member = btf_int_check_member,
2373 .check_kflag_member = btf_int_check_kflag_member,
2374 .log_details = btf_int_log,
2375 .show = btf_int_show,
2378 static int btf_modifier_check_member(struct btf_verifier_env *env,
2379 const struct btf_type *struct_type,
2380 const struct btf_member *member,
2381 const struct btf_type *member_type)
2383 const struct btf_type *resolved_type;
2384 u32 resolved_type_id = member->type;
2385 struct btf_member resolved_member;
2386 struct btf *btf = env->btf;
2388 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2389 if (!resolved_type) {
2390 btf_verifier_log_member(env, struct_type, member,
2395 resolved_member = *member;
2396 resolved_member.type = resolved_type_id;
2398 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2403 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2404 const struct btf_type *struct_type,
2405 const struct btf_member *member,
2406 const struct btf_type *member_type)
2408 const struct btf_type *resolved_type;
2409 u32 resolved_type_id = member->type;
2410 struct btf_member resolved_member;
2411 struct btf *btf = env->btf;
2413 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2414 if (!resolved_type) {
2415 btf_verifier_log_member(env, struct_type, member,
2420 resolved_member = *member;
2421 resolved_member.type = resolved_type_id;
2423 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2428 static int btf_ptr_check_member(struct btf_verifier_env *env,
2429 const struct btf_type *struct_type,
2430 const struct btf_member *member,
2431 const struct btf_type *member_type)
2433 u32 struct_size, struct_bits_off, bytes_offset;
2435 struct_size = struct_type->size;
2436 struct_bits_off = member->offset;
2437 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2439 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2440 btf_verifier_log_member(env, struct_type, member,
2441 "Member is not byte aligned");
2445 if (struct_size - bytes_offset < sizeof(void *)) {
2446 btf_verifier_log_member(env, struct_type, member,
2447 "Member exceeds struct_size");
2454 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2455 const struct btf_type *t,
2460 if (btf_type_vlen(t)) {
2461 btf_verifier_log_type(env, t, "vlen != 0");
2465 if (btf_type_kflag(t)) {
2466 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2470 if (!BTF_TYPE_ID_VALID(t->type)) {
2471 btf_verifier_log_type(env, t, "Invalid type_id");
2475 /* typedef/type_tag type must have a valid name, and other ref types,
2476 * volatile, const, restrict, should have a null name.
2478 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2480 !btf_name_valid_identifier(env->btf, t->name_off)) {
2481 btf_verifier_log_type(env, t, "Invalid name");
2484 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2485 value = btf_name_by_offset(env->btf, t->name_off);
2486 if (!value || !value[0]) {
2487 btf_verifier_log_type(env, t, "Invalid name");
2492 btf_verifier_log_type(env, t, "Invalid name");
2497 btf_verifier_log_type(env, t, NULL);
2502 static int btf_modifier_resolve(struct btf_verifier_env *env,
2503 const struct resolve_vertex *v)
2505 const struct btf_type *t = v->t;
2506 const struct btf_type *next_type;
2507 u32 next_type_id = t->type;
2508 struct btf *btf = env->btf;
2510 next_type = btf_type_by_id(btf, next_type_id);
2511 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2512 btf_verifier_log_type(env, v->t, "Invalid type_id");
2516 if (!env_type_is_resolve_sink(env, next_type) &&
2517 !env_type_is_resolved(env, next_type_id))
2518 return env_stack_push(env, next_type, next_type_id);
2520 /* Figure out the resolved next_type_id with size.
2521 * They will be stored in the current modifier's
2522 * resolved_ids and resolved_sizes such that it can
2523 * save us a few type-following when we use it later (e.g. in
2526 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2527 if (env_type_is_resolved(env, next_type_id))
2528 next_type = btf_type_id_resolve(btf, &next_type_id);
2530 /* "typedef void new_void", "const void"...etc */
2531 if (!btf_type_is_void(next_type) &&
2532 !btf_type_is_fwd(next_type) &&
2533 !btf_type_is_func_proto(next_type)) {
2534 btf_verifier_log_type(env, v->t, "Invalid type_id");
2539 env_stack_pop_resolved(env, next_type_id, 0);
2544 static int btf_var_resolve(struct btf_verifier_env *env,
2545 const struct resolve_vertex *v)
2547 const struct btf_type *next_type;
2548 const struct btf_type *t = v->t;
2549 u32 next_type_id = t->type;
2550 struct btf *btf = env->btf;
2552 next_type = btf_type_by_id(btf, next_type_id);
2553 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2554 btf_verifier_log_type(env, v->t, "Invalid type_id");
2558 if (!env_type_is_resolve_sink(env, next_type) &&
2559 !env_type_is_resolved(env, next_type_id))
2560 return env_stack_push(env, next_type, next_type_id);
2562 if (btf_type_is_modifier(next_type)) {
2563 const struct btf_type *resolved_type;
2564 u32 resolved_type_id;
2566 resolved_type_id = next_type_id;
2567 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2569 if (btf_type_is_ptr(resolved_type) &&
2570 !env_type_is_resolve_sink(env, resolved_type) &&
2571 !env_type_is_resolved(env, resolved_type_id))
2572 return env_stack_push(env, resolved_type,
2576 /* We must resolve to something concrete at this point, no
2577 * forward types or similar that would resolve to size of
2580 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2581 btf_verifier_log_type(env, v->t, "Invalid type_id");
2585 env_stack_pop_resolved(env, next_type_id, 0);
2590 static int btf_ptr_resolve(struct btf_verifier_env *env,
2591 const struct resolve_vertex *v)
2593 const struct btf_type *next_type;
2594 const struct btf_type *t = v->t;
2595 u32 next_type_id = t->type;
2596 struct btf *btf = env->btf;
2598 next_type = btf_type_by_id(btf, next_type_id);
2599 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2600 btf_verifier_log_type(env, v->t, "Invalid type_id");
2604 if (!env_type_is_resolve_sink(env, next_type) &&
2605 !env_type_is_resolved(env, next_type_id))
2606 return env_stack_push(env, next_type, next_type_id);
2608 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2609 * the modifier may have stopped resolving when it was resolved
2610 * to a ptr (last-resolved-ptr).
2612 * We now need to continue from the last-resolved-ptr to
2613 * ensure the last-resolved-ptr will not referring back to
2614 * the current ptr (t).
2616 if (btf_type_is_modifier(next_type)) {
2617 const struct btf_type *resolved_type;
2618 u32 resolved_type_id;
2620 resolved_type_id = next_type_id;
2621 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2623 if (btf_type_is_ptr(resolved_type) &&
2624 !env_type_is_resolve_sink(env, resolved_type) &&
2625 !env_type_is_resolved(env, resolved_type_id))
2626 return env_stack_push(env, resolved_type,
2630 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2631 if (env_type_is_resolved(env, next_type_id))
2632 next_type = btf_type_id_resolve(btf, &next_type_id);
2634 if (!btf_type_is_void(next_type) &&
2635 !btf_type_is_fwd(next_type) &&
2636 !btf_type_is_func_proto(next_type)) {
2637 btf_verifier_log_type(env, v->t, "Invalid type_id");
2642 env_stack_pop_resolved(env, next_type_id, 0);
2647 static void btf_modifier_show(const struct btf *btf,
2648 const struct btf_type *t,
2649 u32 type_id, void *data,
2650 u8 bits_offset, struct btf_show *show)
2652 if (btf->resolved_ids)
2653 t = btf_type_id_resolve(btf, &type_id);
2655 t = btf_type_skip_modifiers(btf, type_id, NULL);
2657 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2660 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2661 u32 type_id, void *data, u8 bits_offset,
2662 struct btf_show *show)
2664 t = btf_type_id_resolve(btf, &type_id);
2666 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2669 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2670 u32 type_id, void *data, u8 bits_offset,
2671 struct btf_show *show)
2675 safe_data = btf_show_start_type(show, t, type_id, data);
2679 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2680 if (show->flags & BTF_SHOW_PTR_RAW)
2681 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2683 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2684 btf_show_end_type(show);
2687 static void btf_ref_type_log(struct btf_verifier_env *env,
2688 const struct btf_type *t)
2690 btf_verifier_log(env, "type_id=%u", t->type);
2693 static struct btf_kind_operations modifier_ops = {
2694 .check_meta = btf_ref_type_check_meta,
2695 .resolve = btf_modifier_resolve,
2696 .check_member = btf_modifier_check_member,
2697 .check_kflag_member = btf_modifier_check_kflag_member,
2698 .log_details = btf_ref_type_log,
2699 .show = btf_modifier_show,
2702 static struct btf_kind_operations ptr_ops = {
2703 .check_meta = btf_ref_type_check_meta,
2704 .resolve = btf_ptr_resolve,
2705 .check_member = btf_ptr_check_member,
2706 .check_kflag_member = btf_generic_check_kflag_member,
2707 .log_details = btf_ref_type_log,
2708 .show = btf_ptr_show,
2711 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2712 const struct btf_type *t,
2715 if (btf_type_vlen(t)) {
2716 btf_verifier_log_type(env, t, "vlen != 0");
2721 btf_verifier_log_type(env, t, "type != 0");
2725 /* fwd type must have a valid name */
2727 !btf_name_valid_identifier(env->btf, t->name_off)) {
2728 btf_verifier_log_type(env, t, "Invalid name");
2732 btf_verifier_log_type(env, t, NULL);
2737 static void btf_fwd_type_log(struct btf_verifier_env *env,
2738 const struct btf_type *t)
2740 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2743 static struct btf_kind_operations fwd_ops = {
2744 .check_meta = btf_fwd_check_meta,
2745 .resolve = btf_df_resolve,
2746 .check_member = btf_df_check_member,
2747 .check_kflag_member = btf_df_check_kflag_member,
2748 .log_details = btf_fwd_type_log,
2749 .show = btf_df_show,
2752 static int btf_array_check_member(struct btf_verifier_env *env,
2753 const struct btf_type *struct_type,
2754 const struct btf_member *member,
2755 const struct btf_type *member_type)
2757 u32 struct_bits_off = member->offset;
2758 u32 struct_size, bytes_offset;
2759 u32 array_type_id, array_size;
2760 struct btf *btf = env->btf;
2762 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2763 btf_verifier_log_member(env, struct_type, member,
2764 "Member is not byte aligned");
2768 array_type_id = member->type;
2769 btf_type_id_size(btf, &array_type_id, &array_size);
2770 struct_size = struct_type->size;
2771 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2772 if (struct_size - bytes_offset < array_size) {
2773 btf_verifier_log_member(env, struct_type, member,
2774 "Member exceeds struct_size");
2781 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2782 const struct btf_type *t,
2785 const struct btf_array *array = btf_type_array(t);
2786 u32 meta_needed = sizeof(*array);
2788 if (meta_left < meta_needed) {
2789 btf_verifier_log_basic(env, t,
2790 "meta_left:%u meta_needed:%u",
2791 meta_left, meta_needed);
2795 /* array type should not have a name */
2797 btf_verifier_log_type(env, t, "Invalid name");
2801 if (btf_type_vlen(t)) {
2802 btf_verifier_log_type(env, t, "vlen != 0");
2806 if (btf_type_kflag(t)) {
2807 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2812 btf_verifier_log_type(env, t, "size != 0");
2816 /* Array elem type and index type cannot be in type void,
2817 * so !array->type and !array->index_type are not allowed.
2819 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2820 btf_verifier_log_type(env, t, "Invalid elem");
2824 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2825 btf_verifier_log_type(env, t, "Invalid index");
2829 btf_verifier_log_type(env, t, NULL);
2834 static int btf_array_resolve(struct btf_verifier_env *env,
2835 const struct resolve_vertex *v)
2837 const struct btf_array *array = btf_type_array(v->t);
2838 const struct btf_type *elem_type, *index_type;
2839 u32 elem_type_id, index_type_id;
2840 struct btf *btf = env->btf;
2843 /* Check array->index_type */
2844 index_type_id = array->index_type;
2845 index_type = btf_type_by_id(btf, index_type_id);
2846 if (btf_type_nosize_or_null(index_type) ||
2847 btf_type_is_resolve_source_only(index_type)) {
2848 btf_verifier_log_type(env, v->t, "Invalid index");
2852 if (!env_type_is_resolve_sink(env, index_type) &&
2853 !env_type_is_resolved(env, index_type_id))
2854 return env_stack_push(env, index_type, index_type_id);
2856 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2857 if (!index_type || !btf_type_is_int(index_type) ||
2858 !btf_type_int_is_regular(index_type)) {
2859 btf_verifier_log_type(env, v->t, "Invalid index");
2863 /* Check array->type */
2864 elem_type_id = array->type;
2865 elem_type = btf_type_by_id(btf, elem_type_id);
2866 if (btf_type_nosize_or_null(elem_type) ||
2867 btf_type_is_resolve_source_only(elem_type)) {
2868 btf_verifier_log_type(env, v->t,
2873 if (!env_type_is_resolve_sink(env, elem_type) &&
2874 !env_type_is_resolved(env, elem_type_id))
2875 return env_stack_push(env, elem_type, elem_type_id);
2877 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2879 btf_verifier_log_type(env, v->t, "Invalid elem");
2883 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2884 btf_verifier_log_type(env, v->t, "Invalid array of int");
2888 if (array->nelems && elem_size > U32_MAX / array->nelems) {
2889 btf_verifier_log_type(env, v->t,
2890 "Array size overflows U32_MAX");
2894 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2899 static void btf_array_log(struct btf_verifier_env *env,
2900 const struct btf_type *t)
2902 const struct btf_array *array = btf_type_array(t);
2904 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2905 array->type, array->index_type, array->nelems);
2908 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2909 u32 type_id, void *data, u8 bits_offset,
2910 struct btf_show *show)
2912 const struct btf_array *array = btf_type_array(t);
2913 const struct btf_kind_operations *elem_ops;
2914 const struct btf_type *elem_type;
2915 u32 i, elem_size = 0, elem_type_id;
2918 elem_type_id = array->type;
2919 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2920 if (elem_type && btf_type_has_size(elem_type))
2921 elem_size = elem_type->size;
2923 if (elem_type && btf_type_is_int(elem_type)) {
2924 u32 int_type = btf_type_int(elem_type);
2926 encoding = BTF_INT_ENCODING(int_type);
2929 * BTF_INT_CHAR encoding never seems to be set for
2930 * char arrays, so if size is 1 and element is
2931 * printable as a char, we'll do that.
2934 encoding = BTF_INT_CHAR;
2937 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2942 elem_ops = btf_type_ops(elem_type);
2944 for (i = 0; i < array->nelems; i++) {
2946 btf_show_start_array_member(show);
2948 elem_ops->show(btf, elem_type, elem_type_id, data,
2952 btf_show_end_array_member(show);
2954 if (show->state.array_terminated)
2958 btf_show_end_array_type(show);
2961 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2962 u32 type_id, void *data, u8 bits_offset,
2963 struct btf_show *show)
2965 const struct btf_member *m = show->state.member;
2968 * First check if any members would be shown (are non-zero).
2969 * See comments above "struct btf_show" definition for more
2970 * details on how this works at a high-level.
2972 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2973 if (!show->state.depth_check) {
2974 show->state.depth_check = show->state.depth + 1;
2975 show->state.depth_to_show = 0;
2977 __btf_array_show(btf, t, type_id, data, bits_offset, show);
2978 show->state.member = m;
2980 if (show->state.depth_check != show->state.depth + 1)
2982 show->state.depth_check = 0;
2984 if (show->state.depth_to_show <= show->state.depth)
2987 * Reaching here indicates we have recursed and found
2988 * non-zero array member(s).
2991 __btf_array_show(btf, t, type_id, data, bits_offset, show);
2994 static struct btf_kind_operations array_ops = {
2995 .check_meta = btf_array_check_meta,
2996 .resolve = btf_array_resolve,
2997 .check_member = btf_array_check_member,
2998 .check_kflag_member = btf_generic_check_kflag_member,
2999 .log_details = btf_array_log,
3000 .show = btf_array_show,
3003 static int btf_struct_check_member(struct btf_verifier_env *env,
3004 const struct btf_type *struct_type,
3005 const struct btf_member *member,
3006 const struct btf_type *member_type)
3008 u32 struct_bits_off = member->offset;
3009 u32 struct_size, bytes_offset;
3011 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3012 btf_verifier_log_member(env, struct_type, member,
3013 "Member is not byte aligned");
3017 struct_size = struct_type->size;
3018 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3019 if (struct_size - bytes_offset < member_type->size) {
3020 btf_verifier_log_member(env, struct_type, member,
3021 "Member exceeds struct_size");
3028 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3029 const struct btf_type *t,
3032 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3033 const struct btf_member *member;
3034 u32 meta_needed, last_offset;
3035 struct btf *btf = env->btf;
3036 u32 struct_size = t->size;
3040 meta_needed = btf_type_vlen(t) * sizeof(*member);
3041 if (meta_left < meta_needed) {
3042 btf_verifier_log_basic(env, t,
3043 "meta_left:%u meta_needed:%u",
3044 meta_left, meta_needed);
3048 /* struct type either no name or a valid one */
3050 !btf_name_valid_identifier(env->btf, t->name_off)) {
3051 btf_verifier_log_type(env, t, "Invalid name");
3055 btf_verifier_log_type(env, t, NULL);
3058 for_each_member(i, t, member) {
3059 if (!btf_name_offset_valid(btf, member->name_off)) {
3060 btf_verifier_log_member(env, t, member,
3061 "Invalid member name_offset:%u",
3066 /* struct member either no name or a valid one */
3067 if (member->name_off &&
3068 !btf_name_valid_identifier(btf, member->name_off)) {
3069 btf_verifier_log_member(env, t, member, "Invalid name");
3072 /* A member cannot be in type void */
3073 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3074 btf_verifier_log_member(env, t, member,
3079 offset = __btf_member_bit_offset(t, member);
3080 if (is_union && offset) {
3081 btf_verifier_log_member(env, t, member,
3082 "Invalid member bits_offset");
3087 * ">" instead of ">=" because the last member could be
3090 if (last_offset > offset) {
3091 btf_verifier_log_member(env, t, member,
3092 "Invalid member bits_offset");
3096 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3097 btf_verifier_log_member(env, t, member,
3098 "Member bits_offset exceeds its struct size");
3102 btf_verifier_log_member(env, t, member, NULL);
3103 last_offset = offset;
3109 static int btf_struct_resolve(struct btf_verifier_env *env,
3110 const struct resolve_vertex *v)
3112 const struct btf_member *member;
3116 /* Before continue resolving the next_member,
3117 * ensure the last member is indeed resolved to a
3118 * type with size info.
3120 if (v->next_member) {
3121 const struct btf_type *last_member_type;
3122 const struct btf_member *last_member;
3123 u16 last_member_type_id;
3125 last_member = btf_type_member(v->t) + v->next_member - 1;
3126 last_member_type_id = last_member->type;
3127 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3128 last_member_type_id)))
3131 last_member_type = btf_type_by_id(env->btf,
3132 last_member_type_id);
3133 if (btf_type_kflag(v->t))
3134 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3138 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3145 for_each_member_from(i, v->next_member, v->t, member) {
3146 u32 member_type_id = member->type;
3147 const struct btf_type *member_type = btf_type_by_id(env->btf,
3150 if (btf_type_nosize_or_null(member_type) ||
3151 btf_type_is_resolve_source_only(member_type)) {
3152 btf_verifier_log_member(env, v->t, member,
3157 if (!env_type_is_resolve_sink(env, member_type) &&
3158 !env_type_is_resolved(env, member_type_id)) {
3159 env_stack_set_next_member(env, i + 1);
3160 return env_stack_push(env, member_type, member_type_id);
3163 if (btf_type_kflag(v->t))
3164 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3168 err = btf_type_ops(member_type)->check_member(env, v->t,
3175 env_stack_pop_resolved(env, 0, 0);
3180 static void btf_struct_log(struct btf_verifier_env *env,
3181 const struct btf_type *t)
3183 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3186 enum btf_field_type {
3187 BTF_FIELD_SPIN_LOCK,
3193 BTF_FIELD_IGNORE = 0,
3194 BTF_FIELD_FOUND = 1,
3197 struct btf_field_info {
3200 enum bpf_kptr_type type;
3203 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3204 u32 off, int sz, struct btf_field_info *info)
3206 if (!__btf_type_is_struct(t))
3207 return BTF_FIELD_IGNORE;
3209 return BTF_FIELD_IGNORE;
3211 return BTF_FIELD_FOUND;
3214 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3215 u32 off, int sz, struct btf_field_info *info)
3217 enum bpf_kptr_type type;
3220 /* For PTR, sz is always == 8 */
3221 if (!btf_type_is_ptr(t))
3222 return BTF_FIELD_IGNORE;
3223 t = btf_type_by_id(btf, t->type);
3225 if (!btf_type_is_type_tag(t))
3226 return BTF_FIELD_IGNORE;
3227 /* Reject extra tags */
3228 if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3230 if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3231 type = BPF_KPTR_UNREF;
3232 else if (!strcmp("kptr_ref", __btf_name_by_offset(btf, t->name_off)))
3233 type = BPF_KPTR_REF;
3237 /* Get the base type */
3238 t = btf_type_skip_modifiers(btf, t->type, &res_id);
3239 /* Only pointer to struct is allowed */
3240 if (!__btf_type_is_struct(t))
3243 info->type_id = res_id;
3246 return BTF_FIELD_FOUND;
3249 static int btf_find_struct_field(const struct btf *btf, const struct btf_type *t,
3250 const char *name, int sz, int align,
3251 enum btf_field_type field_type,
3252 struct btf_field_info *info, int info_cnt)
3254 const struct btf_member *member;
3255 struct btf_field_info tmp;
3259 for_each_member(i, t, member) {
3260 const struct btf_type *member_type = btf_type_by_id(btf,
3263 if (name && strcmp(__btf_name_by_offset(btf, member_type->name_off), name))
3266 off = __btf_member_bit_offset(t, member);
3268 /* valid C code cannot generate such BTF */
3274 switch (field_type) {
3275 case BTF_FIELD_SPIN_LOCK:
3276 case BTF_FIELD_TIMER:
3277 ret = btf_find_struct(btf, member_type, off, sz,
3278 idx < info_cnt ? &info[idx] : &tmp);
3282 case BTF_FIELD_KPTR:
3283 ret = btf_find_kptr(btf, member_type, off, sz,
3284 idx < info_cnt ? &info[idx] : &tmp);
3292 if (ret == BTF_FIELD_IGNORE)
3294 if (idx >= info_cnt)
3301 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3302 const char *name, int sz, int align,
3303 enum btf_field_type field_type,
3304 struct btf_field_info *info, int info_cnt)
3306 const struct btf_var_secinfo *vsi;
3307 struct btf_field_info tmp;
3311 for_each_vsi(i, t, vsi) {
3312 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3313 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3317 if (name && strcmp(__btf_name_by_offset(btf, var_type->name_off), name))
3319 if (vsi->size != sz)
3324 switch (field_type) {
3325 case BTF_FIELD_SPIN_LOCK:
3326 case BTF_FIELD_TIMER:
3327 ret = btf_find_struct(btf, var_type, off, sz,
3328 idx < info_cnt ? &info[idx] : &tmp);
3332 case BTF_FIELD_KPTR:
3333 ret = btf_find_kptr(btf, var_type, off, sz,
3334 idx < info_cnt ? &info[idx] : &tmp);
3342 if (ret == BTF_FIELD_IGNORE)
3344 if (idx >= info_cnt)
3351 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3352 enum btf_field_type field_type,
3353 struct btf_field_info *info, int info_cnt)
3358 switch (field_type) {
3359 case BTF_FIELD_SPIN_LOCK:
3360 name = "bpf_spin_lock";
3361 sz = sizeof(struct bpf_spin_lock);
3362 align = __alignof__(struct bpf_spin_lock);
3364 case BTF_FIELD_TIMER:
3366 sz = sizeof(struct bpf_timer);
3367 align = __alignof__(struct bpf_timer);
3369 case BTF_FIELD_KPTR:
3378 if (__btf_type_is_struct(t))
3379 return btf_find_struct_field(btf, t, name, sz, align, field_type, info, info_cnt);
3380 else if (btf_type_is_datasec(t))
3381 return btf_find_datasec_var(btf, t, name, sz, align, field_type, info, info_cnt);
3385 /* find 'struct bpf_spin_lock' in map value.
3386 * return >= 0 offset if found
3387 * and < 0 in case of error
3389 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3391 struct btf_field_info info;
3394 ret = btf_find_field(btf, t, BTF_FIELD_SPIN_LOCK, &info, 1);
3402 int btf_find_timer(const struct btf *btf, const struct btf_type *t)
3404 struct btf_field_info info;
3407 ret = btf_find_field(btf, t, BTF_FIELD_TIMER, &info, 1);
3415 struct bpf_map_value_off *btf_parse_kptrs(const struct btf *btf,
3416 const struct btf_type *t)
3418 struct btf_field_info info_arr[BPF_MAP_VALUE_OFF_MAX];
3419 struct bpf_map_value_off *tab;
3420 struct btf *kernel_btf = NULL;
3421 struct module *mod = NULL;
3424 ret = btf_find_field(btf, t, BTF_FIELD_KPTR, info_arr, ARRAY_SIZE(info_arr));
3426 return ERR_PTR(ret);
3431 tab = kzalloc(offsetof(struct bpf_map_value_off, off[nr_off]), GFP_KERNEL | __GFP_NOWARN);
3433 return ERR_PTR(-ENOMEM);
3435 for (i = 0; i < nr_off; i++) {
3436 const struct btf_type *t;
3439 /* Find type in map BTF, and use it to look up the matching type
3440 * in vmlinux or module BTFs, by name and kind.
3442 t = btf_type_by_id(btf, info_arr[i].type_id);
3443 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3450 /* Find and stash the function pointer for the destruction function that
3451 * needs to be eventually invoked from the map free path.
3453 if (info_arr[i].type == BPF_KPTR_REF) {
3454 const struct btf_type *dtor_func;
3455 const char *dtor_func_name;
3459 /* This call also serves as a whitelist of allowed objects that
3460 * can be used as a referenced pointer and be stored in a map at
3463 dtor_btf_id = btf_find_dtor_kfunc(kernel_btf, id);
3464 if (dtor_btf_id < 0) {
3469 dtor_func = btf_type_by_id(kernel_btf, dtor_btf_id);
3475 if (btf_is_module(kernel_btf)) {
3476 mod = btf_try_get_module(kernel_btf);
3483 /* We already verified dtor_func to be btf_type_is_func
3484 * in register_btf_id_dtor_kfuncs.
3486 dtor_func_name = __btf_name_by_offset(kernel_btf, dtor_func->name_off);
3487 addr = kallsyms_lookup_name(dtor_func_name);
3492 tab->off[i].kptr.dtor = (void *)addr;
3495 tab->off[i].offset = info_arr[i].off;
3496 tab->off[i].type = info_arr[i].type;
3497 tab->off[i].kptr.btf_id = id;
3498 tab->off[i].kptr.btf = kernel_btf;
3499 tab->off[i].kptr.module = mod;
3501 tab->nr_off = nr_off;
3506 btf_put(kernel_btf);
3509 btf_put(tab->off[i].kptr.btf);
3510 if (tab->off[i].kptr.module)
3511 module_put(tab->off[i].kptr.module);
3514 return ERR_PTR(ret);
3517 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3518 u32 type_id, void *data, u8 bits_offset,
3519 struct btf_show *show)
3521 const struct btf_member *member;
3525 safe_data = btf_show_start_struct_type(show, t, type_id, data);
3529 for_each_member(i, t, member) {
3530 const struct btf_type *member_type = btf_type_by_id(btf,
3532 const struct btf_kind_operations *ops;
3533 u32 member_offset, bitfield_size;
3537 btf_show_start_member(show, member);
3539 member_offset = __btf_member_bit_offset(t, member);
3540 bitfield_size = __btf_member_bitfield_size(t, member);
3541 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3542 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3543 if (bitfield_size) {
3544 safe_data = btf_show_start_type(show, member_type,
3546 data + bytes_offset);
3548 btf_bitfield_show(safe_data,
3550 bitfield_size, show);
3551 btf_show_end_type(show);
3553 ops = btf_type_ops(member_type);
3554 ops->show(btf, member_type, member->type,
3555 data + bytes_offset, bits8_offset, show);
3558 btf_show_end_member(show);
3561 btf_show_end_struct_type(show);
3564 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3565 u32 type_id, void *data, u8 bits_offset,
3566 struct btf_show *show)
3568 const struct btf_member *m = show->state.member;
3571 * First check if any members would be shown (are non-zero).
3572 * See comments above "struct btf_show" definition for more
3573 * details on how this works at a high-level.
3575 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3576 if (!show->state.depth_check) {
3577 show->state.depth_check = show->state.depth + 1;
3578 show->state.depth_to_show = 0;
3580 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3581 /* Restore saved member data here */
3582 show->state.member = m;
3583 if (show->state.depth_check != show->state.depth + 1)
3585 show->state.depth_check = 0;
3587 if (show->state.depth_to_show <= show->state.depth)
3590 * Reaching here indicates we have recursed and found
3591 * non-zero child values.
3595 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3598 static struct btf_kind_operations struct_ops = {
3599 .check_meta = btf_struct_check_meta,
3600 .resolve = btf_struct_resolve,
3601 .check_member = btf_struct_check_member,
3602 .check_kflag_member = btf_generic_check_kflag_member,
3603 .log_details = btf_struct_log,
3604 .show = btf_struct_show,
3607 static int btf_enum_check_member(struct btf_verifier_env *env,
3608 const struct btf_type *struct_type,
3609 const struct btf_member *member,
3610 const struct btf_type *member_type)
3612 u32 struct_bits_off = member->offset;
3613 u32 struct_size, bytes_offset;
3615 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3616 btf_verifier_log_member(env, struct_type, member,
3617 "Member is not byte aligned");
3621 struct_size = struct_type->size;
3622 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3623 if (struct_size - bytes_offset < member_type->size) {
3624 btf_verifier_log_member(env, struct_type, member,
3625 "Member exceeds struct_size");
3632 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3633 const struct btf_type *struct_type,
3634 const struct btf_member *member,
3635 const struct btf_type *member_type)
3637 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3638 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3640 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3641 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3643 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3644 btf_verifier_log_member(env, struct_type, member,
3645 "Member is not byte aligned");
3649 nr_bits = int_bitsize;
3650 } else if (nr_bits > int_bitsize) {
3651 btf_verifier_log_member(env, struct_type, member,
3652 "Invalid member bitfield_size");
3656 struct_size = struct_type->size;
3657 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3658 if (struct_size < bytes_end) {
3659 btf_verifier_log_member(env, struct_type, member,
3660 "Member exceeds struct_size");
3667 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3668 const struct btf_type *t,
3671 const struct btf_enum *enums = btf_type_enum(t);
3672 struct btf *btf = env->btf;
3676 nr_enums = btf_type_vlen(t);
3677 meta_needed = nr_enums * sizeof(*enums);
3679 if (meta_left < meta_needed) {
3680 btf_verifier_log_basic(env, t,
3681 "meta_left:%u meta_needed:%u",
3682 meta_left, meta_needed);
3686 if (btf_type_kflag(t)) {
3687 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3691 if (t->size > 8 || !is_power_of_2(t->size)) {
3692 btf_verifier_log_type(env, t, "Unexpected size");
3696 /* enum type either no name or a valid one */
3698 !btf_name_valid_identifier(env->btf, t->name_off)) {
3699 btf_verifier_log_type(env, t, "Invalid name");
3703 btf_verifier_log_type(env, t, NULL);
3705 for (i = 0; i < nr_enums; i++) {
3706 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3707 btf_verifier_log(env, "\tInvalid name_offset:%u",
3712 /* enum member must have a valid name */
3713 if (!enums[i].name_off ||
3714 !btf_name_valid_identifier(btf, enums[i].name_off)) {
3715 btf_verifier_log_type(env, t, "Invalid name");
3719 if (env->log.level == BPF_LOG_KERNEL)
3721 btf_verifier_log(env, "\t%s val=%d\n",
3722 __btf_name_by_offset(btf, enums[i].name_off),
3729 static void btf_enum_log(struct btf_verifier_env *env,
3730 const struct btf_type *t)
3732 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3735 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3736 u32 type_id, void *data, u8 bits_offset,
3737 struct btf_show *show)
3739 const struct btf_enum *enums = btf_type_enum(t);
3740 u32 i, nr_enums = btf_type_vlen(t);
3744 safe_data = btf_show_start_type(show, t, type_id, data);
3748 v = *(int *)safe_data;
3750 for (i = 0; i < nr_enums; i++) {
3751 if (v != enums[i].val)
3754 btf_show_type_value(show, "%s",
3755 __btf_name_by_offset(btf,
3756 enums[i].name_off));
3758 btf_show_end_type(show);
3762 btf_show_type_value(show, "%d", v);
3763 btf_show_end_type(show);
3766 static struct btf_kind_operations enum_ops = {
3767 .check_meta = btf_enum_check_meta,
3768 .resolve = btf_df_resolve,
3769 .check_member = btf_enum_check_member,
3770 .check_kflag_member = btf_enum_check_kflag_member,
3771 .log_details = btf_enum_log,
3772 .show = btf_enum_show,
3775 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3776 const struct btf_type *t,
3779 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3781 if (meta_left < meta_needed) {
3782 btf_verifier_log_basic(env, t,
3783 "meta_left:%u meta_needed:%u",
3784 meta_left, meta_needed);
3789 btf_verifier_log_type(env, t, "Invalid name");
3793 if (btf_type_kflag(t)) {
3794 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3798 btf_verifier_log_type(env, t, NULL);
3803 static void btf_func_proto_log(struct btf_verifier_env *env,
3804 const struct btf_type *t)
3806 const struct btf_param *args = (const struct btf_param *)(t + 1);
3807 u16 nr_args = btf_type_vlen(t), i;
3809 btf_verifier_log(env, "return=%u args=(", t->type);
3811 btf_verifier_log(env, "void");
3815 if (nr_args == 1 && !args[0].type) {
3816 /* Only one vararg */
3817 btf_verifier_log(env, "vararg");
3821 btf_verifier_log(env, "%u %s", args[0].type,
3822 __btf_name_by_offset(env->btf,
3824 for (i = 1; i < nr_args - 1; i++)
3825 btf_verifier_log(env, ", %u %s", args[i].type,
3826 __btf_name_by_offset(env->btf,
3830 const struct btf_param *last_arg = &args[nr_args - 1];
3833 btf_verifier_log(env, ", %u %s", last_arg->type,
3834 __btf_name_by_offset(env->btf,
3835 last_arg->name_off));
3837 btf_verifier_log(env, ", vararg");
3841 btf_verifier_log(env, ")");
3844 static struct btf_kind_operations func_proto_ops = {
3845 .check_meta = btf_func_proto_check_meta,
3846 .resolve = btf_df_resolve,
3848 * BTF_KIND_FUNC_PROTO cannot be directly referred by
3849 * a struct's member.
3851 * It should be a function pointer instead.
3852 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3854 * Hence, there is no btf_func_check_member().
3856 .check_member = btf_df_check_member,
3857 .check_kflag_member = btf_df_check_kflag_member,
3858 .log_details = btf_func_proto_log,
3859 .show = btf_df_show,
3862 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3863 const struct btf_type *t,
3867 !btf_name_valid_identifier(env->btf, t->name_off)) {
3868 btf_verifier_log_type(env, t, "Invalid name");
3872 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3873 btf_verifier_log_type(env, t, "Invalid func linkage");
3877 if (btf_type_kflag(t)) {
3878 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3882 btf_verifier_log_type(env, t, NULL);
3887 static int btf_func_resolve(struct btf_verifier_env *env,
3888 const struct resolve_vertex *v)
3890 const struct btf_type *t = v->t;
3891 u32 next_type_id = t->type;
3894 err = btf_func_check(env, t);
3898 env_stack_pop_resolved(env, next_type_id, 0);
3902 static struct btf_kind_operations func_ops = {
3903 .check_meta = btf_func_check_meta,
3904 .resolve = btf_func_resolve,
3905 .check_member = btf_df_check_member,
3906 .check_kflag_member = btf_df_check_kflag_member,
3907 .log_details = btf_ref_type_log,
3908 .show = btf_df_show,
3911 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3912 const struct btf_type *t,
3915 const struct btf_var *var;
3916 u32 meta_needed = sizeof(*var);
3918 if (meta_left < meta_needed) {
3919 btf_verifier_log_basic(env, t,
3920 "meta_left:%u meta_needed:%u",
3921 meta_left, meta_needed);
3925 if (btf_type_vlen(t)) {
3926 btf_verifier_log_type(env, t, "vlen != 0");
3930 if (btf_type_kflag(t)) {
3931 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3936 !__btf_name_valid(env->btf, t->name_off, true)) {
3937 btf_verifier_log_type(env, t, "Invalid name");
3941 /* A var cannot be in type void */
3942 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3943 btf_verifier_log_type(env, t, "Invalid type_id");
3947 var = btf_type_var(t);
3948 if (var->linkage != BTF_VAR_STATIC &&
3949 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3950 btf_verifier_log_type(env, t, "Linkage not supported");
3954 btf_verifier_log_type(env, t, NULL);
3959 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3961 const struct btf_var *var = btf_type_var(t);
3963 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3966 static const struct btf_kind_operations var_ops = {
3967 .check_meta = btf_var_check_meta,
3968 .resolve = btf_var_resolve,
3969 .check_member = btf_df_check_member,
3970 .check_kflag_member = btf_df_check_kflag_member,
3971 .log_details = btf_var_log,
3972 .show = btf_var_show,
3975 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3976 const struct btf_type *t,
3979 const struct btf_var_secinfo *vsi;
3980 u64 last_vsi_end_off = 0, sum = 0;
3983 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3984 if (meta_left < meta_needed) {
3985 btf_verifier_log_basic(env, t,
3986 "meta_left:%u meta_needed:%u",
3987 meta_left, meta_needed);
3992 btf_verifier_log_type(env, t, "size == 0");
3996 if (btf_type_kflag(t)) {
3997 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4002 !btf_name_valid_section(env->btf, t->name_off)) {
4003 btf_verifier_log_type(env, t, "Invalid name");
4007 btf_verifier_log_type(env, t, NULL);
4009 for_each_vsi(i, t, vsi) {
4010 /* A var cannot be in type void */
4011 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4012 btf_verifier_log_vsi(env, t, vsi,
4017 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4018 btf_verifier_log_vsi(env, t, vsi,
4023 if (!vsi->size || vsi->size > t->size) {
4024 btf_verifier_log_vsi(env, t, vsi,
4029 last_vsi_end_off = vsi->offset + vsi->size;
4030 if (last_vsi_end_off > t->size) {
4031 btf_verifier_log_vsi(env, t, vsi,
4032 "Invalid offset+size");
4036 btf_verifier_log_vsi(env, t, vsi, NULL);
4040 if (t->size < sum) {
4041 btf_verifier_log_type(env, t, "Invalid btf_info size");
4048 static int btf_datasec_resolve(struct btf_verifier_env *env,
4049 const struct resolve_vertex *v)
4051 const struct btf_var_secinfo *vsi;
4052 struct btf *btf = env->btf;
4055 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4056 u32 var_type_id = vsi->type, type_id, type_size = 0;
4057 const struct btf_type *var_type = btf_type_by_id(env->btf,
4059 if (!var_type || !btf_type_is_var(var_type)) {
4060 btf_verifier_log_vsi(env, v->t, vsi,
4061 "Not a VAR kind member");
4065 if (!env_type_is_resolve_sink(env, var_type) &&
4066 !env_type_is_resolved(env, var_type_id)) {
4067 env_stack_set_next_member(env, i + 1);
4068 return env_stack_push(env, var_type, var_type_id);
4071 type_id = var_type->type;
4072 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4073 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4077 if (vsi->size < type_size) {
4078 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4083 env_stack_pop_resolved(env, 0, 0);
4087 static void btf_datasec_log(struct btf_verifier_env *env,
4088 const struct btf_type *t)
4090 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4093 static void btf_datasec_show(const struct btf *btf,
4094 const struct btf_type *t, u32 type_id,
4095 void *data, u8 bits_offset,
4096 struct btf_show *show)
4098 const struct btf_var_secinfo *vsi;
4099 const struct btf_type *var;
4102 if (!btf_show_start_type(show, t, type_id, data))
4105 btf_show_type_value(show, "section (\"%s\") = {",
4106 __btf_name_by_offset(btf, t->name_off));
4107 for_each_vsi(i, t, vsi) {
4108 var = btf_type_by_id(btf, vsi->type);
4110 btf_show(show, ",");
4111 btf_type_ops(var)->show(btf, var, vsi->type,
4112 data + vsi->offset, bits_offset, show);
4114 btf_show_end_type(show);
4117 static const struct btf_kind_operations datasec_ops = {
4118 .check_meta = btf_datasec_check_meta,
4119 .resolve = btf_datasec_resolve,
4120 .check_member = btf_df_check_member,
4121 .check_kflag_member = btf_df_check_kflag_member,
4122 .log_details = btf_datasec_log,
4123 .show = btf_datasec_show,
4126 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4127 const struct btf_type *t,
4130 if (btf_type_vlen(t)) {
4131 btf_verifier_log_type(env, t, "vlen != 0");
4135 if (btf_type_kflag(t)) {
4136 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4140 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4142 btf_verifier_log_type(env, t, "Invalid type_size");
4146 btf_verifier_log_type(env, t, NULL);
4151 static int btf_float_check_member(struct btf_verifier_env *env,
4152 const struct btf_type *struct_type,
4153 const struct btf_member *member,
4154 const struct btf_type *member_type)
4156 u64 start_offset_bytes;
4157 u64 end_offset_bytes;
4162 /* Different architectures have different alignment requirements, so
4163 * here we check only for the reasonable minimum. This way we ensure
4164 * that types after CO-RE can pass the kernel BTF verifier.
4166 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4167 align_bits = align_bytes * BITS_PER_BYTE;
4168 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4169 if (misalign_bits) {
4170 btf_verifier_log_member(env, struct_type, member,
4171 "Member is not properly aligned");
4175 start_offset_bytes = member->offset / BITS_PER_BYTE;
4176 end_offset_bytes = start_offset_bytes + member_type->size;
4177 if (end_offset_bytes > struct_type->size) {
4178 btf_verifier_log_member(env, struct_type, member,
4179 "Member exceeds struct_size");
4186 static void btf_float_log(struct btf_verifier_env *env,
4187 const struct btf_type *t)
4189 btf_verifier_log(env, "size=%u", t->size);
4192 static const struct btf_kind_operations float_ops = {
4193 .check_meta = btf_float_check_meta,
4194 .resolve = btf_df_resolve,
4195 .check_member = btf_float_check_member,
4196 .check_kflag_member = btf_generic_check_kflag_member,
4197 .log_details = btf_float_log,
4198 .show = btf_df_show,
4201 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4202 const struct btf_type *t,
4205 const struct btf_decl_tag *tag;
4206 u32 meta_needed = sizeof(*tag);
4210 if (meta_left < meta_needed) {
4211 btf_verifier_log_basic(env, t,
4212 "meta_left:%u meta_needed:%u",
4213 meta_left, meta_needed);
4217 value = btf_name_by_offset(env->btf, t->name_off);
4218 if (!value || !value[0]) {
4219 btf_verifier_log_type(env, t, "Invalid value");
4223 if (btf_type_vlen(t)) {
4224 btf_verifier_log_type(env, t, "vlen != 0");
4228 if (btf_type_kflag(t)) {
4229 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4233 component_idx = btf_type_decl_tag(t)->component_idx;
4234 if (component_idx < -1) {
4235 btf_verifier_log_type(env, t, "Invalid component_idx");
4239 btf_verifier_log_type(env, t, NULL);
4244 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4245 const struct resolve_vertex *v)
4247 const struct btf_type *next_type;
4248 const struct btf_type *t = v->t;
4249 u32 next_type_id = t->type;
4250 struct btf *btf = env->btf;
4254 next_type = btf_type_by_id(btf, next_type_id);
4255 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4256 btf_verifier_log_type(env, v->t, "Invalid type_id");
4260 if (!env_type_is_resolve_sink(env, next_type) &&
4261 !env_type_is_resolved(env, next_type_id))
4262 return env_stack_push(env, next_type, next_type_id);
4264 component_idx = btf_type_decl_tag(t)->component_idx;
4265 if (component_idx != -1) {
4266 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4267 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4271 if (btf_type_is_struct(next_type)) {
4272 vlen = btf_type_vlen(next_type);
4274 /* next_type should be a function */
4275 next_type = btf_type_by_id(btf, next_type->type);
4276 vlen = btf_type_vlen(next_type);
4279 if ((u32)component_idx >= vlen) {
4280 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4285 env_stack_pop_resolved(env, next_type_id, 0);
4290 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4292 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4293 btf_type_decl_tag(t)->component_idx);
4296 static const struct btf_kind_operations decl_tag_ops = {
4297 .check_meta = btf_decl_tag_check_meta,
4298 .resolve = btf_decl_tag_resolve,
4299 .check_member = btf_df_check_member,
4300 .check_kflag_member = btf_df_check_kflag_member,
4301 .log_details = btf_decl_tag_log,
4302 .show = btf_df_show,
4305 static int btf_func_proto_check(struct btf_verifier_env *env,
4306 const struct btf_type *t)
4308 const struct btf_type *ret_type;
4309 const struct btf_param *args;
4310 const struct btf *btf;
4315 args = (const struct btf_param *)(t + 1);
4316 nr_args = btf_type_vlen(t);
4318 /* Check func return type which could be "void" (t->type == 0) */
4320 u32 ret_type_id = t->type;
4322 ret_type = btf_type_by_id(btf, ret_type_id);
4324 btf_verifier_log_type(env, t, "Invalid return type");
4328 if (btf_type_needs_resolve(ret_type) &&
4329 !env_type_is_resolved(env, ret_type_id)) {
4330 err = btf_resolve(env, ret_type, ret_type_id);
4335 /* Ensure the return type is a type that has a size */
4336 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4337 btf_verifier_log_type(env, t, "Invalid return type");
4345 /* Last func arg type_id could be 0 if it is a vararg */
4346 if (!args[nr_args - 1].type) {
4347 if (args[nr_args - 1].name_off) {
4348 btf_verifier_log_type(env, t, "Invalid arg#%u",
4356 for (i = 0; i < nr_args; i++) {
4357 const struct btf_type *arg_type;
4360 arg_type_id = args[i].type;
4361 arg_type = btf_type_by_id(btf, arg_type_id);
4363 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4368 if (args[i].name_off &&
4369 (!btf_name_offset_valid(btf, args[i].name_off) ||
4370 !btf_name_valid_identifier(btf, args[i].name_off))) {
4371 btf_verifier_log_type(env, t,
4372 "Invalid arg#%u", i + 1);
4377 if (btf_type_needs_resolve(arg_type) &&
4378 !env_type_is_resolved(env, arg_type_id)) {
4379 err = btf_resolve(env, arg_type, arg_type_id);
4384 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4385 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4394 static int btf_func_check(struct btf_verifier_env *env,
4395 const struct btf_type *t)
4397 const struct btf_type *proto_type;
4398 const struct btf_param *args;
4399 const struct btf *btf;
4403 proto_type = btf_type_by_id(btf, t->type);
4405 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4406 btf_verifier_log_type(env, t, "Invalid type_id");
4410 args = (const struct btf_param *)(proto_type + 1);
4411 nr_args = btf_type_vlen(proto_type);
4412 for (i = 0; i < nr_args; i++) {
4413 if (!args[i].name_off && args[i].type) {
4414 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4422 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4423 [BTF_KIND_INT] = &int_ops,
4424 [BTF_KIND_PTR] = &ptr_ops,
4425 [BTF_KIND_ARRAY] = &array_ops,
4426 [BTF_KIND_STRUCT] = &struct_ops,
4427 [BTF_KIND_UNION] = &struct_ops,
4428 [BTF_KIND_ENUM] = &enum_ops,
4429 [BTF_KIND_FWD] = &fwd_ops,
4430 [BTF_KIND_TYPEDEF] = &modifier_ops,
4431 [BTF_KIND_VOLATILE] = &modifier_ops,
4432 [BTF_KIND_CONST] = &modifier_ops,
4433 [BTF_KIND_RESTRICT] = &modifier_ops,
4434 [BTF_KIND_FUNC] = &func_ops,
4435 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4436 [BTF_KIND_VAR] = &var_ops,
4437 [BTF_KIND_DATASEC] = &datasec_ops,
4438 [BTF_KIND_FLOAT] = &float_ops,
4439 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
4440 [BTF_KIND_TYPE_TAG] = &modifier_ops,
4443 static s32 btf_check_meta(struct btf_verifier_env *env,
4444 const struct btf_type *t,
4447 u32 saved_meta_left = meta_left;
4450 if (meta_left < sizeof(*t)) {
4451 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4452 env->log_type_id, meta_left, sizeof(*t));
4455 meta_left -= sizeof(*t);
4457 if (t->info & ~BTF_INFO_MASK) {
4458 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4459 env->log_type_id, t->info);
4463 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4464 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4465 btf_verifier_log(env, "[%u] Invalid kind:%u",
4466 env->log_type_id, BTF_INFO_KIND(t->info));
4470 if (!btf_name_offset_valid(env->btf, t->name_off)) {
4471 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4472 env->log_type_id, t->name_off);
4476 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4477 if (var_meta_size < 0)
4478 return var_meta_size;
4480 meta_left -= var_meta_size;
4482 return saved_meta_left - meta_left;
4485 static int btf_check_all_metas(struct btf_verifier_env *env)
4487 struct btf *btf = env->btf;
4488 struct btf_header *hdr;
4492 cur = btf->nohdr_data + hdr->type_off;
4493 end = cur + hdr->type_len;
4495 env->log_type_id = btf->base_btf ? btf->start_id : 1;
4497 struct btf_type *t = cur;
4500 meta_size = btf_check_meta(env, t, end - cur);
4504 btf_add_type(env, t);
4512 static bool btf_resolve_valid(struct btf_verifier_env *env,
4513 const struct btf_type *t,
4516 struct btf *btf = env->btf;
4518 if (!env_type_is_resolved(env, type_id))
4521 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
4522 return !btf_resolved_type_id(btf, type_id) &&
4523 !btf_resolved_type_size(btf, type_id);
4525 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
4526 return btf_resolved_type_id(btf, type_id) &&
4527 !btf_resolved_type_size(btf, type_id);
4529 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
4530 btf_type_is_var(t)) {
4531 t = btf_type_id_resolve(btf, &type_id);
4533 !btf_type_is_modifier(t) &&
4534 !btf_type_is_var(t) &&
4535 !btf_type_is_datasec(t);
4538 if (btf_type_is_array(t)) {
4539 const struct btf_array *array = btf_type_array(t);
4540 const struct btf_type *elem_type;
4541 u32 elem_type_id = array->type;
4544 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
4545 return elem_type && !btf_type_is_modifier(elem_type) &&
4546 (array->nelems * elem_size ==
4547 btf_resolved_type_size(btf, type_id));
4553 static int btf_resolve(struct btf_verifier_env *env,
4554 const struct btf_type *t, u32 type_id)
4556 u32 save_log_type_id = env->log_type_id;
4557 const struct resolve_vertex *v;
4560 env->resolve_mode = RESOLVE_TBD;
4561 env_stack_push(env, t, type_id);
4562 while (!err && (v = env_stack_peak(env))) {
4563 env->log_type_id = v->type_id;
4564 err = btf_type_ops(v->t)->resolve(env, v);
4567 env->log_type_id = type_id;
4568 if (err == -E2BIG) {
4569 btf_verifier_log_type(env, t,
4570 "Exceeded max resolving depth:%u",
4572 } else if (err == -EEXIST) {
4573 btf_verifier_log_type(env, t, "Loop detected");
4576 /* Final sanity check */
4577 if (!err && !btf_resolve_valid(env, t, type_id)) {
4578 btf_verifier_log_type(env, t, "Invalid resolve state");
4582 env->log_type_id = save_log_type_id;
4586 static int btf_check_all_types(struct btf_verifier_env *env)
4588 struct btf *btf = env->btf;
4589 const struct btf_type *t;
4593 err = env_resolve_init(env);
4598 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
4599 type_id = btf->start_id + i;
4600 t = btf_type_by_id(btf, type_id);
4602 env->log_type_id = type_id;
4603 if (btf_type_needs_resolve(t) &&
4604 !env_type_is_resolved(env, type_id)) {
4605 err = btf_resolve(env, t, type_id);
4610 if (btf_type_is_func_proto(t)) {
4611 err = btf_func_proto_check(env, t);
4620 static int btf_parse_type_sec(struct btf_verifier_env *env)
4622 const struct btf_header *hdr = &env->btf->hdr;
4625 /* Type section must align to 4 bytes */
4626 if (hdr->type_off & (sizeof(u32) - 1)) {
4627 btf_verifier_log(env, "Unaligned type_off");
4631 if (!env->btf->base_btf && !hdr->type_len) {
4632 btf_verifier_log(env, "No type found");
4636 err = btf_check_all_metas(env);
4640 return btf_check_all_types(env);
4643 static int btf_parse_str_sec(struct btf_verifier_env *env)
4645 const struct btf_header *hdr;
4646 struct btf *btf = env->btf;
4647 const char *start, *end;
4650 start = btf->nohdr_data + hdr->str_off;
4651 end = start + hdr->str_len;
4653 if (end != btf->data + btf->data_size) {
4654 btf_verifier_log(env, "String section is not at the end");
4658 btf->strings = start;
4660 if (btf->base_btf && !hdr->str_len)
4662 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
4663 btf_verifier_log(env, "Invalid string section");
4666 if (!btf->base_btf && start[0]) {
4667 btf_verifier_log(env, "Invalid string section");
4674 static const size_t btf_sec_info_offset[] = {
4675 offsetof(struct btf_header, type_off),
4676 offsetof(struct btf_header, str_off),
4679 static int btf_sec_info_cmp(const void *a, const void *b)
4681 const struct btf_sec_info *x = a;
4682 const struct btf_sec_info *y = b;
4684 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
4687 static int btf_check_sec_info(struct btf_verifier_env *env,
4690 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
4691 u32 total, expected_total, i;
4692 const struct btf_header *hdr;
4693 const struct btf *btf;
4698 /* Populate the secs from hdr */
4699 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
4700 secs[i] = *(struct btf_sec_info *)((void *)hdr +
4701 btf_sec_info_offset[i]);
4703 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
4704 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
4706 /* Check for gaps and overlap among sections */
4708 expected_total = btf_data_size - hdr->hdr_len;
4709 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
4710 if (expected_total < secs[i].off) {
4711 btf_verifier_log(env, "Invalid section offset");
4714 if (total < secs[i].off) {
4716 btf_verifier_log(env, "Unsupported section found");
4719 if (total > secs[i].off) {
4720 btf_verifier_log(env, "Section overlap found");
4723 if (expected_total - total < secs[i].len) {
4724 btf_verifier_log(env,
4725 "Total section length too long");
4728 total += secs[i].len;
4731 /* There is data other than hdr and known sections */
4732 if (expected_total != total) {
4733 btf_verifier_log(env, "Unsupported section found");
4740 static int btf_parse_hdr(struct btf_verifier_env *env)
4742 u32 hdr_len, hdr_copy, btf_data_size;
4743 const struct btf_header *hdr;
4748 btf_data_size = btf->data_size;
4750 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
4751 btf_verifier_log(env, "hdr_len not found");
4756 hdr_len = hdr->hdr_len;
4757 if (btf_data_size < hdr_len) {
4758 btf_verifier_log(env, "btf_header not found");
4762 /* Ensure the unsupported header fields are zero */
4763 if (hdr_len > sizeof(btf->hdr)) {
4764 u8 *expected_zero = btf->data + sizeof(btf->hdr);
4765 u8 *end = btf->data + hdr_len;
4767 for (; expected_zero < end; expected_zero++) {
4768 if (*expected_zero) {
4769 btf_verifier_log(env, "Unsupported btf_header");
4775 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4776 memcpy(&btf->hdr, btf->data, hdr_copy);
4780 btf_verifier_log_hdr(env, btf_data_size);
4782 if (hdr->magic != BTF_MAGIC) {
4783 btf_verifier_log(env, "Invalid magic");
4787 if (hdr->version != BTF_VERSION) {
4788 btf_verifier_log(env, "Unsupported version");
4793 btf_verifier_log(env, "Unsupported flags");
4797 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
4798 btf_verifier_log(env, "No data");
4802 err = btf_check_sec_info(env, btf_data_size);
4809 static int btf_check_type_tags(struct btf_verifier_env *env,
4810 struct btf *btf, int start_id)
4812 int i, n, good_id = start_id - 1;
4815 n = btf_nr_types(btf);
4816 for (i = start_id; i < n; i++) {
4817 const struct btf_type *t;
4820 t = btf_type_by_id(btf, i);
4823 if (!btf_type_is_modifier(t))
4828 in_tags = btf_type_is_type_tag(t);
4829 while (btf_type_is_modifier(t)) {
4830 if (btf_type_is_type_tag(t)) {
4832 btf_verifier_log(env, "Type tags don't precede modifiers");
4835 } else if (in_tags) {
4838 if (cur_id <= good_id)
4840 /* Move to next type */
4842 t = btf_type_by_id(btf, cur_id);
4851 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
4852 u32 log_level, char __user *log_ubuf, u32 log_size)
4854 struct btf_verifier_env *env = NULL;
4855 struct bpf_verifier_log *log;
4856 struct btf *btf = NULL;
4860 if (btf_data_size > BTF_MAX_SIZE)
4861 return ERR_PTR(-E2BIG);
4863 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4865 return ERR_PTR(-ENOMEM);
4868 if (log_level || log_ubuf || log_size) {
4869 /* user requested verbose verifier output
4870 * and supplied buffer to store the verification trace
4872 log->level = log_level;
4873 log->ubuf = log_ubuf;
4874 log->len_total = log_size;
4876 /* log attributes have to be sane */
4877 if (!bpf_verifier_log_attr_valid(log)) {
4883 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4890 data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4897 btf->data_size = btf_data_size;
4899 if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
4904 err = btf_parse_hdr(env);
4908 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4910 err = btf_parse_str_sec(env);
4914 err = btf_parse_type_sec(env);
4918 err = btf_check_type_tags(env, btf, 1);
4922 if (log->level && bpf_verifier_log_full(log)) {
4927 btf_verifier_env_free(env);
4928 refcount_set(&btf->refcnt, 1);
4932 btf_verifier_env_free(env);
4935 return ERR_PTR(err);
4938 extern char __weak __start_BTF[];
4939 extern char __weak __stop_BTF[];
4940 extern struct btf *btf_vmlinux;
4942 #define BPF_MAP_TYPE(_id, _ops)
4943 #define BPF_LINK_TYPE(_id, _name)
4945 struct bpf_ctx_convert {
4946 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4947 prog_ctx_type _id##_prog; \
4948 kern_ctx_type _id##_kern;
4949 #include <linux/bpf_types.h>
4950 #undef BPF_PROG_TYPE
4952 /* 't' is written once under lock. Read many times. */
4953 const struct btf_type *t;
4956 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4958 #include <linux/bpf_types.h>
4959 #undef BPF_PROG_TYPE
4960 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
4962 static u8 bpf_ctx_convert_map[] = {
4963 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4964 [_id] = __ctx_convert##_id,
4965 #include <linux/bpf_types.h>
4966 #undef BPF_PROG_TYPE
4967 0, /* avoid empty array */
4970 #undef BPF_LINK_TYPE
4972 static const struct btf_member *
4973 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
4974 const struct btf_type *t, enum bpf_prog_type prog_type,
4977 const struct btf_type *conv_struct;
4978 const struct btf_type *ctx_struct;
4979 const struct btf_member *ctx_type;
4980 const char *tname, *ctx_tname;
4982 conv_struct = bpf_ctx_convert.t;
4984 bpf_log(log, "btf_vmlinux is malformed\n");
4987 t = btf_type_by_id(btf, t->type);
4988 while (btf_type_is_modifier(t))
4989 t = btf_type_by_id(btf, t->type);
4990 if (!btf_type_is_struct(t)) {
4991 /* Only pointer to struct is supported for now.
4992 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4993 * is not supported yet.
4994 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
4998 tname = btf_name_by_offset(btf, t->name_off);
5000 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5003 /* prog_type is valid bpf program type. No need for bounds check. */
5004 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5005 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5006 * Like 'struct __sk_buff'
5008 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5010 /* should not happen */
5012 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5014 /* should not happen */
5015 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5018 /* only compare that prog's ctx type name is the same as
5019 * kernel expects. No need to compare field by field.
5020 * It's ok for bpf prog to do:
5021 * struct __sk_buff {};
5022 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5023 * { // no fields of skb are ever used }
5025 if (strcmp(ctx_tname, tname))
5030 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5032 const struct btf_type *t,
5033 enum bpf_prog_type prog_type,
5036 const struct btf_member *prog_ctx_type, *kern_ctx_type;
5038 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5041 kern_ctx_type = prog_ctx_type + 1;
5042 return kern_ctx_type->type;
5045 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5046 BTF_ID(struct, bpf_ctx_convert)
5048 struct btf *btf_parse_vmlinux(void)
5050 struct btf_verifier_env *env = NULL;
5051 struct bpf_verifier_log *log;
5052 struct btf *btf = NULL;
5055 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5057 return ERR_PTR(-ENOMEM);
5060 log->level = BPF_LOG_KERNEL;
5062 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5069 btf->data = __start_BTF;
5070 btf->data_size = __stop_BTF - __start_BTF;
5071 btf->kernel_btf = true;
5072 snprintf(btf->name, sizeof(btf->name), "vmlinux");
5074 err = btf_parse_hdr(env);
5078 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5080 err = btf_parse_str_sec(env);
5084 err = btf_check_all_metas(env);
5088 err = btf_check_type_tags(env, btf, 1);
5092 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
5093 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5095 bpf_struct_ops_init(btf, log);
5097 refcount_set(&btf->refcnt, 1);
5099 err = btf_alloc_id(btf);
5103 btf_verifier_env_free(env);
5107 btf_verifier_env_free(env);
5112 return ERR_PTR(err);
5115 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5117 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5119 struct btf_verifier_env *env = NULL;
5120 struct bpf_verifier_log *log;
5121 struct btf *btf = NULL, *base_btf;
5124 base_btf = bpf_get_btf_vmlinux();
5125 if (IS_ERR(base_btf))
5128 return ERR_PTR(-EINVAL);
5130 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5132 return ERR_PTR(-ENOMEM);
5135 log->level = BPF_LOG_KERNEL;
5137 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5144 btf->base_btf = base_btf;
5145 btf->start_id = base_btf->nr_types;
5146 btf->start_str_off = base_btf->hdr.str_len;
5147 btf->kernel_btf = true;
5148 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5150 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5155 memcpy(btf->data, data, data_size);
5156 btf->data_size = data_size;
5158 err = btf_parse_hdr(env);
5162 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5164 err = btf_parse_str_sec(env);
5168 err = btf_check_all_metas(env);
5172 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5176 btf_verifier_env_free(env);
5177 refcount_set(&btf->refcnt, 1);
5181 btf_verifier_env_free(env);
5187 return ERR_PTR(err);
5190 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5192 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5194 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5197 return tgt_prog->aux->btf;
5199 return prog->aux->attach_btf;
5202 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5204 /* t comes in already as a pointer */
5205 t = btf_type_by_id(btf, t->type);
5208 if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5209 t = btf_type_by_id(btf, t->type);
5211 return btf_type_is_int(t);
5214 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5215 const struct bpf_prog *prog,
5216 struct bpf_insn_access_aux *info)
5218 const struct btf_type *t = prog->aux->attach_func_proto;
5219 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5220 struct btf *btf = bpf_prog_get_target_btf(prog);
5221 const char *tname = prog->aux->attach_func_name;
5222 struct bpf_verifier_log *log = info->log;
5223 const struct btf_param *args;
5224 const char *tag_value;
5229 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5234 args = (const struct btf_param *)(t + 1);
5235 /* if (t == NULL) Fall back to default BPF prog with
5236 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5238 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5239 if (prog->aux->attach_btf_trace) {
5240 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5245 if (arg > nr_args) {
5246 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5251 if (arg == nr_args) {
5252 switch (prog->expected_attach_type) {
5254 case BPF_TRACE_FEXIT:
5255 /* When LSM programs are attached to void LSM hooks
5256 * they use FEXIT trampolines and when attached to
5257 * int LSM hooks, they use MODIFY_RETURN trampolines.
5259 * While the LSM programs are BPF_MODIFY_RETURN-like
5262 * if (ret_type != 'int')
5265 * is _not_ done here. This is still safe as LSM hooks
5266 * have only void and int return types.
5270 t = btf_type_by_id(btf, t->type);
5272 case BPF_MODIFY_RETURN:
5273 /* For now the BPF_MODIFY_RETURN can only be attached to
5274 * functions that return an int.
5279 t = btf_type_skip_modifiers(btf, t->type, NULL);
5280 if (!btf_type_is_small_int(t)) {
5282 "ret type %s not allowed for fmod_ret\n",
5283 btf_kind_str[BTF_INFO_KIND(t->info)]);
5288 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5294 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
5296 t = btf_type_by_id(btf, args[arg].type);
5299 /* skip modifiers */
5300 while (btf_type_is_modifier(t))
5301 t = btf_type_by_id(btf, t->type);
5302 if (btf_type_is_small_int(t) || btf_type_is_enum(t))
5303 /* accessing a scalar */
5305 if (!btf_type_is_ptr(t)) {
5307 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
5309 __btf_name_by_offset(btf, t->name_off),
5310 btf_kind_str[BTF_INFO_KIND(t->info)]);
5314 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
5315 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5316 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5319 type = base_type(ctx_arg_info->reg_type);
5320 flag = type_flag(ctx_arg_info->reg_type);
5321 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
5322 (flag & PTR_MAYBE_NULL)) {
5323 info->reg_type = ctx_arg_info->reg_type;
5329 /* This is a pointer to void.
5330 * It is the same as scalar from the verifier safety pov.
5331 * No further pointer walking is allowed.
5335 if (is_int_ptr(btf, t))
5338 /* this is a pointer to another type */
5339 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5340 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5342 if (ctx_arg_info->offset == off) {
5343 if (!ctx_arg_info->btf_id) {
5344 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
5348 info->reg_type = ctx_arg_info->reg_type;
5349 info->btf = btf_vmlinux;
5350 info->btf_id = ctx_arg_info->btf_id;
5355 info->reg_type = PTR_TO_BTF_ID;
5357 enum bpf_prog_type tgt_type;
5359 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
5360 tgt_type = tgt_prog->aux->saved_dst_prog_type;
5362 tgt_type = tgt_prog->type;
5364 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
5366 info->btf = btf_vmlinux;
5375 info->btf_id = t->type;
5376 t = btf_type_by_id(btf, t->type);
5378 if (btf_type_is_type_tag(t)) {
5379 tag_value = __btf_name_by_offset(btf, t->name_off);
5380 if (strcmp(tag_value, "user") == 0)
5381 info->reg_type |= MEM_USER;
5382 if (strcmp(tag_value, "percpu") == 0)
5383 info->reg_type |= MEM_PERCPU;
5386 /* skip modifiers */
5387 while (btf_type_is_modifier(t)) {
5388 info->btf_id = t->type;
5389 t = btf_type_by_id(btf, t->type);
5391 if (!btf_type_is_struct(t)) {
5393 "func '%s' arg%d type %s is not a struct\n",
5394 tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
5397 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
5398 tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
5399 __btf_name_by_offset(btf, t->name_off));
5403 enum bpf_struct_walk_result {
5410 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
5411 const struct btf_type *t, int off, int size,
5412 u32 *next_btf_id, enum bpf_type_flag *flag)
5414 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
5415 const struct btf_type *mtype, *elem_type = NULL;
5416 const struct btf_member *member;
5417 const char *tname, *mname, *tag_value;
5418 u32 vlen, elem_id, mid;
5421 tname = __btf_name_by_offset(btf, t->name_off);
5422 if (!btf_type_is_struct(t)) {
5423 bpf_log(log, "Type '%s' is not a struct\n", tname);
5427 vlen = btf_type_vlen(t);
5428 if (off + size > t->size) {
5429 /* If the last element is a variable size array, we may
5430 * need to relax the rule.
5432 struct btf_array *array_elem;
5437 member = btf_type_member(t) + vlen - 1;
5438 mtype = btf_type_skip_modifiers(btf, member->type,
5440 if (!btf_type_is_array(mtype))
5443 array_elem = (struct btf_array *)(mtype + 1);
5444 if (array_elem->nelems != 0)
5447 moff = __btf_member_bit_offset(t, member) / 8;
5451 /* Only allow structure for now, can be relaxed for
5452 * other types later.
5454 t = btf_type_skip_modifiers(btf, array_elem->type,
5456 if (!btf_type_is_struct(t))
5459 off = (off - moff) % t->size;
5463 bpf_log(log, "access beyond struct %s at off %u size %u\n",
5468 for_each_member(i, t, member) {
5469 /* offset of the field in bytes */
5470 moff = __btf_member_bit_offset(t, member) / 8;
5471 if (off + size <= moff)
5472 /* won't find anything, field is already too far */
5475 if (__btf_member_bitfield_size(t, member)) {
5476 u32 end_bit = __btf_member_bit_offset(t, member) +
5477 __btf_member_bitfield_size(t, member);
5479 /* off <= moff instead of off == moff because clang
5480 * does not generate a BTF member for anonymous
5481 * bitfield like the ":16" here:
5488 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
5491 /* off may be accessing a following member
5495 * Doing partial access at either end of this
5496 * bitfield. Continue on this case also to
5497 * treat it as not accessing this bitfield
5498 * and eventually error out as field not
5499 * found to keep it simple.
5500 * It could be relaxed if there was a legit
5501 * partial access case later.
5506 /* In case of "off" is pointing to holes of a struct */
5510 /* type of the field */
5512 mtype = btf_type_by_id(btf, member->type);
5513 mname = __btf_name_by_offset(btf, member->name_off);
5515 mtype = __btf_resolve_size(btf, mtype, &msize,
5516 &elem_type, &elem_id, &total_nelems,
5518 if (IS_ERR(mtype)) {
5519 bpf_log(log, "field %s doesn't have size\n", mname);
5523 mtrue_end = moff + msize;
5524 if (off >= mtrue_end)
5525 /* no overlap with member, keep iterating */
5528 if (btf_type_is_array(mtype)) {
5531 /* __btf_resolve_size() above helps to
5532 * linearize a multi-dimensional array.
5534 * The logic here is treating an array
5535 * in a struct as the following way:
5538 * struct inner array[2][2];
5544 * struct inner array_elem0;
5545 * struct inner array_elem1;
5546 * struct inner array_elem2;
5547 * struct inner array_elem3;
5550 * When accessing outer->array[1][0], it moves
5551 * moff to "array_elem2", set mtype to
5552 * "struct inner", and msize also becomes
5553 * sizeof(struct inner). Then most of the
5554 * remaining logic will fall through without
5555 * caring the current member is an array or
5558 * Unlike mtype/msize/moff, mtrue_end does not
5559 * change. The naming difference ("_true") tells
5560 * that it is not always corresponding to
5561 * the current mtype/msize/moff.
5562 * It is the true end of the current
5563 * member (i.e. array in this case). That
5564 * will allow an int array to be accessed like
5566 * i.e. allow access beyond the size of
5567 * the array's element as long as it is
5568 * within the mtrue_end boundary.
5571 /* skip empty array */
5572 if (moff == mtrue_end)
5575 msize /= total_nelems;
5576 elem_idx = (off - moff) / msize;
5577 moff += elem_idx * msize;
5582 /* the 'off' we're looking for is either equal to start
5583 * of this field or inside of this struct
5585 if (btf_type_is_struct(mtype)) {
5586 /* our field must be inside that union or struct */
5589 /* return if the offset matches the member offset */
5595 /* adjust offset we're looking for */
5600 if (btf_type_is_ptr(mtype)) {
5601 const struct btf_type *stype, *t;
5602 enum bpf_type_flag tmp_flag = 0;
5605 if (msize != size || off != moff) {
5607 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
5608 mname, moff, tname, off, size);
5612 /* check type tag */
5613 t = btf_type_by_id(btf, mtype->type);
5614 if (btf_type_is_type_tag(t)) {
5615 tag_value = __btf_name_by_offset(btf, t->name_off);
5616 /* check __user tag */
5617 if (strcmp(tag_value, "user") == 0)
5618 tmp_flag = MEM_USER;
5619 /* check __percpu tag */
5620 if (strcmp(tag_value, "percpu") == 0)
5621 tmp_flag = MEM_PERCPU;
5624 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
5625 if (btf_type_is_struct(stype)) {
5632 /* Allow more flexible access within an int as long as
5633 * it is within mtrue_end.
5634 * Since mtrue_end could be the end of an array,
5635 * that also allows using an array of int as a scratch
5636 * space. e.g. skb->cb[].
5638 if (off + size > mtrue_end) {
5640 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
5641 mname, mtrue_end, tname, off, size);
5647 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
5651 int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
5652 const struct btf_type *t, int off, int size,
5653 enum bpf_access_type atype __maybe_unused,
5654 u32 *next_btf_id, enum bpf_type_flag *flag)
5656 enum bpf_type_flag tmp_flag = 0;
5661 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
5665 /* If we found the pointer or scalar on t+off,
5670 return PTR_TO_BTF_ID;
5672 return SCALAR_VALUE;
5674 /* We found nested struct, so continue the search
5675 * by diving in it. At this point the offset is
5676 * aligned with the new type, so set it to 0.
5678 t = btf_type_by_id(btf, id);
5682 /* It's either error or unknown return value..
5685 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5694 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5695 * the same. Trivial ID check is not enough due to module BTFs, because we can
5696 * end up with two different module BTFs, but IDs point to the common type in
5699 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5700 const struct btf *btf2, u32 id2)
5706 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5709 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5710 const struct btf *btf, u32 id, int off,
5711 const struct btf *need_btf, u32 need_type_id,
5714 const struct btf_type *type;
5715 enum bpf_type_flag flag;
5718 /* Are we already done? */
5719 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5721 /* In case of strict type match, we do not walk struct, the top level
5722 * type match must succeed. When strict is true, off should have already
5728 type = btf_type_by_id(btf, id);
5731 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
5732 if (err != WALK_STRUCT)
5735 /* We found nested struct object. If it matches
5736 * the requested ID, we're done. Otherwise let's
5737 * continue the search with offset 0 in the new
5740 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5748 static int __get_type_size(struct btf *btf, u32 btf_id,
5749 const struct btf_type **bad_type)
5751 const struct btf_type *t;
5756 t = btf_type_by_id(btf, btf_id);
5757 while (t && btf_type_is_modifier(t))
5758 t = btf_type_by_id(btf, t->type);
5760 *bad_type = btf_type_by_id(btf, 0);
5763 if (btf_type_is_ptr(t))
5764 /* kernel size of pointer. Not BPF's size of pointer*/
5765 return sizeof(void *);
5766 if (btf_type_is_int(t) || btf_type_is_enum(t))
5772 int btf_distill_func_proto(struct bpf_verifier_log *log,
5774 const struct btf_type *func,
5776 struct btf_func_model *m)
5778 const struct btf_param *args;
5779 const struct btf_type *t;
5784 /* BTF function prototype doesn't match the verifier types.
5785 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
5787 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
5790 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
5793 args = (const struct btf_param *)(func + 1);
5794 nargs = btf_type_vlen(func);
5795 if (nargs > MAX_BPF_FUNC_ARGS) {
5797 "The function %s has %d arguments. Too many.\n",
5801 ret = __get_type_size(btf, func->type, &t);
5804 "The function %s return type %s is unsupported.\n",
5805 tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5810 for (i = 0; i < nargs; i++) {
5811 if (i == nargs - 1 && args[i].type == 0) {
5813 "The function %s with variable args is unsupported.\n",
5817 ret = __get_type_size(btf, args[i].type, &t);
5820 "The function %s arg%d type %s is unsupported.\n",
5821 tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5826 "The function %s has malformed void argument.\n",
5830 m->arg_size[i] = ret;
5836 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5837 * t1 points to BTF_KIND_FUNC in btf1
5838 * t2 points to BTF_KIND_FUNC in btf2
5840 * EINVAL - function prototype mismatch
5841 * EFAULT - verifier bug
5842 * 0 - 99% match. The last 1% is validated by the verifier.
5844 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5845 struct btf *btf1, const struct btf_type *t1,
5846 struct btf *btf2, const struct btf_type *t2)
5848 const struct btf_param *args1, *args2;
5849 const char *fn1, *fn2, *s1, *s2;
5850 u32 nargs1, nargs2, i;
5852 fn1 = btf_name_by_offset(btf1, t1->name_off);
5853 fn2 = btf_name_by_offset(btf2, t2->name_off);
5855 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5856 bpf_log(log, "%s() is not a global function\n", fn1);
5859 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5860 bpf_log(log, "%s() is not a global function\n", fn2);
5864 t1 = btf_type_by_id(btf1, t1->type);
5865 if (!t1 || !btf_type_is_func_proto(t1))
5867 t2 = btf_type_by_id(btf2, t2->type);
5868 if (!t2 || !btf_type_is_func_proto(t2))
5871 args1 = (const struct btf_param *)(t1 + 1);
5872 nargs1 = btf_type_vlen(t1);
5873 args2 = (const struct btf_param *)(t2 + 1);
5874 nargs2 = btf_type_vlen(t2);
5876 if (nargs1 != nargs2) {
5877 bpf_log(log, "%s() has %d args while %s() has %d args\n",
5878 fn1, nargs1, fn2, nargs2);
5882 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5883 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5884 if (t1->info != t2->info) {
5886 "Return type %s of %s() doesn't match type %s of %s()\n",
5887 btf_type_str(t1), fn1,
5888 btf_type_str(t2), fn2);
5892 for (i = 0; i < nargs1; i++) {
5893 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5894 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5896 if (t1->info != t2->info) {
5897 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5898 i, fn1, btf_type_str(t1),
5899 fn2, btf_type_str(t2));
5902 if (btf_type_has_size(t1) && t1->size != t2->size) {
5904 "arg%d in %s() has size %d while %s() has %d\n",
5910 /* global functions are validated with scalars and pointers
5911 * to context only. And only global functions can be replaced.
5912 * Hence type check only those types.
5914 if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5916 if (!btf_type_is_ptr(t1)) {
5918 "arg%d in %s() has unrecognized type\n",
5922 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5923 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5924 if (!btf_type_is_struct(t1)) {
5926 "arg%d in %s() is not a pointer to context\n",
5930 if (!btf_type_is_struct(t2)) {
5932 "arg%d in %s() is not a pointer to context\n",
5936 /* This is an optional check to make program writing easier.
5937 * Compare names of structs and report an error to the user.
5938 * btf_prepare_func_args() already checked that t2 struct
5939 * is a context type. btf_prepare_func_args() will check
5940 * later that t1 struct is a context type as well.
5942 s1 = btf_name_by_offset(btf1, t1->name_off);
5943 s2 = btf_name_by_offset(btf2, t2->name_off);
5944 if (strcmp(s1, s2)) {
5946 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5947 i, fn1, s1, fn2, s2);
5954 /* Compare BTFs of given program with BTF of target program */
5955 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5956 struct btf *btf2, const struct btf_type *t2)
5958 struct btf *btf1 = prog->aux->btf;
5959 const struct btf_type *t1;
5962 if (!prog->aux->func_info) {
5963 bpf_log(log, "Program extension requires BTF\n");
5967 btf_id = prog->aux->func_info[0].type_id;
5971 t1 = btf_type_by_id(btf1, btf_id);
5972 if (!t1 || !btf_type_is_func(t1))
5975 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5978 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5980 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5981 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5982 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5986 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
5987 static bool __btf_type_is_scalar_struct(struct bpf_verifier_log *log,
5988 const struct btf *btf,
5989 const struct btf_type *t, int rec)
5991 const struct btf_type *member_type;
5992 const struct btf_member *member;
5995 if (!btf_type_is_struct(t))
5998 for_each_member(i, t, member) {
5999 const struct btf_array *array;
6001 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
6002 if (btf_type_is_struct(member_type)) {
6004 bpf_log(log, "max struct nesting depth exceeded\n");
6007 if (!__btf_type_is_scalar_struct(log, btf, member_type, rec + 1))
6011 if (btf_type_is_array(member_type)) {
6012 array = btf_type_array(member_type);
6015 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
6016 if (!btf_type_is_scalar(member_type))
6020 if (!btf_type_is_scalar(member_type))
6026 static bool is_kfunc_arg_mem_size(const struct btf *btf,
6027 const struct btf_param *arg,
6028 const struct bpf_reg_state *reg)
6030 int len, sfx_len = sizeof("__sz") - 1;
6031 const struct btf_type *t;
6032 const char *param_name;
6034 t = btf_type_skip_modifiers(btf, arg->type, NULL);
6035 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
6038 /* In the future, this can be ported to use BTF tagging */
6039 param_name = btf_name_by_offset(btf, arg->name_off);
6040 if (str_is_empty(param_name))
6042 len = strlen(param_name);
6045 param_name += len - sfx_len;
6046 if (strncmp(param_name, "__sz", sfx_len))
6052 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6053 const struct btf *btf, u32 func_id,
6054 struct bpf_reg_state *regs,
6057 struct bpf_verifier_log *log = &env->log;
6058 u32 i, nargs, ref_id, ref_obj_id = 0;
6059 bool is_kfunc = btf_is_kernel(btf);
6060 bool rel = false, kptr_get = false;
6061 const char *func_name, *ref_tname;
6062 const struct btf_type *t, *ref_t;
6063 const struct btf_param *args;
6064 int ref_regno = 0, ret;
6066 t = btf_type_by_id(btf, func_id);
6067 if (!t || !btf_type_is_func(t)) {
6068 /* These checks were already done by the verifier while loading
6069 * struct bpf_func_info or in add_kfunc_call().
6071 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6075 func_name = btf_name_by_offset(btf, t->name_off);
6077 t = btf_type_by_id(btf, t->type);
6078 if (!t || !btf_type_is_func_proto(t)) {
6079 bpf_log(log, "Invalid BTF of func %s\n", func_name);
6082 args = (const struct btf_param *)(t + 1);
6083 nargs = btf_type_vlen(t);
6084 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6085 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6086 MAX_BPF_FUNC_REG_ARGS);
6091 /* Only kfunc can be release func */
6092 rel = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
6093 BTF_KFUNC_TYPE_RELEASE, func_id);
6094 kptr_get = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
6095 BTF_KFUNC_TYPE_KPTR_ACQUIRE, func_id);
6098 /* check that BTF function arguments match actual types that the
6101 for (i = 0; i < nargs; i++) {
6102 enum bpf_arg_type arg_type = ARG_DONTCARE;
6104 struct bpf_reg_state *reg = ®s[regno];
6106 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6107 if (btf_type_is_scalar(t)) {
6108 if (reg->type == SCALAR_VALUE)
6110 bpf_log(log, "R%d is not a scalar\n", regno);
6114 if (!btf_type_is_ptr(t)) {
6115 bpf_log(log, "Unrecognized arg#%d type %s\n",
6116 i, btf_type_str(t));
6120 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6121 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6123 if (rel && reg->ref_obj_id)
6124 arg_type |= OBJ_RELEASE;
6125 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6129 /* kptr_get is only true for kfunc */
6130 if (i == 0 && kptr_get) {
6131 struct bpf_map_value_off_desc *off_desc;
6133 if (reg->type != PTR_TO_MAP_VALUE) {
6134 bpf_log(log, "arg#0 expected pointer to map value\n");
6138 /* check_func_arg_reg_off allows var_off for
6139 * PTR_TO_MAP_VALUE, but we need fixed offset to find
6142 if (!tnum_is_const(reg->var_off)) {
6143 bpf_log(log, "arg#0 must have constant offset\n");
6147 off_desc = bpf_map_kptr_off_contains(reg->map_ptr, reg->off + reg->var_off.value);
6148 if (!off_desc || off_desc->type != BPF_KPTR_REF) {
6149 bpf_log(log, "arg#0 no referenced kptr at map value offset=%llu\n",
6150 reg->off + reg->var_off.value);
6154 if (!btf_type_is_ptr(ref_t)) {
6155 bpf_log(log, "arg#0 BTF type must be a double pointer\n");
6159 ref_t = btf_type_skip_modifiers(btf, ref_t->type, &ref_id);
6160 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6162 if (!btf_type_is_struct(ref_t)) {
6163 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6164 func_name, i, btf_type_str(ref_t), ref_tname);
6167 if (!btf_struct_ids_match(log, btf, ref_id, 0, off_desc->kptr.btf,
6168 off_desc->kptr.btf_id, true)) {
6169 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s\n",
6170 func_name, i, btf_type_str(ref_t), ref_tname);
6173 /* rest of the arguments can be anything, like normal kfunc */
6174 } else if (btf_get_prog_ctx_type(log, btf, t, env->prog->type, i)) {
6175 /* If function expects ctx type in BTF check that caller
6176 * is passing PTR_TO_CTX.
6178 if (reg->type != PTR_TO_CTX) {
6180 "arg#%d expected pointer to ctx, but got %s\n",
6181 i, btf_type_str(t));
6184 } else if (is_kfunc && (reg->type == PTR_TO_BTF_ID ||
6185 (reg2btf_ids[base_type(reg->type)] && !type_flag(reg->type)))) {
6186 const struct btf_type *reg_ref_t;
6187 const struct btf *reg_btf;
6188 const char *reg_ref_tname;
6191 if (!btf_type_is_struct(ref_t)) {
6192 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6193 func_name, i, btf_type_str(ref_t),
6198 if (reg->type == PTR_TO_BTF_ID) {
6200 reg_ref_id = reg->btf_id;
6201 /* Ensure only one argument is referenced PTR_TO_BTF_ID */
6202 if (reg->ref_obj_id) {
6204 bpf_log(log, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6205 regno, reg->ref_obj_id, ref_obj_id);
6209 ref_obj_id = reg->ref_obj_id;
6212 reg_btf = btf_vmlinux;
6213 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
6216 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id,
6218 reg_ref_tname = btf_name_by_offset(reg_btf,
6219 reg_ref_t->name_off);
6220 if (!btf_struct_ids_match(log, reg_btf, reg_ref_id,
6221 reg->off, btf, ref_id, rel && reg->ref_obj_id)) {
6222 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
6224 btf_type_str(ref_t), ref_tname,
6225 regno, btf_type_str(reg_ref_t),
6229 } else if (ptr_to_mem_ok) {
6230 const struct btf_type *resolve_ret;
6234 bool arg_mem_size = i + 1 < nargs && is_kfunc_arg_mem_size(btf, &args[i + 1], ®s[regno + 1]);
6236 /* Permit pointer to mem, but only when argument
6237 * type is pointer to scalar, or struct composed
6238 * (recursively) of scalars.
6239 * When arg_mem_size is true, the pointer can be
6242 if (!btf_type_is_scalar(ref_t) &&
6243 !__btf_type_is_scalar_struct(log, btf, ref_t, 0) &&
6244 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
6246 "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
6247 i, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
6251 /* Check for mem, len pair */
6253 if (check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1)) {
6254 bpf_log(log, "arg#%d arg#%d memory, len pair leads to invalid memory access\n",
6263 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6264 if (IS_ERR(resolve_ret)) {
6266 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6267 i, btf_type_str(ref_t), ref_tname,
6268 PTR_ERR(resolve_ret));
6272 if (check_mem_reg(env, reg, regno, type_size))
6275 bpf_log(log, "reg type unsupported for arg#%d %sfunction %s#%d\n", i,
6276 is_kfunc ? "kernel " : "", func_name, func_id);
6281 /* Either both are set, or neither */
6282 WARN_ON_ONCE((ref_obj_id && !ref_regno) || (!ref_obj_id && ref_regno));
6283 /* We already made sure ref_obj_id is set only for one argument. We do
6284 * allow (!rel && ref_obj_id), so that passing such referenced
6285 * PTR_TO_BTF_ID to other kfuncs works. Note that rel is only true when
6288 if (rel && !ref_obj_id) {
6289 bpf_log(log, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
6293 /* returns argument register number > 0 in case of reference release kfunc */
6294 return rel ? ref_regno : 0;
6297 /* Compare BTF of a function with given bpf_reg_state.
6299 * EFAULT - there is a verifier bug. Abort verification.
6300 * EINVAL - there is a type mismatch or BTF is not available.
6301 * 0 - BTF matches with what bpf_reg_state expects.
6302 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6304 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6305 struct bpf_reg_state *regs)
6307 struct bpf_prog *prog = env->prog;
6308 struct btf *btf = prog->aux->btf;
6313 if (!prog->aux->func_info)
6316 btf_id = prog->aux->func_info[subprog].type_id;
6320 if (prog->aux->func_info_aux[subprog].unreliable)
6323 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6324 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global);
6326 /* Compiler optimizations can remove arguments from static functions
6327 * or mismatched type can be passed into a global function.
6328 * In such cases mark the function as unreliable from BTF point of view.
6331 prog->aux->func_info_aux[subprog].unreliable = true;
6335 int btf_check_kfunc_arg_match(struct bpf_verifier_env *env,
6336 const struct btf *btf, u32 func_id,
6337 struct bpf_reg_state *regs)
6339 return btf_check_func_arg_match(env, btf, func_id, regs, true);
6342 /* Convert BTF of a function into bpf_reg_state if possible
6344 * EFAULT - there is a verifier bug. Abort verification.
6345 * EINVAL - cannot convert BTF.
6346 * 0 - Successfully converted BTF into bpf_reg_state
6347 * (either PTR_TO_CTX or SCALAR_VALUE).
6349 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6350 struct bpf_reg_state *regs)
6352 struct bpf_verifier_log *log = &env->log;
6353 struct bpf_prog *prog = env->prog;
6354 enum bpf_prog_type prog_type = prog->type;
6355 struct btf *btf = prog->aux->btf;
6356 const struct btf_param *args;
6357 const struct btf_type *t, *ref_t;
6358 u32 i, nargs, btf_id;
6361 if (!prog->aux->func_info ||
6362 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6363 bpf_log(log, "Verifier bug\n");
6367 btf_id = prog->aux->func_info[subprog].type_id;
6369 bpf_log(log, "Global functions need valid BTF\n");
6373 t = btf_type_by_id(btf, btf_id);
6374 if (!t || !btf_type_is_func(t)) {
6375 /* These checks were already done by the verifier while loading
6376 * struct bpf_func_info
6378 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6382 tname = btf_name_by_offset(btf, t->name_off);
6384 if (log->level & BPF_LOG_LEVEL)
6385 bpf_log(log, "Validating %s() func#%d...\n",
6388 if (prog->aux->func_info_aux[subprog].unreliable) {
6389 bpf_log(log, "Verifier bug in function %s()\n", tname);
6392 if (prog_type == BPF_PROG_TYPE_EXT)
6393 prog_type = prog->aux->dst_prog->type;
6395 t = btf_type_by_id(btf, t->type);
6396 if (!t || !btf_type_is_func_proto(t)) {
6397 bpf_log(log, "Invalid type of function %s()\n", tname);
6400 args = (const struct btf_param *)(t + 1);
6401 nargs = btf_type_vlen(t);
6402 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6403 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
6404 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
6407 /* check that function returns int */
6408 t = btf_type_by_id(btf, t->type);
6409 while (btf_type_is_modifier(t))
6410 t = btf_type_by_id(btf, t->type);
6411 if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
6413 "Global function %s() doesn't return scalar. Only those are supported.\n",
6417 /* Convert BTF function arguments into verifier types.
6418 * Only PTR_TO_CTX and SCALAR are supported atm.
6420 for (i = 0; i < nargs; i++) {
6421 struct bpf_reg_state *reg = ®s[i + 1];
6423 t = btf_type_by_id(btf, args[i].type);
6424 while (btf_type_is_modifier(t))
6425 t = btf_type_by_id(btf, t->type);
6426 if (btf_type_is_int(t) || btf_type_is_enum(t)) {
6427 reg->type = SCALAR_VALUE;
6430 if (btf_type_is_ptr(t)) {
6431 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6432 reg->type = PTR_TO_CTX;
6436 t = btf_type_skip_modifiers(btf, t->type, NULL);
6438 ref_t = btf_resolve_size(btf, t, ®->mem_size);
6439 if (IS_ERR(ref_t)) {
6441 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6442 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
6447 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6448 reg->id = ++env->id_gen;
6452 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
6453 i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
6459 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
6460 struct btf_show *show)
6462 const struct btf_type *t = btf_type_by_id(btf, type_id);
6465 memset(&show->state, 0, sizeof(show->state));
6466 memset(&show->obj, 0, sizeof(show->obj));
6468 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
6471 static void btf_seq_show(struct btf_show *show, const char *fmt,
6474 seq_vprintf((struct seq_file *)show->target, fmt, args);
6477 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
6478 void *obj, struct seq_file *m, u64 flags)
6480 struct btf_show sseq;
6483 sseq.showfn = btf_seq_show;
6486 btf_type_show(btf, type_id, obj, &sseq);
6488 return sseq.state.status;
6491 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
6494 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
6495 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
6496 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
6499 struct btf_show_snprintf {
6500 struct btf_show show;
6501 int len_left; /* space left in string */
6502 int len; /* length we would have written */
6505 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
6508 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
6511 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
6514 ssnprintf->len_left = 0;
6515 ssnprintf->len = len;
6516 } else if (len > ssnprintf->len_left) {
6517 /* no space, drive on to get length we would have written */
6518 ssnprintf->len_left = 0;
6519 ssnprintf->len += len;
6521 ssnprintf->len_left -= len;
6522 ssnprintf->len += len;
6523 show->target += len;
6527 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
6528 char *buf, int len, u64 flags)
6530 struct btf_show_snprintf ssnprintf;
6532 ssnprintf.show.target = buf;
6533 ssnprintf.show.flags = flags;
6534 ssnprintf.show.showfn = btf_snprintf_show;
6535 ssnprintf.len_left = len;
6538 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
6540 /* If we encountered an error, return it. */
6541 if (ssnprintf.show.state.status)
6542 return ssnprintf.show.state.status;
6544 /* Otherwise return length we would have written */
6545 return ssnprintf.len;
6548 #ifdef CONFIG_PROC_FS
6549 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
6551 const struct btf *btf = filp->private_data;
6553 seq_printf(m, "btf_id:\t%u\n", btf->id);
6557 static int btf_release(struct inode *inode, struct file *filp)
6559 btf_put(filp->private_data);
6563 const struct file_operations btf_fops = {
6564 #ifdef CONFIG_PROC_FS
6565 .show_fdinfo = bpf_btf_show_fdinfo,
6567 .release = btf_release,
6570 static int __btf_new_fd(struct btf *btf)
6572 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
6575 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
6580 btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
6581 attr->btf_size, attr->btf_log_level,
6582 u64_to_user_ptr(attr->btf_log_buf),
6583 attr->btf_log_size);
6585 return PTR_ERR(btf);
6587 ret = btf_alloc_id(btf);
6594 * The BTF ID is published to the userspace.
6595 * All BTF free must go through call_rcu() from
6596 * now on (i.e. free by calling btf_put()).
6599 ret = __btf_new_fd(btf);
6606 struct btf *btf_get_by_fd(int fd)
6614 return ERR_PTR(-EBADF);
6616 if (f.file->f_op != &btf_fops) {
6618 return ERR_PTR(-EINVAL);
6621 btf = f.file->private_data;
6622 refcount_inc(&btf->refcnt);
6628 int btf_get_info_by_fd(const struct btf *btf,
6629 const union bpf_attr *attr,
6630 union bpf_attr __user *uattr)
6632 struct bpf_btf_info __user *uinfo;
6633 struct bpf_btf_info info;
6634 u32 info_copy, btf_copy;
6637 u32 uinfo_len, uname_len, name_len;
6640 uinfo = u64_to_user_ptr(attr->info.info);
6641 uinfo_len = attr->info.info_len;
6643 info_copy = min_t(u32, uinfo_len, sizeof(info));
6644 memset(&info, 0, sizeof(info));
6645 if (copy_from_user(&info, uinfo, info_copy))
6649 ubtf = u64_to_user_ptr(info.btf);
6650 btf_copy = min_t(u32, btf->data_size, info.btf_size);
6651 if (copy_to_user(ubtf, btf->data, btf_copy))
6653 info.btf_size = btf->data_size;
6655 info.kernel_btf = btf->kernel_btf;
6657 uname = u64_to_user_ptr(info.name);
6658 uname_len = info.name_len;
6659 if (!uname ^ !uname_len)
6662 name_len = strlen(btf->name);
6663 info.name_len = name_len;
6666 if (uname_len >= name_len + 1) {
6667 if (copy_to_user(uname, btf->name, name_len + 1))
6672 if (copy_to_user(uname, btf->name, uname_len - 1))
6674 if (put_user(zero, uname + uname_len - 1))
6676 /* let user-space know about too short buffer */
6681 if (copy_to_user(uinfo, &info, info_copy) ||
6682 put_user(info_copy, &uattr->info.info_len))
6688 int btf_get_fd_by_id(u32 id)
6694 btf = idr_find(&btf_idr, id);
6695 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
6696 btf = ERR_PTR(-ENOENT);
6700 return PTR_ERR(btf);
6702 fd = __btf_new_fd(btf);
6709 u32 btf_obj_id(const struct btf *btf)
6714 bool btf_is_kernel(const struct btf *btf)
6716 return btf->kernel_btf;
6719 bool btf_is_module(const struct btf *btf)
6721 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
6724 static int btf_id_cmp_func(const void *a, const void *b)
6726 const int *pa = a, *pb = b;
6731 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
6733 return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
6737 BTF_MODULE_F_LIVE = (1 << 0),
6740 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6742 struct list_head list;
6743 struct module *module;
6745 struct bin_attribute *sysfs_attr;
6749 static LIST_HEAD(btf_modules);
6750 static DEFINE_MUTEX(btf_module_mutex);
6753 btf_module_read(struct file *file, struct kobject *kobj,
6754 struct bin_attribute *bin_attr,
6755 char *buf, loff_t off, size_t len)
6757 const struct btf *btf = bin_attr->private;
6759 memcpy(buf, btf->data + off, len);
6763 static void purge_cand_cache(struct btf *btf);
6765 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
6768 struct btf_module *btf_mod, *tmp;
6769 struct module *mod = module;
6773 if (mod->btf_data_size == 0 ||
6774 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
6775 op != MODULE_STATE_GOING))
6779 case MODULE_STATE_COMING:
6780 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
6785 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
6787 pr_warn("failed to validate module [%s] BTF: %ld\n",
6788 mod->name, PTR_ERR(btf));
6790 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
6794 err = btf_alloc_id(btf);
6801 purge_cand_cache(NULL);
6802 mutex_lock(&btf_module_mutex);
6803 btf_mod->module = module;
6805 list_add(&btf_mod->list, &btf_modules);
6806 mutex_unlock(&btf_module_mutex);
6808 if (IS_ENABLED(CONFIG_SYSFS)) {
6809 struct bin_attribute *attr;
6811 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
6815 sysfs_bin_attr_init(attr);
6816 attr->attr.name = btf->name;
6817 attr->attr.mode = 0444;
6818 attr->size = btf->data_size;
6819 attr->private = btf;
6820 attr->read = btf_module_read;
6822 err = sysfs_create_bin_file(btf_kobj, attr);
6824 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
6831 btf_mod->sysfs_attr = attr;
6835 case MODULE_STATE_LIVE:
6836 mutex_lock(&btf_module_mutex);
6837 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6838 if (btf_mod->module != module)
6841 btf_mod->flags |= BTF_MODULE_F_LIVE;
6844 mutex_unlock(&btf_module_mutex);
6846 case MODULE_STATE_GOING:
6847 mutex_lock(&btf_module_mutex);
6848 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6849 if (btf_mod->module != module)
6852 list_del(&btf_mod->list);
6853 if (btf_mod->sysfs_attr)
6854 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
6855 purge_cand_cache(btf_mod->btf);
6856 btf_put(btf_mod->btf);
6857 kfree(btf_mod->sysfs_attr);
6861 mutex_unlock(&btf_module_mutex);
6865 return notifier_from_errno(err);
6868 static struct notifier_block btf_module_nb = {
6869 .notifier_call = btf_module_notify,
6872 static int __init btf_module_init(void)
6874 register_module_notifier(&btf_module_nb);
6878 fs_initcall(btf_module_init);
6879 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6881 struct module *btf_try_get_module(const struct btf *btf)
6883 struct module *res = NULL;
6884 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6885 struct btf_module *btf_mod, *tmp;
6887 mutex_lock(&btf_module_mutex);
6888 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6889 if (btf_mod->btf != btf)
6892 /* We must only consider module whose __init routine has
6893 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
6894 * which is set from the notifier callback for
6895 * MODULE_STATE_LIVE.
6897 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
6898 res = btf_mod->module;
6902 mutex_unlock(&btf_module_mutex);
6908 /* Returns struct btf corresponding to the struct module.
6909 * This function can return NULL or ERR_PTR.
6911 static struct btf *btf_get_module_btf(const struct module *module)
6913 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6914 struct btf_module *btf_mod, *tmp;
6916 struct btf *btf = NULL;
6919 btf = bpf_get_btf_vmlinux();
6920 if (!IS_ERR_OR_NULL(btf))
6925 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6926 mutex_lock(&btf_module_mutex);
6927 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6928 if (btf_mod->module != module)
6931 btf_get(btf_mod->btf);
6935 mutex_unlock(&btf_module_mutex);
6941 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
6943 struct btf *btf = NULL;
6950 if (name_sz <= 1 || name[name_sz - 1])
6953 ret = bpf_find_btf_id(name, kind, &btf);
6954 if (ret > 0 && btf_is_module(btf)) {
6955 btf_obj_fd = __btf_new_fd(btf);
6956 if (btf_obj_fd < 0) {
6960 return ret | (((u64)btf_obj_fd) << 32);
6967 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
6968 .func = bpf_btf_find_by_name_kind,
6970 .ret_type = RET_INTEGER,
6971 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
6972 .arg2_type = ARG_CONST_SIZE,
6973 .arg3_type = ARG_ANYTHING,
6974 .arg4_type = ARG_ANYTHING,
6977 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
6978 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
6979 BTF_TRACING_TYPE_xxx
6980 #undef BTF_TRACING_TYPE
6982 /* Kernel Function (kfunc) BTF ID set registration API */
6984 static int __btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
6985 enum btf_kfunc_type type,
6986 struct btf_id_set *add_set, bool vmlinux_set)
6988 struct btf_kfunc_set_tab *tab;
6989 struct btf_id_set *set;
6993 if (hook >= BTF_KFUNC_HOOK_MAX || type >= BTF_KFUNC_TYPE_MAX) {
7001 tab = btf->kfunc_set_tab;
7003 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7006 btf->kfunc_set_tab = tab;
7009 set = tab->sets[hook][type];
7010 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7013 if (WARN_ON_ONCE(set && !vmlinux_set)) {
7018 /* We don't need to allocate, concatenate, and sort module sets, because
7019 * only one is allowed per hook. Hence, we can directly assign the
7020 * pointer and return.
7023 tab->sets[hook][type] = add_set;
7027 /* In case of vmlinux sets, there may be more than one set being
7028 * registered per hook. To create a unified set, we allocate a new set
7029 * and concatenate all individual sets being registered. While each set
7030 * is individually sorted, they may become unsorted when concatenated,
7031 * hence re-sorting the final set again is required to make binary
7032 * searching the set using btf_id_set_contains function work.
7034 set_cnt = set ? set->cnt : 0;
7036 if (set_cnt > U32_MAX - add_set->cnt) {
7041 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7047 set = krealloc(tab->sets[hook][type],
7048 offsetof(struct btf_id_set, ids[set_cnt + add_set->cnt]),
7049 GFP_KERNEL | __GFP_NOWARN);
7055 /* For newly allocated set, initialize set->cnt to 0 */
7056 if (!tab->sets[hook][type])
7058 tab->sets[hook][type] = set;
7060 /* Concatenate the two sets */
7061 memcpy(set->ids + set->cnt, add_set->ids, add_set->cnt * sizeof(set->ids[0]));
7062 set->cnt += add_set->cnt;
7064 sort(set->ids, set->cnt, sizeof(set->ids[0]), btf_id_cmp_func, NULL);
7068 btf_free_kfunc_set_tab(btf);
7072 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7073 const struct btf_kfunc_id_set *kset)
7075 bool vmlinux_set = !btf_is_module(btf);
7078 for (type = 0; type < ARRAY_SIZE(kset->sets); type++) {
7079 if (!kset->sets[type])
7082 ret = __btf_populate_kfunc_set(btf, hook, type, kset->sets[type], vmlinux_set);
7089 static bool __btf_kfunc_id_set_contains(const struct btf *btf,
7090 enum btf_kfunc_hook hook,
7091 enum btf_kfunc_type type,
7094 struct btf_id_set *set;
7096 if (hook >= BTF_KFUNC_HOOK_MAX || type >= BTF_KFUNC_TYPE_MAX)
7098 if (!btf->kfunc_set_tab)
7100 set = btf->kfunc_set_tab->sets[hook][type];
7103 return btf_id_set_contains(set, kfunc_btf_id);
7106 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7108 switch (prog_type) {
7109 case BPF_PROG_TYPE_XDP:
7110 return BTF_KFUNC_HOOK_XDP;
7111 case BPF_PROG_TYPE_SCHED_CLS:
7112 return BTF_KFUNC_HOOK_TC;
7113 case BPF_PROG_TYPE_STRUCT_OPS:
7114 return BTF_KFUNC_HOOK_STRUCT_OPS;
7115 case BPF_PROG_TYPE_TRACING:
7116 return BTF_KFUNC_HOOK_TRACING;
7117 case BPF_PROG_TYPE_SYSCALL:
7118 return BTF_KFUNC_HOOK_SYSCALL;
7120 return BTF_KFUNC_HOOK_MAX;
7125 * Reference to the module (obtained using btf_try_get_module) corresponding to
7126 * the struct btf *MUST* be held when calling this function from verifier
7127 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7128 * keeping the reference for the duration of the call provides the necessary
7129 * protection for looking up a well-formed btf->kfunc_set_tab.
7131 bool btf_kfunc_id_set_contains(const struct btf *btf,
7132 enum bpf_prog_type prog_type,
7133 enum btf_kfunc_type type, u32 kfunc_btf_id)
7135 enum btf_kfunc_hook hook;
7137 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7138 return __btf_kfunc_id_set_contains(btf, hook, type, kfunc_btf_id);
7141 /* This function must be invoked only from initcalls/module init functions */
7142 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7143 const struct btf_kfunc_id_set *kset)
7145 enum btf_kfunc_hook hook;
7149 btf = btf_get_module_btf(kset->owner);
7151 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7152 pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7155 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7156 pr_err("missing module BTF, cannot register kfuncs\n");
7162 return PTR_ERR(btf);
7164 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7165 ret = btf_populate_kfunc_set(btf, hook, kset);
7169 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7171 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7173 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7174 struct btf_id_dtor_kfunc *dtor;
7178 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7179 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7181 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7182 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7185 return dtor->kfunc_btf_id;
7188 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7190 const struct btf_type *dtor_func, *dtor_func_proto, *t;
7191 const struct btf_param *args;
7195 for (i = 0; i < cnt; i++) {
7196 dtor_btf_id = dtors[i].kfunc_btf_id;
7198 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7199 if (!dtor_func || !btf_type_is_func(dtor_func))
7202 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7203 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7206 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7207 t = btf_type_by_id(btf, dtor_func_proto->type);
7208 if (!t || !btf_type_is_void(t))
7211 nr_args = btf_type_vlen(dtor_func_proto);
7214 args = btf_params(dtor_func_proto);
7215 t = btf_type_by_id(btf, args[0].type);
7216 /* Allow any pointer type, as width on targets Linux supports
7217 * will be same for all pointer types (i.e. sizeof(void *))
7219 if (!t || !btf_type_is_ptr(t))
7225 /* This function must be invoked only from initcalls/module init functions */
7226 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7227 struct module *owner)
7229 struct btf_id_dtor_kfunc_tab *tab;
7234 btf = btf_get_module_btf(owner);
7236 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7237 pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7240 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7241 pr_err("missing module BTF, cannot register dtor kfuncs\n");
7247 return PTR_ERR(btf);
7249 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7250 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7255 /* Ensure that the prototype of dtor kfuncs being registered is sane */
7256 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7260 tab = btf->dtor_kfunc_tab;
7261 /* Only one call allowed for modules */
7262 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7267 tab_cnt = tab ? tab->cnt : 0;
7268 if (tab_cnt > U32_MAX - add_cnt) {
7272 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7273 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7278 tab = krealloc(btf->dtor_kfunc_tab,
7279 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7280 GFP_KERNEL | __GFP_NOWARN);
7286 if (!btf->dtor_kfunc_tab)
7288 btf->dtor_kfunc_tab = tab;
7290 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7291 tab->cnt += add_cnt;
7293 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7297 btf_free_dtor_kfunc_tab(btf);
7301 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7303 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
7306 int __bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7307 const struct btf *targ_btf, __u32 targ_id,
7310 const struct btf_type *local_type, *targ_type;
7311 int depth = 32; /* max recursion depth */
7313 /* caller made sure that names match (ignoring flavor suffix) */
7314 local_type = btf_type_by_id(local_btf, local_id);
7315 targ_type = btf_type_by_id(targ_btf, targ_id);
7316 if (btf_kind(local_type) != btf_kind(targ_type))
7324 local_type = btf_type_skip_modifiers(local_btf, local_id, &local_id);
7325 targ_type = btf_type_skip_modifiers(targ_btf, targ_id, &targ_id);
7326 if (!local_type || !targ_type)
7329 if (btf_kind(local_type) != btf_kind(targ_type))
7332 switch (btf_kind(local_type)) {
7334 case BTF_KIND_STRUCT:
7335 case BTF_KIND_UNION:
7340 /* just reject deprecated bitfield-like integers; all other
7341 * integers are by default compatible between each other
7343 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
7345 local_id = local_type->type;
7346 targ_id = targ_type->type;
7348 case BTF_KIND_ARRAY:
7349 local_id = btf_array(local_type)->type;
7350 targ_id = btf_array(targ_type)->type;
7352 case BTF_KIND_FUNC_PROTO: {
7353 struct btf_param *local_p = btf_params(local_type);
7354 struct btf_param *targ_p = btf_params(targ_type);
7355 __u16 local_vlen = btf_vlen(local_type);
7356 __u16 targ_vlen = btf_vlen(targ_type);
7359 if (local_vlen != targ_vlen)
7362 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
7366 btf_type_skip_modifiers(local_btf, local_p->type, &local_id);
7367 btf_type_skip_modifiers(targ_btf, targ_p->type, &targ_id);
7368 err = __bpf_core_types_are_compat(local_btf, local_id,
7375 /* tail recurse for return type check */
7376 btf_type_skip_modifiers(local_btf, local_type->type, &local_id);
7377 btf_type_skip_modifiers(targ_btf, targ_type->type, &targ_id);
7385 /* Check local and target types for compatibility. This check is used for
7386 * type-based CO-RE relocations and follow slightly different rules than
7387 * field-based relocations. This function assumes that root types were already
7388 * checked for name match. Beyond that initial root-level name check, names
7389 * are completely ignored. Compatibility rules are as follows:
7390 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
7391 * kind should match for local and target types (i.e., STRUCT is not
7392 * compatible with UNION);
7393 * - for ENUMs, the size is ignored;
7394 * - for INT, size and signedness are ignored;
7395 * - for ARRAY, dimensionality is ignored, element types are checked for
7396 * compatibility recursively;
7397 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
7398 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7399 * - FUNC_PROTOs are compatible if they have compatible signature: same
7400 * number of input args and compatible return and argument types.
7401 * These rules are not set in stone and probably will be adjusted as we get
7402 * more experience with using BPF CO-RE relocations.
7404 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7405 const struct btf *targ_btf, __u32 targ_id)
7407 return __bpf_core_types_are_compat(local_btf, local_id,
7409 MAX_TYPES_ARE_COMPAT_DEPTH);
7412 static bool bpf_core_is_flavor_sep(const char *s)
7414 /* check X___Y name pattern, where X and Y are not underscores */
7415 return s[0] != '_' && /* X */
7416 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
7417 s[4] != '_'; /* Y */
7420 size_t bpf_core_essential_name_len(const char *name)
7422 size_t n = strlen(name);
7425 for (i = n - 5; i >= 0; i--) {
7426 if (bpf_core_is_flavor_sep(name + i))
7432 struct bpf_cand_cache {
7438 const struct btf *btf;
7443 static void bpf_free_cands(struct bpf_cand_cache *cands)
7446 /* empty candidate array was allocated on stack */
7451 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
7457 #define VMLINUX_CAND_CACHE_SIZE 31
7458 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
7460 #define MODULE_CAND_CACHE_SIZE 31
7461 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
7463 static DEFINE_MUTEX(cand_cache_mutex);
7465 static void __print_cand_cache(struct bpf_verifier_log *log,
7466 struct bpf_cand_cache **cache,
7469 struct bpf_cand_cache *cc;
7472 for (i = 0; i < cache_size; i++) {
7476 bpf_log(log, "[%d]%s(", i, cc->name);
7477 for (j = 0; j < cc->cnt; j++) {
7478 bpf_log(log, "%d", cc->cands[j].id);
7479 if (j < cc->cnt - 1)
7482 bpf_log(log, "), ");
7486 static void print_cand_cache(struct bpf_verifier_log *log)
7488 mutex_lock(&cand_cache_mutex);
7489 bpf_log(log, "vmlinux_cand_cache:");
7490 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7491 bpf_log(log, "\nmodule_cand_cache:");
7492 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7494 mutex_unlock(&cand_cache_mutex);
7497 static u32 hash_cands(struct bpf_cand_cache *cands)
7499 return jhash(cands->name, cands->name_len, 0);
7502 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
7503 struct bpf_cand_cache **cache,
7506 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
7508 if (cc && cc->name_len == cands->name_len &&
7509 !strncmp(cc->name, cands->name, cands->name_len))
7514 static size_t sizeof_cands(int cnt)
7516 return offsetof(struct bpf_cand_cache, cands[cnt]);
7519 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
7520 struct bpf_cand_cache **cache,
7523 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
7526 bpf_free_cands_from_cache(*cc);
7529 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
7531 bpf_free_cands(cands);
7532 return ERR_PTR(-ENOMEM);
7534 /* strdup the name, since it will stay in cache.
7535 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
7537 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
7538 bpf_free_cands(cands);
7539 if (!new_cands->name) {
7541 return ERR_PTR(-ENOMEM);
7547 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7548 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
7551 struct bpf_cand_cache *cc;
7554 for (i = 0; i < cache_size; i++) {
7559 /* when new module is loaded purge all of module_cand_cache,
7560 * since new module might have candidates with the name
7561 * that matches cached cands.
7563 bpf_free_cands_from_cache(cc);
7567 /* when module is unloaded purge cache entries
7568 * that match module's btf
7570 for (j = 0; j < cc->cnt; j++)
7571 if (cc->cands[j].btf == btf) {
7572 bpf_free_cands_from_cache(cc);
7580 static void purge_cand_cache(struct btf *btf)
7582 mutex_lock(&cand_cache_mutex);
7583 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7584 mutex_unlock(&cand_cache_mutex);
7588 static struct bpf_cand_cache *
7589 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
7592 struct bpf_cand_cache *new_cands;
7593 const struct btf_type *t;
7594 const char *targ_name;
7595 size_t targ_essent_len;
7598 n = btf_nr_types(targ_btf);
7599 for (i = targ_start_id; i < n; i++) {
7600 t = btf_type_by_id(targ_btf, i);
7601 if (btf_kind(t) != cands->kind)
7604 targ_name = btf_name_by_offset(targ_btf, t->name_off);
7608 /* the resched point is before strncmp to make sure that search
7609 * for non-existing name will have a chance to schedule().
7613 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
7616 targ_essent_len = bpf_core_essential_name_len(targ_name);
7617 if (targ_essent_len != cands->name_len)
7620 /* most of the time there is only one candidate for a given kind+name pair */
7621 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
7623 bpf_free_cands(cands);
7624 return ERR_PTR(-ENOMEM);
7627 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
7628 bpf_free_cands(cands);
7630 cands->cands[cands->cnt].btf = targ_btf;
7631 cands->cands[cands->cnt].id = i;
7637 static struct bpf_cand_cache *
7638 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
7640 struct bpf_cand_cache *cands, *cc, local_cand = {};
7641 const struct btf *local_btf = ctx->btf;
7642 const struct btf_type *local_type;
7643 const struct btf *main_btf;
7644 size_t local_essent_len;
7645 struct btf *mod_btf;
7649 main_btf = bpf_get_btf_vmlinux();
7650 if (IS_ERR(main_btf))
7651 return ERR_CAST(main_btf);
7653 return ERR_PTR(-EINVAL);
7655 local_type = btf_type_by_id(local_btf, local_type_id);
7657 return ERR_PTR(-EINVAL);
7659 name = btf_name_by_offset(local_btf, local_type->name_off);
7660 if (str_is_empty(name))
7661 return ERR_PTR(-EINVAL);
7662 local_essent_len = bpf_core_essential_name_len(name);
7664 cands = &local_cand;
7666 cands->kind = btf_kind(local_type);
7667 cands->name_len = local_essent_len;
7669 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7670 /* cands is a pointer to stack here */
7677 /* Attempt to find target candidates in vmlinux BTF first */
7678 cands = bpf_core_add_cands(cands, main_btf, 1);
7680 return ERR_CAST(cands);
7682 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
7684 /* populate cache even when cands->cnt == 0 */
7685 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7687 return ERR_CAST(cc);
7689 /* if vmlinux BTF has any candidate, don't go for module BTFs */
7694 /* cands is a pointer to stack here and cands->cnt == 0 */
7695 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7697 /* if cache has it return it even if cc->cnt == 0 */
7700 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
7701 spin_lock_bh(&btf_idr_lock);
7702 idr_for_each_entry(&btf_idr, mod_btf, id) {
7703 if (!btf_is_module(mod_btf))
7705 /* linear search could be slow hence unlock/lock
7706 * the IDR to avoiding holding it for too long
7709 spin_unlock_bh(&btf_idr_lock);
7710 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
7711 if (IS_ERR(cands)) {
7713 return ERR_CAST(cands);
7715 spin_lock_bh(&btf_idr_lock);
7718 spin_unlock_bh(&btf_idr_lock);
7719 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
7720 * or pointer to stack if cands->cnd == 0.
7721 * Copy it into the cache even when cands->cnt == 0 and
7722 * return the result.
7724 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7727 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
7728 int relo_idx, void *insn)
7730 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
7731 struct bpf_core_cand_list cands = {};
7732 struct bpf_core_relo_res targ_res;
7733 struct bpf_core_spec *specs;
7736 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
7737 * into arrays of btf_ids of struct fields and array indices.
7739 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
7744 struct bpf_cand_cache *cc;
7747 mutex_lock(&cand_cache_mutex);
7748 cc = bpf_core_find_cands(ctx, relo->type_id);
7750 bpf_log(ctx->log, "target candidate search failed for %d\n",
7756 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
7762 for (i = 0; i < cc->cnt; i++) {
7764 "CO-RE relocating %s %s: found target candidate [%d]\n",
7765 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
7766 cands.cands[i].btf = cc->cands[i].btf;
7767 cands.cands[i].id = cc->cands[i].id;
7769 cands.len = cc->cnt;
7770 /* cand_cache_mutex needs to span the cache lookup and
7771 * copy of btf pointer into bpf_core_cand_list,
7772 * since module can be unloaded while bpf_core_calc_relo_insn
7773 * is working with module's btf.
7777 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
7782 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
7789 mutex_unlock(&cand_cache_mutex);
7790 if (ctx->log->level & BPF_LOG_LEVEL2)
7791 print_cand_cache(ctx->log);