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/bpf.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/skmsg.h>
25 #include <linux/perf_event.h>
26 #include <linux/bsearch.h>
27 #include <linux/kobject.h>
28 #include <linux/sysfs.h>
30 #include <net/netfilter/nf_bpf_link.h>
34 #include "../tools/lib/bpf/relo_core.h"
36 /* BTF (BPF Type Format) is the meta data format which describes
37 * the data types of BPF program/map. Hence, it basically focus
38 * on the C programming language which the modern BPF is primary
43 * The BTF data is stored under the ".BTF" ELF section
47 * Each 'struct btf_type' object describes a C data type.
48 * Depending on the type it is describing, a 'struct btf_type'
49 * object may be followed by more data. F.e.
50 * To describe an array, 'struct btf_type' is followed by
53 * 'struct btf_type' and any extra data following it are
58 * The BTF type section contains a list of 'struct btf_type' objects.
59 * Each one describes a C type. Recall from the above section
60 * that a 'struct btf_type' object could be immediately followed by extra
61 * data in order to describe some particular C types.
65 * Each btf_type object is identified by a type_id. The type_id
66 * is implicitly implied by the location of the btf_type object in
67 * the BTF type section. The first one has type_id 1. The second
68 * one has type_id 2...etc. Hence, an earlier btf_type has
71 * A btf_type object may refer to another btf_type object by using
72 * type_id (i.e. the "type" in the "struct btf_type").
74 * NOTE that we cannot assume any reference-order.
75 * A btf_type object can refer to an earlier btf_type object
76 * but it can also refer to a later btf_type object.
78 * For example, to describe "const void *". A btf_type
79 * object describing "const" may refer to another btf_type
80 * object describing "void *". This type-reference is done
81 * by specifying type_id:
83 * [1] CONST (anon) type_id=2
84 * [2] PTR (anon) type_id=0
86 * The above is the btf_verifier debug log:
87 * - Each line started with "[?]" is a btf_type object
88 * - [?] is the type_id of the btf_type object.
89 * - CONST/PTR is the BTF_KIND_XXX
90 * - "(anon)" is the name of the type. It just
91 * happens that CONST and PTR has no name.
92 * - type_id=XXX is the 'u32 type' in btf_type
94 * NOTE: "void" has type_id 0
98 * The BTF string section contains the names used by the type section.
99 * Each string is referred by an "offset" from the beginning of the
102 * Each string is '\0' terminated.
104 * The first character in the string section must be '\0'
105 * which is used to mean 'anonymous'. Some btf_type may not
111 * To verify BTF data, two passes are needed.
115 * The first pass is to collect all btf_type objects to
116 * an array: "btf->types".
118 * Depending on the C type that a btf_type is describing,
119 * a btf_type may be followed by extra data. We don't know
120 * how many btf_type is there, and more importantly we don't
121 * know where each btf_type is located in the type section.
123 * Without knowing the location of each type_id, most verifications
124 * cannot be done. e.g. an earlier btf_type may refer to a later
125 * btf_type (recall the "const void *" above), so we cannot
126 * check this type-reference in the first pass.
128 * In the first pass, it still does some verifications (e.g.
129 * checking the name is a valid offset to the string section).
133 * The main focus is to resolve a btf_type that is referring
136 * We have to ensure the referring type:
137 * 1) does exist in the BTF (i.e. in btf->types[])
138 * 2) does not cause a loop:
147 * btf_type_needs_resolve() decides if a btf_type needs
150 * The needs_resolve type implements the "resolve()" ops which
151 * essentially does a DFS and detects backedge.
153 * During resolve (or DFS), different C types have different
154 * "RESOLVED" conditions.
156 * When resolving a BTF_KIND_STRUCT, we need to resolve all its
157 * members because a member is always referring to another
158 * type. A struct's member can be treated as "RESOLVED" if
159 * it is referring to a BTF_KIND_PTR. Otherwise, the
160 * following valid C struct would be rejected:
167 * When resolving a BTF_KIND_PTR, it needs to keep resolving if
168 * it is referring to another BTF_KIND_PTR. Otherwise, we cannot
169 * detect a pointer loop, e.g.:
170 * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
172 * +-----------------------------------------+
176 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
177 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
178 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
179 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
180 #define BITS_ROUNDUP_BYTES(bits) \
181 (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
183 #define BTF_INFO_MASK 0x9f00ffff
184 #define BTF_INT_MASK 0x0fffffff
185 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
186 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
188 /* 16MB for 64k structs and each has 16 members and
189 * a few MB spaces for the string section.
190 * The hard limit is S32_MAX.
192 #define BTF_MAX_SIZE (16 * 1024 * 1024)
194 #define for_each_member_from(i, from, struct_type, member) \
195 for (i = from, member = btf_type_member(struct_type) + from; \
196 i < btf_type_vlen(struct_type); \
199 #define for_each_vsi_from(i, from, struct_type, member) \
200 for (i = from, member = btf_type_var_secinfo(struct_type) + from; \
201 i < btf_type_vlen(struct_type); \
205 DEFINE_SPINLOCK(btf_idr_lock);
207 enum btf_kfunc_hook {
208 BTF_KFUNC_HOOK_COMMON,
211 BTF_KFUNC_HOOK_STRUCT_OPS,
212 BTF_KFUNC_HOOK_TRACING,
213 BTF_KFUNC_HOOK_SYSCALL,
214 BTF_KFUNC_HOOK_FMODRET,
215 BTF_KFUNC_HOOK_CGROUP_SKB,
216 BTF_KFUNC_HOOK_SCHED_ACT,
217 BTF_KFUNC_HOOK_SK_SKB,
218 BTF_KFUNC_HOOK_SOCKET_FILTER,
220 BTF_KFUNC_HOOK_NETFILTER,
221 BTF_KFUNC_HOOK_KPROBE,
226 BTF_KFUNC_SET_MAX_CNT = 256,
227 BTF_DTOR_KFUNC_MAX_CNT = 256,
228 BTF_KFUNC_FILTER_MAX_CNT = 16,
231 struct btf_kfunc_hook_filter {
232 btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
236 struct btf_kfunc_set_tab {
237 struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
238 struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
241 struct btf_id_dtor_kfunc_tab {
243 struct btf_id_dtor_kfunc dtors[];
246 struct btf_struct_ops_tab {
249 struct bpf_struct_ops_desc ops[];
254 struct btf_type **types;
259 struct btf_header hdr;
260 u32 nr_types; /* includes VOID for base BTF */
266 struct btf_kfunc_set_tab *kfunc_set_tab;
267 struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
268 struct btf_struct_metas *struct_meta_tab;
269 struct btf_struct_ops_tab *struct_ops_tab;
271 /* split BTF support */
272 struct btf *base_btf;
273 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
274 u32 start_str_off; /* first string offset (0 for base BTF) */
275 char name[MODULE_NAME_LEN];
277 __u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
280 enum verifier_phase {
285 struct resolve_vertex {
286 const struct btf_type *t;
298 RESOLVE_TBD, /* To Be Determined */
299 RESOLVE_PTR, /* Resolving for Pointer */
300 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
305 #define MAX_RESOLVE_DEPTH 32
307 struct btf_sec_info {
312 struct btf_verifier_env {
315 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
316 struct bpf_verifier_log log;
319 enum verifier_phase phase;
320 enum resolve_mode resolve_mode;
323 static const char * const btf_kind_str[NR_BTF_KINDS] = {
324 [BTF_KIND_UNKN] = "UNKNOWN",
325 [BTF_KIND_INT] = "INT",
326 [BTF_KIND_PTR] = "PTR",
327 [BTF_KIND_ARRAY] = "ARRAY",
328 [BTF_KIND_STRUCT] = "STRUCT",
329 [BTF_KIND_UNION] = "UNION",
330 [BTF_KIND_ENUM] = "ENUM",
331 [BTF_KIND_FWD] = "FWD",
332 [BTF_KIND_TYPEDEF] = "TYPEDEF",
333 [BTF_KIND_VOLATILE] = "VOLATILE",
334 [BTF_KIND_CONST] = "CONST",
335 [BTF_KIND_RESTRICT] = "RESTRICT",
336 [BTF_KIND_FUNC] = "FUNC",
337 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
338 [BTF_KIND_VAR] = "VAR",
339 [BTF_KIND_DATASEC] = "DATASEC",
340 [BTF_KIND_FLOAT] = "FLOAT",
341 [BTF_KIND_DECL_TAG] = "DECL_TAG",
342 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
343 [BTF_KIND_ENUM64] = "ENUM64",
346 const char *btf_type_str(const struct btf_type *t)
348 return btf_kind_str[BTF_INFO_KIND(t->info)];
351 /* Chunk size we use in safe copy of data to be shown. */
352 #define BTF_SHOW_OBJ_SAFE_SIZE 32
355 * This is the maximum size of a base type value (equivalent to a
356 * 128-bit int); if we are at the end of our safe buffer and have
357 * less than 16 bytes space we can't be assured of being able
358 * to copy the next type safely, so in such cases we will initiate
361 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
364 #define BTF_SHOW_NAME_SIZE 80
367 * The suffix of a type that indicates it cannot alias another type when
368 * comparing BTF IDs for kfunc invocations.
370 #define NOCAST_ALIAS_SUFFIX "___init"
373 * Common data to all BTF show operations. Private show functions can add
374 * their own data to a structure containing a struct btf_show and consult it
375 * in the show callback. See btf_type_show() below.
377 * One challenge with showing nested data is we want to skip 0-valued
378 * data, but in order to figure out whether a nested object is all zeros
379 * we need to walk through it. As a result, we need to make two passes
380 * when handling structs, unions and arrays; the first path simply looks
381 * for nonzero data, while the second actually does the display. The first
382 * pass is signalled by show->state.depth_check being set, and if we
383 * encounter a non-zero value we set show->state.depth_to_show to
384 * the depth at which we encountered it. When we have completed the
385 * first pass, we will know if anything needs to be displayed if
386 * depth_to_show > depth. See btf_[struct,array]_show() for the
387 * implementation of this.
389 * Another problem is we want to ensure the data for display is safe to
390 * access. To support this, the anonymous "struct {} obj" tracks the data
391 * object and our safe copy of it. We copy portions of the data needed
392 * to the object "copy" buffer, but because its size is limited to
393 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
394 * traverse larger objects for display.
396 * The various data type show functions all start with a call to
397 * btf_show_start_type() which returns a pointer to the safe copy
398 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
399 * raw data itself). btf_show_obj_safe() is responsible for
400 * using copy_from_kernel_nofault() to update the safe data if necessary
401 * as we traverse the object's data. skbuff-like semantics are
404 * - obj.head points to the start of the toplevel object for display
405 * - obj.size is the size of the toplevel object
406 * - obj.data points to the current point in the original data at
407 * which our safe data starts. obj.data will advance as we copy
408 * portions of the data.
410 * In most cases a single copy will suffice, but larger data structures
411 * such as "struct task_struct" will require many copies. The logic in
412 * btf_show_obj_safe() handles the logic that determines if a new
413 * copy_from_kernel_nofault() is needed.
417 void *target; /* target of show operation (seq file, buffer) */
418 __printf(2, 0) void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
419 const struct btf *btf;
420 /* below are used during iteration */
429 int status; /* non-zero for error */
430 const struct btf_type *type;
431 const struct btf_member *member;
432 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
438 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
442 struct btf_kind_operations {
443 s32 (*check_meta)(struct btf_verifier_env *env,
444 const struct btf_type *t,
446 int (*resolve)(struct btf_verifier_env *env,
447 const struct resolve_vertex *v);
448 int (*check_member)(struct btf_verifier_env *env,
449 const struct btf_type *struct_type,
450 const struct btf_member *member,
451 const struct btf_type *member_type);
452 int (*check_kflag_member)(struct btf_verifier_env *env,
453 const struct btf_type *struct_type,
454 const struct btf_member *member,
455 const struct btf_type *member_type);
456 void (*log_details)(struct btf_verifier_env *env,
457 const struct btf_type *t);
458 void (*show)(const struct btf *btf, const struct btf_type *t,
459 u32 type_id, void *data, u8 bits_offsets,
460 struct btf_show *show);
463 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
464 static struct btf_type btf_void;
466 static int btf_resolve(struct btf_verifier_env *env,
467 const struct btf_type *t, u32 type_id);
469 static int btf_func_check(struct btf_verifier_env *env,
470 const struct btf_type *t);
472 static bool btf_type_is_modifier(const struct btf_type *t)
474 /* Some of them is not strictly a C modifier
475 * but they are grouped into the same bucket
477 * A type (t) that refers to another
478 * type through t->type AND its size cannot
479 * be determined without following the t->type.
481 * ptr does not fall into this bucket
482 * because its size is always sizeof(void *).
484 switch (BTF_INFO_KIND(t->info)) {
485 case BTF_KIND_TYPEDEF:
486 case BTF_KIND_VOLATILE:
488 case BTF_KIND_RESTRICT:
489 case BTF_KIND_TYPE_TAG:
496 bool btf_type_is_void(const struct btf_type *t)
498 return t == &btf_void;
501 static bool btf_type_is_fwd(const struct btf_type *t)
503 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
506 static bool btf_type_is_datasec(const struct btf_type *t)
508 return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
511 static bool btf_type_is_decl_tag(const struct btf_type *t)
513 return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
516 static bool btf_type_nosize(const struct btf_type *t)
518 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
519 btf_type_is_func(t) || btf_type_is_func_proto(t) ||
520 btf_type_is_decl_tag(t);
523 static bool btf_type_nosize_or_null(const struct btf_type *t)
525 return !t || btf_type_nosize(t);
528 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
530 return btf_type_is_func(t) || btf_type_is_struct(t) ||
531 btf_type_is_var(t) || btf_type_is_typedef(t);
534 bool btf_is_vmlinux(const struct btf *btf)
536 return btf->kernel_btf && !btf->base_btf;
539 u32 btf_nr_types(const struct btf *btf)
544 total += btf->nr_types;
551 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
553 const struct btf_type *t;
557 total = btf_nr_types(btf);
558 for (i = 1; i < total; i++) {
559 t = btf_type_by_id(btf, i);
560 if (BTF_INFO_KIND(t->info) != kind)
563 tname = btf_name_by_offset(btf, t->name_off);
564 if (!strcmp(tname, name))
571 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
577 btf = bpf_get_btf_vmlinux();
583 ret = btf_find_by_name_kind(btf, name, kind);
584 /* ret is never zero, since btf_find_by_name_kind returns
585 * positive btf_id or negative error.
593 /* If name is not found in vmlinux's BTF then search in module's BTFs */
594 spin_lock_bh(&btf_idr_lock);
595 idr_for_each_entry(&btf_idr, btf, id) {
596 if (!btf_is_module(btf))
598 /* linear search could be slow hence unlock/lock
599 * the IDR to avoiding holding it for too long
602 spin_unlock_bh(&btf_idr_lock);
603 ret = btf_find_by_name_kind(btf, name, kind);
609 spin_lock_bh(&btf_idr_lock);
611 spin_unlock_bh(&btf_idr_lock);
615 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
618 const struct btf_type *t = btf_type_by_id(btf, id);
620 while (btf_type_is_modifier(t)) {
622 t = btf_type_by_id(btf, t->type);
631 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
634 const struct btf_type *t;
636 t = btf_type_skip_modifiers(btf, id, NULL);
637 if (!btf_type_is_ptr(t))
640 return btf_type_skip_modifiers(btf, t->type, res_id);
643 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
646 const struct btf_type *ptype;
648 ptype = btf_type_resolve_ptr(btf, id, res_id);
649 if (ptype && btf_type_is_func_proto(ptype))
655 /* Types that act only as a source, not sink or intermediate
656 * type when resolving.
658 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
660 return btf_type_is_var(t) ||
661 btf_type_is_decl_tag(t) ||
662 btf_type_is_datasec(t);
665 /* What types need to be resolved?
667 * btf_type_is_modifier() is an obvious one.
669 * btf_type_is_struct() because its member refers to
670 * another type (through member->type).
672 * btf_type_is_var() because the variable refers to
673 * another type. btf_type_is_datasec() holds multiple
674 * btf_type_is_var() types that need resolving.
676 * btf_type_is_array() because its element (array->type)
677 * refers to another type. Array can be thought of a
678 * special case of struct while array just has the same
679 * member-type repeated by array->nelems of times.
681 static bool btf_type_needs_resolve(const struct btf_type *t)
683 return btf_type_is_modifier(t) ||
684 btf_type_is_ptr(t) ||
685 btf_type_is_struct(t) ||
686 btf_type_is_array(t) ||
687 btf_type_is_var(t) ||
688 btf_type_is_func(t) ||
689 btf_type_is_decl_tag(t) ||
690 btf_type_is_datasec(t);
693 /* t->size can be used */
694 static bool btf_type_has_size(const struct btf_type *t)
696 switch (BTF_INFO_KIND(t->info)) {
698 case BTF_KIND_STRUCT:
701 case BTF_KIND_DATASEC:
703 case BTF_KIND_ENUM64:
710 static const char *btf_int_encoding_str(u8 encoding)
714 else if (encoding == BTF_INT_SIGNED)
716 else if (encoding == BTF_INT_CHAR)
718 else if (encoding == BTF_INT_BOOL)
724 static u32 btf_type_int(const struct btf_type *t)
726 return *(u32 *)(t + 1);
729 static const struct btf_array *btf_type_array(const struct btf_type *t)
731 return (const struct btf_array *)(t + 1);
734 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
736 return (const struct btf_enum *)(t + 1);
739 static const struct btf_var *btf_type_var(const struct btf_type *t)
741 return (const struct btf_var *)(t + 1);
744 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
746 return (const struct btf_decl_tag *)(t + 1);
749 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
751 return (const struct btf_enum64 *)(t + 1);
754 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
756 return kind_ops[BTF_INFO_KIND(t->info)];
759 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
761 if (!BTF_STR_OFFSET_VALID(offset))
764 while (offset < btf->start_str_off)
767 offset -= btf->start_str_off;
768 return offset < btf->hdr.str_len;
771 static bool __btf_name_char_ok(char c, bool first)
773 if ((first ? !isalpha(c) :
781 const char *btf_str_by_offset(const struct btf *btf, u32 offset)
783 while (offset < btf->start_str_off)
786 offset -= btf->start_str_off;
787 if (offset < btf->hdr.str_len)
788 return &btf->strings[offset];
793 static bool __btf_name_valid(const struct btf *btf, u32 offset)
795 /* offset must be valid */
796 const char *src = btf_str_by_offset(btf, offset);
797 const char *src_limit;
799 if (!__btf_name_char_ok(*src, true))
802 /* set a limit on identifier length */
803 src_limit = src + KSYM_NAME_LEN;
805 while (*src && src < src_limit) {
806 if (!__btf_name_char_ok(*src, false))
814 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
816 return __btf_name_valid(btf, offset);
819 /* Allow any printable character in DATASEC names */
820 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
822 /* offset must be valid */
823 const char *src = btf_str_by_offset(btf, offset);
824 const char *src_limit;
826 /* set a limit on identifier length */
827 src_limit = src + KSYM_NAME_LEN;
829 while (*src && src < src_limit) {
838 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
845 name = btf_str_by_offset(btf, offset);
846 return name ?: "(invalid-name-offset)";
849 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
851 return btf_str_by_offset(btf, offset);
854 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
856 while (type_id < btf->start_id)
859 type_id -= btf->start_id;
860 if (type_id >= btf->nr_types)
862 return btf->types[type_id];
864 EXPORT_SYMBOL_GPL(btf_type_by_id);
867 * Regular int is not a bit field and it must be either
868 * u8/u16/u32/u64 or __int128.
870 static bool btf_type_int_is_regular(const struct btf_type *t)
872 u8 nr_bits, nr_bytes;
875 int_data = btf_type_int(t);
876 nr_bits = BTF_INT_BITS(int_data);
877 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
878 if (BITS_PER_BYTE_MASKED(nr_bits) ||
879 BTF_INT_OFFSET(int_data) ||
880 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
881 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
882 nr_bytes != (2 * sizeof(u64)))) {
890 * Check that given struct member is a regular int with expected
893 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
894 const struct btf_member *m,
895 u32 expected_offset, u32 expected_size)
897 const struct btf_type *t;
902 t = btf_type_id_size(btf, &id, NULL);
903 if (!t || !btf_type_is_int(t))
906 int_data = btf_type_int(t);
907 nr_bits = BTF_INT_BITS(int_data);
908 if (btf_type_kflag(s)) {
909 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
910 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
912 /* if kflag set, int should be a regular int and
913 * bit offset should be at byte boundary.
915 return !bitfield_size &&
916 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
917 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
920 if (BTF_INT_OFFSET(int_data) ||
921 BITS_PER_BYTE_MASKED(m->offset) ||
922 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
923 BITS_PER_BYTE_MASKED(nr_bits) ||
924 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
930 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
931 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
934 const struct btf_type *t = btf_type_by_id(btf, id);
936 while (btf_type_is_modifier(t) &&
937 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
938 t = btf_type_by_id(btf, t->type);
944 #define BTF_SHOW_MAX_ITER 10
946 #define BTF_KIND_BIT(kind) (1ULL << kind)
949 * Populate show->state.name with type name information.
950 * Format of type name is
952 * [.member_name = ] (type_name)
954 static const char *btf_show_name(struct btf_show *show)
956 /* BTF_MAX_ITER array suffixes "[]" */
957 const char *array_suffixes = "[][][][][][][][][][]";
958 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
959 /* BTF_MAX_ITER pointer suffixes "*" */
960 const char *ptr_suffixes = "**********";
961 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
962 const char *name = NULL, *prefix = "", *parens = "";
963 const struct btf_member *m = show->state.member;
964 const struct btf_type *t;
965 const struct btf_array *array;
966 u32 id = show->state.type_id;
967 const char *member = NULL;
968 bool show_member = false;
972 show->state.name[0] = '\0';
975 * Don't show type name if we're showing an array member;
976 * in that case we show the array type so don't need to repeat
977 * ourselves for each member.
979 if (show->state.array_member)
982 /* Retrieve member name, if any. */
984 member = btf_name_by_offset(show->btf, m->name_off);
985 show_member = strlen(member) > 0;
990 * Start with type_id, as we have resolved the struct btf_type *
991 * via btf_modifier_show() past the parent typedef to the child
992 * struct, int etc it is defined as. In such cases, the type_id
993 * still represents the starting type while the struct btf_type *
994 * in our show->state points at the resolved type of the typedef.
996 t = btf_type_by_id(show->btf, id);
1001 * The goal here is to build up the right number of pointer and
1002 * array suffixes while ensuring the type name for a typedef
1003 * is represented. Along the way we accumulate a list of
1004 * BTF kinds we have encountered, since these will inform later
1005 * display; for example, pointer types will not require an
1006 * opening "{" for struct, we will just display the pointer value.
1008 * We also want to accumulate the right number of pointer or array
1009 * indices in the format string while iterating until we get to
1010 * the typedef/pointee/array member target type.
1012 * We start by pointing at the end of pointer and array suffix
1013 * strings; as we accumulate pointers and arrays we move the pointer
1014 * or array string backwards so it will show the expected number of
1015 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
1016 * and/or arrays and typedefs are supported as a precaution.
1018 * We also want to get typedef name while proceeding to resolve
1019 * type it points to so that we can add parentheses if it is a
1020 * "typedef struct" etc.
1022 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1024 switch (BTF_INFO_KIND(t->info)) {
1025 case BTF_KIND_TYPEDEF:
1027 name = btf_name_by_offset(show->btf,
1029 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1032 case BTF_KIND_ARRAY:
1033 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1037 array = btf_type_array(t);
1038 if (array_suffix > array_suffixes)
1043 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1044 if (ptr_suffix > ptr_suffixes)
1054 t = btf_type_skip_qualifiers(show->btf, id);
1056 /* We may not be able to represent this type; bail to be safe */
1057 if (i == BTF_SHOW_MAX_ITER)
1061 name = btf_name_by_offset(show->btf, t->name_off);
1063 switch (BTF_INFO_KIND(t->info)) {
1064 case BTF_KIND_STRUCT:
1065 case BTF_KIND_UNION:
1066 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1068 /* if it's an array of struct/union, parens is already set */
1069 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1073 case BTF_KIND_ENUM64:
1080 /* pointer does not require parens */
1081 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1083 /* typedef does not require struct/union/enum prefix */
1084 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1090 /* Even if we don't want type name info, we want parentheses etc */
1091 if (show->flags & BTF_SHOW_NONAME)
1092 snprintf(show->state.name, sizeof(show->state.name), "%s",
1095 snprintf(show->state.name, sizeof(show->state.name),
1096 "%s%s%s(%s%s%s%s%s%s)%s",
1097 /* first 3 strings comprise ".member = " */
1098 show_member ? "." : "",
1099 show_member ? member : "",
1100 show_member ? " = " : "",
1101 /* ...next is our prefix (struct, enum, etc) */
1103 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1104 /* ...this is the type name itself */
1106 /* ...suffixed by the appropriate '*', '[]' suffixes */
1107 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1108 array_suffix, parens);
1110 return show->state.name;
1113 static const char *__btf_show_indent(struct btf_show *show)
1115 const char *indents = " ";
1116 const char *indent = &indents[strlen(indents)];
1118 if ((indent - show->state.depth) >= indents)
1119 return indent - show->state.depth;
1123 static const char *btf_show_indent(struct btf_show *show)
1125 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1128 static const char *btf_show_newline(struct btf_show *show)
1130 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1133 static const char *btf_show_delim(struct btf_show *show)
1135 if (show->state.depth == 0)
1138 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1139 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1145 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1149 if (!show->state.depth_check) {
1150 va_start(args, fmt);
1151 show->showfn(show, fmt, args);
1156 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1157 * format specifiers to the format specifier passed in; these do the work of
1158 * adding indentation, delimiters etc while the caller simply has to specify
1159 * the type value(s) in the format specifier + value(s).
1161 #define btf_show_type_value(show, fmt, value) \
1163 if ((value) != (__typeof__(value))0 || \
1164 (show->flags & BTF_SHOW_ZERO) || \
1165 show->state.depth == 0) { \
1166 btf_show(show, "%s%s" fmt "%s%s", \
1167 btf_show_indent(show), \
1168 btf_show_name(show), \
1169 value, btf_show_delim(show), \
1170 btf_show_newline(show)); \
1171 if (show->state.depth > show->state.depth_to_show) \
1172 show->state.depth_to_show = show->state.depth; \
1176 #define btf_show_type_values(show, fmt, ...) \
1178 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1179 btf_show_name(show), \
1180 __VA_ARGS__, btf_show_delim(show), \
1181 btf_show_newline(show)); \
1182 if (show->state.depth > show->state.depth_to_show) \
1183 show->state.depth_to_show = show->state.depth; \
1186 /* How much is left to copy to safe buffer after @data? */
1187 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1189 return show->obj.head + show->obj.size - data;
1192 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1193 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1195 return data >= show->obj.data &&
1196 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1200 * If object pointed to by @data of @size falls within our safe buffer, return
1201 * the equivalent pointer to the same safe data. Assumes
1202 * copy_from_kernel_nofault() has already happened and our safe buffer is
1205 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1207 if (btf_show_obj_is_safe(show, data, size))
1208 return show->obj.safe + (data - show->obj.data);
1213 * Return a safe-to-access version of data pointed to by @data.
1214 * We do this by copying the relevant amount of information
1215 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1217 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1218 * safe copy is needed.
1220 * Otherwise we need to determine if we have the required amount
1221 * of data (determined by the @data pointer and the size of the
1222 * largest base type we can encounter (represented by
1223 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1224 * that we will be able to print some of the current object,
1225 * and if more is needed a copy will be triggered.
1226 * Some objects such as structs will not fit into the buffer;
1227 * in such cases additional copies when we iterate over their
1228 * members may be needed.
1230 * btf_show_obj_safe() is used to return a safe buffer for
1231 * btf_show_start_type(); this ensures that as we recurse into
1232 * nested types we always have safe data for the given type.
1233 * This approach is somewhat wasteful; it's possible for example
1234 * that when iterating over a large union we'll end up copying the
1235 * same data repeatedly, but the goal is safety not performance.
1236 * We use stack data as opposed to per-CPU buffers because the
1237 * iteration over a type can take some time, and preemption handling
1238 * would greatly complicate use of the safe buffer.
1240 static void *btf_show_obj_safe(struct btf_show *show,
1241 const struct btf_type *t,
1244 const struct btf_type *rt;
1245 int size_left, size;
1248 if (show->flags & BTF_SHOW_UNSAFE)
1251 rt = btf_resolve_size(show->btf, t, &size);
1253 show->state.status = PTR_ERR(rt);
1258 * Is this toplevel object? If so, set total object size and
1259 * initialize pointers. Otherwise check if we still fall within
1260 * our safe object data.
1262 if (show->state.depth == 0) {
1263 show->obj.size = size;
1264 show->obj.head = data;
1267 * If the size of the current object is > our remaining
1268 * safe buffer we _may_ need to do a new copy. However
1269 * consider the case of a nested struct; it's size pushes
1270 * us over the safe buffer limit, but showing any individual
1271 * struct members does not. In such cases, we don't need
1272 * to initiate a fresh copy yet; however we definitely need
1273 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1274 * in our buffer, regardless of the current object size.
1275 * The logic here is that as we resolve types we will
1276 * hit a base type at some point, and we need to be sure
1277 * the next chunk of data is safely available to display
1278 * that type info safely. We cannot rely on the size of
1279 * the current object here because it may be much larger
1280 * than our current buffer (e.g. task_struct is 8k).
1281 * All we want to do here is ensure that we can print the
1282 * next basic type, which we can if either
1283 * - the current type size is within the safe buffer; or
1284 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1287 safe = __btf_show_obj_safe(show, data,
1289 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1293 * We need a new copy to our safe object, either because we haven't
1294 * yet copied and are initializing safe data, or because the data
1295 * we want falls outside the boundaries of the safe object.
1298 size_left = btf_show_obj_size_left(show, data);
1299 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1300 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1301 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1303 if (!show->state.status) {
1304 show->obj.data = data;
1305 safe = show->obj.safe;
1313 * Set the type we are starting to show and return a safe data pointer
1314 * to be used for showing the associated data.
1316 static void *btf_show_start_type(struct btf_show *show,
1317 const struct btf_type *t,
1318 u32 type_id, void *data)
1320 show->state.type = t;
1321 show->state.type_id = type_id;
1322 show->state.name[0] = '\0';
1324 return btf_show_obj_safe(show, t, data);
1327 static void btf_show_end_type(struct btf_show *show)
1329 show->state.type = NULL;
1330 show->state.type_id = 0;
1331 show->state.name[0] = '\0';
1334 static void *btf_show_start_aggr_type(struct btf_show *show,
1335 const struct btf_type *t,
1336 u32 type_id, void *data)
1338 void *safe_data = btf_show_start_type(show, t, type_id, data);
1343 btf_show(show, "%s%s%s", btf_show_indent(show),
1344 btf_show_name(show),
1345 btf_show_newline(show));
1346 show->state.depth++;
1350 static void btf_show_end_aggr_type(struct btf_show *show,
1353 show->state.depth--;
1354 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1355 btf_show_delim(show), btf_show_newline(show));
1356 btf_show_end_type(show);
1359 static void btf_show_start_member(struct btf_show *show,
1360 const struct btf_member *m)
1362 show->state.member = m;
1365 static void btf_show_start_array_member(struct btf_show *show)
1367 show->state.array_member = 1;
1368 btf_show_start_member(show, NULL);
1371 static void btf_show_end_member(struct btf_show *show)
1373 show->state.member = NULL;
1376 static void btf_show_end_array_member(struct btf_show *show)
1378 show->state.array_member = 0;
1379 btf_show_end_member(show);
1382 static void *btf_show_start_array_type(struct btf_show *show,
1383 const struct btf_type *t,
1388 show->state.array_encoding = array_encoding;
1389 show->state.array_terminated = 0;
1390 return btf_show_start_aggr_type(show, t, type_id, data);
1393 static void btf_show_end_array_type(struct btf_show *show)
1395 show->state.array_encoding = 0;
1396 show->state.array_terminated = 0;
1397 btf_show_end_aggr_type(show, "]");
1400 static void *btf_show_start_struct_type(struct btf_show *show,
1401 const struct btf_type *t,
1405 return btf_show_start_aggr_type(show, t, type_id, data);
1408 static void btf_show_end_struct_type(struct btf_show *show)
1410 btf_show_end_aggr_type(show, "}");
1413 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1414 const char *fmt, ...)
1418 va_start(args, fmt);
1419 bpf_verifier_vlog(log, fmt, args);
1423 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1424 const char *fmt, ...)
1426 struct bpf_verifier_log *log = &env->log;
1429 if (!bpf_verifier_log_needed(log))
1432 va_start(args, fmt);
1433 bpf_verifier_vlog(log, fmt, args);
1437 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1438 const struct btf_type *t,
1440 const char *fmt, ...)
1442 struct bpf_verifier_log *log = &env->log;
1443 struct btf *btf = env->btf;
1446 if (!bpf_verifier_log_needed(log))
1449 if (log->level == BPF_LOG_KERNEL) {
1450 /* btf verifier prints all types it is processing via
1451 * btf_verifier_log_type(..., fmt = NULL).
1452 * Skip those prints for in-kernel BTF verification.
1457 /* Skip logging when loading module BTF with mismatches permitted */
1458 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1462 __btf_verifier_log(log, "[%u] %s %s%s",
1465 __btf_name_by_offset(btf, t->name_off),
1466 log_details ? " " : "");
1469 btf_type_ops(t)->log_details(env, t);
1472 __btf_verifier_log(log, " ");
1473 va_start(args, fmt);
1474 bpf_verifier_vlog(log, fmt, args);
1478 __btf_verifier_log(log, "\n");
1481 #define btf_verifier_log_type(env, t, ...) \
1482 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1483 #define btf_verifier_log_basic(env, t, ...) \
1484 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1487 static void btf_verifier_log_member(struct btf_verifier_env *env,
1488 const struct btf_type *struct_type,
1489 const struct btf_member *member,
1490 const char *fmt, ...)
1492 struct bpf_verifier_log *log = &env->log;
1493 struct btf *btf = env->btf;
1496 if (!bpf_verifier_log_needed(log))
1499 if (log->level == BPF_LOG_KERNEL) {
1503 /* Skip logging when loading module BTF with mismatches permitted */
1504 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1508 /* The CHECK_META phase already did a btf dump.
1510 * If member is logged again, it must hit an error in
1511 * parsing this member. It is useful to print out which
1512 * struct this member belongs to.
1514 if (env->phase != CHECK_META)
1515 btf_verifier_log_type(env, struct_type, NULL);
1517 if (btf_type_kflag(struct_type))
1518 __btf_verifier_log(log,
1519 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1520 __btf_name_by_offset(btf, member->name_off),
1522 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1523 BTF_MEMBER_BIT_OFFSET(member->offset));
1525 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1526 __btf_name_by_offset(btf, member->name_off),
1527 member->type, member->offset);
1530 __btf_verifier_log(log, " ");
1531 va_start(args, fmt);
1532 bpf_verifier_vlog(log, fmt, args);
1536 __btf_verifier_log(log, "\n");
1540 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1541 const struct btf_type *datasec_type,
1542 const struct btf_var_secinfo *vsi,
1543 const char *fmt, ...)
1545 struct bpf_verifier_log *log = &env->log;
1548 if (!bpf_verifier_log_needed(log))
1550 if (log->level == BPF_LOG_KERNEL && !fmt)
1552 if (env->phase != CHECK_META)
1553 btf_verifier_log_type(env, datasec_type, NULL);
1555 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1556 vsi->type, vsi->offset, vsi->size);
1558 __btf_verifier_log(log, " ");
1559 va_start(args, fmt);
1560 bpf_verifier_vlog(log, fmt, args);
1564 __btf_verifier_log(log, "\n");
1567 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1570 struct bpf_verifier_log *log = &env->log;
1571 const struct btf *btf = env->btf;
1572 const struct btf_header *hdr;
1574 if (!bpf_verifier_log_needed(log))
1577 if (log->level == BPF_LOG_KERNEL)
1580 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1581 __btf_verifier_log(log, "version: %u\n", hdr->version);
1582 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1583 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1584 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1585 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1586 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1587 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1588 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1591 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1593 struct btf *btf = env->btf;
1595 if (btf->types_size == btf->nr_types) {
1596 /* Expand 'types' array */
1598 struct btf_type **new_types;
1599 u32 expand_by, new_size;
1601 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1602 btf_verifier_log(env, "Exceeded max num of types");
1606 expand_by = max_t(u32, btf->types_size >> 2, 16);
1607 new_size = min_t(u32, BTF_MAX_TYPE,
1608 btf->types_size + expand_by);
1610 new_types = kvcalloc(new_size, sizeof(*new_types),
1611 GFP_KERNEL | __GFP_NOWARN);
1615 if (btf->nr_types == 0) {
1616 if (!btf->base_btf) {
1617 /* lazily init VOID type */
1618 new_types[0] = &btf_void;
1622 memcpy(new_types, btf->types,
1623 sizeof(*btf->types) * btf->nr_types);
1627 btf->types = new_types;
1628 btf->types_size = new_size;
1631 btf->types[btf->nr_types++] = t;
1636 static int btf_alloc_id(struct btf *btf)
1640 idr_preload(GFP_KERNEL);
1641 spin_lock_bh(&btf_idr_lock);
1642 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1645 spin_unlock_bh(&btf_idr_lock);
1648 if (WARN_ON_ONCE(!id))
1651 return id > 0 ? 0 : id;
1654 static void btf_free_id(struct btf *btf)
1656 unsigned long flags;
1659 * In map-in-map, calling map_delete_elem() on outer
1660 * map will call bpf_map_put on the inner map.
1661 * It will then eventually call btf_free_id()
1662 * on the inner map. Some of the map_delete_elem()
1663 * implementation may have irq disabled, so
1664 * we need to use the _irqsave() version instead
1665 * of the _bh() version.
1667 spin_lock_irqsave(&btf_idr_lock, flags);
1668 idr_remove(&btf_idr, btf->id);
1669 spin_unlock_irqrestore(&btf_idr_lock, flags);
1672 static void btf_free_kfunc_set_tab(struct btf *btf)
1674 struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1679 for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1680 kfree(tab->sets[hook]);
1682 btf->kfunc_set_tab = NULL;
1685 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1687 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1692 btf->dtor_kfunc_tab = NULL;
1695 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1701 for (i = 0; i < tab->cnt; i++)
1702 btf_record_free(tab->types[i].record);
1706 static void btf_free_struct_meta_tab(struct btf *btf)
1708 struct btf_struct_metas *tab = btf->struct_meta_tab;
1710 btf_struct_metas_free(tab);
1711 btf->struct_meta_tab = NULL;
1714 static void btf_free_struct_ops_tab(struct btf *btf)
1716 struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1722 for (i = 0; i < tab->cnt; i++)
1723 bpf_struct_ops_desc_release(&tab->ops[i]);
1726 btf->struct_ops_tab = NULL;
1729 static void btf_free(struct btf *btf)
1731 btf_free_struct_meta_tab(btf);
1732 btf_free_dtor_kfunc_tab(btf);
1733 btf_free_kfunc_set_tab(btf);
1734 btf_free_struct_ops_tab(btf);
1736 kvfree(btf->resolved_sizes);
1737 kvfree(btf->resolved_ids);
1738 /* vmlinux does not allocate btf->data, it simply points it at
1741 if (!btf_is_vmlinux(btf))
1743 kvfree(btf->base_id_map);
1747 static void btf_free_rcu(struct rcu_head *rcu)
1749 struct btf *btf = container_of(rcu, struct btf, rcu);
1754 const char *btf_get_name(const struct btf *btf)
1759 void btf_get(struct btf *btf)
1761 refcount_inc(&btf->refcnt);
1764 void btf_put(struct btf *btf)
1766 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1768 call_rcu(&btf->rcu, btf_free_rcu);
1772 struct btf *btf_base_btf(const struct btf *btf)
1774 return btf->base_btf;
1777 const struct btf_header *btf_header(const struct btf *btf)
1782 void btf_set_base_btf(struct btf *btf, const struct btf *base_btf)
1784 btf->base_btf = (struct btf *)base_btf;
1785 btf->start_id = btf_nr_types(base_btf);
1786 btf->start_str_off = base_btf->hdr.str_len;
1789 static int env_resolve_init(struct btf_verifier_env *env)
1791 struct btf *btf = env->btf;
1792 u32 nr_types = btf->nr_types;
1793 u32 *resolved_sizes = NULL;
1794 u32 *resolved_ids = NULL;
1795 u8 *visit_states = NULL;
1797 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1798 GFP_KERNEL | __GFP_NOWARN);
1799 if (!resolved_sizes)
1802 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1803 GFP_KERNEL | __GFP_NOWARN);
1807 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1808 GFP_KERNEL | __GFP_NOWARN);
1812 btf->resolved_sizes = resolved_sizes;
1813 btf->resolved_ids = resolved_ids;
1814 env->visit_states = visit_states;
1819 kvfree(resolved_sizes);
1820 kvfree(resolved_ids);
1821 kvfree(visit_states);
1825 static void btf_verifier_env_free(struct btf_verifier_env *env)
1827 kvfree(env->visit_states);
1831 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1832 const struct btf_type *next_type)
1834 switch (env->resolve_mode) {
1836 /* int, enum or void is a sink */
1837 return !btf_type_needs_resolve(next_type);
1839 /* int, enum, void, struct, array, func or func_proto is a sink
1842 return !btf_type_is_modifier(next_type) &&
1843 !btf_type_is_ptr(next_type);
1844 case RESOLVE_STRUCT_OR_ARRAY:
1845 /* int, enum, void, ptr, func or func_proto is a sink
1846 * for struct and array
1848 return !btf_type_is_modifier(next_type) &&
1849 !btf_type_is_array(next_type) &&
1850 !btf_type_is_struct(next_type);
1856 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1859 /* base BTF types should be resolved by now */
1860 if (type_id < env->btf->start_id)
1863 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1866 static int env_stack_push(struct btf_verifier_env *env,
1867 const struct btf_type *t, u32 type_id)
1869 const struct btf *btf = env->btf;
1870 struct resolve_vertex *v;
1872 if (env->top_stack == MAX_RESOLVE_DEPTH)
1875 if (type_id < btf->start_id
1876 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1879 env->visit_states[type_id - btf->start_id] = VISITED;
1881 v = &env->stack[env->top_stack++];
1883 v->type_id = type_id;
1886 if (env->resolve_mode == RESOLVE_TBD) {
1887 if (btf_type_is_ptr(t))
1888 env->resolve_mode = RESOLVE_PTR;
1889 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1890 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1896 static void env_stack_set_next_member(struct btf_verifier_env *env,
1899 env->stack[env->top_stack - 1].next_member = next_member;
1902 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1903 u32 resolved_type_id,
1906 u32 type_id = env->stack[--(env->top_stack)].type_id;
1907 struct btf *btf = env->btf;
1909 type_id -= btf->start_id; /* adjust to local type id */
1910 btf->resolved_sizes[type_id] = resolved_size;
1911 btf->resolved_ids[type_id] = resolved_type_id;
1912 env->visit_states[type_id] = RESOLVED;
1915 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1917 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1920 /* Resolve the size of a passed-in "type"
1922 * type: is an array (e.g. u32 array[x][y])
1923 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1924 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1925 * corresponds to the return type.
1927 * *elem_id: id of u32
1928 * *total_nelems: (x * y). Hence, individual elem size is
1929 * (*type_size / *total_nelems)
1930 * *type_id: id of type if it's changed within the function, 0 if not
1932 * type: is not an array (e.g. const struct X)
1933 * return type: type "struct X"
1934 * *type_size: sizeof(struct X)
1935 * *elem_type: same as return type ("struct X")
1938 * *type_id: id of type if it's changed within the function, 0 if not
1940 static const struct btf_type *
1941 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1942 u32 *type_size, const struct btf_type **elem_type,
1943 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1945 const struct btf_type *array_type = NULL;
1946 const struct btf_array *array = NULL;
1947 u32 i, size, nelems = 1, id = 0;
1949 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1950 switch (BTF_INFO_KIND(type->info)) {
1951 /* type->size can be used */
1953 case BTF_KIND_STRUCT:
1954 case BTF_KIND_UNION:
1956 case BTF_KIND_FLOAT:
1957 case BTF_KIND_ENUM64:
1962 size = sizeof(void *);
1966 case BTF_KIND_TYPEDEF:
1967 case BTF_KIND_VOLATILE:
1968 case BTF_KIND_CONST:
1969 case BTF_KIND_RESTRICT:
1970 case BTF_KIND_TYPE_TAG:
1972 type = btf_type_by_id(btf, type->type);
1975 case BTF_KIND_ARRAY:
1978 array = btf_type_array(type);
1979 if (nelems && array->nelems > U32_MAX / nelems)
1980 return ERR_PTR(-EINVAL);
1981 nelems *= array->nelems;
1982 type = btf_type_by_id(btf, array->type);
1985 /* type without size */
1987 return ERR_PTR(-EINVAL);
1991 return ERR_PTR(-EINVAL);
1994 if (nelems && size > U32_MAX / nelems)
1995 return ERR_PTR(-EINVAL);
1997 *type_size = nelems * size;
1999 *total_nelems = nelems;
2003 *elem_id = array ? array->type : 0;
2007 return array_type ? : type;
2010 const struct btf_type *
2011 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2014 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
2017 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
2019 while (type_id < btf->start_id)
2020 btf = btf->base_btf;
2022 return btf->resolved_ids[type_id - btf->start_id];
2025 /* The input param "type_id" must point to a needs_resolve type */
2026 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
2029 *type_id = btf_resolved_type_id(btf, *type_id);
2030 return btf_type_by_id(btf, *type_id);
2033 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2035 while (type_id < btf->start_id)
2036 btf = btf->base_btf;
2038 return btf->resolved_sizes[type_id - btf->start_id];
2041 const struct btf_type *btf_type_id_size(const struct btf *btf,
2042 u32 *type_id, u32 *ret_size)
2044 const struct btf_type *size_type;
2045 u32 size_type_id = *type_id;
2048 size_type = btf_type_by_id(btf, size_type_id);
2049 if (btf_type_nosize_or_null(size_type))
2052 if (btf_type_has_size(size_type)) {
2053 size = size_type->size;
2054 } else if (btf_type_is_array(size_type)) {
2055 size = btf_resolved_type_size(btf, size_type_id);
2056 } else if (btf_type_is_ptr(size_type)) {
2057 size = sizeof(void *);
2059 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2060 !btf_type_is_var(size_type)))
2063 size_type_id = btf_resolved_type_id(btf, size_type_id);
2064 size_type = btf_type_by_id(btf, size_type_id);
2065 if (btf_type_nosize_or_null(size_type))
2067 else if (btf_type_has_size(size_type))
2068 size = size_type->size;
2069 else if (btf_type_is_array(size_type))
2070 size = btf_resolved_type_size(btf, size_type_id);
2071 else if (btf_type_is_ptr(size_type))
2072 size = sizeof(void *);
2077 *type_id = size_type_id;
2084 static int btf_df_check_member(struct btf_verifier_env *env,
2085 const struct btf_type *struct_type,
2086 const struct btf_member *member,
2087 const struct btf_type *member_type)
2089 btf_verifier_log_basic(env, struct_type,
2090 "Unsupported check_member");
2094 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2095 const struct btf_type *struct_type,
2096 const struct btf_member *member,
2097 const struct btf_type *member_type)
2099 btf_verifier_log_basic(env, struct_type,
2100 "Unsupported check_kflag_member");
2104 /* Used for ptr, array struct/union and float type members.
2105 * int, enum and modifier types have their specific callback functions.
2107 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2108 const struct btf_type *struct_type,
2109 const struct btf_member *member,
2110 const struct btf_type *member_type)
2112 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2113 btf_verifier_log_member(env, struct_type, member,
2114 "Invalid member bitfield_size");
2118 /* bitfield size is 0, so member->offset represents bit offset only.
2119 * It is safe to call non kflag check_member variants.
2121 return btf_type_ops(member_type)->check_member(env, struct_type,
2126 static int btf_df_resolve(struct btf_verifier_env *env,
2127 const struct resolve_vertex *v)
2129 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2133 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2134 u32 type_id, void *data, u8 bits_offsets,
2135 struct btf_show *show)
2137 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2140 static int btf_int_check_member(struct btf_verifier_env *env,
2141 const struct btf_type *struct_type,
2142 const struct btf_member *member,
2143 const struct btf_type *member_type)
2145 u32 int_data = btf_type_int(member_type);
2146 u32 struct_bits_off = member->offset;
2147 u32 struct_size = struct_type->size;
2151 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2152 btf_verifier_log_member(env, struct_type, member,
2153 "bits_offset exceeds U32_MAX");
2157 struct_bits_off += BTF_INT_OFFSET(int_data);
2158 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2159 nr_copy_bits = BTF_INT_BITS(int_data) +
2160 BITS_PER_BYTE_MASKED(struct_bits_off);
2162 if (nr_copy_bits > BITS_PER_U128) {
2163 btf_verifier_log_member(env, struct_type, member,
2164 "nr_copy_bits exceeds 128");
2168 if (struct_size < bytes_offset ||
2169 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2170 btf_verifier_log_member(env, struct_type, member,
2171 "Member exceeds struct_size");
2178 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2179 const struct btf_type *struct_type,
2180 const struct btf_member *member,
2181 const struct btf_type *member_type)
2183 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2184 u32 int_data = btf_type_int(member_type);
2185 u32 struct_size = struct_type->size;
2188 /* a regular int type is required for the kflag int member */
2189 if (!btf_type_int_is_regular(member_type)) {
2190 btf_verifier_log_member(env, struct_type, member,
2191 "Invalid member base type");
2195 /* check sanity of bitfield size */
2196 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2197 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2198 nr_int_data_bits = BTF_INT_BITS(int_data);
2200 /* Not a bitfield member, member offset must be at byte
2203 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2204 btf_verifier_log_member(env, struct_type, member,
2205 "Invalid member offset");
2209 nr_bits = nr_int_data_bits;
2210 } else if (nr_bits > nr_int_data_bits) {
2211 btf_verifier_log_member(env, struct_type, member,
2212 "Invalid member bitfield_size");
2216 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2217 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2218 if (nr_copy_bits > BITS_PER_U128) {
2219 btf_verifier_log_member(env, struct_type, member,
2220 "nr_copy_bits exceeds 128");
2224 if (struct_size < bytes_offset ||
2225 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2226 btf_verifier_log_member(env, struct_type, member,
2227 "Member exceeds struct_size");
2234 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2235 const struct btf_type *t,
2238 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2241 if (meta_left < meta_needed) {
2242 btf_verifier_log_basic(env, t,
2243 "meta_left:%u meta_needed:%u",
2244 meta_left, meta_needed);
2248 if (btf_type_vlen(t)) {
2249 btf_verifier_log_type(env, t, "vlen != 0");
2253 if (btf_type_kflag(t)) {
2254 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2258 int_data = btf_type_int(t);
2259 if (int_data & ~BTF_INT_MASK) {
2260 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2265 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2267 if (nr_bits > BITS_PER_U128) {
2268 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2273 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2274 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2279 * Only one of the encoding bits is allowed and it
2280 * should be sufficient for the pretty print purpose (i.e. decoding).
2281 * Multiple bits can be allowed later if it is found
2282 * to be insufficient.
2284 encoding = BTF_INT_ENCODING(int_data);
2286 encoding != BTF_INT_SIGNED &&
2287 encoding != BTF_INT_CHAR &&
2288 encoding != BTF_INT_BOOL) {
2289 btf_verifier_log_type(env, t, "Unsupported encoding");
2293 btf_verifier_log_type(env, t, NULL);
2298 static void btf_int_log(struct btf_verifier_env *env,
2299 const struct btf_type *t)
2301 int int_data = btf_type_int(t);
2303 btf_verifier_log(env,
2304 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2305 t->size, BTF_INT_OFFSET(int_data),
2306 BTF_INT_BITS(int_data),
2307 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2310 static void btf_int128_print(struct btf_show *show, void *data)
2312 /* data points to a __int128 number.
2314 * int128_num = *(__int128 *)data;
2315 * The below formulas shows what upper_num and lower_num represents:
2316 * upper_num = int128_num >> 64;
2317 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2319 u64 upper_num, lower_num;
2321 #ifdef __BIG_ENDIAN_BITFIELD
2322 upper_num = *(u64 *)data;
2323 lower_num = *(u64 *)(data + 8);
2325 upper_num = *(u64 *)(data + 8);
2326 lower_num = *(u64 *)data;
2329 btf_show_type_value(show, "0x%llx", lower_num);
2331 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2335 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2336 u16 right_shift_bits)
2338 u64 upper_num, lower_num;
2340 #ifdef __BIG_ENDIAN_BITFIELD
2341 upper_num = print_num[0];
2342 lower_num = print_num[1];
2344 upper_num = print_num[1];
2345 lower_num = print_num[0];
2348 /* shake out un-needed bits by shift/or operations */
2349 if (left_shift_bits >= 64) {
2350 upper_num = lower_num << (left_shift_bits - 64);
2353 upper_num = (upper_num << left_shift_bits) |
2354 (lower_num >> (64 - left_shift_bits));
2355 lower_num = lower_num << left_shift_bits;
2358 if (right_shift_bits >= 64) {
2359 lower_num = upper_num >> (right_shift_bits - 64);
2362 lower_num = (lower_num >> right_shift_bits) |
2363 (upper_num << (64 - right_shift_bits));
2364 upper_num = upper_num >> right_shift_bits;
2367 #ifdef __BIG_ENDIAN_BITFIELD
2368 print_num[0] = upper_num;
2369 print_num[1] = lower_num;
2371 print_num[0] = lower_num;
2372 print_num[1] = upper_num;
2376 static void btf_bitfield_show(void *data, u8 bits_offset,
2377 u8 nr_bits, struct btf_show *show)
2379 u16 left_shift_bits, right_shift_bits;
2382 u64 print_num[2] = {};
2384 nr_copy_bits = nr_bits + bits_offset;
2385 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2387 memcpy(print_num, data, nr_copy_bytes);
2389 #ifdef __BIG_ENDIAN_BITFIELD
2390 left_shift_bits = bits_offset;
2392 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2394 right_shift_bits = BITS_PER_U128 - nr_bits;
2396 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2397 btf_int128_print(show, print_num);
2401 static void btf_int_bits_show(const struct btf *btf,
2402 const struct btf_type *t,
2403 void *data, u8 bits_offset,
2404 struct btf_show *show)
2406 u32 int_data = btf_type_int(t);
2407 u8 nr_bits = BTF_INT_BITS(int_data);
2408 u8 total_bits_offset;
2411 * bits_offset is at most 7.
2412 * BTF_INT_OFFSET() cannot exceed 128 bits.
2414 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2415 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2416 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2417 btf_bitfield_show(data, bits_offset, nr_bits, show);
2420 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2421 u32 type_id, void *data, u8 bits_offset,
2422 struct btf_show *show)
2424 u32 int_data = btf_type_int(t);
2425 u8 encoding = BTF_INT_ENCODING(int_data);
2426 bool sign = encoding & BTF_INT_SIGNED;
2427 u8 nr_bits = BTF_INT_BITS(int_data);
2430 safe_data = btf_show_start_type(show, t, type_id, data);
2434 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2435 BITS_PER_BYTE_MASKED(nr_bits)) {
2436 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2442 btf_int128_print(show, safe_data);
2446 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2448 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2452 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2454 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2458 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2460 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2463 if (show->state.array_encoding == BTF_INT_CHAR) {
2464 /* check for null terminator */
2465 if (show->state.array_terminated)
2467 if (*(char *)data == '\0') {
2468 show->state.array_terminated = 1;
2471 if (isprint(*(char *)data)) {
2472 btf_show_type_value(show, "'%c'",
2473 *(char *)safe_data);
2478 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2480 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2483 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2487 btf_show_end_type(show);
2490 static const struct btf_kind_operations int_ops = {
2491 .check_meta = btf_int_check_meta,
2492 .resolve = btf_df_resolve,
2493 .check_member = btf_int_check_member,
2494 .check_kflag_member = btf_int_check_kflag_member,
2495 .log_details = btf_int_log,
2496 .show = btf_int_show,
2499 static int btf_modifier_check_member(struct btf_verifier_env *env,
2500 const struct btf_type *struct_type,
2501 const struct btf_member *member,
2502 const struct btf_type *member_type)
2504 const struct btf_type *resolved_type;
2505 u32 resolved_type_id = member->type;
2506 struct btf_member resolved_member;
2507 struct btf *btf = env->btf;
2509 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2510 if (!resolved_type) {
2511 btf_verifier_log_member(env, struct_type, member,
2516 resolved_member = *member;
2517 resolved_member.type = resolved_type_id;
2519 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2524 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2525 const struct btf_type *struct_type,
2526 const struct btf_member *member,
2527 const struct btf_type *member_type)
2529 const struct btf_type *resolved_type;
2530 u32 resolved_type_id = member->type;
2531 struct btf_member resolved_member;
2532 struct btf *btf = env->btf;
2534 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2535 if (!resolved_type) {
2536 btf_verifier_log_member(env, struct_type, member,
2541 resolved_member = *member;
2542 resolved_member.type = resolved_type_id;
2544 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2549 static int btf_ptr_check_member(struct btf_verifier_env *env,
2550 const struct btf_type *struct_type,
2551 const struct btf_member *member,
2552 const struct btf_type *member_type)
2554 u32 struct_size, struct_bits_off, bytes_offset;
2556 struct_size = struct_type->size;
2557 struct_bits_off = member->offset;
2558 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2560 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2561 btf_verifier_log_member(env, struct_type, member,
2562 "Member is not byte aligned");
2566 if (struct_size - bytes_offset < sizeof(void *)) {
2567 btf_verifier_log_member(env, struct_type, member,
2568 "Member exceeds struct_size");
2575 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2576 const struct btf_type *t,
2581 if (btf_type_vlen(t)) {
2582 btf_verifier_log_type(env, t, "vlen != 0");
2586 if (btf_type_kflag(t)) {
2587 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2591 if (!BTF_TYPE_ID_VALID(t->type)) {
2592 btf_verifier_log_type(env, t, "Invalid type_id");
2596 /* typedef/type_tag type must have a valid name, and other ref types,
2597 * volatile, const, restrict, should have a null name.
2599 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2601 !btf_name_valid_identifier(env->btf, t->name_off)) {
2602 btf_verifier_log_type(env, t, "Invalid name");
2605 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2606 value = btf_name_by_offset(env->btf, t->name_off);
2607 if (!value || !value[0]) {
2608 btf_verifier_log_type(env, t, "Invalid name");
2613 btf_verifier_log_type(env, t, "Invalid name");
2618 btf_verifier_log_type(env, t, NULL);
2623 static int btf_modifier_resolve(struct btf_verifier_env *env,
2624 const struct resolve_vertex *v)
2626 const struct btf_type *t = v->t;
2627 const struct btf_type *next_type;
2628 u32 next_type_id = t->type;
2629 struct btf *btf = env->btf;
2631 next_type = btf_type_by_id(btf, next_type_id);
2632 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2633 btf_verifier_log_type(env, v->t, "Invalid type_id");
2637 if (!env_type_is_resolve_sink(env, next_type) &&
2638 !env_type_is_resolved(env, next_type_id))
2639 return env_stack_push(env, next_type, next_type_id);
2641 /* Figure out the resolved next_type_id with size.
2642 * They will be stored in the current modifier's
2643 * resolved_ids and resolved_sizes such that it can
2644 * save us a few type-following when we use it later (e.g. in
2647 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2648 if (env_type_is_resolved(env, next_type_id))
2649 next_type = btf_type_id_resolve(btf, &next_type_id);
2651 /* "typedef void new_void", "const void"...etc */
2652 if (!btf_type_is_void(next_type) &&
2653 !btf_type_is_fwd(next_type) &&
2654 !btf_type_is_func_proto(next_type)) {
2655 btf_verifier_log_type(env, v->t, "Invalid type_id");
2660 env_stack_pop_resolved(env, next_type_id, 0);
2665 static int btf_var_resolve(struct btf_verifier_env *env,
2666 const struct resolve_vertex *v)
2668 const struct btf_type *next_type;
2669 const struct btf_type *t = v->t;
2670 u32 next_type_id = t->type;
2671 struct btf *btf = env->btf;
2673 next_type = btf_type_by_id(btf, next_type_id);
2674 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2675 btf_verifier_log_type(env, v->t, "Invalid type_id");
2679 if (!env_type_is_resolve_sink(env, next_type) &&
2680 !env_type_is_resolved(env, next_type_id))
2681 return env_stack_push(env, next_type, next_type_id);
2683 if (btf_type_is_modifier(next_type)) {
2684 const struct btf_type *resolved_type;
2685 u32 resolved_type_id;
2687 resolved_type_id = next_type_id;
2688 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2690 if (btf_type_is_ptr(resolved_type) &&
2691 !env_type_is_resolve_sink(env, resolved_type) &&
2692 !env_type_is_resolved(env, resolved_type_id))
2693 return env_stack_push(env, resolved_type,
2697 /* We must resolve to something concrete at this point, no
2698 * forward types or similar that would resolve to size of
2701 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2702 btf_verifier_log_type(env, v->t, "Invalid type_id");
2706 env_stack_pop_resolved(env, next_type_id, 0);
2711 static int btf_ptr_resolve(struct btf_verifier_env *env,
2712 const struct resolve_vertex *v)
2714 const struct btf_type *next_type;
2715 const struct btf_type *t = v->t;
2716 u32 next_type_id = t->type;
2717 struct btf *btf = env->btf;
2719 next_type = btf_type_by_id(btf, next_type_id);
2720 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2721 btf_verifier_log_type(env, v->t, "Invalid type_id");
2725 if (!env_type_is_resolve_sink(env, next_type) &&
2726 !env_type_is_resolved(env, next_type_id))
2727 return env_stack_push(env, next_type, next_type_id);
2729 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2730 * the modifier may have stopped resolving when it was resolved
2731 * to a ptr (last-resolved-ptr).
2733 * We now need to continue from the last-resolved-ptr to
2734 * ensure the last-resolved-ptr will not referring back to
2735 * the current ptr (t).
2737 if (btf_type_is_modifier(next_type)) {
2738 const struct btf_type *resolved_type;
2739 u32 resolved_type_id;
2741 resolved_type_id = next_type_id;
2742 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2744 if (btf_type_is_ptr(resolved_type) &&
2745 !env_type_is_resolve_sink(env, resolved_type) &&
2746 !env_type_is_resolved(env, resolved_type_id))
2747 return env_stack_push(env, resolved_type,
2751 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2752 if (env_type_is_resolved(env, next_type_id))
2753 next_type = btf_type_id_resolve(btf, &next_type_id);
2755 if (!btf_type_is_void(next_type) &&
2756 !btf_type_is_fwd(next_type) &&
2757 !btf_type_is_func_proto(next_type)) {
2758 btf_verifier_log_type(env, v->t, "Invalid type_id");
2763 env_stack_pop_resolved(env, next_type_id, 0);
2768 static void btf_modifier_show(const struct btf *btf,
2769 const struct btf_type *t,
2770 u32 type_id, void *data,
2771 u8 bits_offset, struct btf_show *show)
2773 if (btf->resolved_ids)
2774 t = btf_type_id_resolve(btf, &type_id);
2776 t = btf_type_skip_modifiers(btf, type_id, NULL);
2778 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2781 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2782 u32 type_id, void *data, u8 bits_offset,
2783 struct btf_show *show)
2785 t = btf_type_id_resolve(btf, &type_id);
2787 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2790 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2791 u32 type_id, void *data, u8 bits_offset,
2792 struct btf_show *show)
2796 safe_data = btf_show_start_type(show, t, type_id, data);
2800 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2801 if (show->flags & BTF_SHOW_PTR_RAW)
2802 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2804 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2805 btf_show_end_type(show);
2808 static void btf_ref_type_log(struct btf_verifier_env *env,
2809 const struct btf_type *t)
2811 btf_verifier_log(env, "type_id=%u", t->type);
2814 static struct btf_kind_operations modifier_ops = {
2815 .check_meta = btf_ref_type_check_meta,
2816 .resolve = btf_modifier_resolve,
2817 .check_member = btf_modifier_check_member,
2818 .check_kflag_member = btf_modifier_check_kflag_member,
2819 .log_details = btf_ref_type_log,
2820 .show = btf_modifier_show,
2823 static struct btf_kind_operations ptr_ops = {
2824 .check_meta = btf_ref_type_check_meta,
2825 .resolve = btf_ptr_resolve,
2826 .check_member = btf_ptr_check_member,
2827 .check_kflag_member = btf_generic_check_kflag_member,
2828 .log_details = btf_ref_type_log,
2829 .show = btf_ptr_show,
2832 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2833 const struct btf_type *t,
2836 if (btf_type_vlen(t)) {
2837 btf_verifier_log_type(env, t, "vlen != 0");
2842 btf_verifier_log_type(env, t, "type != 0");
2846 /* fwd type must have a valid name */
2848 !btf_name_valid_identifier(env->btf, t->name_off)) {
2849 btf_verifier_log_type(env, t, "Invalid name");
2853 btf_verifier_log_type(env, t, NULL);
2858 static void btf_fwd_type_log(struct btf_verifier_env *env,
2859 const struct btf_type *t)
2861 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2864 static struct btf_kind_operations fwd_ops = {
2865 .check_meta = btf_fwd_check_meta,
2866 .resolve = btf_df_resolve,
2867 .check_member = btf_df_check_member,
2868 .check_kflag_member = btf_df_check_kflag_member,
2869 .log_details = btf_fwd_type_log,
2870 .show = btf_df_show,
2873 static int btf_array_check_member(struct btf_verifier_env *env,
2874 const struct btf_type *struct_type,
2875 const struct btf_member *member,
2876 const struct btf_type *member_type)
2878 u32 struct_bits_off = member->offset;
2879 u32 struct_size, bytes_offset;
2880 u32 array_type_id, array_size;
2881 struct btf *btf = env->btf;
2883 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2884 btf_verifier_log_member(env, struct_type, member,
2885 "Member is not byte aligned");
2889 array_type_id = member->type;
2890 btf_type_id_size(btf, &array_type_id, &array_size);
2891 struct_size = struct_type->size;
2892 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2893 if (struct_size - bytes_offset < array_size) {
2894 btf_verifier_log_member(env, struct_type, member,
2895 "Member exceeds struct_size");
2902 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2903 const struct btf_type *t,
2906 const struct btf_array *array = btf_type_array(t);
2907 u32 meta_needed = sizeof(*array);
2909 if (meta_left < meta_needed) {
2910 btf_verifier_log_basic(env, t,
2911 "meta_left:%u meta_needed:%u",
2912 meta_left, meta_needed);
2916 /* array type should not have a name */
2918 btf_verifier_log_type(env, t, "Invalid name");
2922 if (btf_type_vlen(t)) {
2923 btf_verifier_log_type(env, t, "vlen != 0");
2927 if (btf_type_kflag(t)) {
2928 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2933 btf_verifier_log_type(env, t, "size != 0");
2937 /* Array elem type and index type cannot be in type void,
2938 * so !array->type and !array->index_type are not allowed.
2940 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2941 btf_verifier_log_type(env, t, "Invalid elem");
2945 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2946 btf_verifier_log_type(env, t, "Invalid index");
2950 btf_verifier_log_type(env, t, NULL);
2955 static int btf_array_resolve(struct btf_verifier_env *env,
2956 const struct resolve_vertex *v)
2958 const struct btf_array *array = btf_type_array(v->t);
2959 const struct btf_type *elem_type, *index_type;
2960 u32 elem_type_id, index_type_id;
2961 struct btf *btf = env->btf;
2964 /* Check array->index_type */
2965 index_type_id = array->index_type;
2966 index_type = btf_type_by_id(btf, index_type_id);
2967 if (btf_type_nosize_or_null(index_type) ||
2968 btf_type_is_resolve_source_only(index_type)) {
2969 btf_verifier_log_type(env, v->t, "Invalid index");
2973 if (!env_type_is_resolve_sink(env, index_type) &&
2974 !env_type_is_resolved(env, index_type_id))
2975 return env_stack_push(env, index_type, index_type_id);
2977 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2978 if (!index_type || !btf_type_is_int(index_type) ||
2979 !btf_type_int_is_regular(index_type)) {
2980 btf_verifier_log_type(env, v->t, "Invalid index");
2984 /* Check array->type */
2985 elem_type_id = array->type;
2986 elem_type = btf_type_by_id(btf, elem_type_id);
2987 if (btf_type_nosize_or_null(elem_type) ||
2988 btf_type_is_resolve_source_only(elem_type)) {
2989 btf_verifier_log_type(env, v->t,
2994 if (!env_type_is_resolve_sink(env, elem_type) &&
2995 !env_type_is_resolved(env, elem_type_id))
2996 return env_stack_push(env, elem_type, elem_type_id);
2998 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3000 btf_verifier_log_type(env, v->t, "Invalid elem");
3004 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
3005 btf_verifier_log_type(env, v->t, "Invalid array of int");
3009 if (array->nelems && elem_size > U32_MAX / array->nelems) {
3010 btf_verifier_log_type(env, v->t,
3011 "Array size overflows U32_MAX");
3015 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
3020 static void btf_array_log(struct btf_verifier_env *env,
3021 const struct btf_type *t)
3023 const struct btf_array *array = btf_type_array(t);
3025 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3026 array->type, array->index_type, array->nelems);
3029 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
3030 u32 type_id, void *data, u8 bits_offset,
3031 struct btf_show *show)
3033 const struct btf_array *array = btf_type_array(t);
3034 const struct btf_kind_operations *elem_ops;
3035 const struct btf_type *elem_type;
3036 u32 i, elem_size = 0, elem_type_id;
3039 elem_type_id = array->type;
3040 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
3041 if (elem_type && btf_type_has_size(elem_type))
3042 elem_size = elem_type->size;
3044 if (elem_type && btf_type_is_int(elem_type)) {
3045 u32 int_type = btf_type_int(elem_type);
3047 encoding = BTF_INT_ENCODING(int_type);
3050 * BTF_INT_CHAR encoding never seems to be set for
3051 * char arrays, so if size is 1 and element is
3052 * printable as a char, we'll do that.
3055 encoding = BTF_INT_CHAR;
3058 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3063 elem_ops = btf_type_ops(elem_type);
3065 for (i = 0; i < array->nelems; i++) {
3067 btf_show_start_array_member(show);
3069 elem_ops->show(btf, elem_type, elem_type_id, data,
3073 btf_show_end_array_member(show);
3075 if (show->state.array_terminated)
3079 btf_show_end_array_type(show);
3082 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3083 u32 type_id, void *data, u8 bits_offset,
3084 struct btf_show *show)
3086 const struct btf_member *m = show->state.member;
3089 * First check if any members would be shown (are non-zero).
3090 * See comments above "struct btf_show" definition for more
3091 * details on how this works at a high-level.
3093 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3094 if (!show->state.depth_check) {
3095 show->state.depth_check = show->state.depth + 1;
3096 show->state.depth_to_show = 0;
3098 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3099 show->state.member = m;
3101 if (show->state.depth_check != show->state.depth + 1)
3103 show->state.depth_check = 0;
3105 if (show->state.depth_to_show <= show->state.depth)
3108 * Reaching here indicates we have recursed and found
3109 * non-zero array member(s).
3112 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3115 static struct btf_kind_operations array_ops = {
3116 .check_meta = btf_array_check_meta,
3117 .resolve = btf_array_resolve,
3118 .check_member = btf_array_check_member,
3119 .check_kflag_member = btf_generic_check_kflag_member,
3120 .log_details = btf_array_log,
3121 .show = btf_array_show,
3124 static int btf_struct_check_member(struct btf_verifier_env *env,
3125 const struct btf_type *struct_type,
3126 const struct btf_member *member,
3127 const struct btf_type *member_type)
3129 u32 struct_bits_off = member->offset;
3130 u32 struct_size, bytes_offset;
3132 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3133 btf_verifier_log_member(env, struct_type, member,
3134 "Member is not byte aligned");
3138 struct_size = struct_type->size;
3139 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3140 if (struct_size - bytes_offset < member_type->size) {
3141 btf_verifier_log_member(env, struct_type, member,
3142 "Member exceeds struct_size");
3149 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3150 const struct btf_type *t,
3153 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3154 const struct btf_member *member;
3155 u32 meta_needed, last_offset;
3156 struct btf *btf = env->btf;
3157 u32 struct_size = t->size;
3161 meta_needed = btf_type_vlen(t) * sizeof(*member);
3162 if (meta_left < meta_needed) {
3163 btf_verifier_log_basic(env, t,
3164 "meta_left:%u meta_needed:%u",
3165 meta_left, meta_needed);
3169 /* struct type either no name or a valid one */
3171 !btf_name_valid_identifier(env->btf, t->name_off)) {
3172 btf_verifier_log_type(env, t, "Invalid name");
3176 btf_verifier_log_type(env, t, NULL);
3179 for_each_member(i, t, member) {
3180 if (!btf_name_offset_valid(btf, member->name_off)) {
3181 btf_verifier_log_member(env, t, member,
3182 "Invalid member name_offset:%u",
3187 /* struct member either no name or a valid one */
3188 if (member->name_off &&
3189 !btf_name_valid_identifier(btf, member->name_off)) {
3190 btf_verifier_log_member(env, t, member, "Invalid name");
3193 /* A member cannot be in type void */
3194 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3195 btf_verifier_log_member(env, t, member,
3200 offset = __btf_member_bit_offset(t, member);
3201 if (is_union && offset) {
3202 btf_verifier_log_member(env, t, member,
3203 "Invalid member bits_offset");
3208 * ">" instead of ">=" because the last member could be
3211 if (last_offset > offset) {
3212 btf_verifier_log_member(env, t, member,
3213 "Invalid member bits_offset");
3217 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3218 btf_verifier_log_member(env, t, member,
3219 "Member bits_offset exceeds its struct size");
3223 btf_verifier_log_member(env, t, member, NULL);
3224 last_offset = offset;
3230 static int btf_struct_resolve(struct btf_verifier_env *env,
3231 const struct resolve_vertex *v)
3233 const struct btf_member *member;
3237 /* Before continue resolving the next_member,
3238 * ensure the last member is indeed resolved to a
3239 * type with size info.
3241 if (v->next_member) {
3242 const struct btf_type *last_member_type;
3243 const struct btf_member *last_member;
3244 u32 last_member_type_id;
3246 last_member = btf_type_member(v->t) + v->next_member - 1;
3247 last_member_type_id = last_member->type;
3248 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3249 last_member_type_id)))
3252 last_member_type = btf_type_by_id(env->btf,
3253 last_member_type_id);
3254 if (btf_type_kflag(v->t))
3255 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3259 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3266 for_each_member_from(i, v->next_member, v->t, member) {
3267 u32 member_type_id = member->type;
3268 const struct btf_type *member_type = btf_type_by_id(env->btf,
3271 if (btf_type_nosize_or_null(member_type) ||
3272 btf_type_is_resolve_source_only(member_type)) {
3273 btf_verifier_log_member(env, v->t, member,
3278 if (!env_type_is_resolve_sink(env, member_type) &&
3279 !env_type_is_resolved(env, member_type_id)) {
3280 env_stack_set_next_member(env, i + 1);
3281 return env_stack_push(env, member_type, member_type_id);
3284 if (btf_type_kflag(v->t))
3285 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3289 err = btf_type_ops(member_type)->check_member(env, v->t,
3296 env_stack_pop_resolved(env, 0, 0);
3301 static void btf_struct_log(struct btf_verifier_env *env,
3302 const struct btf_type *t)
3304 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3308 BTF_FIELD_IGNORE = 0,
3309 BTF_FIELD_FOUND = 1,
3312 struct btf_field_info {
3313 enum btf_field_type type;
3320 const char *node_name;
3326 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3327 u32 off, int sz, enum btf_field_type field_type,
3328 struct btf_field_info *info)
3330 if (!__btf_type_is_struct(t))
3331 return BTF_FIELD_IGNORE;
3333 return BTF_FIELD_IGNORE;
3334 info->type = field_type;
3336 return BTF_FIELD_FOUND;
3339 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3340 u32 off, int sz, struct btf_field_info *info)
3342 enum btf_field_type type;
3345 /* Permit modifiers on the pointer itself */
3346 if (btf_type_is_volatile(t))
3347 t = btf_type_by_id(btf, t->type);
3348 /* For PTR, sz is always == 8 */
3349 if (!btf_type_is_ptr(t))
3350 return BTF_FIELD_IGNORE;
3351 t = btf_type_by_id(btf, t->type);
3353 if (!btf_type_is_type_tag(t))
3354 return BTF_FIELD_IGNORE;
3355 /* Reject extra tags */
3356 if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3358 if (!strcmp("kptr_untrusted", __btf_name_by_offset(btf, t->name_off)))
3359 type = BPF_KPTR_UNREF;
3360 else if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3361 type = BPF_KPTR_REF;
3362 else if (!strcmp("percpu_kptr", __btf_name_by_offset(btf, t->name_off)))
3363 type = BPF_KPTR_PERCPU;
3367 /* Get the base type */
3368 t = btf_type_skip_modifiers(btf, t->type, &res_id);
3369 /* Only pointer to struct is allowed */
3370 if (!__btf_type_is_struct(t))
3375 info->kptr.type_id = res_id;
3376 return BTF_FIELD_FOUND;
3379 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3380 int comp_idx, const char *tag_key, int last_id)
3382 int len = strlen(tag_key);
3385 for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
3386 const struct btf_type *t = btf_type_by_id(btf, i);
3388 if (!btf_type_is_decl_tag(t))
3390 if (pt != btf_type_by_id(btf, t->type))
3392 if (btf_type_decl_tag(t)->component_idx != comp_idx)
3394 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3401 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3402 int comp_idx, const char *tag_key)
3404 const char *value = NULL;
3405 const struct btf_type *t;
3408 id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, 0);
3412 t = btf_type_by_id(btf, id);
3413 len = strlen(tag_key);
3414 value = __btf_name_by_offset(btf, t->name_off) + len;
3416 /* Prevent duplicate entries for same type */
3417 id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3419 return ERR_PTR(-EEXIST);
3425 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3426 const struct btf_type *t, int comp_idx, u32 off,
3427 int sz, struct btf_field_info *info,
3428 enum btf_field_type head_type)
3430 const char *node_field_name;
3431 const char *value_type;
3434 if (!__btf_type_is_struct(t))
3435 return BTF_FIELD_IGNORE;
3437 return BTF_FIELD_IGNORE;
3438 value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3439 if (IS_ERR(value_type))
3441 node_field_name = strstr(value_type, ":");
3442 if (!node_field_name)
3444 value_type = kstrndup(value_type, node_field_name - value_type, GFP_KERNEL | __GFP_NOWARN);
3447 id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3452 if (str_is_empty(node_field_name))
3454 info->type = head_type;
3456 info->graph_root.value_btf_id = id;
3457 info->graph_root.node_name = node_field_name;
3458 return BTF_FIELD_FOUND;
3461 #define field_mask_test_name(field_type, field_type_str) \
3462 if (field_mask & field_type && !strcmp(name, field_type_str)) { \
3463 type = field_type; \
3467 static int btf_get_field_type(const struct btf *btf, const struct btf_type *var_type,
3468 u32 field_mask, u32 *seen_mask,
3469 int *align, int *sz)
3472 const char *name = __btf_name_by_offset(btf, var_type->name_off);
3474 if (field_mask & BPF_SPIN_LOCK) {
3475 if (!strcmp(name, "bpf_spin_lock")) {
3476 if (*seen_mask & BPF_SPIN_LOCK)
3478 *seen_mask |= BPF_SPIN_LOCK;
3479 type = BPF_SPIN_LOCK;
3483 if (field_mask & BPF_TIMER) {
3484 if (!strcmp(name, "bpf_timer")) {
3485 if (*seen_mask & BPF_TIMER)
3487 *seen_mask |= BPF_TIMER;
3492 if (field_mask & BPF_WORKQUEUE) {
3493 if (!strcmp(name, "bpf_wq")) {
3494 if (*seen_mask & BPF_WORKQUEUE)
3496 *seen_mask |= BPF_WORKQUEUE;
3497 type = BPF_WORKQUEUE;
3501 field_mask_test_name(BPF_LIST_HEAD, "bpf_list_head");
3502 field_mask_test_name(BPF_LIST_NODE, "bpf_list_node");
3503 field_mask_test_name(BPF_RB_ROOT, "bpf_rb_root");
3504 field_mask_test_name(BPF_RB_NODE, "bpf_rb_node");
3505 field_mask_test_name(BPF_REFCOUNT, "bpf_refcount");
3507 /* Only return BPF_KPTR when all other types with matchable names fail */
3508 if (field_mask & BPF_KPTR && !__btf_type_is_struct(var_type)) {
3509 type = BPF_KPTR_REF;
3514 *sz = btf_field_type_size(type);
3515 *align = btf_field_type_align(type);
3519 #undef field_mask_test_name
3521 /* Repeat a number of fields for a specified number of times.
3523 * Copy the fields starting from the first field and repeat them for
3524 * repeat_cnt times. The fields are repeated by adding the offset of each
3526 * (i + 1) * elem_size
3527 * where i is the repeat index and elem_size is the size of an element.
3529 static int btf_repeat_fields(struct btf_field_info *info,
3530 u32 field_cnt, u32 repeat_cnt, u32 elem_size)
3535 /* Ensure not repeating fields that should not be repeated. */
3536 for (i = 0; i < field_cnt; i++) {
3537 switch (info[i].type) {
3538 case BPF_KPTR_UNREF:
3540 case BPF_KPTR_PERCPU:
3550 for (i = 0; i < repeat_cnt; i++) {
3551 memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
3552 for (j = 0; j < field_cnt; j++)
3553 info[cur++].off += (i + 1) * elem_size;
3559 static int btf_find_struct_field(const struct btf *btf,
3560 const struct btf_type *t, u32 field_mask,
3561 struct btf_field_info *info, int info_cnt,
3564 /* Find special fields in the struct type of a field.
3566 * This function is used to find fields of special types that is not a
3567 * global variable or a direct field of a struct type. It also handles the
3568 * repetition if it is the element type of an array.
3570 static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
3571 u32 off, u32 nelems,
3572 u32 field_mask, struct btf_field_info *info,
3573 int info_cnt, u32 level)
3578 if (level >= MAX_RESOLVE_DEPTH)
3581 ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level);
3586 /* Shift the offsets of the nested struct fields to the offsets
3587 * related to the container.
3589 for (i = 0; i < ret; i++)
3593 err = btf_repeat_fields(info, ret, nelems - 1, t->size);
3603 static int btf_find_field_one(const struct btf *btf,
3604 const struct btf_type *var,
3605 const struct btf_type *var_type,
3607 u32 off, u32 expected_size,
3608 u32 field_mask, u32 *seen_mask,
3609 struct btf_field_info *info, int info_cnt,
3612 int ret, align, sz, field_type;
3613 struct btf_field_info tmp;
3614 const struct btf_array *array;
3617 /* Walk into array types to find the element type and the number of
3618 * elements in the (flattened) array.
3620 for (i = 0; i < MAX_RESOLVE_DEPTH && btf_type_is_array(var_type); i++) {
3621 array = btf_array(var_type);
3622 nelems *= array->nelems;
3623 var_type = btf_type_by_id(btf, array->type);
3625 if (i == MAX_RESOLVE_DEPTH)
3630 field_type = btf_get_field_type(btf, var_type,
3631 field_mask, seen_mask, &align, &sz);
3632 /* Look into variables of struct types */
3633 if (!field_type && __btf_type_is_struct(var_type)) {
3634 sz = var_type->size;
3635 if (expected_size && expected_size != sz * nelems)
3637 ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
3638 &info[0], info_cnt, level);
3642 if (field_type == 0)
3647 if (expected_size && expected_size != sz * nelems)
3652 switch (field_type) {
3659 ret = btf_find_struct(btf, var_type, off, sz, field_type,
3660 info_cnt ? &info[0] : &tmp);
3664 case BPF_KPTR_UNREF:
3666 case BPF_KPTR_PERCPU:
3667 ret = btf_find_kptr(btf, var_type, off, sz,
3668 info_cnt ? &info[0] : &tmp);
3674 ret = btf_find_graph_root(btf, var, var_type,
3676 info_cnt ? &info[0] : &tmp,
3685 if (ret == BTF_FIELD_IGNORE)
3687 if (nelems > info_cnt)
3690 ret = btf_repeat_fields(info, 1, nelems - 1, sz);
3697 static int btf_find_struct_field(const struct btf *btf,
3698 const struct btf_type *t, u32 field_mask,
3699 struct btf_field_info *info, int info_cnt,
3703 const struct btf_member *member;
3704 u32 i, off, seen_mask = 0;
3706 for_each_member(i, t, member) {
3707 const struct btf_type *member_type = btf_type_by_id(btf,
3710 off = __btf_member_bit_offset(t, member);
3712 /* valid C code cannot generate such BTF */
3716 ret = btf_find_field_one(btf, t, member_type, i,
3718 field_mask, &seen_mask,
3719 &info[idx], info_cnt - idx, level);
3727 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3728 u32 field_mask, struct btf_field_info *info,
3729 int info_cnt, u32 level)
3732 const struct btf_var_secinfo *vsi;
3733 u32 i, off, seen_mask = 0;
3735 for_each_vsi(i, t, vsi) {
3736 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3737 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3740 ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
3741 field_mask, &seen_mask,
3742 &info[idx], info_cnt - idx,
3751 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3752 u32 field_mask, struct btf_field_info *info,
3755 if (__btf_type_is_struct(t))
3756 return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0);
3757 else if (btf_type_is_datasec(t))
3758 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0);
3762 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3763 struct btf_field_info *info)
3765 struct module *mod = NULL;
3766 const struct btf_type *t;
3767 /* If a matching btf type is found in kernel or module BTFs, kptr_ref
3768 * is that BTF, otherwise it's program BTF
3770 struct btf *kptr_btf;
3774 /* Find type in map BTF, and use it to look up the matching type
3775 * in vmlinux or module BTFs, by name and kind.
3777 t = btf_type_by_id(btf, info->kptr.type_id);
3778 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3780 if (id == -ENOENT) {
3781 /* btf_parse_kptr should only be called w/ btf = program BTF */
3782 WARN_ON_ONCE(btf_is_kernel(btf));
3784 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3785 * kptr allocated via bpf_obj_new
3787 field->kptr.dtor = NULL;
3788 id = info->kptr.type_id;
3789 kptr_btf = (struct btf *)btf;
3796 /* Find and stash the function pointer for the destruction function that
3797 * needs to be eventually invoked from the map free path.
3799 if (info->type == BPF_KPTR_REF) {
3800 const struct btf_type *dtor_func;
3801 const char *dtor_func_name;
3805 /* This call also serves as a whitelist of allowed objects that
3806 * can be used as a referenced pointer and be stored in a map at
3809 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3810 if (dtor_btf_id < 0) {
3815 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3821 if (btf_is_module(kptr_btf)) {
3822 mod = btf_try_get_module(kptr_btf);
3829 /* We already verified dtor_func to be btf_type_is_func
3830 * in register_btf_id_dtor_kfuncs.
3832 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3833 addr = kallsyms_lookup_name(dtor_func_name);
3838 field->kptr.dtor = (void *)addr;
3842 field->kptr.btf_id = id;
3843 field->kptr.btf = kptr_btf;
3844 field->kptr.module = mod;
3853 static int btf_parse_graph_root(const struct btf *btf,
3854 struct btf_field *field,
3855 struct btf_field_info *info,
3856 const char *node_type_name,
3857 size_t node_type_align)
3859 const struct btf_type *t, *n = NULL;
3860 const struct btf_member *member;
3864 t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3865 /* We've already checked that value_btf_id is a struct type. We
3866 * just need to figure out the offset of the list_node, and
3869 for_each_member(i, t, member) {
3870 if (strcmp(info->graph_root.node_name,
3871 __btf_name_by_offset(btf, member->name_off)))
3873 /* Invalid BTF, two members with same name */
3876 n = btf_type_by_id(btf, member->type);
3877 if (!__btf_type_is_struct(n))
3879 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3881 offset = __btf_member_bit_offset(n, member);
3885 if (offset % node_type_align)
3888 field->graph_root.btf = (struct btf *)btf;
3889 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3890 field->graph_root.node_offset = offset;
3897 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3898 struct btf_field_info *info)
3900 return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3901 __alignof__(struct bpf_list_node));
3904 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3905 struct btf_field_info *info)
3907 return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3908 __alignof__(struct bpf_rb_node));
3911 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3913 const struct btf_field *a = (const struct btf_field *)_a;
3914 const struct btf_field *b = (const struct btf_field *)_b;
3916 if (a->offset < b->offset)
3918 else if (a->offset > b->offset)
3923 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3924 u32 field_mask, u32 value_size)
3926 struct btf_field_info info_arr[BTF_FIELDS_MAX];
3927 u32 next_off = 0, field_type_size;
3928 struct btf_record *rec;
3931 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3933 return ERR_PTR(ret);
3938 /* This needs to be kzalloc to zero out padding and unused fields, see
3939 * comment in btf_record_equal.
3941 rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3943 return ERR_PTR(-ENOMEM);
3945 rec->spin_lock_off = -EINVAL;
3946 rec->timer_off = -EINVAL;
3947 rec->wq_off = -EINVAL;
3948 rec->refcount_off = -EINVAL;
3949 for (i = 0; i < cnt; i++) {
3950 field_type_size = btf_field_type_size(info_arr[i].type);
3951 if (info_arr[i].off + field_type_size > value_size) {
3952 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3956 if (info_arr[i].off < next_off) {
3960 next_off = info_arr[i].off + field_type_size;
3962 rec->field_mask |= info_arr[i].type;
3963 rec->fields[i].offset = info_arr[i].off;
3964 rec->fields[i].type = info_arr[i].type;
3965 rec->fields[i].size = field_type_size;
3967 switch (info_arr[i].type) {
3969 WARN_ON_ONCE(rec->spin_lock_off >= 0);
3970 /* Cache offset for faster lookup at runtime */
3971 rec->spin_lock_off = rec->fields[i].offset;
3974 WARN_ON_ONCE(rec->timer_off >= 0);
3975 /* Cache offset for faster lookup at runtime */
3976 rec->timer_off = rec->fields[i].offset;
3979 WARN_ON_ONCE(rec->wq_off >= 0);
3980 /* Cache offset for faster lookup at runtime */
3981 rec->wq_off = rec->fields[i].offset;
3984 WARN_ON_ONCE(rec->refcount_off >= 0);
3985 /* Cache offset for faster lookup at runtime */
3986 rec->refcount_off = rec->fields[i].offset;
3988 case BPF_KPTR_UNREF:
3990 case BPF_KPTR_PERCPU:
3991 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3996 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
4001 ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
4015 /* bpf_{list_head, rb_node} require bpf_spin_lock */
4016 if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
4017 btf_record_has_field(rec, BPF_RB_ROOT)) && rec->spin_lock_off < 0) {
4022 if (rec->refcount_off < 0 &&
4023 btf_record_has_field(rec, BPF_LIST_NODE) &&
4024 btf_record_has_field(rec, BPF_RB_NODE)) {
4029 sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
4034 btf_record_free(rec);
4035 return ERR_PTR(ret);
4038 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
4042 /* There are three types that signify ownership of some other type:
4043 * kptr_ref, bpf_list_head, bpf_rb_root.
4044 * kptr_ref only supports storing kernel types, which can't store
4045 * references to program allocated local types.
4047 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
4048 * does not form cycles.
4050 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & BPF_GRAPH_ROOT))
4052 for (i = 0; i < rec->cnt; i++) {
4053 struct btf_struct_meta *meta;
4056 if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
4058 btf_id = rec->fields[i].graph_root.value_btf_id;
4059 meta = btf_find_struct_meta(btf, btf_id);
4062 rec->fields[i].graph_root.value_rec = meta->record;
4064 /* We need to set value_rec for all root types, but no need
4065 * to check ownership cycle for a type unless it's also a
4068 if (!(rec->field_mask & BPF_GRAPH_NODE))
4071 /* We need to ensure ownership acyclicity among all types. The
4072 * proper way to do it would be to topologically sort all BTF
4073 * IDs based on the ownership edges, since there can be multiple
4074 * bpf_{list_head,rb_node} in a type. Instead, we use the
4075 * following resaoning:
4077 * - A type can only be owned by another type in user BTF if it
4078 * has a bpf_{list,rb}_node. Let's call these node types.
4079 * - A type can only _own_ another type in user BTF if it has a
4080 * bpf_{list_head,rb_root}. Let's call these root types.
4082 * We ensure that if a type is both a root and node, its
4083 * element types cannot be root types.
4085 * To ensure acyclicity:
4087 * When A is an root type but not a node, its ownership
4091 * - A is an root, e.g. has bpf_rb_root.
4092 * - B is both a root and node, e.g. has bpf_rb_node and
4094 * - C is only an root, e.g. has bpf_list_node
4096 * When A is both a root and node, some other type already
4097 * owns it in the BTF domain, hence it can not own
4098 * another root type through any of the ownership edges.
4101 * - A is both an root and node.
4102 * - B is only an node.
4104 if (meta->record->field_mask & BPF_GRAPH_ROOT)
4110 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
4111 u32 type_id, void *data, u8 bits_offset,
4112 struct btf_show *show)
4114 const struct btf_member *member;
4118 safe_data = btf_show_start_struct_type(show, t, type_id, data);
4122 for_each_member(i, t, member) {
4123 const struct btf_type *member_type = btf_type_by_id(btf,
4125 const struct btf_kind_operations *ops;
4126 u32 member_offset, bitfield_size;
4130 btf_show_start_member(show, member);
4132 member_offset = __btf_member_bit_offset(t, member);
4133 bitfield_size = __btf_member_bitfield_size(t, member);
4134 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4135 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4136 if (bitfield_size) {
4137 safe_data = btf_show_start_type(show, member_type,
4139 data + bytes_offset);
4141 btf_bitfield_show(safe_data,
4143 bitfield_size, show);
4144 btf_show_end_type(show);
4146 ops = btf_type_ops(member_type);
4147 ops->show(btf, member_type, member->type,
4148 data + bytes_offset, bits8_offset, show);
4151 btf_show_end_member(show);
4154 btf_show_end_struct_type(show);
4157 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4158 u32 type_id, void *data, u8 bits_offset,
4159 struct btf_show *show)
4161 const struct btf_member *m = show->state.member;
4164 * First check if any members would be shown (are non-zero).
4165 * See comments above "struct btf_show" definition for more
4166 * details on how this works at a high-level.
4168 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4169 if (!show->state.depth_check) {
4170 show->state.depth_check = show->state.depth + 1;
4171 show->state.depth_to_show = 0;
4173 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4174 /* Restore saved member data here */
4175 show->state.member = m;
4176 if (show->state.depth_check != show->state.depth + 1)
4178 show->state.depth_check = 0;
4180 if (show->state.depth_to_show <= show->state.depth)
4183 * Reaching here indicates we have recursed and found
4184 * non-zero child values.
4188 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4191 static struct btf_kind_operations struct_ops = {
4192 .check_meta = btf_struct_check_meta,
4193 .resolve = btf_struct_resolve,
4194 .check_member = btf_struct_check_member,
4195 .check_kflag_member = btf_generic_check_kflag_member,
4196 .log_details = btf_struct_log,
4197 .show = btf_struct_show,
4200 static int btf_enum_check_member(struct btf_verifier_env *env,
4201 const struct btf_type *struct_type,
4202 const struct btf_member *member,
4203 const struct btf_type *member_type)
4205 u32 struct_bits_off = member->offset;
4206 u32 struct_size, bytes_offset;
4208 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4209 btf_verifier_log_member(env, struct_type, member,
4210 "Member is not byte aligned");
4214 struct_size = struct_type->size;
4215 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4216 if (struct_size - bytes_offset < member_type->size) {
4217 btf_verifier_log_member(env, struct_type, member,
4218 "Member exceeds struct_size");
4225 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4226 const struct btf_type *struct_type,
4227 const struct btf_member *member,
4228 const struct btf_type *member_type)
4230 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4231 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4233 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4234 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4236 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4237 btf_verifier_log_member(env, struct_type, member,
4238 "Member is not byte aligned");
4242 nr_bits = int_bitsize;
4243 } else if (nr_bits > int_bitsize) {
4244 btf_verifier_log_member(env, struct_type, member,
4245 "Invalid member bitfield_size");
4249 struct_size = struct_type->size;
4250 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4251 if (struct_size < bytes_end) {
4252 btf_verifier_log_member(env, struct_type, member,
4253 "Member exceeds struct_size");
4260 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4261 const struct btf_type *t,
4264 const struct btf_enum *enums = btf_type_enum(t);
4265 struct btf *btf = env->btf;
4266 const char *fmt_str;
4270 nr_enums = btf_type_vlen(t);
4271 meta_needed = nr_enums * sizeof(*enums);
4273 if (meta_left < meta_needed) {
4274 btf_verifier_log_basic(env, t,
4275 "meta_left:%u meta_needed:%u",
4276 meta_left, meta_needed);
4280 if (t->size > 8 || !is_power_of_2(t->size)) {
4281 btf_verifier_log_type(env, t, "Unexpected size");
4285 /* enum type either no name or a valid one */
4287 !btf_name_valid_identifier(env->btf, t->name_off)) {
4288 btf_verifier_log_type(env, t, "Invalid name");
4292 btf_verifier_log_type(env, t, NULL);
4294 for (i = 0; i < nr_enums; i++) {
4295 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4296 btf_verifier_log(env, "\tInvalid name_offset:%u",
4301 /* enum member must have a valid name */
4302 if (!enums[i].name_off ||
4303 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4304 btf_verifier_log_type(env, t, "Invalid name");
4308 if (env->log.level == BPF_LOG_KERNEL)
4310 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4311 btf_verifier_log(env, fmt_str,
4312 __btf_name_by_offset(btf, enums[i].name_off),
4319 static void btf_enum_log(struct btf_verifier_env *env,
4320 const struct btf_type *t)
4322 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4325 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4326 u32 type_id, void *data, u8 bits_offset,
4327 struct btf_show *show)
4329 const struct btf_enum *enums = btf_type_enum(t);
4330 u32 i, nr_enums = btf_type_vlen(t);
4334 safe_data = btf_show_start_type(show, t, type_id, data);
4338 v = *(int *)safe_data;
4340 for (i = 0; i < nr_enums; i++) {
4341 if (v != enums[i].val)
4344 btf_show_type_value(show, "%s",
4345 __btf_name_by_offset(btf,
4346 enums[i].name_off));
4348 btf_show_end_type(show);
4352 if (btf_type_kflag(t))
4353 btf_show_type_value(show, "%d", v);
4355 btf_show_type_value(show, "%u", v);
4356 btf_show_end_type(show);
4359 static struct btf_kind_operations enum_ops = {
4360 .check_meta = btf_enum_check_meta,
4361 .resolve = btf_df_resolve,
4362 .check_member = btf_enum_check_member,
4363 .check_kflag_member = btf_enum_check_kflag_member,
4364 .log_details = btf_enum_log,
4365 .show = btf_enum_show,
4368 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4369 const struct btf_type *t,
4372 const struct btf_enum64 *enums = btf_type_enum64(t);
4373 struct btf *btf = env->btf;
4374 const char *fmt_str;
4378 nr_enums = btf_type_vlen(t);
4379 meta_needed = nr_enums * sizeof(*enums);
4381 if (meta_left < meta_needed) {
4382 btf_verifier_log_basic(env, t,
4383 "meta_left:%u meta_needed:%u",
4384 meta_left, meta_needed);
4388 if (t->size > 8 || !is_power_of_2(t->size)) {
4389 btf_verifier_log_type(env, t, "Unexpected size");
4393 /* enum type either no name or a valid one */
4395 !btf_name_valid_identifier(env->btf, t->name_off)) {
4396 btf_verifier_log_type(env, t, "Invalid name");
4400 btf_verifier_log_type(env, t, NULL);
4402 for (i = 0; i < nr_enums; i++) {
4403 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4404 btf_verifier_log(env, "\tInvalid name_offset:%u",
4409 /* enum member must have a valid name */
4410 if (!enums[i].name_off ||
4411 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4412 btf_verifier_log_type(env, t, "Invalid name");
4416 if (env->log.level == BPF_LOG_KERNEL)
4419 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4420 btf_verifier_log(env, fmt_str,
4421 __btf_name_by_offset(btf, enums[i].name_off),
4422 btf_enum64_value(enums + i));
4428 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4429 u32 type_id, void *data, u8 bits_offset,
4430 struct btf_show *show)
4432 const struct btf_enum64 *enums = btf_type_enum64(t);
4433 u32 i, nr_enums = btf_type_vlen(t);
4437 safe_data = btf_show_start_type(show, t, type_id, data);
4441 v = *(u64 *)safe_data;
4443 for (i = 0; i < nr_enums; i++) {
4444 if (v != btf_enum64_value(enums + i))
4447 btf_show_type_value(show, "%s",
4448 __btf_name_by_offset(btf,
4449 enums[i].name_off));
4451 btf_show_end_type(show);
4455 if (btf_type_kflag(t))
4456 btf_show_type_value(show, "%lld", v);
4458 btf_show_type_value(show, "%llu", v);
4459 btf_show_end_type(show);
4462 static struct btf_kind_operations enum64_ops = {
4463 .check_meta = btf_enum64_check_meta,
4464 .resolve = btf_df_resolve,
4465 .check_member = btf_enum_check_member,
4466 .check_kflag_member = btf_enum_check_kflag_member,
4467 .log_details = btf_enum_log,
4468 .show = btf_enum64_show,
4471 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4472 const struct btf_type *t,
4475 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4477 if (meta_left < meta_needed) {
4478 btf_verifier_log_basic(env, t,
4479 "meta_left:%u meta_needed:%u",
4480 meta_left, meta_needed);
4485 btf_verifier_log_type(env, t, "Invalid name");
4489 if (btf_type_kflag(t)) {
4490 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4494 btf_verifier_log_type(env, t, NULL);
4499 static void btf_func_proto_log(struct btf_verifier_env *env,
4500 const struct btf_type *t)
4502 const struct btf_param *args = (const struct btf_param *)(t + 1);
4503 u16 nr_args = btf_type_vlen(t), i;
4505 btf_verifier_log(env, "return=%u args=(", t->type);
4507 btf_verifier_log(env, "void");
4511 if (nr_args == 1 && !args[0].type) {
4512 /* Only one vararg */
4513 btf_verifier_log(env, "vararg");
4517 btf_verifier_log(env, "%u %s", args[0].type,
4518 __btf_name_by_offset(env->btf,
4520 for (i = 1; i < nr_args - 1; i++)
4521 btf_verifier_log(env, ", %u %s", args[i].type,
4522 __btf_name_by_offset(env->btf,
4526 const struct btf_param *last_arg = &args[nr_args - 1];
4529 btf_verifier_log(env, ", %u %s", last_arg->type,
4530 __btf_name_by_offset(env->btf,
4531 last_arg->name_off));
4533 btf_verifier_log(env, ", vararg");
4537 btf_verifier_log(env, ")");
4540 static struct btf_kind_operations func_proto_ops = {
4541 .check_meta = btf_func_proto_check_meta,
4542 .resolve = btf_df_resolve,
4544 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4545 * a struct's member.
4547 * It should be a function pointer instead.
4548 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4550 * Hence, there is no btf_func_check_member().
4552 .check_member = btf_df_check_member,
4553 .check_kflag_member = btf_df_check_kflag_member,
4554 .log_details = btf_func_proto_log,
4555 .show = btf_df_show,
4558 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4559 const struct btf_type *t,
4563 !btf_name_valid_identifier(env->btf, t->name_off)) {
4564 btf_verifier_log_type(env, t, "Invalid name");
4568 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4569 btf_verifier_log_type(env, t, "Invalid func linkage");
4573 if (btf_type_kflag(t)) {
4574 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4578 btf_verifier_log_type(env, t, NULL);
4583 static int btf_func_resolve(struct btf_verifier_env *env,
4584 const struct resolve_vertex *v)
4586 const struct btf_type *t = v->t;
4587 u32 next_type_id = t->type;
4590 err = btf_func_check(env, t);
4594 env_stack_pop_resolved(env, next_type_id, 0);
4598 static struct btf_kind_operations func_ops = {
4599 .check_meta = btf_func_check_meta,
4600 .resolve = btf_func_resolve,
4601 .check_member = btf_df_check_member,
4602 .check_kflag_member = btf_df_check_kflag_member,
4603 .log_details = btf_ref_type_log,
4604 .show = btf_df_show,
4607 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4608 const struct btf_type *t,
4611 const struct btf_var *var;
4612 u32 meta_needed = sizeof(*var);
4614 if (meta_left < meta_needed) {
4615 btf_verifier_log_basic(env, t,
4616 "meta_left:%u meta_needed:%u",
4617 meta_left, meta_needed);
4621 if (btf_type_vlen(t)) {
4622 btf_verifier_log_type(env, t, "vlen != 0");
4626 if (btf_type_kflag(t)) {
4627 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4632 !__btf_name_valid(env->btf, t->name_off)) {
4633 btf_verifier_log_type(env, t, "Invalid name");
4637 /* A var cannot be in type void */
4638 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4639 btf_verifier_log_type(env, t, "Invalid type_id");
4643 var = btf_type_var(t);
4644 if (var->linkage != BTF_VAR_STATIC &&
4645 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4646 btf_verifier_log_type(env, t, "Linkage not supported");
4650 btf_verifier_log_type(env, t, NULL);
4655 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4657 const struct btf_var *var = btf_type_var(t);
4659 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4662 static const struct btf_kind_operations var_ops = {
4663 .check_meta = btf_var_check_meta,
4664 .resolve = btf_var_resolve,
4665 .check_member = btf_df_check_member,
4666 .check_kflag_member = btf_df_check_kflag_member,
4667 .log_details = btf_var_log,
4668 .show = btf_var_show,
4671 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4672 const struct btf_type *t,
4675 const struct btf_var_secinfo *vsi;
4676 u64 last_vsi_end_off = 0, sum = 0;
4679 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4680 if (meta_left < meta_needed) {
4681 btf_verifier_log_basic(env, t,
4682 "meta_left:%u meta_needed:%u",
4683 meta_left, meta_needed);
4688 btf_verifier_log_type(env, t, "size == 0");
4692 if (btf_type_kflag(t)) {
4693 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4698 !btf_name_valid_section(env->btf, t->name_off)) {
4699 btf_verifier_log_type(env, t, "Invalid name");
4703 btf_verifier_log_type(env, t, NULL);
4705 for_each_vsi(i, t, vsi) {
4706 /* A var cannot be in type void */
4707 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4708 btf_verifier_log_vsi(env, t, vsi,
4713 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4714 btf_verifier_log_vsi(env, t, vsi,
4719 if (!vsi->size || vsi->size > t->size) {
4720 btf_verifier_log_vsi(env, t, vsi,
4725 last_vsi_end_off = vsi->offset + vsi->size;
4726 if (last_vsi_end_off > t->size) {
4727 btf_verifier_log_vsi(env, t, vsi,
4728 "Invalid offset+size");
4732 btf_verifier_log_vsi(env, t, vsi, NULL);
4736 if (t->size < sum) {
4737 btf_verifier_log_type(env, t, "Invalid btf_info size");
4744 static int btf_datasec_resolve(struct btf_verifier_env *env,
4745 const struct resolve_vertex *v)
4747 const struct btf_var_secinfo *vsi;
4748 struct btf *btf = env->btf;
4751 env->resolve_mode = RESOLVE_TBD;
4752 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4753 u32 var_type_id = vsi->type, type_id, type_size = 0;
4754 const struct btf_type *var_type = btf_type_by_id(env->btf,
4756 if (!var_type || !btf_type_is_var(var_type)) {
4757 btf_verifier_log_vsi(env, v->t, vsi,
4758 "Not a VAR kind member");
4762 if (!env_type_is_resolve_sink(env, var_type) &&
4763 !env_type_is_resolved(env, var_type_id)) {
4764 env_stack_set_next_member(env, i + 1);
4765 return env_stack_push(env, var_type, var_type_id);
4768 type_id = var_type->type;
4769 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4770 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4774 if (vsi->size < type_size) {
4775 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4780 env_stack_pop_resolved(env, 0, 0);
4784 static void btf_datasec_log(struct btf_verifier_env *env,
4785 const struct btf_type *t)
4787 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4790 static void btf_datasec_show(const struct btf *btf,
4791 const struct btf_type *t, u32 type_id,
4792 void *data, u8 bits_offset,
4793 struct btf_show *show)
4795 const struct btf_var_secinfo *vsi;
4796 const struct btf_type *var;
4799 if (!btf_show_start_type(show, t, type_id, data))
4802 btf_show_type_value(show, "section (\"%s\") = {",
4803 __btf_name_by_offset(btf, t->name_off));
4804 for_each_vsi(i, t, vsi) {
4805 var = btf_type_by_id(btf, vsi->type);
4807 btf_show(show, ",");
4808 btf_type_ops(var)->show(btf, var, vsi->type,
4809 data + vsi->offset, bits_offset, show);
4811 btf_show_end_type(show);
4814 static const struct btf_kind_operations datasec_ops = {
4815 .check_meta = btf_datasec_check_meta,
4816 .resolve = btf_datasec_resolve,
4817 .check_member = btf_df_check_member,
4818 .check_kflag_member = btf_df_check_kflag_member,
4819 .log_details = btf_datasec_log,
4820 .show = btf_datasec_show,
4823 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4824 const struct btf_type *t,
4827 if (btf_type_vlen(t)) {
4828 btf_verifier_log_type(env, t, "vlen != 0");
4832 if (btf_type_kflag(t)) {
4833 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4837 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4839 btf_verifier_log_type(env, t, "Invalid type_size");
4843 btf_verifier_log_type(env, t, NULL);
4848 static int btf_float_check_member(struct btf_verifier_env *env,
4849 const struct btf_type *struct_type,
4850 const struct btf_member *member,
4851 const struct btf_type *member_type)
4853 u64 start_offset_bytes;
4854 u64 end_offset_bytes;
4859 /* Different architectures have different alignment requirements, so
4860 * here we check only for the reasonable minimum. This way we ensure
4861 * that types after CO-RE can pass the kernel BTF verifier.
4863 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4864 align_bits = align_bytes * BITS_PER_BYTE;
4865 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4866 if (misalign_bits) {
4867 btf_verifier_log_member(env, struct_type, member,
4868 "Member is not properly aligned");
4872 start_offset_bytes = member->offset / BITS_PER_BYTE;
4873 end_offset_bytes = start_offset_bytes + member_type->size;
4874 if (end_offset_bytes > struct_type->size) {
4875 btf_verifier_log_member(env, struct_type, member,
4876 "Member exceeds struct_size");
4883 static void btf_float_log(struct btf_verifier_env *env,
4884 const struct btf_type *t)
4886 btf_verifier_log(env, "size=%u", t->size);
4889 static const struct btf_kind_operations float_ops = {
4890 .check_meta = btf_float_check_meta,
4891 .resolve = btf_df_resolve,
4892 .check_member = btf_float_check_member,
4893 .check_kflag_member = btf_generic_check_kflag_member,
4894 .log_details = btf_float_log,
4895 .show = btf_df_show,
4898 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4899 const struct btf_type *t,
4902 const struct btf_decl_tag *tag;
4903 u32 meta_needed = sizeof(*tag);
4907 if (meta_left < meta_needed) {
4908 btf_verifier_log_basic(env, t,
4909 "meta_left:%u meta_needed:%u",
4910 meta_left, meta_needed);
4914 value = btf_name_by_offset(env->btf, t->name_off);
4915 if (!value || !value[0]) {
4916 btf_verifier_log_type(env, t, "Invalid value");
4920 if (btf_type_vlen(t)) {
4921 btf_verifier_log_type(env, t, "vlen != 0");
4925 if (btf_type_kflag(t)) {
4926 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4930 component_idx = btf_type_decl_tag(t)->component_idx;
4931 if (component_idx < -1) {
4932 btf_verifier_log_type(env, t, "Invalid component_idx");
4936 btf_verifier_log_type(env, t, NULL);
4941 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4942 const struct resolve_vertex *v)
4944 const struct btf_type *next_type;
4945 const struct btf_type *t = v->t;
4946 u32 next_type_id = t->type;
4947 struct btf *btf = env->btf;
4951 next_type = btf_type_by_id(btf, next_type_id);
4952 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4953 btf_verifier_log_type(env, v->t, "Invalid type_id");
4957 if (!env_type_is_resolve_sink(env, next_type) &&
4958 !env_type_is_resolved(env, next_type_id))
4959 return env_stack_push(env, next_type, next_type_id);
4961 component_idx = btf_type_decl_tag(t)->component_idx;
4962 if (component_idx != -1) {
4963 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4964 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4968 if (btf_type_is_struct(next_type)) {
4969 vlen = btf_type_vlen(next_type);
4971 /* next_type should be a function */
4972 next_type = btf_type_by_id(btf, next_type->type);
4973 vlen = btf_type_vlen(next_type);
4976 if ((u32)component_idx >= vlen) {
4977 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4982 env_stack_pop_resolved(env, next_type_id, 0);
4987 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4989 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4990 btf_type_decl_tag(t)->component_idx);
4993 static const struct btf_kind_operations decl_tag_ops = {
4994 .check_meta = btf_decl_tag_check_meta,
4995 .resolve = btf_decl_tag_resolve,
4996 .check_member = btf_df_check_member,
4997 .check_kflag_member = btf_df_check_kflag_member,
4998 .log_details = btf_decl_tag_log,
4999 .show = btf_df_show,
5002 static int btf_func_proto_check(struct btf_verifier_env *env,
5003 const struct btf_type *t)
5005 const struct btf_type *ret_type;
5006 const struct btf_param *args;
5007 const struct btf *btf;
5012 args = (const struct btf_param *)(t + 1);
5013 nr_args = btf_type_vlen(t);
5015 /* Check func return type which could be "void" (t->type == 0) */
5017 u32 ret_type_id = t->type;
5019 ret_type = btf_type_by_id(btf, ret_type_id);
5021 btf_verifier_log_type(env, t, "Invalid return type");
5025 if (btf_type_is_resolve_source_only(ret_type)) {
5026 btf_verifier_log_type(env, t, "Invalid return type");
5030 if (btf_type_needs_resolve(ret_type) &&
5031 !env_type_is_resolved(env, ret_type_id)) {
5032 err = btf_resolve(env, ret_type, ret_type_id);
5037 /* Ensure the return type is a type that has a size */
5038 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
5039 btf_verifier_log_type(env, t, "Invalid return type");
5047 /* Last func arg type_id could be 0 if it is a vararg */
5048 if (!args[nr_args - 1].type) {
5049 if (args[nr_args - 1].name_off) {
5050 btf_verifier_log_type(env, t, "Invalid arg#%u",
5057 for (i = 0; i < nr_args; i++) {
5058 const struct btf_type *arg_type;
5061 arg_type_id = args[i].type;
5062 arg_type = btf_type_by_id(btf, arg_type_id);
5064 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5068 if (btf_type_is_resolve_source_only(arg_type)) {
5069 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5073 if (args[i].name_off &&
5074 (!btf_name_offset_valid(btf, args[i].name_off) ||
5075 !btf_name_valid_identifier(btf, args[i].name_off))) {
5076 btf_verifier_log_type(env, t,
5077 "Invalid arg#%u", i + 1);
5081 if (btf_type_needs_resolve(arg_type) &&
5082 !env_type_is_resolved(env, arg_type_id)) {
5083 err = btf_resolve(env, arg_type, arg_type_id);
5088 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
5089 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5097 static int btf_func_check(struct btf_verifier_env *env,
5098 const struct btf_type *t)
5100 const struct btf_type *proto_type;
5101 const struct btf_param *args;
5102 const struct btf *btf;
5106 proto_type = btf_type_by_id(btf, t->type);
5108 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
5109 btf_verifier_log_type(env, t, "Invalid type_id");
5113 args = (const struct btf_param *)(proto_type + 1);
5114 nr_args = btf_type_vlen(proto_type);
5115 for (i = 0; i < nr_args; i++) {
5116 if (!args[i].name_off && args[i].type) {
5117 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5125 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5126 [BTF_KIND_INT] = &int_ops,
5127 [BTF_KIND_PTR] = &ptr_ops,
5128 [BTF_KIND_ARRAY] = &array_ops,
5129 [BTF_KIND_STRUCT] = &struct_ops,
5130 [BTF_KIND_UNION] = &struct_ops,
5131 [BTF_KIND_ENUM] = &enum_ops,
5132 [BTF_KIND_FWD] = &fwd_ops,
5133 [BTF_KIND_TYPEDEF] = &modifier_ops,
5134 [BTF_KIND_VOLATILE] = &modifier_ops,
5135 [BTF_KIND_CONST] = &modifier_ops,
5136 [BTF_KIND_RESTRICT] = &modifier_ops,
5137 [BTF_KIND_FUNC] = &func_ops,
5138 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5139 [BTF_KIND_VAR] = &var_ops,
5140 [BTF_KIND_DATASEC] = &datasec_ops,
5141 [BTF_KIND_FLOAT] = &float_ops,
5142 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
5143 [BTF_KIND_TYPE_TAG] = &modifier_ops,
5144 [BTF_KIND_ENUM64] = &enum64_ops,
5147 static s32 btf_check_meta(struct btf_verifier_env *env,
5148 const struct btf_type *t,
5151 u32 saved_meta_left = meta_left;
5154 if (meta_left < sizeof(*t)) {
5155 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5156 env->log_type_id, meta_left, sizeof(*t));
5159 meta_left -= sizeof(*t);
5161 if (t->info & ~BTF_INFO_MASK) {
5162 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
5163 env->log_type_id, t->info);
5167 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5168 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5169 btf_verifier_log(env, "[%u] Invalid kind:%u",
5170 env->log_type_id, BTF_INFO_KIND(t->info));
5174 if (!btf_name_offset_valid(env->btf, t->name_off)) {
5175 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5176 env->log_type_id, t->name_off);
5180 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5181 if (var_meta_size < 0)
5182 return var_meta_size;
5184 meta_left -= var_meta_size;
5186 return saved_meta_left - meta_left;
5189 static int btf_check_all_metas(struct btf_verifier_env *env)
5191 struct btf *btf = env->btf;
5192 struct btf_header *hdr;
5196 cur = btf->nohdr_data + hdr->type_off;
5197 end = cur + hdr->type_len;
5199 env->log_type_id = btf->base_btf ? btf->start_id : 1;
5201 struct btf_type *t = cur;
5204 meta_size = btf_check_meta(env, t, end - cur);
5208 btf_add_type(env, t);
5216 static bool btf_resolve_valid(struct btf_verifier_env *env,
5217 const struct btf_type *t,
5220 struct btf *btf = env->btf;
5222 if (!env_type_is_resolved(env, type_id))
5225 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5226 return !btf_resolved_type_id(btf, type_id) &&
5227 !btf_resolved_type_size(btf, type_id);
5229 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5230 return btf_resolved_type_id(btf, type_id) &&
5231 !btf_resolved_type_size(btf, type_id);
5233 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5234 btf_type_is_var(t)) {
5235 t = btf_type_id_resolve(btf, &type_id);
5237 !btf_type_is_modifier(t) &&
5238 !btf_type_is_var(t) &&
5239 !btf_type_is_datasec(t);
5242 if (btf_type_is_array(t)) {
5243 const struct btf_array *array = btf_type_array(t);
5244 const struct btf_type *elem_type;
5245 u32 elem_type_id = array->type;
5248 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5249 return elem_type && !btf_type_is_modifier(elem_type) &&
5250 (array->nelems * elem_size ==
5251 btf_resolved_type_size(btf, type_id));
5257 static int btf_resolve(struct btf_verifier_env *env,
5258 const struct btf_type *t, u32 type_id)
5260 u32 save_log_type_id = env->log_type_id;
5261 const struct resolve_vertex *v;
5264 env->resolve_mode = RESOLVE_TBD;
5265 env_stack_push(env, t, type_id);
5266 while (!err && (v = env_stack_peak(env))) {
5267 env->log_type_id = v->type_id;
5268 err = btf_type_ops(v->t)->resolve(env, v);
5271 env->log_type_id = type_id;
5272 if (err == -E2BIG) {
5273 btf_verifier_log_type(env, t,
5274 "Exceeded max resolving depth:%u",
5276 } else if (err == -EEXIST) {
5277 btf_verifier_log_type(env, t, "Loop detected");
5280 /* Final sanity check */
5281 if (!err && !btf_resolve_valid(env, t, type_id)) {
5282 btf_verifier_log_type(env, t, "Invalid resolve state");
5286 env->log_type_id = save_log_type_id;
5290 static int btf_check_all_types(struct btf_verifier_env *env)
5292 struct btf *btf = env->btf;
5293 const struct btf_type *t;
5297 err = env_resolve_init(env);
5302 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5303 type_id = btf->start_id + i;
5304 t = btf_type_by_id(btf, type_id);
5306 env->log_type_id = type_id;
5307 if (btf_type_needs_resolve(t) &&
5308 !env_type_is_resolved(env, type_id)) {
5309 err = btf_resolve(env, t, type_id);
5314 if (btf_type_is_func_proto(t)) {
5315 err = btf_func_proto_check(env, t);
5324 static int btf_parse_type_sec(struct btf_verifier_env *env)
5326 const struct btf_header *hdr = &env->btf->hdr;
5329 /* Type section must align to 4 bytes */
5330 if (hdr->type_off & (sizeof(u32) - 1)) {
5331 btf_verifier_log(env, "Unaligned type_off");
5335 if (!env->btf->base_btf && !hdr->type_len) {
5336 btf_verifier_log(env, "No type found");
5340 err = btf_check_all_metas(env);
5344 return btf_check_all_types(env);
5347 static int btf_parse_str_sec(struct btf_verifier_env *env)
5349 const struct btf_header *hdr;
5350 struct btf *btf = env->btf;
5351 const char *start, *end;
5354 start = btf->nohdr_data + hdr->str_off;
5355 end = start + hdr->str_len;
5357 if (end != btf->data + btf->data_size) {
5358 btf_verifier_log(env, "String section is not at the end");
5362 btf->strings = start;
5364 if (btf->base_btf && !hdr->str_len)
5366 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5367 btf_verifier_log(env, "Invalid string section");
5370 if (!btf->base_btf && start[0]) {
5371 btf_verifier_log(env, "Invalid string section");
5378 static const size_t btf_sec_info_offset[] = {
5379 offsetof(struct btf_header, type_off),
5380 offsetof(struct btf_header, str_off),
5383 static int btf_sec_info_cmp(const void *a, const void *b)
5385 const struct btf_sec_info *x = a;
5386 const struct btf_sec_info *y = b;
5388 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5391 static int btf_check_sec_info(struct btf_verifier_env *env,
5394 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5395 u32 total, expected_total, i;
5396 const struct btf_header *hdr;
5397 const struct btf *btf;
5402 /* Populate the secs from hdr */
5403 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5404 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5405 btf_sec_info_offset[i]);
5407 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5408 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5410 /* Check for gaps and overlap among sections */
5412 expected_total = btf_data_size - hdr->hdr_len;
5413 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5414 if (expected_total < secs[i].off) {
5415 btf_verifier_log(env, "Invalid section offset");
5418 if (total < secs[i].off) {
5420 btf_verifier_log(env, "Unsupported section found");
5423 if (total > secs[i].off) {
5424 btf_verifier_log(env, "Section overlap found");
5427 if (expected_total - total < secs[i].len) {
5428 btf_verifier_log(env,
5429 "Total section length too long");
5432 total += secs[i].len;
5435 /* There is data other than hdr and known sections */
5436 if (expected_total != total) {
5437 btf_verifier_log(env, "Unsupported section found");
5444 static int btf_parse_hdr(struct btf_verifier_env *env)
5446 u32 hdr_len, hdr_copy, btf_data_size;
5447 const struct btf_header *hdr;
5451 btf_data_size = btf->data_size;
5453 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5454 btf_verifier_log(env, "hdr_len not found");
5459 hdr_len = hdr->hdr_len;
5460 if (btf_data_size < hdr_len) {
5461 btf_verifier_log(env, "btf_header not found");
5465 /* Ensure the unsupported header fields are zero */
5466 if (hdr_len > sizeof(btf->hdr)) {
5467 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5468 u8 *end = btf->data + hdr_len;
5470 for (; expected_zero < end; expected_zero++) {
5471 if (*expected_zero) {
5472 btf_verifier_log(env, "Unsupported btf_header");
5478 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5479 memcpy(&btf->hdr, btf->data, hdr_copy);
5483 btf_verifier_log_hdr(env, btf_data_size);
5485 if (hdr->magic != BTF_MAGIC) {
5486 btf_verifier_log(env, "Invalid magic");
5490 if (hdr->version != BTF_VERSION) {
5491 btf_verifier_log(env, "Unsupported version");
5496 btf_verifier_log(env, "Unsupported flags");
5500 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5501 btf_verifier_log(env, "No data");
5505 return btf_check_sec_info(env, btf_data_size);
5508 static const char *alloc_obj_fields[] = {
5517 static struct btf_struct_metas *
5518 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5521 struct btf_id_set set;
5524 u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5527 struct btf_struct_metas *tab = NULL;
5530 BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5531 BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5533 memset(&aof, 0, sizeof(aof));
5534 for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5535 /* Try to find whether this special type exists in user BTF, and
5536 * if so remember its ID so we can easily find it among members
5537 * of structs that we iterate in the next loop.
5539 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5542 aof.set.ids[aof.set.cnt++] = id;
5547 sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5549 n = btf_nr_types(btf);
5550 for (i = 1; i < n; i++) {
5551 struct btf_struct_metas *new_tab;
5552 const struct btf_member *member;
5553 struct btf_struct_meta *type;
5554 struct btf_record *record;
5555 const struct btf_type *t;
5558 t = btf_type_by_id(btf, i);
5563 if (!__btf_type_is_struct(t))
5568 for_each_member(j, t, member) {
5569 if (btf_id_set_contains(&aof.set, member->type))
5574 tab_cnt = tab ? tab->cnt : 0;
5575 new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5576 GFP_KERNEL | __GFP_NOWARN);
5585 type = &tab->types[tab->cnt];
5587 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5588 BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT, t->size);
5589 /* The record cannot be unset, treat it as an error if so */
5590 if (IS_ERR_OR_NULL(record)) {
5591 ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5594 type->record = record;
5599 btf_struct_metas_free(tab);
5600 return ERR_PTR(ret);
5603 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5605 struct btf_struct_metas *tab;
5607 BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5608 tab = btf->struct_meta_tab;
5611 return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5614 static int btf_check_type_tags(struct btf_verifier_env *env,
5615 struct btf *btf, int start_id)
5617 int i, n, good_id = start_id - 1;
5620 n = btf_nr_types(btf);
5621 for (i = start_id; i < n; i++) {
5622 const struct btf_type *t;
5623 int chain_limit = 32;
5626 t = btf_type_by_id(btf, i);
5629 if (!btf_type_is_modifier(t))
5634 in_tags = btf_type_is_type_tag(t);
5635 while (btf_type_is_modifier(t)) {
5636 if (!chain_limit--) {
5637 btf_verifier_log(env, "Max chain length or cycle detected");
5640 if (btf_type_is_type_tag(t)) {
5642 btf_verifier_log(env, "Type tags don't precede modifiers");
5645 } else if (in_tags) {
5648 if (cur_id <= good_id)
5650 /* Move to next type */
5652 t = btf_type_by_id(btf, cur_id);
5661 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5666 err = bpf_vlog_finalize(log, &log_true_size);
5668 if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5669 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5670 &log_true_size, sizeof(log_true_size)))
5676 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5678 bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5679 char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5680 struct btf_struct_metas *struct_meta_tab;
5681 struct btf_verifier_env *env = NULL;
5682 struct btf *btf = NULL;
5686 if (attr->btf_size > BTF_MAX_SIZE)
5687 return ERR_PTR(-E2BIG);
5689 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5691 return ERR_PTR(-ENOMEM);
5693 /* user could have requested verbose verifier output
5694 * and supplied buffer to store the verification trace
5696 err = bpf_vlog_init(&env->log, attr->btf_log_level,
5697 log_ubuf, attr->btf_log_size);
5701 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5708 data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5715 btf->data_size = attr->btf_size;
5717 if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5722 err = btf_parse_hdr(env);
5726 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5728 err = btf_parse_str_sec(env);
5732 err = btf_parse_type_sec(env);
5736 err = btf_check_type_tags(env, btf, 1);
5740 struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5741 if (IS_ERR(struct_meta_tab)) {
5742 err = PTR_ERR(struct_meta_tab);
5745 btf->struct_meta_tab = struct_meta_tab;
5747 if (struct_meta_tab) {
5750 for (i = 0; i < struct_meta_tab->cnt; i++) {
5751 err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5757 err = finalize_log(&env->log, uattr, uattr_size);
5761 btf_verifier_env_free(env);
5762 refcount_set(&btf->refcnt, 1);
5766 btf_free_struct_meta_tab(btf);
5768 /* overwrite err with -ENOSPC or -EFAULT */
5769 ret = finalize_log(&env->log, uattr, uattr_size);
5773 btf_verifier_env_free(env);
5776 return ERR_PTR(err);
5779 extern char __start_BTF[];
5780 extern char __stop_BTF[];
5781 extern struct btf *btf_vmlinux;
5783 #define BPF_MAP_TYPE(_id, _ops)
5784 #define BPF_LINK_TYPE(_id, _name)
5786 struct bpf_ctx_convert {
5787 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5788 prog_ctx_type _id##_prog; \
5789 kern_ctx_type _id##_kern;
5790 #include <linux/bpf_types.h>
5791 #undef BPF_PROG_TYPE
5793 /* 't' is written once under lock. Read many times. */
5794 const struct btf_type *t;
5797 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5799 #include <linux/bpf_types.h>
5800 #undef BPF_PROG_TYPE
5801 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5803 static u8 bpf_ctx_convert_map[] = {
5804 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5805 [_id] = __ctx_convert##_id,
5806 #include <linux/bpf_types.h>
5807 #undef BPF_PROG_TYPE
5808 0, /* avoid empty array */
5811 #undef BPF_LINK_TYPE
5813 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
5815 const struct btf_type *conv_struct;
5816 const struct btf_member *ctx_type;
5818 conv_struct = bpf_ctx_convert.t;
5821 /* prog_type is valid bpf program type. No need for bounds check. */
5822 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5823 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5824 * Like 'struct __sk_buff'
5826 return btf_type_by_id(btf_vmlinux, ctx_type->type);
5829 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
5831 const struct btf_type *conv_struct;
5832 const struct btf_member *ctx_type;
5834 conv_struct = bpf_ctx_convert.t;
5837 /* prog_type is valid bpf program type. No need for bounds check. */
5838 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5839 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5840 * Like 'struct sk_buff'
5842 return ctx_type->type;
5845 bool btf_is_projection_of(const char *pname, const char *tname)
5847 if (strcmp(pname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5849 if (strcmp(pname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5854 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5855 const struct btf_type *t, enum bpf_prog_type prog_type,
5858 const struct btf_type *ctx_type;
5859 const char *tname, *ctx_tname;
5861 t = btf_type_by_id(btf, t->type);
5863 /* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
5864 * check before we skip all the typedef below.
5866 if (prog_type == BPF_PROG_TYPE_KPROBE) {
5867 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5868 t = btf_type_by_id(btf, t->type);
5870 if (btf_type_is_typedef(t)) {
5871 tname = btf_name_by_offset(btf, t->name_off);
5872 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5877 while (btf_type_is_modifier(t))
5878 t = btf_type_by_id(btf, t->type);
5879 if (!btf_type_is_struct(t)) {
5880 /* Only pointer to struct is supported for now.
5881 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5882 * is not supported yet.
5883 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5887 tname = btf_name_by_offset(btf, t->name_off);
5889 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5893 ctx_type = find_canonical_prog_ctx_type(prog_type);
5895 bpf_log(log, "btf_vmlinux is malformed\n");
5896 /* should not happen */
5900 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5902 /* should not happen */
5903 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5906 /* program types without named context types work only with arg:ctx tag */
5907 if (ctx_tname[0] == '\0')
5909 /* only compare that prog's ctx type name is the same as
5910 * kernel expects. No need to compare field by field.
5911 * It's ok for bpf prog to do:
5912 * struct __sk_buff {};
5913 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5914 * { // no fields of skb are ever used }
5916 if (btf_is_projection_of(ctx_tname, tname))
5918 if (strcmp(ctx_tname, tname)) {
5919 /* bpf_user_pt_regs_t is a typedef, so resolve it to
5920 * underlying struct and check name again
5922 if (!btf_type_is_modifier(ctx_type))
5924 while (btf_type_is_modifier(ctx_type))
5925 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
5931 /* forward declarations for arch-specific underlying types of
5932 * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
5933 * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
5934 * works correctly with __builtin_types_compatible_p() on respective
5937 struct user_regs_struct;
5938 struct user_pt_regs;
5940 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5941 const struct btf_type *t, int arg,
5942 enum bpf_prog_type prog_type,
5943 enum bpf_attach_type attach_type)
5945 const struct btf_type *ctx_type;
5946 const char *tname, *ctx_tname;
5948 if (!btf_is_ptr(t)) {
5949 bpf_log(log, "arg#%d type isn't a pointer\n", arg);
5952 t = btf_type_by_id(btf, t->type);
5954 /* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
5955 if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
5956 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5957 t = btf_type_by_id(btf, t->type);
5959 if (btf_type_is_typedef(t)) {
5960 tname = btf_name_by_offset(btf, t->name_off);
5961 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5966 /* all other program types don't use typedefs for context type */
5967 while (btf_type_is_modifier(t))
5968 t = btf_type_by_id(btf, t->type);
5970 /* `void *ctx __arg_ctx` is always valid */
5971 if (btf_type_is_void(t))
5974 tname = btf_name_by_offset(btf, t->name_off);
5975 if (str_is_empty(tname)) {
5976 bpf_log(log, "arg#%d type doesn't have a name\n", arg);
5981 switch (prog_type) {
5982 case BPF_PROG_TYPE_KPROBE:
5983 if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5986 case BPF_PROG_TYPE_PERF_EVENT:
5987 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
5988 __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5990 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
5991 __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
5993 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
5994 __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
5997 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5998 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
5999 /* allow u64* as ctx */
6000 if (btf_is_int(t) && t->size == 8)
6003 case BPF_PROG_TYPE_TRACING:
6004 switch (attach_type) {
6005 case BPF_TRACE_RAW_TP:
6006 /* tp_btf program is TRACING, so need special case here */
6007 if (__btf_type_is_struct(t) &&
6008 strcmp(tname, "bpf_raw_tracepoint_args") == 0)
6010 /* allow u64* as ctx */
6011 if (btf_is_int(t) && t->size == 8)
6014 case BPF_TRACE_ITER:
6015 /* allow struct bpf_iter__xxx types only */
6016 if (__btf_type_is_struct(t) &&
6017 strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
6020 case BPF_TRACE_FENTRY:
6021 case BPF_TRACE_FEXIT:
6022 case BPF_MODIFY_RETURN:
6023 /* allow u64* as ctx */
6024 if (btf_is_int(t) && t->size == 8)
6031 case BPF_PROG_TYPE_LSM:
6032 case BPF_PROG_TYPE_STRUCT_OPS:
6033 /* allow u64* as ctx */
6034 if (btf_is_int(t) && t->size == 8)
6037 case BPF_PROG_TYPE_TRACEPOINT:
6038 case BPF_PROG_TYPE_SYSCALL:
6039 case BPF_PROG_TYPE_EXT:
6040 return 0; /* anything goes */
6045 ctx_type = find_canonical_prog_ctx_type(prog_type);
6047 /* should not happen */
6048 bpf_log(log, "btf_vmlinux is malformed\n");
6052 /* resolve typedefs and check that underlying structs are matching as well */
6053 while (btf_type_is_modifier(ctx_type))
6054 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6056 /* if program type doesn't have distinctly named struct type for
6057 * context, then __arg_ctx argument can only be `void *`, which we
6058 * already checked above
6060 if (!__btf_type_is_struct(ctx_type)) {
6061 bpf_log(log, "arg#%d should be void pointer\n", arg);
6065 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6066 if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6067 bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6074 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6076 const struct btf_type *t,
6077 enum bpf_prog_type prog_type,
6080 if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6082 return find_kern_ctx_type_id(prog_type);
6085 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6087 const struct btf_member *kctx_member;
6088 const struct btf_type *conv_struct;
6089 const struct btf_type *kctx_type;
6092 conv_struct = bpf_ctx_convert.t;
6093 /* get member for kernel ctx type */
6094 kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6095 kctx_type_id = kctx_member->type;
6096 kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6097 if (!btf_type_is_struct(kctx_type)) {
6098 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6102 return kctx_type_id;
6105 BTF_ID_LIST(bpf_ctx_convert_btf_id)
6106 BTF_ID(struct, bpf_ctx_convert)
6108 static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,
6109 void *data, unsigned int data_size)
6111 struct btf *btf = NULL;
6114 if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6115 return ERR_PTR(-ENOENT);
6117 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6125 btf->data_size = data_size;
6126 btf->kernel_btf = true;
6127 snprintf(btf->name, sizeof(btf->name), "%s", name);
6129 err = btf_parse_hdr(env);
6133 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6135 err = btf_parse_str_sec(env);
6139 err = btf_check_all_metas(env);
6143 err = btf_check_type_tags(env, btf, 1);
6147 refcount_set(&btf->refcnt, 1);
6156 return ERR_PTR(err);
6159 struct btf *btf_parse_vmlinux(void)
6161 struct btf_verifier_env *env = NULL;
6162 struct bpf_verifier_log *log;
6166 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6168 return ERR_PTR(-ENOMEM);
6171 log->level = BPF_LOG_KERNEL;
6172 btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
6176 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
6177 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6178 err = btf_alloc_id(btf);
6184 btf_verifier_env_free(env);
6188 /* If .BTF_ids section was created with distilled base BTF, both base and
6189 * split BTF ids will need to be mapped to actual base/split ids for
6190 * BTF now that it has been relocated.
6192 static __u32 btf_relocate_id(const struct btf *btf, __u32 id)
6194 if (!btf->base_btf || !btf->base_id_map)
6196 return btf->base_id_map[id];
6199 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6201 static struct btf *btf_parse_module(const char *module_name, const void *data,
6202 unsigned int data_size, void *base_data,
6203 unsigned int base_data_size)
6205 struct btf *btf = NULL, *vmlinux_btf, *base_btf = NULL;
6206 struct btf_verifier_env *env = NULL;
6207 struct bpf_verifier_log *log;
6210 vmlinux_btf = bpf_get_btf_vmlinux();
6211 if (IS_ERR(vmlinux_btf))
6214 return ERR_PTR(-EINVAL);
6216 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6218 return ERR_PTR(-ENOMEM);
6221 log->level = BPF_LOG_KERNEL;
6224 base_btf = btf_parse_base(env, ".BTF.base", base_data, base_data_size);
6225 if (IS_ERR(base_btf)) {
6226 err = PTR_ERR(base_btf);
6230 base_btf = vmlinux_btf;
6233 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6240 btf->base_btf = base_btf;
6241 btf->start_id = base_btf->nr_types;
6242 btf->start_str_off = base_btf->hdr.str_len;
6243 btf->kernel_btf = true;
6244 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
6246 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
6251 memcpy(btf->data, data, data_size);
6252 btf->data_size = data_size;
6254 err = btf_parse_hdr(env);
6258 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6260 err = btf_parse_str_sec(env);
6264 err = btf_check_all_metas(env);
6268 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6272 if (base_btf != vmlinux_btf) {
6273 err = btf_relocate(btf, vmlinux_btf, &btf->base_id_map);
6277 base_btf = vmlinux_btf;
6280 btf_verifier_env_free(env);
6281 refcount_set(&btf->refcnt, 1);
6285 btf_verifier_env_free(env);
6286 if (base_btf != vmlinux_btf)
6293 return ERR_PTR(err);
6296 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6298 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6300 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6303 return tgt_prog->aux->btf;
6305 return prog->aux->attach_btf;
6308 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
6310 /* skip modifiers */
6311 t = btf_type_skip_modifiers(btf, t->type, NULL);
6313 return btf_type_is_int(t);
6316 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6319 const struct btf_param *args;
6320 const struct btf_type *t;
6321 u32 offset = 0, nr_args;
6327 nr_args = btf_type_vlen(func_proto);
6328 args = (const struct btf_param *)(func_proto + 1);
6329 for (i = 0; i < nr_args; i++) {
6330 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6331 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6336 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6337 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6344 static bool prog_args_trusted(const struct bpf_prog *prog)
6346 enum bpf_attach_type atype = prog->expected_attach_type;
6348 switch (prog->type) {
6349 case BPF_PROG_TYPE_TRACING:
6350 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
6351 case BPF_PROG_TYPE_LSM:
6352 return bpf_lsm_is_trusted(prog);
6353 case BPF_PROG_TYPE_STRUCT_OPS:
6360 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6363 const struct btf_param *args;
6364 const struct btf_type *t;
6368 args = btf_params(func_proto);
6369 for (i = 0; i < arg_no; i++) {
6370 t = btf_type_by_id(btf, args[i].type);
6371 t = btf_resolve_size(btf, t, &sz);
6374 off += roundup(sz, 8);
6380 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
6381 const struct bpf_prog *prog,
6382 struct bpf_insn_access_aux *info)
6384 const struct btf_type *t = prog->aux->attach_func_proto;
6385 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6386 struct btf *btf = bpf_prog_get_target_btf(prog);
6387 const char *tname = prog->aux->attach_func_name;
6388 struct bpf_verifier_log *log = info->log;
6389 const struct btf_param *args;
6390 const char *tag_value;
6395 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6399 arg = get_ctx_arg_idx(btf, t, off);
6400 args = (const struct btf_param *)(t + 1);
6401 /* if (t == NULL) Fall back to default BPF prog with
6402 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
6404 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
6405 if (prog->aux->attach_btf_trace) {
6406 /* skip first 'void *__data' argument in btf_trace_##name typedef */
6411 if (arg > nr_args) {
6412 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6417 if (arg == nr_args) {
6418 switch (prog->expected_attach_type) {
6419 case BPF_LSM_CGROUP:
6421 case BPF_TRACE_FEXIT:
6422 /* When LSM programs are attached to void LSM hooks
6423 * they use FEXIT trampolines and when attached to
6424 * int LSM hooks, they use MODIFY_RETURN trampolines.
6426 * While the LSM programs are BPF_MODIFY_RETURN-like
6429 * if (ret_type != 'int')
6432 * is _not_ done here. This is still safe as LSM hooks
6433 * have only void and int return types.
6437 t = btf_type_by_id(btf, t->type);
6439 case BPF_MODIFY_RETURN:
6440 /* For now the BPF_MODIFY_RETURN can only be attached to
6441 * functions that return an int.
6446 t = btf_type_skip_modifiers(btf, t->type, NULL);
6447 if (!btf_type_is_small_int(t)) {
6449 "ret type %s not allowed for fmod_ret\n",
6455 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6461 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6463 t = btf_type_by_id(btf, args[arg].type);
6466 /* skip modifiers */
6467 while (btf_type_is_modifier(t))
6468 t = btf_type_by_id(btf, t->type);
6469 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6470 /* accessing a scalar */
6472 if (!btf_type_is_ptr(t)) {
6474 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6476 __btf_name_by_offset(btf, t->name_off),
6481 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6482 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6483 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6486 type = base_type(ctx_arg_info->reg_type);
6487 flag = type_flag(ctx_arg_info->reg_type);
6488 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6489 (flag & PTR_MAYBE_NULL)) {
6490 info->reg_type = ctx_arg_info->reg_type;
6496 /* This is a pointer to void.
6497 * It is the same as scalar from the verifier safety pov.
6498 * No further pointer walking is allowed.
6502 if (is_int_ptr(btf, t))
6505 /* this is a pointer to another type */
6506 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6507 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6509 if (ctx_arg_info->offset == off) {
6510 if (!ctx_arg_info->btf_id) {
6511 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6515 info->reg_type = ctx_arg_info->reg_type;
6516 info->btf = ctx_arg_info->btf ? : btf_vmlinux;
6517 info->btf_id = ctx_arg_info->btf_id;
6522 info->reg_type = PTR_TO_BTF_ID;
6523 if (prog_args_trusted(prog))
6524 info->reg_type |= PTR_TRUSTED;
6527 enum bpf_prog_type tgt_type;
6529 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6530 tgt_type = tgt_prog->aux->saved_dst_prog_type;
6532 tgt_type = tgt_prog->type;
6534 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6536 info->btf = btf_vmlinux;
6545 info->btf_id = t->type;
6546 t = btf_type_by_id(btf, t->type);
6548 if (btf_type_is_type_tag(t)) {
6549 tag_value = __btf_name_by_offset(btf, t->name_off);
6550 if (strcmp(tag_value, "user") == 0)
6551 info->reg_type |= MEM_USER;
6552 if (strcmp(tag_value, "percpu") == 0)
6553 info->reg_type |= MEM_PERCPU;
6556 /* skip modifiers */
6557 while (btf_type_is_modifier(t)) {
6558 info->btf_id = t->type;
6559 t = btf_type_by_id(btf, t->type);
6561 if (!btf_type_is_struct(t)) {
6563 "func '%s' arg%d type %s is not a struct\n",
6564 tname, arg, btf_type_str(t));
6567 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6568 tname, arg, info->btf_id, btf_type_str(t),
6569 __btf_name_by_offset(btf, t->name_off));
6572 EXPORT_SYMBOL_GPL(btf_ctx_access);
6574 enum bpf_struct_walk_result {
6581 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6582 const struct btf_type *t, int off, int size,
6583 u32 *next_btf_id, enum bpf_type_flag *flag,
6584 const char **field_name)
6586 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6587 const struct btf_type *mtype, *elem_type = NULL;
6588 const struct btf_member *member;
6589 const char *tname, *mname, *tag_value;
6590 u32 vlen, elem_id, mid;
6593 if (btf_type_is_modifier(t))
6594 t = btf_type_skip_modifiers(btf, t->type, NULL);
6595 tname = __btf_name_by_offset(btf, t->name_off);
6596 if (!btf_type_is_struct(t)) {
6597 bpf_log(log, "Type '%s' is not a struct\n", tname);
6601 vlen = btf_type_vlen(t);
6602 if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
6604 * walking unions yields untrusted pointers
6605 * with exception of __bpf_md_ptr and other
6606 * unions with a single member
6608 *flag |= PTR_UNTRUSTED;
6610 if (off + size > t->size) {
6611 /* If the last element is a variable size array, we may
6612 * need to relax the rule.
6614 struct btf_array *array_elem;
6619 member = btf_type_member(t) + vlen - 1;
6620 mtype = btf_type_skip_modifiers(btf, member->type,
6622 if (!btf_type_is_array(mtype))
6625 array_elem = (struct btf_array *)(mtype + 1);
6626 if (array_elem->nelems != 0)
6629 moff = __btf_member_bit_offset(t, member) / 8;
6633 /* allow structure and integer */
6634 t = btf_type_skip_modifiers(btf, array_elem->type,
6637 if (btf_type_is_int(t))
6640 if (!btf_type_is_struct(t))
6643 off = (off - moff) % t->size;
6647 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6652 for_each_member(i, t, member) {
6653 /* offset of the field in bytes */
6654 moff = __btf_member_bit_offset(t, member) / 8;
6655 if (off + size <= moff)
6656 /* won't find anything, field is already too far */
6659 if (__btf_member_bitfield_size(t, member)) {
6660 u32 end_bit = __btf_member_bit_offset(t, member) +
6661 __btf_member_bitfield_size(t, member);
6663 /* off <= moff instead of off == moff because clang
6664 * does not generate a BTF member for anonymous
6665 * bitfield like the ":16" here:
6672 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6675 /* off may be accessing a following member
6679 * Doing partial access at either end of this
6680 * bitfield. Continue on this case also to
6681 * treat it as not accessing this bitfield
6682 * and eventually error out as field not
6683 * found to keep it simple.
6684 * It could be relaxed if there was a legit
6685 * partial access case later.
6690 /* In case of "off" is pointing to holes of a struct */
6694 /* type of the field */
6696 mtype = btf_type_by_id(btf, member->type);
6697 mname = __btf_name_by_offset(btf, member->name_off);
6699 mtype = __btf_resolve_size(btf, mtype, &msize,
6700 &elem_type, &elem_id, &total_nelems,
6702 if (IS_ERR(mtype)) {
6703 bpf_log(log, "field %s doesn't have size\n", mname);
6707 mtrue_end = moff + msize;
6708 if (off >= mtrue_end)
6709 /* no overlap with member, keep iterating */
6712 if (btf_type_is_array(mtype)) {
6715 /* __btf_resolve_size() above helps to
6716 * linearize a multi-dimensional array.
6718 * The logic here is treating an array
6719 * in a struct as the following way:
6722 * struct inner array[2][2];
6728 * struct inner array_elem0;
6729 * struct inner array_elem1;
6730 * struct inner array_elem2;
6731 * struct inner array_elem3;
6734 * When accessing outer->array[1][0], it moves
6735 * moff to "array_elem2", set mtype to
6736 * "struct inner", and msize also becomes
6737 * sizeof(struct inner). Then most of the
6738 * remaining logic will fall through without
6739 * caring the current member is an array or
6742 * Unlike mtype/msize/moff, mtrue_end does not
6743 * change. The naming difference ("_true") tells
6744 * that it is not always corresponding to
6745 * the current mtype/msize/moff.
6746 * It is the true end of the current
6747 * member (i.e. array in this case). That
6748 * will allow an int array to be accessed like
6750 * i.e. allow access beyond the size of
6751 * the array's element as long as it is
6752 * within the mtrue_end boundary.
6755 /* skip empty array */
6756 if (moff == mtrue_end)
6759 msize /= total_nelems;
6760 elem_idx = (off - moff) / msize;
6761 moff += elem_idx * msize;
6766 /* the 'off' we're looking for is either equal to start
6767 * of this field or inside of this struct
6769 if (btf_type_is_struct(mtype)) {
6770 /* our field must be inside that union or struct */
6773 /* return if the offset matches the member offset */
6779 /* adjust offset we're looking for */
6784 if (btf_type_is_ptr(mtype)) {
6785 const struct btf_type *stype, *t;
6786 enum bpf_type_flag tmp_flag = 0;
6789 if (msize != size || off != moff) {
6791 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6792 mname, moff, tname, off, size);
6796 /* check type tag */
6797 t = btf_type_by_id(btf, mtype->type);
6798 if (btf_type_is_type_tag(t)) {
6799 tag_value = __btf_name_by_offset(btf, t->name_off);
6800 /* check __user tag */
6801 if (strcmp(tag_value, "user") == 0)
6802 tmp_flag = MEM_USER;
6803 /* check __percpu tag */
6804 if (strcmp(tag_value, "percpu") == 0)
6805 tmp_flag = MEM_PERCPU;
6806 /* check __rcu tag */
6807 if (strcmp(tag_value, "rcu") == 0)
6811 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6812 if (btf_type_is_struct(stype)) {
6816 *field_name = mname;
6821 /* Allow more flexible access within an int as long as
6822 * it is within mtrue_end.
6823 * Since mtrue_end could be the end of an array,
6824 * that also allows using an array of int as a scratch
6825 * space. e.g. skb->cb[].
6827 if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
6829 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6830 mname, mtrue_end, tname, off, size);
6836 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6840 int btf_struct_access(struct bpf_verifier_log *log,
6841 const struct bpf_reg_state *reg,
6842 int off, int size, enum bpf_access_type atype __maybe_unused,
6843 u32 *next_btf_id, enum bpf_type_flag *flag,
6844 const char **field_name)
6846 const struct btf *btf = reg->btf;
6847 enum bpf_type_flag tmp_flag = 0;
6848 const struct btf_type *t;
6849 u32 id = reg->btf_id;
6852 while (type_is_alloc(reg->type)) {
6853 struct btf_struct_meta *meta;
6854 struct btf_record *rec;
6857 meta = btf_find_struct_meta(btf, id);
6861 for (i = 0; i < rec->cnt; i++) {
6862 struct btf_field *field = &rec->fields[i];
6863 u32 offset = field->offset;
6864 if (off < offset + field->size && offset < off + size) {
6866 "direct access to %s is disallowed\n",
6867 btf_field_type_name(field->type));
6874 t = btf_type_by_id(btf, id);
6876 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6880 /* For local types, the destination register cannot
6881 * become a pointer again.
6883 if (type_is_alloc(reg->type))
6884 return SCALAR_VALUE;
6885 /* If we found the pointer or scalar on t+off,
6890 return PTR_TO_BTF_ID;
6892 return SCALAR_VALUE;
6894 /* We found nested struct, so continue the search
6895 * by diving in it. At this point the offset is
6896 * aligned with the new type, so set it to 0.
6898 t = btf_type_by_id(btf, id);
6902 /* It's either error or unknown return value..
6905 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6914 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6915 * the same. Trivial ID check is not enough due to module BTFs, because we can
6916 * end up with two different module BTFs, but IDs point to the common type in
6919 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6920 const struct btf *btf2, u32 id2)
6926 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6929 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6930 const struct btf *btf, u32 id, int off,
6931 const struct btf *need_btf, u32 need_type_id,
6934 const struct btf_type *type;
6935 enum bpf_type_flag flag = 0;
6938 /* Are we already done? */
6939 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6941 /* In case of strict type match, we do not walk struct, the top level
6942 * type match must succeed. When strict is true, off should have already
6948 type = btf_type_by_id(btf, id);
6951 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6952 if (err != WALK_STRUCT)
6955 /* We found nested struct object. If it matches
6956 * the requested ID, we're done. Otherwise let's
6957 * continue the search with offset 0 in the new
6960 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6968 static int __get_type_size(struct btf *btf, u32 btf_id,
6969 const struct btf_type **ret_type)
6971 const struct btf_type *t;
6973 *ret_type = btf_type_by_id(btf, 0);
6977 t = btf_type_by_id(btf, btf_id);
6978 while (t && btf_type_is_modifier(t))
6979 t = btf_type_by_id(btf, t->type);
6983 if (btf_type_is_ptr(t))
6984 /* kernel size of pointer. Not BPF's size of pointer*/
6985 return sizeof(void *);
6986 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6991 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6995 if (__btf_type_is_struct(t))
6996 flags |= BTF_FMODEL_STRUCT_ARG;
6997 if (btf_type_is_signed_int(t))
6998 flags |= BTF_FMODEL_SIGNED_ARG;
7003 int btf_distill_func_proto(struct bpf_verifier_log *log,
7005 const struct btf_type *func,
7007 struct btf_func_model *m)
7009 const struct btf_param *args;
7010 const struct btf_type *t;
7015 /* BTF function prototype doesn't match the verifier types.
7016 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
7018 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7020 m->arg_flags[i] = 0;
7024 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
7027 args = (const struct btf_param *)(func + 1);
7028 nargs = btf_type_vlen(func);
7029 if (nargs > MAX_BPF_FUNC_ARGS) {
7031 "The function %s has %d arguments. Too many.\n",
7035 ret = __get_type_size(btf, func->type, &t);
7036 if (ret < 0 || __btf_type_is_struct(t)) {
7038 "The function %s return type %s is unsupported.\n",
7039 tname, btf_type_str(t));
7043 m->ret_flags = __get_type_fmodel_flags(t);
7045 for (i = 0; i < nargs; i++) {
7046 if (i == nargs - 1 && args[i].type == 0) {
7048 "The function %s with variable args is unsupported.\n",
7052 ret = __get_type_size(btf, args[i].type, &t);
7054 /* No support of struct argument size greater than 16 bytes */
7055 if (ret < 0 || ret > 16) {
7057 "The function %s arg%d type %s is unsupported.\n",
7058 tname, i, btf_type_str(t));
7063 "The function %s has malformed void argument.\n",
7067 m->arg_size[i] = ret;
7068 m->arg_flags[i] = __get_type_fmodel_flags(t);
7074 /* Compare BTFs of two functions assuming only scalars and pointers to context.
7075 * t1 points to BTF_KIND_FUNC in btf1
7076 * t2 points to BTF_KIND_FUNC in btf2
7078 * EINVAL - function prototype mismatch
7079 * EFAULT - verifier bug
7080 * 0 - 99% match. The last 1% is validated by the verifier.
7082 static int btf_check_func_type_match(struct bpf_verifier_log *log,
7083 struct btf *btf1, const struct btf_type *t1,
7084 struct btf *btf2, const struct btf_type *t2)
7086 const struct btf_param *args1, *args2;
7087 const char *fn1, *fn2, *s1, *s2;
7088 u32 nargs1, nargs2, i;
7090 fn1 = btf_name_by_offset(btf1, t1->name_off);
7091 fn2 = btf_name_by_offset(btf2, t2->name_off);
7093 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
7094 bpf_log(log, "%s() is not a global function\n", fn1);
7097 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
7098 bpf_log(log, "%s() is not a global function\n", fn2);
7102 t1 = btf_type_by_id(btf1, t1->type);
7103 if (!t1 || !btf_type_is_func_proto(t1))
7105 t2 = btf_type_by_id(btf2, t2->type);
7106 if (!t2 || !btf_type_is_func_proto(t2))
7109 args1 = (const struct btf_param *)(t1 + 1);
7110 nargs1 = btf_type_vlen(t1);
7111 args2 = (const struct btf_param *)(t2 + 1);
7112 nargs2 = btf_type_vlen(t2);
7114 if (nargs1 != nargs2) {
7115 bpf_log(log, "%s() has %d args while %s() has %d args\n",
7116 fn1, nargs1, fn2, nargs2);
7120 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7121 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7122 if (t1->info != t2->info) {
7124 "Return type %s of %s() doesn't match type %s of %s()\n",
7125 btf_type_str(t1), fn1,
7126 btf_type_str(t2), fn2);
7130 for (i = 0; i < nargs1; i++) {
7131 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
7132 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
7134 if (t1->info != t2->info) {
7135 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
7136 i, fn1, btf_type_str(t1),
7137 fn2, btf_type_str(t2));
7140 if (btf_type_has_size(t1) && t1->size != t2->size) {
7142 "arg%d in %s() has size %d while %s() has %d\n",
7148 /* global functions are validated with scalars and pointers
7149 * to context only. And only global functions can be replaced.
7150 * Hence type check only those types.
7152 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
7154 if (!btf_type_is_ptr(t1)) {
7156 "arg%d in %s() has unrecognized type\n",
7160 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7161 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7162 if (!btf_type_is_struct(t1)) {
7164 "arg%d in %s() is not a pointer to context\n",
7168 if (!btf_type_is_struct(t2)) {
7170 "arg%d in %s() is not a pointer to context\n",
7174 /* This is an optional check to make program writing easier.
7175 * Compare names of structs and report an error to the user.
7176 * btf_prepare_func_args() already checked that t2 struct
7177 * is a context type. btf_prepare_func_args() will check
7178 * later that t1 struct is a context type as well.
7180 s1 = btf_name_by_offset(btf1, t1->name_off);
7181 s2 = btf_name_by_offset(btf2, t2->name_off);
7182 if (strcmp(s1, s2)) {
7184 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7185 i, fn1, s1, fn2, s2);
7192 /* Compare BTFs of given program with BTF of target program */
7193 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
7194 struct btf *btf2, const struct btf_type *t2)
7196 struct btf *btf1 = prog->aux->btf;
7197 const struct btf_type *t1;
7200 if (!prog->aux->func_info) {
7201 bpf_log(log, "Program extension requires BTF\n");
7205 btf_id = prog->aux->func_info[0].type_id;
7209 t1 = btf_type_by_id(btf1, btf_id);
7210 if (!t1 || !btf_type_is_func(t1))
7213 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7216 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7220 t = btf_type_by_id(btf, t->type); /* skip PTR */
7222 while (btf_type_is_modifier(t))
7223 t = btf_type_by_id(btf, t->type);
7225 /* allow either struct or struct forward declaration */
7226 if (btf_type_is_struct(t) ||
7227 (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
7228 name = btf_str_by_offset(btf, t->name_off);
7229 return name && strcmp(name, "bpf_dynptr") == 0;
7235 struct bpf_cand_cache {
7241 const struct btf *btf;
7246 static DEFINE_MUTEX(cand_cache_mutex);
7248 static struct bpf_cand_cache *
7249 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7251 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
7252 const struct btf *btf, const struct btf_type *t)
7254 struct bpf_cand_cache *cc;
7255 struct bpf_core_ctx ctx = {
7259 u32 kern_type_id, type_id;
7262 /* skip PTR and modifiers */
7264 t = btf_type_by_id(btf, t->type);
7265 while (btf_type_is_modifier(t)) {
7267 t = btf_type_by_id(btf, t->type);
7270 mutex_lock(&cand_cache_mutex);
7271 cc = bpf_core_find_cands(&ctx, type_id);
7274 bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
7275 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7277 goto cand_cache_unlock;
7280 bpf_log(log, "arg#%d reference type('%s %s') %s\n",
7281 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7282 cc->cnt == 0 ? "has no matches" : "is ambiguous");
7283 err = cc->cnt == 0 ? -ENOENT : -ESRCH;
7284 goto cand_cache_unlock;
7286 if (btf_is_module(cc->cands[0].btf)) {
7287 bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
7288 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
7290 goto cand_cache_unlock;
7292 kern_type_id = cc->cands[0].id;
7295 mutex_unlock(&cand_cache_mutex);
7299 return kern_type_id;
7303 ARG_TAG_CTX = BIT_ULL(0),
7304 ARG_TAG_NONNULL = BIT_ULL(1),
7305 ARG_TAG_TRUSTED = BIT_ULL(2),
7306 ARG_TAG_NULLABLE = BIT_ULL(3),
7307 ARG_TAG_ARENA = BIT_ULL(4),
7310 /* Process BTF of a function to produce high-level expectation of function
7311 * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
7312 * is cached in subprog info for reuse.
7314 * EFAULT - there is a verifier bug. Abort verification.
7315 * EINVAL - cannot convert BTF.
7316 * 0 - Successfully processed BTF and constructed argument expectations.
7318 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7320 bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
7321 struct bpf_subprog_info *sub = subprog_info(env, subprog);
7322 struct bpf_verifier_log *log = &env->log;
7323 struct bpf_prog *prog = env->prog;
7324 enum bpf_prog_type prog_type = prog->type;
7325 struct btf *btf = prog->aux->btf;
7326 const struct btf_param *args;
7327 const struct btf_type *t, *ref_t, *fn_t;
7328 u32 i, nargs, btf_id;
7331 if (sub->args_cached)
7334 if (!prog->aux->func_info) {
7335 bpf_log(log, "Verifier bug\n");
7339 btf_id = prog->aux->func_info[subprog].type_id;
7341 if (!is_global) /* not fatal for static funcs */
7343 bpf_log(log, "Global functions need valid BTF\n");
7347 fn_t = btf_type_by_id(btf, btf_id);
7348 if (!fn_t || !btf_type_is_func(fn_t)) {
7349 /* These checks were already done by the verifier while loading
7350 * struct bpf_func_info
7352 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7356 tname = btf_name_by_offset(btf, fn_t->name_off);
7358 if (prog->aux->func_info_aux[subprog].unreliable) {
7359 bpf_log(log, "Verifier bug in function %s()\n", tname);
7362 if (prog_type == BPF_PROG_TYPE_EXT)
7363 prog_type = prog->aux->dst_prog->type;
7365 t = btf_type_by_id(btf, fn_t->type);
7366 if (!t || !btf_type_is_func_proto(t)) {
7367 bpf_log(log, "Invalid type of function %s()\n", tname);
7370 args = (const struct btf_param *)(t + 1);
7371 nargs = btf_type_vlen(t);
7372 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7375 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7376 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7379 /* check that function returns int, exception cb also requires this */
7380 t = btf_type_by_id(btf, t->type);
7381 while (btf_type_is_modifier(t))
7382 t = btf_type_by_id(btf, t->type);
7383 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7387 "Global function %s() doesn't return scalar. Only those are supported.\n",
7391 /* Convert BTF function arguments into verifier types.
7392 * Only PTR_TO_CTX and SCALAR are supported atm.
7394 for (i = 0; i < nargs; i++) {
7398 /* 'arg:<tag>' decl_tag takes precedence over derivation of
7399 * register type from BTF type itself
7401 while ((id = btf_find_next_decl_tag(btf, fn_t, i, "arg:", id)) > 0) {
7402 const struct btf_type *tag_t = btf_type_by_id(btf, id);
7403 const char *tag = __btf_name_by_offset(btf, tag_t->name_off) + 4;
7405 /* disallow arg tags in static subprogs */
7407 bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7411 if (strcmp(tag, "ctx") == 0) {
7412 tags |= ARG_TAG_CTX;
7413 } else if (strcmp(tag, "trusted") == 0) {
7414 tags |= ARG_TAG_TRUSTED;
7415 } else if (strcmp(tag, "nonnull") == 0) {
7416 tags |= ARG_TAG_NONNULL;
7417 } else if (strcmp(tag, "nullable") == 0) {
7418 tags |= ARG_TAG_NULLABLE;
7419 } else if (strcmp(tag, "arena") == 0) {
7420 tags |= ARG_TAG_ARENA;
7422 bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7426 if (id != -ENOENT) {
7427 bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7431 t = btf_type_by_id(btf, args[i].type);
7432 while (btf_type_is_modifier(t))
7433 t = btf_type_by_id(btf, t->type);
7434 if (!btf_type_is_ptr(t))
7437 if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
7438 if (tags & ~ARG_TAG_CTX) {
7439 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7442 if ((tags & ARG_TAG_CTX) &&
7443 btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7444 prog->expected_attach_type))
7446 sub->args[i].arg_type = ARG_PTR_TO_CTX;
7449 if (btf_is_dynptr_ptr(btf, t)) {
7451 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7454 sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7457 if (tags & ARG_TAG_TRUSTED) {
7460 if (tags & ARG_TAG_NONNULL) {
7461 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7465 kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7466 if (kern_type_id < 0)
7467 return kern_type_id;
7469 sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
7470 if (tags & ARG_TAG_NULLABLE)
7471 sub->args[i].arg_type |= PTR_MAYBE_NULL;
7472 sub->args[i].btf_id = kern_type_id;
7475 if (tags & ARG_TAG_ARENA) {
7476 if (tags & ~ARG_TAG_ARENA) {
7477 bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
7480 sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7483 if (is_global) { /* generic user data pointer */
7486 if (tags & ARG_TAG_NULLABLE) {
7487 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7491 t = btf_type_skip_modifiers(btf, t->type, NULL);
7492 ref_t = btf_resolve_size(btf, t, &mem_size);
7493 if (IS_ERR(ref_t)) {
7494 bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7495 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7500 sub->args[i].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
7501 if (tags & ARG_TAG_NONNULL)
7502 sub->args[i].arg_type &= ~PTR_MAYBE_NULL;
7503 sub->args[i].mem_size = mem_size;
7509 bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
7512 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7513 sub->args[i].arg_type = ARG_ANYTHING;
7518 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7519 i, btf_type_str(t), tname);
7523 sub->arg_cnt = nargs;
7524 sub->args_cached = true;
7529 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7530 struct btf_show *show)
7532 const struct btf_type *t = btf_type_by_id(btf, type_id);
7535 memset(&show->state, 0, sizeof(show->state));
7536 memset(&show->obj, 0, sizeof(show->obj));
7538 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7541 __printf(2, 0) static void btf_seq_show(struct btf_show *show, const char *fmt,
7544 seq_vprintf((struct seq_file *)show->target, fmt, args);
7547 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7548 void *obj, struct seq_file *m, u64 flags)
7550 struct btf_show sseq;
7553 sseq.showfn = btf_seq_show;
7556 btf_type_show(btf, type_id, obj, &sseq);
7558 return sseq.state.status;
7561 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7564 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7565 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7566 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7569 struct btf_show_snprintf {
7570 struct btf_show show;
7571 int len_left; /* space left in string */
7572 int len; /* length we would have written */
7575 __printf(2, 0) static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7578 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7581 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7584 ssnprintf->len_left = 0;
7585 ssnprintf->len = len;
7586 } else if (len >= ssnprintf->len_left) {
7587 /* no space, drive on to get length we would have written */
7588 ssnprintf->len_left = 0;
7589 ssnprintf->len += len;
7591 ssnprintf->len_left -= len;
7592 ssnprintf->len += len;
7593 show->target += len;
7597 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7598 char *buf, int len, u64 flags)
7600 struct btf_show_snprintf ssnprintf;
7602 ssnprintf.show.target = buf;
7603 ssnprintf.show.flags = flags;
7604 ssnprintf.show.showfn = btf_snprintf_show;
7605 ssnprintf.len_left = len;
7608 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7610 /* If we encountered an error, return it. */
7611 if (ssnprintf.show.state.status)
7612 return ssnprintf.show.state.status;
7614 /* Otherwise return length we would have written */
7615 return ssnprintf.len;
7618 #ifdef CONFIG_PROC_FS
7619 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7621 const struct btf *btf = filp->private_data;
7623 seq_printf(m, "btf_id:\t%u\n", btf->id);
7627 static int btf_release(struct inode *inode, struct file *filp)
7629 btf_put(filp->private_data);
7633 const struct file_operations btf_fops = {
7634 #ifdef CONFIG_PROC_FS
7635 .show_fdinfo = bpf_btf_show_fdinfo,
7637 .release = btf_release,
7640 static int __btf_new_fd(struct btf *btf)
7642 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7645 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7650 btf = btf_parse(attr, uattr, uattr_size);
7652 return PTR_ERR(btf);
7654 ret = btf_alloc_id(btf);
7661 * The BTF ID is published to the userspace.
7662 * All BTF free must go through call_rcu() from
7663 * now on (i.e. free by calling btf_put()).
7666 ret = __btf_new_fd(btf);
7673 struct btf *btf_get_by_fd(int fd)
7681 return ERR_PTR(-EBADF);
7683 if (f.file->f_op != &btf_fops) {
7685 return ERR_PTR(-EINVAL);
7688 btf = f.file->private_data;
7689 refcount_inc(&btf->refcnt);
7695 int btf_get_info_by_fd(const struct btf *btf,
7696 const union bpf_attr *attr,
7697 union bpf_attr __user *uattr)
7699 struct bpf_btf_info __user *uinfo;
7700 struct bpf_btf_info info;
7701 u32 info_copy, btf_copy;
7704 u32 uinfo_len, uname_len, name_len;
7707 uinfo = u64_to_user_ptr(attr->info.info);
7708 uinfo_len = attr->info.info_len;
7710 info_copy = min_t(u32, uinfo_len, sizeof(info));
7711 memset(&info, 0, sizeof(info));
7712 if (copy_from_user(&info, uinfo, info_copy))
7716 ubtf = u64_to_user_ptr(info.btf);
7717 btf_copy = min_t(u32, btf->data_size, info.btf_size);
7718 if (copy_to_user(ubtf, btf->data, btf_copy))
7720 info.btf_size = btf->data_size;
7722 info.kernel_btf = btf->kernel_btf;
7724 uname = u64_to_user_ptr(info.name);
7725 uname_len = info.name_len;
7726 if (!uname ^ !uname_len)
7729 name_len = strlen(btf->name);
7730 info.name_len = name_len;
7733 if (uname_len >= name_len + 1) {
7734 if (copy_to_user(uname, btf->name, name_len + 1))
7739 if (copy_to_user(uname, btf->name, uname_len - 1))
7741 if (put_user(zero, uname + uname_len - 1))
7743 /* let user-space know about too short buffer */
7748 if (copy_to_user(uinfo, &info, info_copy) ||
7749 put_user(info_copy, &uattr->info.info_len))
7755 int btf_get_fd_by_id(u32 id)
7761 btf = idr_find(&btf_idr, id);
7762 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7763 btf = ERR_PTR(-ENOENT);
7767 return PTR_ERR(btf);
7769 fd = __btf_new_fd(btf);
7776 u32 btf_obj_id(const struct btf *btf)
7781 bool btf_is_kernel(const struct btf *btf)
7783 return btf->kernel_btf;
7786 bool btf_is_module(const struct btf *btf)
7788 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7792 BTF_MODULE_F_LIVE = (1 << 0),
7795 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7797 struct list_head list;
7798 struct module *module;
7800 struct bin_attribute *sysfs_attr;
7804 static LIST_HEAD(btf_modules);
7805 static DEFINE_MUTEX(btf_module_mutex);
7808 btf_module_read(struct file *file, struct kobject *kobj,
7809 struct bin_attribute *bin_attr,
7810 char *buf, loff_t off, size_t len)
7812 const struct btf *btf = bin_attr->private;
7814 memcpy(buf, btf->data + off, len);
7818 static void purge_cand_cache(struct btf *btf);
7820 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7823 struct btf_module *btf_mod, *tmp;
7824 struct module *mod = module;
7828 if (mod->btf_data_size == 0 ||
7829 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7830 op != MODULE_STATE_GOING))
7834 case MODULE_STATE_COMING:
7835 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7840 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size,
7841 mod->btf_base_data, mod->btf_base_data_size);
7844 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7845 pr_warn("failed to validate module [%s] BTF: %ld\n",
7846 mod->name, PTR_ERR(btf));
7849 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7853 err = btf_alloc_id(btf);
7860 purge_cand_cache(NULL);
7861 mutex_lock(&btf_module_mutex);
7862 btf_mod->module = module;
7864 list_add(&btf_mod->list, &btf_modules);
7865 mutex_unlock(&btf_module_mutex);
7867 if (IS_ENABLED(CONFIG_SYSFS)) {
7868 struct bin_attribute *attr;
7870 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7874 sysfs_bin_attr_init(attr);
7875 attr->attr.name = btf->name;
7876 attr->attr.mode = 0444;
7877 attr->size = btf->data_size;
7878 attr->private = btf;
7879 attr->read = btf_module_read;
7881 err = sysfs_create_bin_file(btf_kobj, attr);
7883 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7890 btf_mod->sysfs_attr = attr;
7894 case MODULE_STATE_LIVE:
7895 mutex_lock(&btf_module_mutex);
7896 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7897 if (btf_mod->module != module)
7900 btf_mod->flags |= BTF_MODULE_F_LIVE;
7903 mutex_unlock(&btf_module_mutex);
7905 case MODULE_STATE_GOING:
7906 mutex_lock(&btf_module_mutex);
7907 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7908 if (btf_mod->module != module)
7911 list_del(&btf_mod->list);
7912 if (btf_mod->sysfs_attr)
7913 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7914 purge_cand_cache(btf_mod->btf);
7915 btf_put(btf_mod->btf);
7916 kfree(btf_mod->sysfs_attr);
7920 mutex_unlock(&btf_module_mutex);
7924 return notifier_from_errno(err);
7927 static struct notifier_block btf_module_nb = {
7928 .notifier_call = btf_module_notify,
7931 static int __init btf_module_init(void)
7933 register_module_notifier(&btf_module_nb);
7937 fs_initcall(btf_module_init);
7938 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7940 struct module *btf_try_get_module(const struct btf *btf)
7942 struct module *res = NULL;
7943 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7944 struct btf_module *btf_mod, *tmp;
7946 mutex_lock(&btf_module_mutex);
7947 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7948 if (btf_mod->btf != btf)
7951 /* We must only consider module whose __init routine has
7952 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7953 * which is set from the notifier callback for
7954 * MODULE_STATE_LIVE.
7956 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7957 res = btf_mod->module;
7961 mutex_unlock(&btf_module_mutex);
7967 /* Returns struct btf corresponding to the struct module.
7968 * This function can return NULL or ERR_PTR.
7970 static struct btf *btf_get_module_btf(const struct module *module)
7972 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7973 struct btf_module *btf_mod, *tmp;
7975 struct btf *btf = NULL;
7978 btf = bpf_get_btf_vmlinux();
7979 if (!IS_ERR_OR_NULL(btf))
7984 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7985 mutex_lock(&btf_module_mutex);
7986 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7987 if (btf_mod->module != module)
7990 btf_get(btf_mod->btf);
7994 mutex_unlock(&btf_module_mutex);
8000 static int check_btf_kconfigs(const struct module *module, const char *feature)
8002 if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
8003 pr_err("missing vmlinux BTF, cannot register %s\n", feature);
8006 if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
8007 pr_warn("missing module BTF, cannot register %s\n", feature);
8011 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
8013 struct btf *btf = NULL;
8020 if (name_sz <= 1 || name[name_sz - 1])
8023 ret = bpf_find_btf_id(name, kind, &btf);
8024 if (ret > 0 && btf_is_module(btf)) {
8025 btf_obj_fd = __btf_new_fd(btf);
8026 if (btf_obj_fd < 0) {
8030 return ret | (((u64)btf_obj_fd) << 32);
8037 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
8038 .func = bpf_btf_find_by_name_kind,
8040 .ret_type = RET_INTEGER,
8041 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
8042 .arg2_type = ARG_CONST_SIZE,
8043 .arg3_type = ARG_ANYTHING,
8044 .arg4_type = ARG_ANYTHING,
8047 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
8048 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
8049 BTF_TRACING_TYPE_xxx
8050 #undef BTF_TRACING_TYPE
8052 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
8053 const struct btf_type *func, u32 func_flags)
8055 u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8056 const char *name, *sfx, *iter_name;
8057 const struct btf_param *arg;
8058 const struct btf_type *t;
8062 /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
8063 if (!flags || (flags & (flags - 1)))
8066 /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
8067 nr_args = btf_type_vlen(func);
8071 arg = &btf_params(func)[0];
8072 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8073 if (!t || !btf_type_is_ptr(t))
8075 t = btf_type_skip_modifiers(btf, t->type, NULL);
8076 if (!t || !__btf_type_is_struct(t))
8079 name = btf_name_by_offset(btf, t->name_off);
8080 if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
8083 /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
8084 * fit nicely in stack slots
8086 if (t->size == 0 || (t->size % 8))
8089 /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
8092 iter_name = name + sizeof(ITER_PREFIX) - 1;
8093 if (flags & KF_ITER_NEW)
8095 else if (flags & KF_ITER_NEXT)
8097 else /* (flags & KF_ITER_DESTROY) */
8100 snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
8101 if (strcmp(func_name, exp_name))
8104 /* only iter constructor should have extra arguments */
8105 if (!(flags & KF_ITER_NEW) && nr_args != 1)
8108 if (flags & KF_ITER_NEXT) {
8109 /* bpf_iter_<type>_next() should return pointer */
8110 t = btf_type_skip_modifiers(btf, func->type, NULL);
8111 if (!t || !btf_type_is_ptr(t))
8115 if (flags & KF_ITER_DESTROY) {
8116 /* bpf_iter_<type>_destroy() should return void */
8117 t = btf_type_by_id(btf, func->type);
8118 if (!t || !btf_type_is_void(t))
8125 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
8127 const struct btf_type *func;
8128 const char *func_name;
8131 /* any kfunc should be FUNC -> FUNC_PROTO */
8132 func = btf_type_by_id(btf, func_id);
8133 if (!func || !btf_type_is_func(func))
8136 /* sanity check kfunc name */
8137 func_name = btf_name_by_offset(btf, func->name_off);
8138 if (!func_name || !func_name[0])
8141 func = btf_type_by_id(btf, func->type);
8142 if (!func || !btf_type_is_func_proto(func))
8145 if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
8146 err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
8154 /* Kernel Function (kfunc) BTF ID set registration API */
8156 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
8157 const struct btf_kfunc_id_set *kset)
8159 struct btf_kfunc_hook_filter *hook_filter;
8160 struct btf_id_set8 *add_set = kset->set;
8161 bool vmlinux_set = !btf_is_module(btf);
8162 bool add_filter = !!kset->filter;
8163 struct btf_kfunc_set_tab *tab;
8164 struct btf_id_set8 *set;
8168 if (hook >= BTF_KFUNC_HOOK_MAX) {
8176 tab = btf->kfunc_set_tab;
8178 if (tab && add_filter) {
8181 hook_filter = &tab->hook_filters[hook];
8182 for (i = 0; i < hook_filter->nr_filters; i++) {
8183 if (hook_filter->filters[i] == kset->filter) {
8189 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8196 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
8199 btf->kfunc_set_tab = tab;
8202 set = tab->sets[hook];
8203 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
8206 if (WARN_ON_ONCE(set && !vmlinux_set)) {
8211 /* In case of vmlinux sets, there may be more than one set being
8212 * registered per hook. To create a unified set, we allocate a new set
8213 * and concatenate all individual sets being registered. While each set
8214 * is individually sorted, they may become unsorted when concatenated,
8215 * hence re-sorting the final set again is required to make binary
8216 * searching the set using btf_id_set8_contains function work.
8218 * For module sets, we need to allocate as we may need to relocate
8221 set_cnt = set ? set->cnt : 0;
8223 if (set_cnt > U32_MAX - add_set->cnt) {
8228 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8234 set = krealloc(tab->sets[hook],
8235 offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
8236 GFP_KERNEL | __GFP_NOWARN);
8242 /* For newly allocated set, initialize set->cnt to 0 */
8243 if (!tab->sets[hook])
8245 tab->sets[hook] = set;
8247 /* Concatenate the two sets */
8248 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
8249 /* Now that the set is copied, update with relocated BTF ids */
8250 for (i = set->cnt; i < set->cnt + add_set->cnt; i++)
8251 set->pairs[i].id = btf_relocate_id(btf, set->pairs[i].id);
8253 set->cnt += add_set->cnt;
8255 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8258 hook_filter = &tab->hook_filters[hook];
8259 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8263 btf_free_kfunc_set_tab(btf);
8267 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
8268 enum btf_kfunc_hook hook,
8270 const struct bpf_prog *prog)
8272 struct btf_kfunc_hook_filter *hook_filter;
8273 struct btf_id_set8 *set;
8276 if (hook >= BTF_KFUNC_HOOK_MAX)
8278 if (!btf->kfunc_set_tab)
8280 hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
8281 for (i = 0; i < hook_filter->nr_filters; i++) {
8282 if (hook_filter->filters[i](prog, kfunc_btf_id))
8285 set = btf->kfunc_set_tab->sets[hook];
8288 id = btf_id_set8_contains(set, kfunc_btf_id);
8291 /* The flags for BTF ID are located next to it */
8295 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8297 switch (prog_type) {
8298 case BPF_PROG_TYPE_UNSPEC:
8299 return BTF_KFUNC_HOOK_COMMON;
8300 case BPF_PROG_TYPE_XDP:
8301 return BTF_KFUNC_HOOK_XDP;
8302 case BPF_PROG_TYPE_SCHED_CLS:
8303 return BTF_KFUNC_HOOK_TC;
8304 case BPF_PROG_TYPE_STRUCT_OPS:
8305 return BTF_KFUNC_HOOK_STRUCT_OPS;
8306 case BPF_PROG_TYPE_TRACING:
8307 case BPF_PROG_TYPE_LSM:
8308 return BTF_KFUNC_HOOK_TRACING;
8309 case BPF_PROG_TYPE_SYSCALL:
8310 return BTF_KFUNC_HOOK_SYSCALL;
8311 case BPF_PROG_TYPE_CGROUP_SKB:
8312 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8313 return BTF_KFUNC_HOOK_CGROUP_SKB;
8314 case BPF_PROG_TYPE_SCHED_ACT:
8315 return BTF_KFUNC_HOOK_SCHED_ACT;
8316 case BPF_PROG_TYPE_SK_SKB:
8317 return BTF_KFUNC_HOOK_SK_SKB;
8318 case BPF_PROG_TYPE_SOCKET_FILTER:
8319 return BTF_KFUNC_HOOK_SOCKET_FILTER;
8320 case BPF_PROG_TYPE_LWT_OUT:
8321 case BPF_PROG_TYPE_LWT_IN:
8322 case BPF_PROG_TYPE_LWT_XMIT:
8323 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
8324 return BTF_KFUNC_HOOK_LWT;
8325 case BPF_PROG_TYPE_NETFILTER:
8326 return BTF_KFUNC_HOOK_NETFILTER;
8327 case BPF_PROG_TYPE_KPROBE:
8328 return BTF_KFUNC_HOOK_KPROBE;
8330 return BTF_KFUNC_HOOK_MAX;
8335 * Reference to the module (obtained using btf_try_get_module) corresponding to
8336 * the struct btf *MUST* be held when calling this function from verifier
8337 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
8338 * keeping the reference for the duration of the call provides the necessary
8339 * protection for looking up a well-formed btf->kfunc_set_tab.
8341 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8343 const struct bpf_prog *prog)
8345 enum bpf_prog_type prog_type = resolve_prog_type(prog);
8346 enum btf_kfunc_hook hook;
8349 kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
8353 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8354 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
8357 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8358 const struct bpf_prog *prog)
8360 return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
8363 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8364 const struct btf_kfunc_id_set *kset)
8369 btf = btf_get_module_btf(kset->owner);
8371 return check_btf_kconfigs(kset->owner, "kfunc");
8373 return PTR_ERR(btf);
8375 for (i = 0; i < kset->set->cnt; i++) {
8376 ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
8377 kset->set->pairs[i].flags);
8382 ret = btf_populate_kfunc_set(btf, hook, kset);
8389 /* This function must be invoked only from initcalls/module init functions */
8390 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
8391 const struct btf_kfunc_id_set *kset)
8393 enum btf_kfunc_hook hook;
8395 /* All kfuncs need to be tagged as such in BTF.
8396 * WARN() for initcall registrations that do not check errors.
8398 if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8399 WARN_ON(!kset->owner);
8403 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8404 return __register_btf_kfunc_id_set(hook, kset);
8406 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8408 /* This function must be invoked only from initcalls/module init functions */
8409 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
8411 return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8413 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8415 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8417 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8418 struct btf_id_dtor_kfunc *dtor;
8422 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
8423 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
8425 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
8426 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
8429 return dtor->kfunc_btf_id;
8432 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8434 const struct btf_type *dtor_func, *dtor_func_proto, *t;
8435 const struct btf_param *args;
8439 for (i = 0; i < cnt; i++) {
8440 dtor_btf_id = btf_relocate_id(btf, dtors[i].kfunc_btf_id);
8442 dtor_func = btf_type_by_id(btf, dtor_btf_id);
8443 if (!dtor_func || !btf_type_is_func(dtor_func))
8446 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
8447 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
8450 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
8451 t = btf_type_by_id(btf, dtor_func_proto->type);
8452 if (!t || !btf_type_is_void(t))
8455 nr_args = btf_type_vlen(dtor_func_proto);
8458 args = btf_params(dtor_func_proto);
8459 t = btf_type_by_id(btf, args[0].type);
8460 /* Allow any pointer type, as width on targets Linux supports
8461 * will be same for all pointer types (i.e. sizeof(void *))
8463 if (!t || !btf_type_is_ptr(t))
8469 /* This function must be invoked only from initcalls/module init functions */
8470 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
8471 struct module *owner)
8473 struct btf_id_dtor_kfunc_tab *tab;
8478 btf = btf_get_module_btf(owner);
8480 return check_btf_kconfigs(owner, "dtor kfuncs");
8482 return PTR_ERR(btf);
8484 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8485 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8490 /* Ensure that the prototype of dtor kfuncs being registered is sane */
8491 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8495 tab = btf->dtor_kfunc_tab;
8496 /* Only one call allowed for modules */
8497 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8502 tab_cnt = tab ? tab->cnt : 0;
8503 if (tab_cnt > U32_MAX - add_cnt) {
8507 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8508 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8513 tab = krealloc(btf->dtor_kfunc_tab,
8514 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
8515 GFP_KERNEL | __GFP_NOWARN);
8521 if (!btf->dtor_kfunc_tab)
8523 btf->dtor_kfunc_tab = tab;
8525 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8527 /* remap BTF ids based on BTF relocation (if any) */
8528 for (i = tab_cnt; i < tab_cnt + add_cnt; i++) {
8529 tab->dtors[i].btf_id = btf_relocate_id(btf, tab->dtors[i].btf_id);
8530 tab->dtors[i].kfunc_btf_id = btf_relocate_id(btf, tab->dtors[i].kfunc_btf_id);
8533 tab->cnt += add_cnt;
8535 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8539 btf_free_dtor_kfunc_tab(btf);
8543 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8545 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8547 /* Check local and target types for compatibility. This check is used for
8548 * type-based CO-RE relocations and follow slightly different rules than
8549 * field-based relocations. This function assumes that root types were already
8550 * checked for name match. Beyond that initial root-level name check, names
8551 * are completely ignored. Compatibility rules are as follows:
8552 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8553 * kind should match for local and target types (i.e., STRUCT is not
8554 * compatible with UNION);
8555 * - for ENUMs/ENUM64s, the size is ignored;
8556 * - for INT, size and signedness are ignored;
8557 * - for ARRAY, dimensionality is ignored, element types are checked for
8558 * compatibility recursively;
8559 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
8560 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8561 * - FUNC_PROTOs are compatible if they have compatible signature: same
8562 * number of input args and compatible return and argument types.
8563 * These rules are not set in stone and probably will be adjusted as we get
8564 * more experience with using BPF CO-RE relocations.
8566 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8567 const struct btf *targ_btf, __u32 targ_id)
8569 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8570 MAX_TYPES_ARE_COMPAT_DEPTH);
8573 #define MAX_TYPES_MATCH_DEPTH 2
8575 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8576 const struct btf *targ_btf, u32 targ_id)
8578 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8579 MAX_TYPES_MATCH_DEPTH);
8582 static bool bpf_core_is_flavor_sep(const char *s)
8584 /* check X___Y name pattern, where X and Y are not underscores */
8585 return s[0] != '_' && /* X */
8586 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
8587 s[4] != '_'; /* Y */
8590 size_t bpf_core_essential_name_len(const char *name)
8592 size_t n = strlen(name);
8595 for (i = n - 5; i >= 0; i--) {
8596 if (bpf_core_is_flavor_sep(name + i))
8602 static void bpf_free_cands(struct bpf_cand_cache *cands)
8605 /* empty candidate array was allocated on stack */
8610 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8616 #define VMLINUX_CAND_CACHE_SIZE 31
8617 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8619 #define MODULE_CAND_CACHE_SIZE 31
8620 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8622 static void __print_cand_cache(struct bpf_verifier_log *log,
8623 struct bpf_cand_cache **cache,
8626 struct bpf_cand_cache *cc;
8629 for (i = 0; i < cache_size; i++) {
8633 bpf_log(log, "[%d]%s(", i, cc->name);
8634 for (j = 0; j < cc->cnt; j++) {
8635 bpf_log(log, "%d", cc->cands[j].id);
8636 if (j < cc->cnt - 1)
8639 bpf_log(log, "), ");
8643 static void print_cand_cache(struct bpf_verifier_log *log)
8645 mutex_lock(&cand_cache_mutex);
8646 bpf_log(log, "vmlinux_cand_cache:");
8647 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8648 bpf_log(log, "\nmodule_cand_cache:");
8649 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8651 mutex_unlock(&cand_cache_mutex);
8654 static u32 hash_cands(struct bpf_cand_cache *cands)
8656 return jhash(cands->name, cands->name_len, 0);
8659 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8660 struct bpf_cand_cache **cache,
8663 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8665 if (cc && cc->name_len == cands->name_len &&
8666 !strncmp(cc->name, cands->name, cands->name_len))
8671 static size_t sizeof_cands(int cnt)
8673 return offsetof(struct bpf_cand_cache, cands[cnt]);
8676 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8677 struct bpf_cand_cache **cache,
8680 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8683 bpf_free_cands_from_cache(*cc);
8686 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8688 bpf_free_cands(cands);
8689 return ERR_PTR(-ENOMEM);
8691 /* strdup the name, since it will stay in cache.
8692 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8694 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8695 bpf_free_cands(cands);
8696 if (!new_cands->name) {
8698 return ERR_PTR(-ENOMEM);
8704 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8705 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8708 struct bpf_cand_cache *cc;
8711 for (i = 0; i < cache_size; i++) {
8716 /* when new module is loaded purge all of module_cand_cache,
8717 * since new module might have candidates with the name
8718 * that matches cached cands.
8720 bpf_free_cands_from_cache(cc);
8724 /* when module is unloaded purge cache entries
8725 * that match module's btf
8727 for (j = 0; j < cc->cnt; j++)
8728 if (cc->cands[j].btf == btf) {
8729 bpf_free_cands_from_cache(cc);
8737 static void purge_cand_cache(struct btf *btf)
8739 mutex_lock(&cand_cache_mutex);
8740 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8741 mutex_unlock(&cand_cache_mutex);
8745 static struct bpf_cand_cache *
8746 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8749 struct bpf_cand_cache *new_cands;
8750 const struct btf_type *t;
8751 const char *targ_name;
8752 size_t targ_essent_len;
8755 n = btf_nr_types(targ_btf);
8756 for (i = targ_start_id; i < n; i++) {
8757 t = btf_type_by_id(targ_btf, i);
8758 if (btf_kind(t) != cands->kind)
8761 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8765 /* the resched point is before strncmp to make sure that search
8766 * for non-existing name will have a chance to schedule().
8770 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8773 targ_essent_len = bpf_core_essential_name_len(targ_name);
8774 if (targ_essent_len != cands->name_len)
8777 /* most of the time there is only one candidate for a given kind+name pair */
8778 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8780 bpf_free_cands(cands);
8781 return ERR_PTR(-ENOMEM);
8784 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8785 bpf_free_cands(cands);
8787 cands->cands[cands->cnt].btf = targ_btf;
8788 cands->cands[cands->cnt].id = i;
8794 static struct bpf_cand_cache *
8795 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8797 struct bpf_cand_cache *cands, *cc, local_cand = {};
8798 const struct btf *local_btf = ctx->btf;
8799 const struct btf_type *local_type;
8800 const struct btf *main_btf;
8801 size_t local_essent_len;
8802 struct btf *mod_btf;
8806 main_btf = bpf_get_btf_vmlinux();
8807 if (IS_ERR(main_btf))
8808 return ERR_CAST(main_btf);
8810 return ERR_PTR(-EINVAL);
8812 local_type = btf_type_by_id(local_btf, local_type_id);
8814 return ERR_PTR(-EINVAL);
8816 name = btf_name_by_offset(local_btf, local_type->name_off);
8817 if (str_is_empty(name))
8818 return ERR_PTR(-EINVAL);
8819 local_essent_len = bpf_core_essential_name_len(name);
8821 cands = &local_cand;
8823 cands->kind = btf_kind(local_type);
8824 cands->name_len = local_essent_len;
8826 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8827 /* cands is a pointer to stack here */
8834 /* Attempt to find target candidates in vmlinux BTF first */
8835 cands = bpf_core_add_cands(cands, main_btf, 1);
8837 return ERR_CAST(cands);
8839 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8841 /* populate cache even when cands->cnt == 0 */
8842 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8844 return ERR_CAST(cc);
8846 /* if vmlinux BTF has any candidate, don't go for module BTFs */
8851 /* cands is a pointer to stack here and cands->cnt == 0 */
8852 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8854 /* if cache has it return it even if cc->cnt == 0 */
8857 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8858 spin_lock_bh(&btf_idr_lock);
8859 idr_for_each_entry(&btf_idr, mod_btf, id) {
8860 if (!btf_is_module(mod_btf))
8862 /* linear search could be slow hence unlock/lock
8863 * the IDR to avoiding holding it for too long
8866 spin_unlock_bh(&btf_idr_lock);
8867 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8870 return ERR_CAST(cands);
8871 spin_lock_bh(&btf_idr_lock);
8873 spin_unlock_bh(&btf_idr_lock);
8874 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8875 * or pointer to stack if cands->cnd == 0.
8876 * Copy it into the cache even when cands->cnt == 0 and
8877 * return the result.
8879 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8882 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8883 int relo_idx, void *insn)
8885 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8886 struct bpf_core_cand_list cands = {};
8887 struct bpf_core_relo_res targ_res;
8888 struct bpf_core_spec *specs;
8891 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8892 * into arrays of btf_ids of struct fields and array indices.
8894 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8899 struct bpf_cand_cache *cc;
8902 mutex_lock(&cand_cache_mutex);
8903 cc = bpf_core_find_cands(ctx, relo->type_id);
8905 bpf_log(ctx->log, "target candidate search failed for %d\n",
8911 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8917 for (i = 0; i < cc->cnt; i++) {
8919 "CO-RE relocating %s %s: found target candidate [%d]\n",
8920 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8921 cands.cands[i].btf = cc->cands[i].btf;
8922 cands.cands[i].id = cc->cands[i].id;
8924 cands.len = cc->cnt;
8925 /* cand_cache_mutex needs to span the cache lookup and
8926 * copy of btf pointer into bpf_core_cand_list,
8927 * since module can be unloaded while bpf_core_calc_relo_insn
8928 * is working with module's btf.
8932 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8937 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8944 mutex_unlock(&cand_cache_mutex);
8945 if (ctx->log->level & BPF_LOG_LEVEL2)
8946 print_cand_cache(ctx->log);
8951 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8952 const struct bpf_reg_state *reg,
8953 const char *field_name, u32 btf_id, const char *suffix)
8955 struct btf *btf = reg->btf;
8956 const struct btf_type *walk_type, *safe_type;
8958 char safe_tname[64];
8960 const struct btf_member *member;
8963 walk_type = btf_type_by_id(btf, reg->btf_id);
8967 tname = btf_name_by_offset(btf, walk_type->name_off);
8969 ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8970 if (ret >= sizeof(safe_tname))
8973 safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8977 safe_type = btf_type_by_id(btf, safe_id);
8981 for_each_member(i, safe_type, member) {
8982 const char *m_name = __btf_name_by_offset(btf, member->name_off);
8983 const struct btf_type *mtype = btf_type_by_id(btf, member->type);
8986 if (!btf_type_is_ptr(mtype))
8989 btf_type_skip_modifiers(btf, mtype->type, &id);
8990 /* If we match on both type and name, the field is considered trusted. */
8991 if (btf_id == id && !strcmp(field_name, m_name))
8998 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8999 const struct btf *reg_btf, u32 reg_id,
9000 const struct btf *arg_btf, u32 arg_id)
9002 const char *reg_name, *arg_name, *search_needle;
9003 const struct btf_type *reg_type, *arg_type;
9004 int reg_len, arg_len, cmp_len;
9005 size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
9007 reg_type = btf_type_by_id(reg_btf, reg_id);
9011 arg_type = btf_type_by_id(arg_btf, arg_id);
9015 reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
9016 arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
9018 reg_len = strlen(reg_name);
9019 arg_len = strlen(arg_name);
9021 /* Exactly one of the two type names may be suffixed with ___init, so
9022 * if the strings are the same size, they can't possibly be no-cast
9023 * aliases of one another. If you have two of the same type names, e.g.
9024 * they're both nf_conn___init, it would be improper to return true
9025 * because they are _not_ no-cast aliases, they are the same type.
9027 if (reg_len == arg_len)
9030 /* Either of the two names must be the other name, suffixed with ___init. */
9031 if ((reg_len != arg_len + pattern_len) &&
9032 (arg_len != reg_len + pattern_len))
9035 if (reg_len < arg_len) {
9036 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
9039 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
9046 /* ___init suffix must come at the end of the name */
9047 if (*(search_needle + pattern_len) != '\0')
9050 return !strncmp(reg_name, arg_name, cmp_len);
9053 #ifdef CONFIG_BPF_JIT
9055 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
9056 struct bpf_verifier_log *log)
9058 struct btf_struct_ops_tab *tab, *new_tab;
9061 tab = btf->struct_ops_tab;
9063 tab = kzalloc(offsetof(struct btf_struct_ops_tab, ops[4]),
9068 btf->struct_ops_tab = tab;
9071 for (i = 0; i < tab->cnt; i++)
9072 if (tab->ops[i].st_ops == st_ops)
9075 if (tab->cnt == tab->capacity) {
9076 new_tab = krealloc(tab,
9077 offsetof(struct btf_struct_ops_tab,
9078 ops[tab->capacity * 2]),
9084 btf->struct_ops_tab = tab;
9087 tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
9089 err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
9093 btf->struct_ops_tab->cnt++;
9098 const struct bpf_struct_ops_desc *
9099 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
9101 const struct bpf_struct_ops_desc *st_ops_list;
9107 if (!btf->struct_ops_tab)
9110 cnt = btf->struct_ops_tab->cnt;
9111 st_ops_list = btf->struct_ops_tab->ops;
9112 for (i = 0; i < cnt; i++) {
9113 if (st_ops_list[i].value_id == value_id)
9114 return &st_ops_list[i];
9120 const struct bpf_struct_ops_desc *
9121 bpf_struct_ops_find(struct btf *btf, u32 type_id)
9123 const struct bpf_struct_ops_desc *st_ops_list;
9129 if (!btf->struct_ops_tab)
9132 cnt = btf->struct_ops_tab->cnt;
9133 st_ops_list = btf->struct_ops_tab->ops;
9134 for (i = 0; i < cnt; i++) {
9135 if (st_ops_list[i].type_id == type_id)
9136 return &st_ops_list[i];
9142 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
9144 struct bpf_verifier_log *log;
9148 btf = btf_get_module_btf(st_ops->owner);
9150 return check_btf_kconfigs(st_ops->owner, "struct_ops");
9152 return PTR_ERR(btf);
9154 log = kzalloc(sizeof(*log), GFP_KERNEL | __GFP_NOWARN);
9160 log->level = BPF_LOG_KERNEL;
9162 err = btf_add_struct_ops(btf, st_ops, log);
9170 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
9173 bool btf_param_match_suffix(const struct btf *btf,
9174 const struct btf_param *arg,
9177 int suffix_len = strlen(suffix), len;
9178 const char *param_name;
9180 /* In the future, this can be ported to use BTF tagging */
9181 param_name = btf_name_by_offset(btf, arg->name_off);
9182 if (str_is_empty(param_name))
9184 len = strlen(param_name);
9185 if (len <= suffix_len)
9187 param_name += len - suffix_len;
9188 return !strncmp(param_name, suffix, suffix_len);