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;
4818 int chain_limit = 32;
4821 t = btf_type_by_id(btf, i);
4824 if (!btf_type_is_modifier(t))
4829 in_tags = btf_type_is_type_tag(t);
4830 while (btf_type_is_modifier(t)) {
4831 if (!chain_limit--) {
4832 btf_verifier_log(env, "Max chain length or cycle detected");
4835 if (btf_type_is_type_tag(t)) {
4837 btf_verifier_log(env, "Type tags don't precede modifiers");
4840 } else if (in_tags) {
4843 if (cur_id <= good_id)
4845 /* Move to next type */
4847 t = btf_type_by_id(btf, cur_id);
4856 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
4857 u32 log_level, char __user *log_ubuf, u32 log_size)
4859 struct btf_verifier_env *env = NULL;
4860 struct bpf_verifier_log *log;
4861 struct btf *btf = NULL;
4865 if (btf_data_size > BTF_MAX_SIZE)
4866 return ERR_PTR(-E2BIG);
4868 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4870 return ERR_PTR(-ENOMEM);
4873 if (log_level || log_ubuf || log_size) {
4874 /* user requested verbose verifier output
4875 * and supplied buffer to store the verification trace
4877 log->level = log_level;
4878 log->ubuf = log_ubuf;
4879 log->len_total = log_size;
4881 /* log attributes have to be sane */
4882 if (!bpf_verifier_log_attr_valid(log)) {
4888 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4895 data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4902 btf->data_size = btf_data_size;
4904 if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
4909 err = btf_parse_hdr(env);
4913 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4915 err = btf_parse_str_sec(env);
4919 err = btf_parse_type_sec(env);
4923 err = btf_check_type_tags(env, btf, 1);
4927 if (log->level && bpf_verifier_log_full(log)) {
4932 btf_verifier_env_free(env);
4933 refcount_set(&btf->refcnt, 1);
4937 btf_verifier_env_free(env);
4940 return ERR_PTR(err);
4943 extern char __weak __start_BTF[];
4944 extern char __weak __stop_BTF[];
4945 extern struct btf *btf_vmlinux;
4947 #define BPF_MAP_TYPE(_id, _ops)
4948 #define BPF_LINK_TYPE(_id, _name)
4950 struct bpf_ctx_convert {
4951 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4952 prog_ctx_type _id##_prog; \
4953 kern_ctx_type _id##_kern;
4954 #include <linux/bpf_types.h>
4955 #undef BPF_PROG_TYPE
4957 /* 't' is written once under lock. Read many times. */
4958 const struct btf_type *t;
4961 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4963 #include <linux/bpf_types.h>
4964 #undef BPF_PROG_TYPE
4965 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
4967 static u8 bpf_ctx_convert_map[] = {
4968 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4969 [_id] = __ctx_convert##_id,
4970 #include <linux/bpf_types.h>
4971 #undef BPF_PROG_TYPE
4972 0, /* avoid empty array */
4975 #undef BPF_LINK_TYPE
4977 static const struct btf_member *
4978 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
4979 const struct btf_type *t, enum bpf_prog_type prog_type,
4982 const struct btf_type *conv_struct;
4983 const struct btf_type *ctx_struct;
4984 const struct btf_member *ctx_type;
4985 const char *tname, *ctx_tname;
4987 conv_struct = bpf_ctx_convert.t;
4989 bpf_log(log, "btf_vmlinux is malformed\n");
4992 t = btf_type_by_id(btf, t->type);
4993 while (btf_type_is_modifier(t))
4994 t = btf_type_by_id(btf, t->type);
4995 if (!btf_type_is_struct(t)) {
4996 /* Only pointer to struct is supported for now.
4997 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4998 * is not supported yet.
4999 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5003 tname = btf_name_by_offset(btf, t->name_off);
5005 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5008 /* prog_type is valid bpf program type. No need for bounds check. */
5009 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5010 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5011 * Like 'struct __sk_buff'
5013 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5015 /* should not happen */
5017 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5019 /* should not happen */
5020 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5023 /* only compare that prog's ctx type name is the same as
5024 * kernel expects. No need to compare field by field.
5025 * It's ok for bpf prog to do:
5026 * struct __sk_buff {};
5027 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5028 * { // no fields of skb are ever used }
5030 if (strcmp(ctx_tname, tname))
5035 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5037 const struct btf_type *t,
5038 enum bpf_prog_type prog_type,
5041 const struct btf_member *prog_ctx_type, *kern_ctx_type;
5043 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5046 kern_ctx_type = prog_ctx_type + 1;
5047 return kern_ctx_type->type;
5050 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5051 BTF_ID(struct, bpf_ctx_convert)
5053 struct btf *btf_parse_vmlinux(void)
5055 struct btf_verifier_env *env = NULL;
5056 struct bpf_verifier_log *log;
5057 struct btf *btf = NULL;
5060 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5062 return ERR_PTR(-ENOMEM);
5065 log->level = BPF_LOG_KERNEL;
5067 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5074 btf->data = __start_BTF;
5075 btf->data_size = __stop_BTF - __start_BTF;
5076 btf->kernel_btf = true;
5077 snprintf(btf->name, sizeof(btf->name), "vmlinux");
5079 err = btf_parse_hdr(env);
5083 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5085 err = btf_parse_str_sec(env);
5089 err = btf_check_all_metas(env);
5093 err = btf_check_type_tags(env, btf, 1);
5097 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
5098 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5100 bpf_struct_ops_init(btf, log);
5102 refcount_set(&btf->refcnt, 1);
5104 err = btf_alloc_id(btf);
5108 btf_verifier_env_free(env);
5112 btf_verifier_env_free(env);
5117 return ERR_PTR(err);
5120 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5122 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5124 struct btf_verifier_env *env = NULL;
5125 struct bpf_verifier_log *log;
5126 struct btf *btf = NULL, *base_btf;
5129 base_btf = bpf_get_btf_vmlinux();
5130 if (IS_ERR(base_btf))
5133 return ERR_PTR(-EINVAL);
5135 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5137 return ERR_PTR(-ENOMEM);
5140 log->level = BPF_LOG_KERNEL;
5142 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5149 btf->base_btf = base_btf;
5150 btf->start_id = base_btf->nr_types;
5151 btf->start_str_off = base_btf->hdr.str_len;
5152 btf->kernel_btf = true;
5153 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5155 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5160 memcpy(btf->data, data, data_size);
5161 btf->data_size = data_size;
5163 err = btf_parse_hdr(env);
5167 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5169 err = btf_parse_str_sec(env);
5173 err = btf_check_all_metas(env);
5177 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5181 btf_verifier_env_free(env);
5182 refcount_set(&btf->refcnt, 1);
5186 btf_verifier_env_free(env);
5192 return ERR_PTR(err);
5195 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5197 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5199 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5202 return tgt_prog->aux->btf;
5204 return prog->aux->attach_btf;
5207 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5209 /* t comes in already as a pointer */
5210 t = btf_type_by_id(btf, t->type);
5213 if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5214 t = btf_type_by_id(btf, t->type);
5216 return btf_type_is_int(t);
5219 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5220 const struct bpf_prog *prog,
5221 struct bpf_insn_access_aux *info)
5223 const struct btf_type *t = prog->aux->attach_func_proto;
5224 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5225 struct btf *btf = bpf_prog_get_target_btf(prog);
5226 const char *tname = prog->aux->attach_func_name;
5227 struct bpf_verifier_log *log = info->log;
5228 const struct btf_param *args;
5229 const char *tag_value;
5234 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5239 args = (const struct btf_param *)(t + 1);
5240 /* if (t == NULL) Fall back to default BPF prog with
5241 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5243 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5244 if (prog->aux->attach_btf_trace) {
5245 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5250 if (arg > nr_args) {
5251 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5256 if (arg == nr_args) {
5257 switch (prog->expected_attach_type) {
5259 case BPF_TRACE_FEXIT:
5260 /* When LSM programs are attached to void LSM hooks
5261 * they use FEXIT trampolines and when attached to
5262 * int LSM hooks, they use MODIFY_RETURN trampolines.
5264 * While the LSM programs are BPF_MODIFY_RETURN-like
5267 * if (ret_type != 'int')
5270 * is _not_ done here. This is still safe as LSM hooks
5271 * have only void and int return types.
5275 t = btf_type_by_id(btf, t->type);
5277 case BPF_MODIFY_RETURN:
5278 /* For now the BPF_MODIFY_RETURN can only be attached to
5279 * functions that return an int.
5284 t = btf_type_skip_modifiers(btf, t->type, NULL);
5285 if (!btf_type_is_small_int(t)) {
5287 "ret type %s not allowed for fmod_ret\n",
5288 btf_kind_str[BTF_INFO_KIND(t->info)]);
5293 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5299 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
5301 t = btf_type_by_id(btf, args[arg].type);
5304 /* skip modifiers */
5305 while (btf_type_is_modifier(t))
5306 t = btf_type_by_id(btf, t->type);
5307 if (btf_type_is_small_int(t) || btf_type_is_enum(t))
5308 /* accessing a scalar */
5310 if (!btf_type_is_ptr(t)) {
5312 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
5314 __btf_name_by_offset(btf, t->name_off),
5315 btf_kind_str[BTF_INFO_KIND(t->info)]);
5319 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
5320 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5321 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5324 type = base_type(ctx_arg_info->reg_type);
5325 flag = type_flag(ctx_arg_info->reg_type);
5326 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
5327 (flag & PTR_MAYBE_NULL)) {
5328 info->reg_type = ctx_arg_info->reg_type;
5334 /* This is a pointer to void.
5335 * It is the same as scalar from the verifier safety pov.
5336 * No further pointer walking is allowed.
5340 if (is_int_ptr(btf, t))
5343 /* this is a pointer to another type */
5344 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5345 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5347 if (ctx_arg_info->offset == off) {
5348 if (!ctx_arg_info->btf_id) {
5349 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
5353 info->reg_type = ctx_arg_info->reg_type;
5354 info->btf = btf_vmlinux;
5355 info->btf_id = ctx_arg_info->btf_id;
5360 info->reg_type = PTR_TO_BTF_ID;
5362 enum bpf_prog_type tgt_type;
5364 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
5365 tgt_type = tgt_prog->aux->saved_dst_prog_type;
5367 tgt_type = tgt_prog->type;
5369 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
5371 info->btf = btf_vmlinux;
5380 info->btf_id = t->type;
5381 t = btf_type_by_id(btf, t->type);
5383 if (btf_type_is_type_tag(t)) {
5384 tag_value = __btf_name_by_offset(btf, t->name_off);
5385 if (strcmp(tag_value, "user") == 0)
5386 info->reg_type |= MEM_USER;
5387 if (strcmp(tag_value, "percpu") == 0)
5388 info->reg_type |= MEM_PERCPU;
5391 /* skip modifiers */
5392 while (btf_type_is_modifier(t)) {
5393 info->btf_id = t->type;
5394 t = btf_type_by_id(btf, t->type);
5396 if (!btf_type_is_struct(t)) {
5398 "func '%s' arg%d type %s is not a struct\n",
5399 tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
5402 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
5403 tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
5404 __btf_name_by_offset(btf, t->name_off));
5408 enum bpf_struct_walk_result {
5415 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
5416 const struct btf_type *t, int off, int size,
5417 u32 *next_btf_id, enum bpf_type_flag *flag)
5419 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
5420 const struct btf_type *mtype, *elem_type = NULL;
5421 const struct btf_member *member;
5422 const char *tname, *mname, *tag_value;
5423 u32 vlen, elem_id, mid;
5426 tname = __btf_name_by_offset(btf, t->name_off);
5427 if (!btf_type_is_struct(t)) {
5428 bpf_log(log, "Type '%s' is not a struct\n", tname);
5432 vlen = btf_type_vlen(t);
5433 if (off + size > t->size) {
5434 /* If the last element is a variable size array, we may
5435 * need to relax the rule.
5437 struct btf_array *array_elem;
5442 member = btf_type_member(t) + vlen - 1;
5443 mtype = btf_type_skip_modifiers(btf, member->type,
5445 if (!btf_type_is_array(mtype))
5448 array_elem = (struct btf_array *)(mtype + 1);
5449 if (array_elem->nelems != 0)
5452 moff = __btf_member_bit_offset(t, member) / 8;
5456 /* Only allow structure for now, can be relaxed for
5457 * other types later.
5459 t = btf_type_skip_modifiers(btf, array_elem->type,
5461 if (!btf_type_is_struct(t))
5464 off = (off - moff) % t->size;
5468 bpf_log(log, "access beyond struct %s at off %u size %u\n",
5473 for_each_member(i, t, member) {
5474 /* offset of the field in bytes */
5475 moff = __btf_member_bit_offset(t, member) / 8;
5476 if (off + size <= moff)
5477 /* won't find anything, field is already too far */
5480 if (__btf_member_bitfield_size(t, member)) {
5481 u32 end_bit = __btf_member_bit_offset(t, member) +
5482 __btf_member_bitfield_size(t, member);
5484 /* off <= moff instead of off == moff because clang
5485 * does not generate a BTF member for anonymous
5486 * bitfield like the ":16" here:
5493 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
5496 /* off may be accessing a following member
5500 * Doing partial access at either end of this
5501 * bitfield. Continue on this case also to
5502 * treat it as not accessing this bitfield
5503 * and eventually error out as field not
5504 * found to keep it simple.
5505 * It could be relaxed if there was a legit
5506 * partial access case later.
5511 /* In case of "off" is pointing to holes of a struct */
5515 /* type of the field */
5517 mtype = btf_type_by_id(btf, member->type);
5518 mname = __btf_name_by_offset(btf, member->name_off);
5520 mtype = __btf_resolve_size(btf, mtype, &msize,
5521 &elem_type, &elem_id, &total_nelems,
5523 if (IS_ERR(mtype)) {
5524 bpf_log(log, "field %s doesn't have size\n", mname);
5528 mtrue_end = moff + msize;
5529 if (off >= mtrue_end)
5530 /* no overlap with member, keep iterating */
5533 if (btf_type_is_array(mtype)) {
5536 /* __btf_resolve_size() above helps to
5537 * linearize a multi-dimensional array.
5539 * The logic here is treating an array
5540 * in a struct as the following way:
5543 * struct inner array[2][2];
5549 * struct inner array_elem0;
5550 * struct inner array_elem1;
5551 * struct inner array_elem2;
5552 * struct inner array_elem3;
5555 * When accessing outer->array[1][0], it moves
5556 * moff to "array_elem2", set mtype to
5557 * "struct inner", and msize also becomes
5558 * sizeof(struct inner). Then most of the
5559 * remaining logic will fall through without
5560 * caring the current member is an array or
5563 * Unlike mtype/msize/moff, mtrue_end does not
5564 * change. The naming difference ("_true") tells
5565 * that it is not always corresponding to
5566 * the current mtype/msize/moff.
5567 * It is the true end of the current
5568 * member (i.e. array in this case). That
5569 * will allow an int array to be accessed like
5571 * i.e. allow access beyond the size of
5572 * the array's element as long as it is
5573 * within the mtrue_end boundary.
5576 /* skip empty array */
5577 if (moff == mtrue_end)
5580 msize /= total_nelems;
5581 elem_idx = (off - moff) / msize;
5582 moff += elem_idx * msize;
5587 /* the 'off' we're looking for is either equal to start
5588 * of this field or inside of this struct
5590 if (btf_type_is_struct(mtype)) {
5591 /* our field must be inside that union or struct */
5594 /* return if the offset matches the member offset */
5600 /* adjust offset we're looking for */
5605 if (btf_type_is_ptr(mtype)) {
5606 const struct btf_type *stype, *t;
5607 enum bpf_type_flag tmp_flag = 0;
5610 if (msize != size || off != moff) {
5612 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
5613 mname, moff, tname, off, size);
5617 /* check type tag */
5618 t = btf_type_by_id(btf, mtype->type);
5619 if (btf_type_is_type_tag(t)) {
5620 tag_value = __btf_name_by_offset(btf, t->name_off);
5621 /* check __user tag */
5622 if (strcmp(tag_value, "user") == 0)
5623 tmp_flag = MEM_USER;
5624 /* check __percpu tag */
5625 if (strcmp(tag_value, "percpu") == 0)
5626 tmp_flag = MEM_PERCPU;
5629 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
5630 if (btf_type_is_struct(stype)) {
5637 /* Allow more flexible access within an int as long as
5638 * it is within mtrue_end.
5639 * Since mtrue_end could be the end of an array,
5640 * that also allows using an array of int as a scratch
5641 * space. e.g. skb->cb[].
5643 if (off + size > mtrue_end) {
5645 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
5646 mname, mtrue_end, tname, off, size);
5652 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
5656 int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
5657 const struct btf_type *t, int off, int size,
5658 enum bpf_access_type atype __maybe_unused,
5659 u32 *next_btf_id, enum bpf_type_flag *flag)
5661 enum bpf_type_flag tmp_flag = 0;
5666 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
5670 /* If we found the pointer or scalar on t+off,
5675 return PTR_TO_BTF_ID;
5677 return SCALAR_VALUE;
5679 /* We found nested struct, so continue the search
5680 * by diving in it. At this point the offset is
5681 * aligned with the new type, so set it to 0.
5683 t = btf_type_by_id(btf, id);
5687 /* It's either error or unknown return value..
5690 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5699 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5700 * the same. Trivial ID check is not enough due to module BTFs, because we can
5701 * end up with two different module BTFs, but IDs point to the common type in
5704 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5705 const struct btf *btf2, u32 id2)
5711 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5714 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5715 const struct btf *btf, u32 id, int off,
5716 const struct btf *need_btf, u32 need_type_id,
5719 const struct btf_type *type;
5720 enum bpf_type_flag flag;
5723 /* Are we already done? */
5724 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5726 /* In case of strict type match, we do not walk struct, the top level
5727 * type match must succeed. When strict is true, off should have already
5733 type = btf_type_by_id(btf, id);
5736 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
5737 if (err != WALK_STRUCT)
5740 /* We found nested struct object. If it matches
5741 * the requested ID, we're done. Otherwise let's
5742 * continue the search with offset 0 in the new
5745 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5753 static int __get_type_size(struct btf *btf, u32 btf_id,
5754 const struct btf_type **bad_type)
5756 const struct btf_type *t;
5761 t = btf_type_by_id(btf, btf_id);
5762 while (t && btf_type_is_modifier(t))
5763 t = btf_type_by_id(btf, t->type);
5765 *bad_type = btf_type_by_id(btf, 0);
5768 if (btf_type_is_ptr(t))
5769 /* kernel size of pointer. Not BPF's size of pointer*/
5770 return sizeof(void *);
5771 if (btf_type_is_int(t) || btf_type_is_enum(t))
5777 int btf_distill_func_proto(struct bpf_verifier_log *log,
5779 const struct btf_type *func,
5781 struct btf_func_model *m)
5783 const struct btf_param *args;
5784 const struct btf_type *t;
5789 /* BTF function prototype doesn't match the verifier types.
5790 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
5792 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
5795 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
5798 args = (const struct btf_param *)(func + 1);
5799 nargs = btf_type_vlen(func);
5800 if (nargs > MAX_BPF_FUNC_ARGS) {
5802 "The function %s has %d arguments. Too many.\n",
5806 ret = __get_type_size(btf, func->type, &t);
5809 "The function %s return type %s is unsupported.\n",
5810 tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5815 for (i = 0; i < nargs; i++) {
5816 if (i == nargs - 1 && args[i].type == 0) {
5818 "The function %s with variable args is unsupported.\n",
5822 ret = __get_type_size(btf, args[i].type, &t);
5825 "The function %s arg%d type %s is unsupported.\n",
5826 tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5831 "The function %s has malformed void argument.\n",
5835 m->arg_size[i] = ret;
5841 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5842 * t1 points to BTF_KIND_FUNC in btf1
5843 * t2 points to BTF_KIND_FUNC in btf2
5845 * EINVAL - function prototype mismatch
5846 * EFAULT - verifier bug
5847 * 0 - 99% match. The last 1% is validated by the verifier.
5849 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5850 struct btf *btf1, const struct btf_type *t1,
5851 struct btf *btf2, const struct btf_type *t2)
5853 const struct btf_param *args1, *args2;
5854 const char *fn1, *fn2, *s1, *s2;
5855 u32 nargs1, nargs2, i;
5857 fn1 = btf_name_by_offset(btf1, t1->name_off);
5858 fn2 = btf_name_by_offset(btf2, t2->name_off);
5860 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5861 bpf_log(log, "%s() is not a global function\n", fn1);
5864 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5865 bpf_log(log, "%s() is not a global function\n", fn2);
5869 t1 = btf_type_by_id(btf1, t1->type);
5870 if (!t1 || !btf_type_is_func_proto(t1))
5872 t2 = btf_type_by_id(btf2, t2->type);
5873 if (!t2 || !btf_type_is_func_proto(t2))
5876 args1 = (const struct btf_param *)(t1 + 1);
5877 nargs1 = btf_type_vlen(t1);
5878 args2 = (const struct btf_param *)(t2 + 1);
5879 nargs2 = btf_type_vlen(t2);
5881 if (nargs1 != nargs2) {
5882 bpf_log(log, "%s() has %d args while %s() has %d args\n",
5883 fn1, nargs1, fn2, nargs2);
5887 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5888 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5889 if (t1->info != t2->info) {
5891 "Return type %s of %s() doesn't match type %s of %s()\n",
5892 btf_type_str(t1), fn1,
5893 btf_type_str(t2), fn2);
5897 for (i = 0; i < nargs1; i++) {
5898 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5899 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5901 if (t1->info != t2->info) {
5902 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5903 i, fn1, btf_type_str(t1),
5904 fn2, btf_type_str(t2));
5907 if (btf_type_has_size(t1) && t1->size != t2->size) {
5909 "arg%d in %s() has size %d while %s() has %d\n",
5915 /* global functions are validated with scalars and pointers
5916 * to context only. And only global functions can be replaced.
5917 * Hence type check only those types.
5919 if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5921 if (!btf_type_is_ptr(t1)) {
5923 "arg%d in %s() has unrecognized type\n",
5927 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5928 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5929 if (!btf_type_is_struct(t1)) {
5931 "arg%d in %s() is not a pointer to context\n",
5935 if (!btf_type_is_struct(t2)) {
5937 "arg%d in %s() is not a pointer to context\n",
5941 /* This is an optional check to make program writing easier.
5942 * Compare names of structs and report an error to the user.
5943 * btf_prepare_func_args() already checked that t2 struct
5944 * is a context type. btf_prepare_func_args() will check
5945 * later that t1 struct is a context type as well.
5947 s1 = btf_name_by_offset(btf1, t1->name_off);
5948 s2 = btf_name_by_offset(btf2, t2->name_off);
5949 if (strcmp(s1, s2)) {
5951 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5952 i, fn1, s1, fn2, s2);
5959 /* Compare BTFs of given program with BTF of target program */
5960 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5961 struct btf *btf2, const struct btf_type *t2)
5963 struct btf *btf1 = prog->aux->btf;
5964 const struct btf_type *t1;
5967 if (!prog->aux->func_info) {
5968 bpf_log(log, "Program extension requires BTF\n");
5972 btf_id = prog->aux->func_info[0].type_id;
5976 t1 = btf_type_by_id(btf1, btf_id);
5977 if (!t1 || !btf_type_is_func(t1))
5980 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5983 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5985 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5986 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5987 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5991 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
5992 static bool __btf_type_is_scalar_struct(struct bpf_verifier_log *log,
5993 const struct btf *btf,
5994 const struct btf_type *t, int rec)
5996 const struct btf_type *member_type;
5997 const struct btf_member *member;
6000 if (!btf_type_is_struct(t))
6003 for_each_member(i, t, member) {
6004 const struct btf_array *array;
6006 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
6007 if (btf_type_is_struct(member_type)) {
6009 bpf_log(log, "max struct nesting depth exceeded\n");
6012 if (!__btf_type_is_scalar_struct(log, btf, member_type, rec + 1))
6016 if (btf_type_is_array(member_type)) {
6017 array = btf_type_array(member_type);
6020 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
6021 if (!btf_type_is_scalar(member_type))
6025 if (!btf_type_is_scalar(member_type))
6031 static bool is_kfunc_arg_mem_size(const struct btf *btf,
6032 const struct btf_param *arg,
6033 const struct bpf_reg_state *reg)
6035 int len, sfx_len = sizeof("__sz") - 1;
6036 const struct btf_type *t;
6037 const char *param_name;
6039 t = btf_type_skip_modifiers(btf, arg->type, NULL);
6040 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
6043 /* In the future, this can be ported to use BTF tagging */
6044 param_name = btf_name_by_offset(btf, arg->name_off);
6045 if (str_is_empty(param_name))
6047 len = strlen(param_name);
6050 param_name += len - sfx_len;
6051 if (strncmp(param_name, "__sz", sfx_len))
6057 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6058 const struct btf *btf, u32 func_id,
6059 struct bpf_reg_state *regs,
6062 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6063 struct bpf_verifier_log *log = &env->log;
6064 u32 i, nargs, ref_id, ref_obj_id = 0;
6065 bool is_kfunc = btf_is_kernel(btf);
6066 bool rel = false, kptr_get = false;
6067 const char *func_name, *ref_tname;
6068 const struct btf_type *t, *ref_t;
6069 const struct btf_param *args;
6070 int ref_regno = 0, ret;
6072 t = btf_type_by_id(btf, func_id);
6073 if (!t || !btf_type_is_func(t)) {
6074 /* These checks were already done by the verifier while loading
6075 * struct bpf_func_info or in add_kfunc_call().
6077 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6081 func_name = btf_name_by_offset(btf, t->name_off);
6083 t = btf_type_by_id(btf, t->type);
6084 if (!t || !btf_type_is_func_proto(t)) {
6085 bpf_log(log, "Invalid BTF of func %s\n", func_name);
6088 args = (const struct btf_param *)(t + 1);
6089 nargs = btf_type_vlen(t);
6090 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6091 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6092 MAX_BPF_FUNC_REG_ARGS);
6097 /* Only kfunc can be release func */
6098 rel = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
6099 BTF_KFUNC_TYPE_RELEASE, func_id);
6100 kptr_get = btf_kfunc_id_set_contains(btf, resolve_prog_type(env->prog),
6101 BTF_KFUNC_TYPE_KPTR_ACQUIRE, func_id);
6104 /* check that BTF function arguments match actual types that the
6107 for (i = 0; i < nargs; i++) {
6108 enum bpf_arg_type arg_type = ARG_DONTCARE;
6110 struct bpf_reg_state *reg = ®s[regno];
6112 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6113 if (btf_type_is_scalar(t)) {
6114 if (reg->type == SCALAR_VALUE)
6116 bpf_log(log, "R%d is not a scalar\n", regno);
6120 if (!btf_type_is_ptr(t)) {
6121 bpf_log(log, "Unrecognized arg#%d type %s\n",
6122 i, btf_type_str(t));
6126 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6127 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6129 if (rel && reg->ref_obj_id)
6130 arg_type |= OBJ_RELEASE;
6131 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6135 /* kptr_get is only true for kfunc */
6136 if (i == 0 && kptr_get) {
6137 struct bpf_map_value_off_desc *off_desc;
6139 if (reg->type != PTR_TO_MAP_VALUE) {
6140 bpf_log(log, "arg#0 expected pointer to map value\n");
6144 /* check_func_arg_reg_off allows var_off for
6145 * PTR_TO_MAP_VALUE, but we need fixed offset to find
6148 if (!tnum_is_const(reg->var_off)) {
6149 bpf_log(log, "arg#0 must have constant offset\n");
6153 off_desc = bpf_map_kptr_off_contains(reg->map_ptr, reg->off + reg->var_off.value);
6154 if (!off_desc || off_desc->type != BPF_KPTR_REF) {
6155 bpf_log(log, "arg#0 no referenced kptr at map value offset=%llu\n",
6156 reg->off + reg->var_off.value);
6160 if (!btf_type_is_ptr(ref_t)) {
6161 bpf_log(log, "arg#0 BTF type must be a double pointer\n");
6165 ref_t = btf_type_skip_modifiers(btf, ref_t->type, &ref_id);
6166 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6168 if (!btf_type_is_struct(ref_t)) {
6169 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6170 func_name, i, btf_type_str(ref_t), ref_tname);
6173 if (!btf_struct_ids_match(log, btf, ref_id, 0, off_desc->kptr.btf,
6174 off_desc->kptr.btf_id, true)) {
6175 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s\n",
6176 func_name, i, btf_type_str(ref_t), ref_tname);
6179 /* rest of the arguments can be anything, like normal kfunc */
6180 } else if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6181 /* If function expects ctx type in BTF check that caller
6182 * is passing PTR_TO_CTX.
6184 if (reg->type != PTR_TO_CTX) {
6186 "arg#%d expected pointer to ctx, but got %s\n",
6187 i, btf_type_str(t));
6190 } else if (is_kfunc && (reg->type == PTR_TO_BTF_ID ||
6191 (reg2btf_ids[base_type(reg->type)] && !type_flag(reg->type)))) {
6192 const struct btf_type *reg_ref_t;
6193 const struct btf *reg_btf;
6194 const char *reg_ref_tname;
6197 if (!btf_type_is_struct(ref_t)) {
6198 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6199 func_name, i, btf_type_str(ref_t),
6204 if (reg->type == PTR_TO_BTF_ID) {
6206 reg_ref_id = reg->btf_id;
6207 /* Ensure only one argument is referenced PTR_TO_BTF_ID */
6208 if (reg->ref_obj_id) {
6210 bpf_log(log, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6211 regno, reg->ref_obj_id, ref_obj_id);
6215 ref_obj_id = reg->ref_obj_id;
6218 reg_btf = btf_vmlinux;
6219 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
6222 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id,
6224 reg_ref_tname = btf_name_by_offset(reg_btf,
6225 reg_ref_t->name_off);
6226 if (!btf_struct_ids_match(log, reg_btf, reg_ref_id,
6227 reg->off, btf, ref_id, rel && reg->ref_obj_id)) {
6228 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
6230 btf_type_str(ref_t), ref_tname,
6231 regno, btf_type_str(reg_ref_t),
6235 } else if (ptr_to_mem_ok) {
6236 const struct btf_type *resolve_ret;
6240 bool arg_mem_size = i + 1 < nargs && is_kfunc_arg_mem_size(btf, &args[i + 1], ®s[regno + 1]);
6242 /* Permit pointer to mem, but only when argument
6243 * type is pointer to scalar, or struct composed
6244 * (recursively) of scalars.
6245 * When arg_mem_size is true, the pointer can be
6248 if (!btf_type_is_scalar(ref_t) &&
6249 !__btf_type_is_scalar_struct(log, btf, ref_t, 0) &&
6250 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
6252 "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
6253 i, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
6257 /* Check for mem, len pair */
6259 if (check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1)) {
6260 bpf_log(log, "arg#%d arg#%d memory, len pair leads to invalid memory access\n",
6269 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6270 if (IS_ERR(resolve_ret)) {
6272 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6273 i, btf_type_str(ref_t), ref_tname,
6274 PTR_ERR(resolve_ret));
6278 if (check_mem_reg(env, reg, regno, type_size))
6281 bpf_log(log, "reg type unsupported for arg#%d %sfunction %s#%d\n", i,
6282 is_kfunc ? "kernel " : "", func_name, func_id);
6287 /* Either both are set, or neither */
6288 WARN_ON_ONCE((ref_obj_id && !ref_regno) || (!ref_obj_id && ref_regno));
6289 /* We already made sure ref_obj_id is set only for one argument. We do
6290 * allow (!rel && ref_obj_id), so that passing such referenced
6291 * PTR_TO_BTF_ID to other kfuncs works. Note that rel is only true when
6294 if (rel && !ref_obj_id) {
6295 bpf_log(log, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
6299 /* returns argument register number > 0 in case of reference release kfunc */
6300 return rel ? ref_regno : 0;
6303 /* Compare BTF of a function with given bpf_reg_state.
6305 * EFAULT - there is a verifier bug. Abort verification.
6306 * EINVAL - there is a type mismatch or BTF is not available.
6307 * 0 - BTF matches with what bpf_reg_state expects.
6308 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6310 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6311 struct bpf_reg_state *regs)
6313 struct bpf_prog *prog = env->prog;
6314 struct btf *btf = prog->aux->btf;
6319 if (!prog->aux->func_info)
6322 btf_id = prog->aux->func_info[subprog].type_id;
6326 if (prog->aux->func_info_aux[subprog].unreliable)
6329 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6330 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global);
6332 /* Compiler optimizations can remove arguments from static functions
6333 * or mismatched type can be passed into a global function.
6334 * In such cases mark the function as unreliable from BTF point of view.
6337 prog->aux->func_info_aux[subprog].unreliable = true;
6341 int btf_check_kfunc_arg_match(struct bpf_verifier_env *env,
6342 const struct btf *btf, u32 func_id,
6343 struct bpf_reg_state *regs)
6345 return btf_check_func_arg_match(env, btf, func_id, regs, true);
6348 /* Convert BTF of a function into bpf_reg_state if possible
6350 * EFAULT - there is a verifier bug. Abort verification.
6351 * EINVAL - cannot convert BTF.
6352 * 0 - Successfully converted BTF into bpf_reg_state
6353 * (either PTR_TO_CTX or SCALAR_VALUE).
6355 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6356 struct bpf_reg_state *regs)
6358 struct bpf_verifier_log *log = &env->log;
6359 struct bpf_prog *prog = env->prog;
6360 enum bpf_prog_type prog_type = prog->type;
6361 struct btf *btf = prog->aux->btf;
6362 const struct btf_param *args;
6363 const struct btf_type *t, *ref_t;
6364 u32 i, nargs, btf_id;
6367 if (!prog->aux->func_info ||
6368 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6369 bpf_log(log, "Verifier bug\n");
6373 btf_id = prog->aux->func_info[subprog].type_id;
6375 bpf_log(log, "Global functions need valid BTF\n");
6379 t = btf_type_by_id(btf, btf_id);
6380 if (!t || !btf_type_is_func(t)) {
6381 /* These checks were already done by the verifier while loading
6382 * struct bpf_func_info
6384 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6388 tname = btf_name_by_offset(btf, t->name_off);
6390 if (log->level & BPF_LOG_LEVEL)
6391 bpf_log(log, "Validating %s() func#%d...\n",
6394 if (prog->aux->func_info_aux[subprog].unreliable) {
6395 bpf_log(log, "Verifier bug in function %s()\n", tname);
6398 if (prog_type == BPF_PROG_TYPE_EXT)
6399 prog_type = prog->aux->dst_prog->type;
6401 t = btf_type_by_id(btf, t->type);
6402 if (!t || !btf_type_is_func_proto(t)) {
6403 bpf_log(log, "Invalid type of function %s()\n", tname);
6406 args = (const struct btf_param *)(t + 1);
6407 nargs = btf_type_vlen(t);
6408 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6409 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
6410 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
6413 /* check that function returns int */
6414 t = btf_type_by_id(btf, t->type);
6415 while (btf_type_is_modifier(t))
6416 t = btf_type_by_id(btf, t->type);
6417 if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
6419 "Global function %s() doesn't return scalar. Only those are supported.\n",
6423 /* Convert BTF function arguments into verifier types.
6424 * Only PTR_TO_CTX and SCALAR are supported atm.
6426 for (i = 0; i < nargs; i++) {
6427 struct bpf_reg_state *reg = ®s[i + 1];
6429 t = btf_type_by_id(btf, args[i].type);
6430 while (btf_type_is_modifier(t))
6431 t = btf_type_by_id(btf, t->type);
6432 if (btf_type_is_int(t) || btf_type_is_enum(t)) {
6433 reg->type = SCALAR_VALUE;
6436 if (btf_type_is_ptr(t)) {
6437 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6438 reg->type = PTR_TO_CTX;
6442 t = btf_type_skip_modifiers(btf, t->type, NULL);
6444 ref_t = btf_resolve_size(btf, t, ®->mem_size);
6445 if (IS_ERR(ref_t)) {
6447 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6448 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
6453 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6454 reg->id = ++env->id_gen;
6458 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
6459 i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
6465 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
6466 struct btf_show *show)
6468 const struct btf_type *t = btf_type_by_id(btf, type_id);
6471 memset(&show->state, 0, sizeof(show->state));
6472 memset(&show->obj, 0, sizeof(show->obj));
6474 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
6477 static void btf_seq_show(struct btf_show *show, const char *fmt,
6480 seq_vprintf((struct seq_file *)show->target, fmt, args);
6483 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
6484 void *obj, struct seq_file *m, u64 flags)
6486 struct btf_show sseq;
6489 sseq.showfn = btf_seq_show;
6492 btf_type_show(btf, type_id, obj, &sseq);
6494 return sseq.state.status;
6497 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
6500 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
6501 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
6502 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
6505 struct btf_show_snprintf {
6506 struct btf_show show;
6507 int len_left; /* space left in string */
6508 int len; /* length we would have written */
6511 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
6514 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
6517 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
6520 ssnprintf->len_left = 0;
6521 ssnprintf->len = len;
6522 } else if (len > ssnprintf->len_left) {
6523 /* no space, drive on to get length we would have written */
6524 ssnprintf->len_left = 0;
6525 ssnprintf->len += len;
6527 ssnprintf->len_left -= len;
6528 ssnprintf->len += len;
6529 show->target += len;
6533 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
6534 char *buf, int len, u64 flags)
6536 struct btf_show_snprintf ssnprintf;
6538 ssnprintf.show.target = buf;
6539 ssnprintf.show.flags = flags;
6540 ssnprintf.show.showfn = btf_snprintf_show;
6541 ssnprintf.len_left = len;
6544 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
6546 /* If we encountered an error, return it. */
6547 if (ssnprintf.show.state.status)
6548 return ssnprintf.show.state.status;
6550 /* Otherwise return length we would have written */
6551 return ssnprintf.len;
6554 #ifdef CONFIG_PROC_FS
6555 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
6557 const struct btf *btf = filp->private_data;
6559 seq_printf(m, "btf_id:\t%u\n", btf->id);
6563 static int btf_release(struct inode *inode, struct file *filp)
6565 btf_put(filp->private_data);
6569 const struct file_operations btf_fops = {
6570 #ifdef CONFIG_PROC_FS
6571 .show_fdinfo = bpf_btf_show_fdinfo,
6573 .release = btf_release,
6576 static int __btf_new_fd(struct btf *btf)
6578 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
6581 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
6586 btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
6587 attr->btf_size, attr->btf_log_level,
6588 u64_to_user_ptr(attr->btf_log_buf),
6589 attr->btf_log_size);
6591 return PTR_ERR(btf);
6593 ret = btf_alloc_id(btf);
6600 * The BTF ID is published to the userspace.
6601 * All BTF free must go through call_rcu() from
6602 * now on (i.e. free by calling btf_put()).
6605 ret = __btf_new_fd(btf);
6612 struct btf *btf_get_by_fd(int fd)
6620 return ERR_PTR(-EBADF);
6622 if (f.file->f_op != &btf_fops) {
6624 return ERR_PTR(-EINVAL);
6627 btf = f.file->private_data;
6628 refcount_inc(&btf->refcnt);
6634 int btf_get_info_by_fd(const struct btf *btf,
6635 const union bpf_attr *attr,
6636 union bpf_attr __user *uattr)
6638 struct bpf_btf_info __user *uinfo;
6639 struct bpf_btf_info info;
6640 u32 info_copy, btf_copy;
6643 u32 uinfo_len, uname_len, name_len;
6646 uinfo = u64_to_user_ptr(attr->info.info);
6647 uinfo_len = attr->info.info_len;
6649 info_copy = min_t(u32, uinfo_len, sizeof(info));
6650 memset(&info, 0, sizeof(info));
6651 if (copy_from_user(&info, uinfo, info_copy))
6655 ubtf = u64_to_user_ptr(info.btf);
6656 btf_copy = min_t(u32, btf->data_size, info.btf_size);
6657 if (copy_to_user(ubtf, btf->data, btf_copy))
6659 info.btf_size = btf->data_size;
6661 info.kernel_btf = btf->kernel_btf;
6663 uname = u64_to_user_ptr(info.name);
6664 uname_len = info.name_len;
6665 if (!uname ^ !uname_len)
6668 name_len = strlen(btf->name);
6669 info.name_len = name_len;
6672 if (uname_len >= name_len + 1) {
6673 if (copy_to_user(uname, btf->name, name_len + 1))
6678 if (copy_to_user(uname, btf->name, uname_len - 1))
6680 if (put_user(zero, uname + uname_len - 1))
6682 /* let user-space know about too short buffer */
6687 if (copy_to_user(uinfo, &info, info_copy) ||
6688 put_user(info_copy, &uattr->info.info_len))
6694 int btf_get_fd_by_id(u32 id)
6700 btf = idr_find(&btf_idr, id);
6701 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
6702 btf = ERR_PTR(-ENOENT);
6706 return PTR_ERR(btf);
6708 fd = __btf_new_fd(btf);
6715 u32 btf_obj_id(const struct btf *btf)
6720 bool btf_is_kernel(const struct btf *btf)
6722 return btf->kernel_btf;
6725 bool btf_is_module(const struct btf *btf)
6727 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
6730 static int btf_id_cmp_func(const void *a, const void *b)
6732 const int *pa = a, *pb = b;
6737 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
6739 return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
6743 BTF_MODULE_F_LIVE = (1 << 0),
6746 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6748 struct list_head list;
6749 struct module *module;
6751 struct bin_attribute *sysfs_attr;
6755 static LIST_HEAD(btf_modules);
6756 static DEFINE_MUTEX(btf_module_mutex);
6759 btf_module_read(struct file *file, struct kobject *kobj,
6760 struct bin_attribute *bin_attr,
6761 char *buf, loff_t off, size_t len)
6763 const struct btf *btf = bin_attr->private;
6765 memcpy(buf, btf->data + off, len);
6769 static void purge_cand_cache(struct btf *btf);
6771 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
6774 struct btf_module *btf_mod, *tmp;
6775 struct module *mod = module;
6779 if (mod->btf_data_size == 0 ||
6780 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
6781 op != MODULE_STATE_GOING))
6785 case MODULE_STATE_COMING:
6786 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
6791 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
6793 pr_warn("failed to validate module [%s] BTF: %ld\n",
6794 mod->name, PTR_ERR(btf));
6796 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
6800 err = btf_alloc_id(btf);
6807 purge_cand_cache(NULL);
6808 mutex_lock(&btf_module_mutex);
6809 btf_mod->module = module;
6811 list_add(&btf_mod->list, &btf_modules);
6812 mutex_unlock(&btf_module_mutex);
6814 if (IS_ENABLED(CONFIG_SYSFS)) {
6815 struct bin_attribute *attr;
6817 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
6821 sysfs_bin_attr_init(attr);
6822 attr->attr.name = btf->name;
6823 attr->attr.mode = 0444;
6824 attr->size = btf->data_size;
6825 attr->private = btf;
6826 attr->read = btf_module_read;
6828 err = sysfs_create_bin_file(btf_kobj, attr);
6830 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
6837 btf_mod->sysfs_attr = attr;
6841 case MODULE_STATE_LIVE:
6842 mutex_lock(&btf_module_mutex);
6843 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6844 if (btf_mod->module != module)
6847 btf_mod->flags |= BTF_MODULE_F_LIVE;
6850 mutex_unlock(&btf_module_mutex);
6852 case MODULE_STATE_GOING:
6853 mutex_lock(&btf_module_mutex);
6854 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6855 if (btf_mod->module != module)
6858 list_del(&btf_mod->list);
6859 if (btf_mod->sysfs_attr)
6860 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
6861 purge_cand_cache(btf_mod->btf);
6862 btf_put(btf_mod->btf);
6863 kfree(btf_mod->sysfs_attr);
6867 mutex_unlock(&btf_module_mutex);
6871 return notifier_from_errno(err);
6874 static struct notifier_block btf_module_nb = {
6875 .notifier_call = btf_module_notify,
6878 static int __init btf_module_init(void)
6880 register_module_notifier(&btf_module_nb);
6884 fs_initcall(btf_module_init);
6885 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6887 struct module *btf_try_get_module(const struct btf *btf)
6889 struct module *res = NULL;
6890 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6891 struct btf_module *btf_mod, *tmp;
6893 mutex_lock(&btf_module_mutex);
6894 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6895 if (btf_mod->btf != btf)
6898 /* We must only consider module whose __init routine has
6899 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
6900 * which is set from the notifier callback for
6901 * MODULE_STATE_LIVE.
6903 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
6904 res = btf_mod->module;
6908 mutex_unlock(&btf_module_mutex);
6914 /* Returns struct btf corresponding to the struct module.
6915 * This function can return NULL or ERR_PTR.
6917 static struct btf *btf_get_module_btf(const struct module *module)
6919 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6920 struct btf_module *btf_mod, *tmp;
6922 struct btf *btf = NULL;
6925 btf = bpf_get_btf_vmlinux();
6926 if (!IS_ERR_OR_NULL(btf))
6931 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6932 mutex_lock(&btf_module_mutex);
6933 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6934 if (btf_mod->module != module)
6937 btf_get(btf_mod->btf);
6941 mutex_unlock(&btf_module_mutex);
6947 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
6949 struct btf *btf = NULL;
6956 if (name_sz <= 1 || name[name_sz - 1])
6959 ret = bpf_find_btf_id(name, kind, &btf);
6960 if (ret > 0 && btf_is_module(btf)) {
6961 btf_obj_fd = __btf_new_fd(btf);
6962 if (btf_obj_fd < 0) {
6966 return ret | (((u64)btf_obj_fd) << 32);
6973 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
6974 .func = bpf_btf_find_by_name_kind,
6976 .ret_type = RET_INTEGER,
6977 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
6978 .arg2_type = ARG_CONST_SIZE,
6979 .arg3_type = ARG_ANYTHING,
6980 .arg4_type = ARG_ANYTHING,
6983 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
6984 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
6985 BTF_TRACING_TYPE_xxx
6986 #undef BTF_TRACING_TYPE
6988 /* Kernel Function (kfunc) BTF ID set registration API */
6990 static int __btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
6991 enum btf_kfunc_type type,
6992 struct btf_id_set *add_set, bool vmlinux_set)
6994 struct btf_kfunc_set_tab *tab;
6995 struct btf_id_set *set;
6999 if (hook >= BTF_KFUNC_HOOK_MAX || type >= BTF_KFUNC_TYPE_MAX) {
7007 tab = btf->kfunc_set_tab;
7009 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7012 btf->kfunc_set_tab = tab;
7015 set = tab->sets[hook][type];
7016 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7019 if (WARN_ON_ONCE(set && !vmlinux_set)) {
7024 /* We don't need to allocate, concatenate, and sort module sets, because
7025 * only one is allowed per hook. Hence, we can directly assign the
7026 * pointer and return.
7029 tab->sets[hook][type] = add_set;
7033 /* In case of vmlinux sets, there may be more than one set being
7034 * registered per hook. To create a unified set, we allocate a new set
7035 * and concatenate all individual sets being registered. While each set
7036 * is individually sorted, they may become unsorted when concatenated,
7037 * hence re-sorting the final set again is required to make binary
7038 * searching the set using btf_id_set_contains function work.
7040 set_cnt = set ? set->cnt : 0;
7042 if (set_cnt > U32_MAX - add_set->cnt) {
7047 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7053 set = krealloc(tab->sets[hook][type],
7054 offsetof(struct btf_id_set, ids[set_cnt + add_set->cnt]),
7055 GFP_KERNEL | __GFP_NOWARN);
7061 /* For newly allocated set, initialize set->cnt to 0 */
7062 if (!tab->sets[hook][type])
7064 tab->sets[hook][type] = set;
7066 /* Concatenate the two sets */
7067 memcpy(set->ids + set->cnt, add_set->ids, add_set->cnt * sizeof(set->ids[0]));
7068 set->cnt += add_set->cnt;
7070 sort(set->ids, set->cnt, sizeof(set->ids[0]), btf_id_cmp_func, NULL);
7074 btf_free_kfunc_set_tab(btf);
7078 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7079 const struct btf_kfunc_id_set *kset)
7081 bool vmlinux_set = !btf_is_module(btf);
7084 for (type = 0; type < ARRAY_SIZE(kset->sets); type++) {
7085 if (!kset->sets[type])
7088 ret = __btf_populate_kfunc_set(btf, hook, type, kset->sets[type], vmlinux_set);
7095 static bool __btf_kfunc_id_set_contains(const struct btf *btf,
7096 enum btf_kfunc_hook hook,
7097 enum btf_kfunc_type type,
7100 struct btf_id_set *set;
7102 if (hook >= BTF_KFUNC_HOOK_MAX || type >= BTF_KFUNC_TYPE_MAX)
7104 if (!btf->kfunc_set_tab)
7106 set = btf->kfunc_set_tab->sets[hook][type];
7109 return btf_id_set_contains(set, kfunc_btf_id);
7112 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7114 switch (prog_type) {
7115 case BPF_PROG_TYPE_XDP:
7116 return BTF_KFUNC_HOOK_XDP;
7117 case BPF_PROG_TYPE_SCHED_CLS:
7118 return BTF_KFUNC_HOOK_TC;
7119 case BPF_PROG_TYPE_STRUCT_OPS:
7120 return BTF_KFUNC_HOOK_STRUCT_OPS;
7121 case BPF_PROG_TYPE_TRACING:
7122 return BTF_KFUNC_HOOK_TRACING;
7123 case BPF_PROG_TYPE_SYSCALL:
7124 return BTF_KFUNC_HOOK_SYSCALL;
7126 return BTF_KFUNC_HOOK_MAX;
7131 * Reference to the module (obtained using btf_try_get_module) corresponding to
7132 * the struct btf *MUST* be held when calling this function from verifier
7133 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7134 * keeping the reference for the duration of the call provides the necessary
7135 * protection for looking up a well-formed btf->kfunc_set_tab.
7137 bool btf_kfunc_id_set_contains(const struct btf *btf,
7138 enum bpf_prog_type prog_type,
7139 enum btf_kfunc_type type, u32 kfunc_btf_id)
7141 enum btf_kfunc_hook hook;
7143 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7144 return __btf_kfunc_id_set_contains(btf, hook, type, kfunc_btf_id);
7147 /* This function must be invoked only from initcalls/module init functions */
7148 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7149 const struct btf_kfunc_id_set *kset)
7151 enum btf_kfunc_hook hook;
7155 btf = btf_get_module_btf(kset->owner);
7157 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7158 pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7161 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7162 pr_err("missing module BTF, cannot register kfuncs\n");
7168 return PTR_ERR(btf);
7170 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7171 ret = btf_populate_kfunc_set(btf, hook, kset);
7175 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7177 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7179 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7180 struct btf_id_dtor_kfunc *dtor;
7184 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7185 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7187 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7188 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7191 return dtor->kfunc_btf_id;
7194 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7196 const struct btf_type *dtor_func, *dtor_func_proto, *t;
7197 const struct btf_param *args;
7201 for (i = 0; i < cnt; i++) {
7202 dtor_btf_id = dtors[i].kfunc_btf_id;
7204 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7205 if (!dtor_func || !btf_type_is_func(dtor_func))
7208 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7209 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7212 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7213 t = btf_type_by_id(btf, dtor_func_proto->type);
7214 if (!t || !btf_type_is_void(t))
7217 nr_args = btf_type_vlen(dtor_func_proto);
7220 args = btf_params(dtor_func_proto);
7221 t = btf_type_by_id(btf, args[0].type);
7222 /* Allow any pointer type, as width on targets Linux supports
7223 * will be same for all pointer types (i.e. sizeof(void *))
7225 if (!t || !btf_type_is_ptr(t))
7231 /* This function must be invoked only from initcalls/module init functions */
7232 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7233 struct module *owner)
7235 struct btf_id_dtor_kfunc_tab *tab;
7240 btf = btf_get_module_btf(owner);
7242 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7243 pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7246 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7247 pr_err("missing module BTF, cannot register dtor kfuncs\n");
7253 return PTR_ERR(btf);
7255 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7256 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7261 /* Ensure that the prototype of dtor kfuncs being registered is sane */
7262 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7266 tab = btf->dtor_kfunc_tab;
7267 /* Only one call allowed for modules */
7268 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7273 tab_cnt = tab ? tab->cnt : 0;
7274 if (tab_cnt > U32_MAX - add_cnt) {
7278 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7279 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7284 tab = krealloc(btf->dtor_kfunc_tab,
7285 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7286 GFP_KERNEL | __GFP_NOWARN);
7292 if (!btf->dtor_kfunc_tab)
7294 btf->dtor_kfunc_tab = tab;
7296 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7297 tab->cnt += add_cnt;
7299 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7303 btf_free_dtor_kfunc_tab(btf);
7307 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7309 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
7312 int __bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7313 const struct btf *targ_btf, __u32 targ_id,
7316 const struct btf_type *local_type, *targ_type;
7317 int depth = 32; /* max recursion depth */
7319 /* caller made sure that names match (ignoring flavor suffix) */
7320 local_type = btf_type_by_id(local_btf, local_id);
7321 targ_type = btf_type_by_id(targ_btf, targ_id);
7322 if (btf_kind(local_type) != btf_kind(targ_type))
7330 local_type = btf_type_skip_modifiers(local_btf, local_id, &local_id);
7331 targ_type = btf_type_skip_modifiers(targ_btf, targ_id, &targ_id);
7332 if (!local_type || !targ_type)
7335 if (btf_kind(local_type) != btf_kind(targ_type))
7338 switch (btf_kind(local_type)) {
7340 case BTF_KIND_STRUCT:
7341 case BTF_KIND_UNION:
7346 /* just reject deprecated bitfield-like integers; all other
7347 * integers are by default compatible between each other
7349 return btf_int_offset(local_type) == 0 && btf_int_offset(targ_type) == 0;
7351 local_id = local_type->type;
7352 targ_id = targ_type->type;
7354 case BTF_KIND_ARRAY:
7355 local_id = btf_array(local_type)->type;
7356 targ_id = btf_array(targ_type)->type;
7358 case BTF_KIND_FUNC_PROTO: {
7359 struct btf_param *local_p = btf_params(local_type);
7360 struct btf_param *targ_p = btf_params(targ_type);
7361 __u16 local_vlen = btf_vlen(local_type);
7362 __u16 targ_vlen = btf_vlen(targ_type);
7365 if (local_vlen != targ_vlen)
7368 for (i = 0; i < local_vlen; i++, local_p++, targ_p++) {
7372 btf_type_skip_modifiers(local_btf, local_p->type, &local_id);
7373 btf_type_skip_modifiers(targ_btf, targ_p->type, &targ_id);
7374 err = __bpf_core_types_are_compat(local_btf, local_id,
7381 /* tail recurse for return type check */
7382 btf_type_skip_modifiers(local_btf, local_type->type, &local_id);
7383 btf_type_skip_modifiers(targ_btf, targ_type->type, &targ_id);
7391 /* Check local and target types for compatibility. This check is used for
7392 * type-based CO-RE relocations and follow slightly different rules than
7393 * field-based relocations. This function assumes that root types were already
7394 * checked for name match. Beyond that initial root-level name check, names
7395 * are completely ignored. Compatibility rules are as follows:
7396 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
7397 * kind should match for local and target types (i.e., STRUCT is not
7398 * compatible with UNION);
7399 * - for ENUMs, the size is ignored;
7400 * - for INT, size and signedness are ignored;
7401 * - for ARRAY, dimensionality is ignored, element types are checked for
7402 * compatibility recursively;
7403 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
7404 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7405 * - FUNC_PROTOs are compatible if they have compatible signature: same
7406 * number of input args and compatible return and argument types.
7407 * These rules are not set in stone and probably will be adjusted as we get
7408 * more experience with using BPF CO-RE relocations.
7410 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7411 const struct btf *targ_btf, __u32 targ_id)
7413 return __bpf_core_types_are_compat(local_btf, local_id,
7415 MAX_TYPES_ARE_COMPAT_DEPTH);
7418 static bool bpf_core_is_flavor_sep(const char *s)
7420 /* check X___Y name pattern, where X and Y are not underscores */
7421 return s[0] != '_' && /* X */
7422 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
7423 s[4] != '_'; /* Y */
7426 size_t bpf_core_essential_name_len(const char *name)
7428 size_t n = strlen(name);
7431 for (i = n - 5; i >= 0; i--) {
7432 if (bpf_core_is_flavor_sep(name + i))
7438 struct bpf_cand_cache {
7444 const struct btf *btf;
7449 static void bpf_free_cands(struct bpf_cand_cache *cands)
7452 /* empty candidate array was allocated on stack */
7457 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
7463 #define VMLINUX_CAND_CACHE_SIZE 31
7464 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
7466 #define MODULE_CAND_CACHE_SIZE 31
7467 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
7469 static DEFINE_MUTEX(cand_cache_mutex);
7471 static void __print_cand_cache(struct bpf_verifier_log *log,
7472 struct bpf_cand_cache **cache,
7475 struct bpf_cand_cache *cc;
7478 for (i = 0; i < cache_size; i++) {
7482 bpf_log(log, "[%d]%s(", i, cc->name);
7483 for (j = 0; j < cc->cnt; j++) {
7484 bpf_log(log, "%d", cc->cands[j].id);
7485 if (j < cc->cnt - 1)
7488 bpf_log(log, "), ");
7492 static void print_cand_cache(struct bpf_verifier_log *log)
7494 mutex_lock(&cand_cache_mutex);
7495 bpf_log(log, "vmlinux_cand_cache:");
7496 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7497 bpf_log(log, "\nmodule_cand_cache:");
7498 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7500 mutex_unlock(&cand_cache_mutex);
7503 static u32 hash_cands(struct bpf_cand_cache *cands)
7505 return jhash(cands->name, cands->name_len, 0);
7508 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
7509 struct bpf_cand_cache **cache,
7512 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
7514 if (cc && cc->name_len == cands->name_len &&
7515 !strncmp(cc->name, cands->name, cands->name_len))
7520 static size_t sizeof_cands(int cnt)
7522 return offsetof(struct bpf_cand_cache, cands[cnt]);
7525 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
7526 struct bpf_cand_cache **cache,
7529 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
7532 bpf_free_cands_from_cache(*cc);
7535 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
7537 bpf_free_cands(cands);
7538 return ERR_PTR(-ENOMEM);
7540 /* strdup the name, since it will stay in cache.
7541 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
7543 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
7544 bpf_free_cands(cands);
7545 if (!new_cands->name) {
7547 return ERR_PTR(-ENOMEM);
7553 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7554 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
7557 struct bpf_cand_cache *cc;
7560 for (i = 0; i < cache_size; i++) {
7565 /* when new module is loaded purge all of module_cand_cache,
7566 * since new module might have candidates with the name
7567 * that matches cached cands.
7569 bpf_free_cands_from_cache(cc);
7573 /* when module is unloaded purge cache entries
7574 * that match module's btf
7576 for (j = 0; j < cc->cnt; j++)
7577 if (cc->cands[j].btf == btf) {
7578 bpf_free_cands_from_cache(cc);
7586 static void purge_cand_cache(struct btf *btf)
7588 mutex_lock(&cand_cache_mutex);
7589 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7590 mutex_unlock(&cand_cache_mutex);
7594 static struct bpf_cand_cache *
7595 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
7598 struct bpf_cand_cache *new_cands;
7599 const struct btf_type *t;
7600 const char *targ_name;
7601 size_t targ_essent_len;
7604 n = btf_nr_types(targ_btf);
7605 for (i = targ_start_id; i < n; i++) {
7606 t = btf_type_by_id(targ_btf, i);
7607 if (btf_kind(t) != cands->kind)
7610 targ_name = btf_name_by_offset(targ_btf, t->name_off);
7614 /* the resched point is before strncmp to make sure that search
7615 * for non-existing name will have a chance to schedule().
7619 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
7622 targ_essent_len = bpf_core_essential_name_len(targ_name);
7623 if (targ_essent_len != cands->name_len)
7626 /* most of the time there is only one candidate for a given kind+name pair */
7627 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
7629 bpf_free_cands(cands);
7630 return ERR_PTR(-ENOMEM);
7633 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
7634 bpf_free_cands(cands);
7636 cands->cands[cands->cnt].btf = targ_btf;
7637 cands->cands[cands->cnt].id = i;
7643 static struct bpf_cand_cache *
7644 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
7646 struct bpf_cand_cache *cands, *cc, local_cand = {};
7647 const struct btf *local_btf = ctx->btf;
7648 const struct btf_type *local_type;
7649 const struct btf *main_btf;
7650 size_t local_essent_len;
7651 struct btf *mod_btf;
7655 main_btf = bpf_get_btf_vmlinux();
7656 if (IS_ERR(main_btf))
7657 return ERR_CAST(main_btf);
7659 return ERR_PTR(-EINVAL);
7661 local_type = btf_type_by_id(local_btf, local_type_id);
7663 return ERR_PTR(-EINVAL);
7665 name = btf_name_by_offset(local_btf, local_type->name_off);
7666 if (str_is_empty(name))
7667 return ERR_PTR(-EINVAL);
7668 local_essent_len = bpf_core_essential_name_len(name);
7670 cands = &local_cand;
7672 cands->kind = btf_kind(local_type);
7673 cands->name_len = local_essent_len;
7675 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7676 /* cands is a pointer to stack here */
7683 /* Attempt to find target candidates in vmlinux BTF first */
7684 cands = bpf_core_add_cands(cands, main_btf, 1);
7686 return ERR_CAST(cands);
7688 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
7690 /* populate cache even when cands->cnt == 0 */
7691 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7693 return ERR_CAST(cc);
7695 /* if vmlinux BTF has any candidate, don't go for module BTFs */
7700 /* cands is a pointer to stack here and cands->cnt == 0 */
7701 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7703 /* if cache has it return it even if cc->cnt == 0 */
7706 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
7707 spin_lock_bh(&btf_idr_lock);
7708 idr_for_each_entry(&btf_idr, mod_btf, id) {
7709 if (!btf_is_module(mod_btf))
7711 /* linear search could be slow hence unlock/lock
7712 * the IDR to avoiding holding it for too long
7715 spin_unlock_bh(&btf_idr_lock);
7716 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
7717 if (IS_ERR(cands)) {
7719 return ERR_CAST(cands);
7721 spin_lock_bh(&btf_idr_lock);
7724 spin_unlock_bh(&btf_idr_lock);
7725 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
7726 * or pointer to stack if cands->cnd == 0.
7727 * Copy it into the cache even when cands->cnt == 0 and
7728 * return the result.
7730 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7733 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
7734 int relo_idx, void *insn)
7736 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
7737 struct bpf_core_cand_list cands = {};
7738 struct bpf_core_relo_res targ_res;
7739 struct bpf_core_spec *specs;
7742 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
7743 * into arrays of btf_ids of struct fields and array indices.
7745 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
7750 struct bpf_cand_cache *cc;
7753 mutex_lock(&cand_cache_mutex);
7754 cc = bpf_core_find_cands(ctx, relo->type_id);
7756 bpf_log(ctx->log, "target candidate search failed for %d\n",
7762 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
7768 for (i = 0; i < cc->cnt; i++) {
7770 "CO-RE relocating %s %s: found target candidate [%d]\n",
7771 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
7772 cands.cands[i].btf = cc->cands[i].btf;
7773 cands.cands[i].id = cc->cands[i].id;
7775 cands.len = cc->cnt;
7776 /* cand_cache_mutex needs to span the cache lookup and
7777 * copy of btf pointer into bpf_core_cand_list,
7778 * since module can be unloaded while bpf_core_calc_relo_insn
7779 * is working with module's btf.
7783 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
7788 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
7795 mutex_unlock(&cand_cache_mutex);
7796 if (ctx->log->level & BPF_LOG_LEVEL2)
7797 print_cand_cache(ctx->log);