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_lsm.h>
23 #include <linux/skmsg.h>
24 #include <linux/perf_event.h>
25 #include <linux/bsearch.h>
26 #include <linux/kobject.h>
27 #include <linux/sysfs.h>
29 #include <net/netfilter/nf_bpf_link.h>
32 #include "../tools/lib/bpf/relo_core.h"
34 /* BTF (BPF Type Format) is the meta data format which describes
35 * the data types of BPF program/map. Hence, it basically focus
36 * on the C programming language which the modern BPF is primary
41 * The BTF data is stored under the ".BTF" ELF section
45 * Each 'struct btf_type' object describes a C data type.
46 * Depending on the type it is describing, a 'struct btf_type'
47 * object may be followed by more data. F.e.
48 * To describe an array, 'struct btf_type' is followed by
51 * 'struct btf_type' and any extra data following it are
56 * The BTF type section contains a list of 'struct btf_type' objects.
57 * Each one describes a C type. Recall from the above section
58 * that a 'struct btf_type' object could be immediately followed by extra
59 * data in order to describe some particular C types.
63 * Each btf_type object is identified by a type_id. The type_id
64 * is implicitly implied by the location of the btf_type object in
65 * the BTF type section. The first one has type_id 1. The second
66 * one has type_id 2...etc. Hence, an earlier btf_type has
69 * A btf_type object may refer to another btf_type object by using
70 * type_id (i.e. the "type" in the "struct btf_type").
72 * NOTE that we cannot assume any reference-order.
73 * A btf_type object can refer to an earlier btf_type object
74 * but it can also refer to a later btf_type object.
76 * For example, to describe "const void *". A btf_type
77 * object describing "const" may refer to another btf_type
78 * object describing "void *". This type-reference is done
79 * by specifying type_id:
81 * [1] CONST (anon) type_id=2
82 * [2] PTR (anon) type_id=0
84 * The above is the btf_verifier debug log:
85 * - Each line started with "[?]" is a btf_type object
86 * - [?] is the type_id of the btf_type object.
87 * - CONST/PTR is the BTF_KIND_XXX
88 * - "(anon)" is the name of the type. It just
89 * happens that CONST and PTR has no name.
90 * - type_id=XXX is the 'u32 type' in btf_type
92 * NOTE: "void" has type_id 0
96 * The BTF string section contains the names used by the type section.
97 * Each string is referred by an "offset" from the beginning of the
100 * Each string is '\0' terminated.
102 * The first character in the string section must be '\0'
103 * which is used to mean 'anonymous'. Some btf_type may not
109 * To verify BTF data, two passes are needed.
113 * The first pass is to collect all btf_type objects to
114 * an array: "btf->types".
116 * Depending on the C type that a btf_type is describing,
117 * a btf_type may be followed by extra data. We don't know
118 * how many btf_type is there, and more importantly we don't
119 * know where each btf_type is located in the type section.
121 * Without knowing the location of each type_id, most verifications
122 * cannot be done. e.g. an earlier btf_type may refer to a later
123 * btf_type (recall the "const void *" above), so we cannot
124 * check this type-reference in the first pass.
126 * In the first pass, it still does some verifications (e.g.
127 * checking the name is a valid offset to the string section).
131 * The main focus is to resolve a btf_type that is referring
134 * We have to ensure the referring type:
135 * 1) does exist in the BTF (i.e. in btf->types[])
136 * 2) does not cause a loop:
145 * btf_type_needs_resolve() decides if a btf_type needs
148 * The needs_resolve type implements the "resolve()" ops which
149 * essentially does a DFS and detects backedge.
151 * During resolve (or DFS), different C types have different
152 * "RESOLVED" conditions.
154 * When resolving a BTF_KIND_STRUCT, we need to resolve all its
155 * members because a member is always referring to another
156 * type. A struct's member can be treated as "RESOLVED" if
157 * it is referring to a BTF_KIND_PTR. Otherwise, the
158 * following valid C struct would be rejected:
165 * When resolving a BTF_KIND_PTR, it needs to keep resolving if
166 * it is referring to another BTF_KIND_PTR. Otherwise, we cannot
167 * detect a pointer loop, e.g.:
168 * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
170 * +-----------------------------------------+
174 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
175 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
176 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
177 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
178 #define BITS_ROUNDUP_BYTES(bits) \
179 (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
181 #define BTF_INFO_MASK 0x9f00ffff
182 #define BTF_INT_MASK 0x0fffffff
183 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
184 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
186 /* 16MB for 64k structs and each has 16 members and
187 * a few MB spaces for the string section.
188 * The hard limit is S32_MAX.
190 #define BTF_MAX_SIZE (16 * 1024 * 1024)
192 #define for_each_member_from(i, from, struct_type, member) \
193 for (i = from, member = btf_type_member(struct_type) + from; \
194 i < btf_type_vlen(struct_type); \
197 #define for_each_vsi_from(i, from, struct_type, member) \
198 for (i = from, member = btf_type_var_secinfo(struct_type) + from; \
199 i < btf_type_vlen(struct_type); \
203 DEFINE_SPINLOCK(btf_idr_lock);
205 enum btf_kfunc_hook {
206 BTF_KFUNC_HOOK_COMMON,
209 BTF_KFUNC_HOOK_STRUCT_OPS,
210 BTF_KFUNC_HOOK_TRACING,
211 BTF_KFUNC_HOOK_SYSCALL,
212 BTF_KFUNC_HOOK_FMODRET,
213 BTF_KFUNC_HOOK_CGROUP_SKB,
214 BTF_KFUNC_HOOK_SCHED_ACT,
215 BTF_KFUNC_HOOK_SK_SKB,
216 BTF_KFUNC_HOOK_SOCKET_FILTER,
218 BTF_KFUNC_HOOK_NETFILTER,
223 BTF_KFUNC_SET_MAX_CNT = 256,
224 BTF_DTOR_KFUNC_MAX_CNT = 256,
225 BTF_KFUNC_FILTER_MAX_CNT = 16,
228 struct btf_kfunc_hook_filter {
229 btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
233 struct btf_kfunc_set_tab {
234 struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
235 struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
238 struct btf_id_dtor_kfunc_tab {
240 struct btf_id_dtor_kfunc dtors[];
245 struct btf_type **types;
250 struct btf_header hdr;
251 u32 nr_types; /* includes VOID for base BTF */
257 struct btf_kfunc_set_tab *kfunc_set_tab;
258 struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
259 struct btf_struct_metas *struct_meta_tab;
261 /* split BTF support */
262 struct btf *base_btf;
263 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
264 u32 start_str_off; /* first string offset (0 for base BTF) */
265 char name[MODULE_NAME_LEN];
269 enum verifier_phase {
274 struct resolve_vertex {
275 const struct btf_type *t;
287 RESOLVE_TBD, /* To Be Determined */
288 RESOLVE_PTR, /* Resolving for Pointer */
289 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
294 #define MAX_RESOLVE_DEPTH 32
296 struct btf_sec_info {
301 struct btf_verifier_env {
304 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
305 struct bpf_verifier_log log;
308 enum verifier_phase phase;
309 enum resolve_mode resolve_mode;
312 static const char * const btf_kind_str[NR_BTF_KINDS] = {
313 [BTF_KIND_UNKN] = "UNKNOWN",
314 [BTF_KIND_INT] = "INT",
315 [BTF_KIND_PTR] = "PTR",
316 [BTF_KIND_ARRAY] = "ARRAY",
317 [BTF_KIND_STRUCT] = "STRUCT",
318 [BTF_KIND_UNION] = "UNION",
319 [BTF_KIND_ENUM] = "ENUM",
320 [BTF_KIND_FWD] = "FWD",
321 [BTF_KIND_TYPEDEF] = "TYPEDEF",
322 [BTF_KIND_VOLATILE] = "VOLATILE",
323 [BTF_KIND_CONST] = "CONST",
324 [BTF_KIND_RESTRICT] = "RESTRICT",
325 [BTF_KIND_FUNC] = "FUNC",
326 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
327 [BTF_KIND_VAR] = "VAR",
328 [BTF_KIND_DATASEC] = "DATASEC",
329 [BTF_KIND_FLOAT] = "FLOAT",
330 [BTF_KIND_DECL_TAG] = "DECL_TAG",
331 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
332 [BTF_KIND_ENUM64] = "ENUM64",
335 const char *btf_type_str(const struct btf_type *t)
337 return btf_kind_str[BTF_INFO_KIND(t->info)];
340 /* Chunk size we use in safe copy of data to be shown. */
341 #define BTF_SHOW_OBJ_SAFE_SIZE 32
344 * This is the maximum size of a base type value (equivalent to a
345 * 128-bit int); if we are at the end of our safe buffer and have
346 * less than 16 bytes space we can't be assured of being able
347 * to copy the next type safely, so in such cases we will initiate
350 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
353 #define BTF_SHOW_NAME_SIZE 80
356 * The suffix of a type that indicates it cannot alias another type when
357 * comparing BTF IDs for kfunc invocations.
359 #define NOCAST_ALIAS_SUFFIX "___init"
362 * Common data to all BTF show operations. Private show functions can add
363 * their own data to a structure containing a struct btf_show and consult it
364 * in the show callback. See btf_type_show() below.
366 * One challenge with showing nested data is we want to skip 0-valued
367 * data, but in order to figure out whether a nested object is all zeros
368 * we need to walk through it. As a result, we need to make two passes
369 * when handling structs, unions and arrays; the first path simply looks
370 * for nonzero data, while the second actually does the display. The first
371 * pass is signalled by show->state.depth_check being set, and if we
372 * encounter a non-zero value we set show->state.depth_to_show to
373 * the depth at which we encountered it. When we have completed the
374 * first pass, we will know if anything needs to be displayed if
375 * depth_to_show > depth. See btf_[struct,array]_show() for the
376 * implementation of this.
378 * Another problem is we want to ensure the data for display is safe to
379 * access. To support this, the anonymous "struct {} obj" tracks the data
380 * object and our safe copy of it. We copy portions of the data needed
381 * to the object "copy" buffer, but because its size is limited to
382 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
383 * traverse larger objects for display.
385 * The various data type show functions all start with a call to
386 * btf_show_start_type() which returns a pointer to the safe copy
387 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
388 * raw data itself). btf_show_obj_safe() is responsible for
389 * using copy_from_kernel_nofault() to update the safe data if necessary
390 * as we traverse the object's data. skbuff-like semantics are
393 * - obj.head points to the start of the toplevel object for display
394 * - obj.size is the size of the toplevel object
395 * - obj.data points to the current point in the original data at
396 * which our safe data starts. obj.data will advance as we copy
397 * portions of the data.
399 * In most cases a single copy will suffice, but larger data structures
400 * such as "struct task_struct" will require many copies. The logic in
401 * btf_show_obj_safe() handles the logic that determines if a new
402 * copy_from_kernel_nofault() is needed.
406 void *target; /* target of show operation (seq file, buffer) */
407 void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
408 const struct btf *btf;
409 /* below are used during iteration */
418 int status; /* non-zero for error */
419 const struct btf_type *type;
420 const struct btf_member *member;
421 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
427 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
431 struct btf_kind_operations {
432 s32 (*check_meta)(struct btf_verifier_env *env,
433 const struct btf_type *t,
435 int (*resolve)(struct btf_verifier_env *env,
436 const struct resolve_vertex *v);
437 int (*check_member)(struct btf_verifier_env *env,
438 const struct btf_type *struct_type,
439 const struct btf_member *member,
440 const struct btf_type *member_type);
441 int (*check_kflag_member)(struct btf_verifier_env *env,
442 const struct btf_type *struct_type,
443 const struct btf_member *member,
444 const struct btf_type *member_type);
445 void (*log_details)(struct btf_verifier_env *env,
446 const struct btf_type *t);
447 void (*show)(const struct btf *btf, const struct btf_type *t,
448 u32 type_id, void *data, u8 bits_offsets,
449 struct btf_show *show);
452 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
453 static struct btf_type btf_void;
455 static int btf_resolve(struct btf_verifier_env *env,
456 const struct btf_type *t, u32 type_id);
458 static int btf_func_check(struct btf_verifier_env *env,
459 const struct btf_type *t);
461 static bool btf_type_is_modifier(const struct btf_type *t)
463 /* Some of them is not strictly a C modifier
464 * but they are grouped into the same bucket
466 * A type (t) that refers to another
467 * type through t->type AND its size cannot
468 * be determined without following the t->type.
470 * ptr does not fall into this bucket
471 * because its size is always sizeof(void *).
473 switch (BTF_INFO_KIND(t->info)) {
474 case BTF_KIND_TYPEDEF:
475 case BTF_KIND_VOLATILE:
477 case BTF_KIND_RESTRICT:
478 case BTF_KIND_TYPE_TAG:
485 bool btf_type_is_void(const struct btf_type *t)
487 return t == &btf_void;
490 static bool btf_type_is_fwd(const struct btf_type *t)
492 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
495 static bool btf_type_is_datasec(const struct btf_type *t)
497 return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
500 static bool btf_type_is_decl_tag(const struct btf_type *t)
502 return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
505 static bool btf_type_nosize(const struct btf_type *t)
507 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
508 btf_type_is_func(t) || btf_type_is_func_proto(t) ||
509 btf_type_is_decl_tag(t);
512 static bool btf_type_nosize_or_null(const struct btf_type *t)
514 return !t || btf_type_nosize(t);
517 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
519 return btf_type_is_func(t) || btf_type_is_struct(t) ||
520 btf_type_is_var(t) || btf_type_is_typedef(t);
523 u32 btf_nr_types(const struct btf *btf)
528 total += btf->nr_types;
535 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
537 const struct btf_type *t;
541 total = btf_nr_types(btf);
542 for (i = 1; i < total; i++) {
543 t = btf_type_by_id(btf, i);
544 if (BTF_INFO_KIND(t->info) != kind)
547 tname = btf_name_by_offset(btf, t->name_off);
548 if (!strcmp(tname, name))
555 static s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
561 btf = bpf_get_btf_vmlinux();
567 ret = btf_find_by_name_kind(btf, name, kind);
568 /* ret is never zero, since btf_find_by_name_kind returns
569 * positive btf_id or negative error.
577 /* If name is not found in vmlinux's BTF then search in module's BTFs */
578 spin_lock_bh(&btf_idr_lock);
579 idr_for_each_entry(&btf_idr, btf, id) {
580 if (!btf_is_module(btf))
582 /* linear search could be slow hence unlock/lock
583 * the IDR to avoiding holding it for too long
586 spin_unlock_bh(&btf_idr_lock);
587 ret = btf_find_by_name_kind(btf, name, kind);
593 spin_lock_bh(&btf_idr_lock);
595 spin_unlock_bh(&btf_idr_lock);
599 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
602 const struct btf_type *t = btf_type_by_id(btf, id);
604 while (btf_type_is_modifier(t)) {
606 t = btf_type_by_id(btf, t->type);
615 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
618 const struct btf_type *t;
620 t = btf_type_skip_modifiers(btf, id, NULL);
621 if (!btf_type_is_ptr(t))
624 return btf_type_skip_modifiers(btf, t->type, res_id);
627 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
630 const struct btf_type *ptype;
632 ptype = btf_type_resolve_ptr(btf, id, res_id);
633 if (ptype && btf_type_is_func_proto(ptype))
639 /* Types that act only as a source, not sink or intermediate
640 * type when resolving.
642 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
644 return btf_type_is_var(t) ||
645 btf_type_is_decl_tag(t) ||
646 btf_type_is_datasec(t);
649 /* What types need to be resolved?
651 * btf_type_is_modifier() is an obvious one.
653 * btf_type_is_struct() because its member refers to
654 * another type (through member->type).
656 * btf_type_is_var() because the variable refers to
657 * another type. btf_type_is_datasec() holds multiple
658 * btf_type_is_var() types that need resolving.
660 * btf_type_is_array() because its element (array->type)
661 * refers to another type. Array can be thought of a
662 * special case of struct while array just has the same
663 * member-type repeated by array->nelems of times.
665 static bool btf_type_needs_resolve(const struct btf_type *t)
667 return btf_type_is_modifier(t) ||
668 btf_type_is_ptr(t) ||
669 btf_type_is_struct(t) ||
670 btf_type_is_array(t) ||
671 btf_type_is_var(t) ||
672 btf_type_is_func(t) ||
673 btf_type_is_decl_tag(t) ||
674 btf_type_is_datasec(t);
677 /* t->size can be used */
678 static bool btf_type_has_size(const struct btf_type *t)
680 switch (BTF_INFO_KIND(t->info)) {
682 case BTF_KIND_STRUCT:
685 case BTF_KIND_DATASEC:
687 case BTF_KIND_ENUM64:
694 static const char *btf_int_encoding_str(u8 encoding)
698 else if (encoding == BTF_INT_SIGNED)
700 else if (encoding == BTF_INT_CHAR)
702 else if (encoding == BTF_INT_BOOL)
708 static u32 btf_type_int(const struct btf_type *t)
710 return *(u32 *)(t + 1);
713 static const struct btf_array *btf_type_array(const struct btf_type *t)
715 return (const struct btf_array *)(t + 1);
718 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
720 return (const struct btf_enum *)(t + 1);
723 static const struct btf_var *btf_type_var(const struct btf_type *t)
725 return (const struct btf_var *)(t + 1);
728 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
730 return (const struct btf_decl_tag *)(t + 1);
733 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
735 return (const struct btf_enum64 *)(t + 1);
738 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
740 return kind_ops[BTF_INFO_KIND(t->info)];
743 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
745 if (!BTF_STR_OFFSET_VALID(offset))
748 while (offset < btf->start_str_off)
751 offset -= btf->start_str_off;
752 return offset < btf->hdr.str_len;
755 static bool __btf_name_char_ok(char c, bool first)
757 if ((first ? !isalpha(c) :
765 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
767 while (offset < btf->start_str_off)
770 offset -= btf->start_str_off;
771 if (offset < btf->hdr.str_len)
772 return &btf->strings[offset];
777 static bool __btf_name_valid(const struct btf *btf, u32 offset)
779 /* offset must be valid */
780 const char *src = btf_str_by_offset(btf, offset);
781 const char *src_limit;
783 if (!__btf_name_char_ok(*src, true))
786 /* set a limit on identifier length */
787 src_limit = src + KSYM_NAME_LEN;
789 while (*src && src < src_limit) {
790 if (!__btf_name_char_ok(*src, false))
798 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
800 return __btf_name_valid(btf, offset);
803 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
805 return __btf_name_valid(btf, offset);
808 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
815 name = btf_str_by_offset(btf, offset);
816 return name ?: "(invalid-name-offset)";
819 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
821 return btf_str_by_offset(btf, offset);
824 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
826 while (type_id < btf->start_id)
829 type_id -= btf->start_id;
830 if (type_id >= btf->nr_types)
832 return btf->types[type_id];
834 EXPORT_SYMBOL_GPL(btf_type_by_id);
837 * Regular int is not a bit field and it must be either
838 * u8/u16/u32/u64 or __int128.
840 static bool btf_type_int_is_regular(const struct btf_type *t)
842 u8 nr_bits, nr_bytes;
845 int_data = btf_type_int(t);
846 nr_bits = BTF_INT_BITS(int_data);
847 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
848 if (BITS_PER_BYTE_MASKED(nr_bits) ||
849 BTF_INT_OFFSET(int_data) ||
850 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
851 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
852 nr_bytes != (2 * sizeof(u64)))) {
860 * Check that given struct member is a regular int with expected
863 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
864 const struct btf_member *m,
865 u32 expected_offset, u32 expected_size)
867 const struct btf_type *t;
872 t = btf_type_id_size(btf, &id, NULL);
873 if (!t || !btf_type_is_int(t))
876 int_data = btf_type_int(t);
877 nr_bits = BTF_INT_BITS(int_data);
878 if (btf_type_kflag(s)) {
879 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
880 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
882 /* if kflag set, int should be a regular int and
883 * bit offset should be at byte boundary.
885 return !bitfield_size &&
886 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
887 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
890 if (BTF_INT_OFFSET(int_data) ||
891 BITS_PER_BYTE_MASKED(m->offset) ||
892 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
893 BITS_PER_BYTE_MASKED(nr_bits) ||
894 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
900 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
901 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
904 const struct btf_type *t = btf_type_by_id(btf, id);
906 while (btf_type_is_modifier(t) &&
907 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
908 t = btf_type_by_id(btf, t->type);
914 #define BTF_SHOW_MAX_ITER 10
916 #define BTF_KIND_BIT(kind) (1ULL << kind)
919 * Populate show->state.name with type name information.
920 * Format of type name is
922 * [.member_name = ] (type_name)
924 static const char *btf_show_name(struct btf_show *show)
926 /* BTF_MAX_ITER array suffixes "[]" */
927 const char *array_suffixes = "[][][][][][][][][][]";
928 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
929 /* BTF_MAX_ITER pointer suffixes "*" */
930 const char *ptr_suffixes = "**********";
931 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
932 const char *name = NULL, *prefix = "", *parens = "";
933 const struct btf_member *m = show->state.member;
934 const struct btf_type *t;
935 const struct btf_array *array;
936 u32 id = show->state.type_id;
937 const char *member = NULL;
938 bool show_member = false;
942 show->state.name[0] = '\0';
945 * Don't show type name if we're showing an array member;
946 * in that case we show the array type so don't need to repeat
947 * ourselves for each member.
949 if (show->state.array_member)
952 /* Retrieve member name, if any. */
954 member = btf_name_by_offset(show->btf, m->name_off);
955 show_member = strlen(member) > 0;
960 * Start with type_id, as we have resolved the struct btf_type *
961 * via btf_modifier_show() past the parent typedef to the child
962 * struct, int etc it is defined as. In such cases, the type_id
963 * still represents the starting type while the struct btf_type *
964 * in our show->state points at the resolved type of the typedef.
966 t = btf_type_by_id(show->btf, id);
971 * The goal here is to build up the right number of pointer and
972 * array suffixes while ensuring the type name for a typedef
973 * is represented. Along the way we accumulate a list of
974 * BTF kinds we have encountered, since these will inform later
975 * display; for example, pointer types will not require an
976 * opening "{" for struct, we will just display the pointer value.
978 * We also want to accumulate the right number of pointer or array
979 * indices in the format string while iterating until we get to
980 * the typedef/pointee/array member target type.
982 * We start by pointing at the end of pointer and array suffix
983 * strings; as we accumulate pointers and arrays we move the pointer
984 * or array string backwards so it will show the expected number of
985 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
986 * and/or arrays and typedefs are supported as a precaution.
988 * We also want to get typedef name while proceeding to resolve
989 * type it points to so that we can add parentheses if it is a
990 * "typedef struct" etc.
992 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
994 switch (BTF_INFO_KIND(t->info)) {
995 case BTF_KIND_TYPEDEF:
997 name = btf_name_by_offset(show->btf,
999 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1002 case BTF_KIND_ARRAY:
1003 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1007 array = btf_type_array(t);
1008 if (array_suffix > array_suffixes)
1013 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1014 if (ptr_suffix > ptr_suffixes)
1024 t = btf_type_skip_qualifiers(show->btf, id);
1026 /* We may not be able to represent this type; bail to be safe */
1027 if (i == BTF_SHOW_MAX_ITER)
1031 name = btf_name_by_offset(show->btf, t->name_off);
1033 switch (BTF_INFO_KIND(t->info)) {
1034 case BTF_KIND_STRUCT:
1035 case BTF_KIND_UNION:
1036 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1038 /* if it's an array of struct/union, parens is already set */
1039 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1043 case BTF_KIND_ENUM64:
1050 /* pointer does not require parens */
1051 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1053 /* typedef does not require struct/union/enum prefix */
1054 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1060 /* Even if we don't want type name info, we want parentheses etc */
1061 if (show->flags & BTF_SHOW_NONAME)
1062 snprintf(show->state.name, sizeof(show->state.name), "%s",
1065 snprintf(show->state.name, sizeof(show->state.name),
1066 "%s%s%s(%s%s%s%s%s%s)%s",
1067 /* first 3 strings comprise ".member = " */
1068 show_member ? "." : "",
1069 show_member ? member : "",
1070 show_member ? " = " : "",
1071 /* ...next is our prefix (struct, enum, etc) */
1073 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1074 /* ...this is the type name itself */
1076 /* ...suffixed by the appropriate '*', '[]' suffixes */
1077 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1078 array_suffix, parens);
1080 return show->state.name;
1083 static const char *__btf_show_indent(struct btf_show *show)
1085 const char *indents = " ";
1086 const char *indent = &indents[strlen(indents)];
1088 if ((indent - show->state.depth) >= indents)
1089 return indent - show->state.depth;
1093 static const char *btf_show_indent(struct btf_show *show)
1095 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1098 static const char *btf_show_newline(struct btf_show *show)
1100 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1103 static const char *btf_show_delim(struct btf_show *show)
1105 if (show->state.depth == 0)
1108 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1109 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1115 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1119 if (!show->state.depth_check) {
1120 va_start(args, fmt);
1121 show->showfn(show, fmt, args);
1126 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1127 * format specifiers to the format specifier passed in; these do the work of
1128 * adding indentation, delimiters etc while the caller simply has to specify
1129 * the type value(s) in the format specifier + value(s).
1131 #define btf_show_type_value(show, fmt, value) \
1133 if ((value) != (__typeof__(value))0 || \
1134 (show->flags & BTF_SHOW_ZERO) || \
1135 show->state.depth == 0) { \
1136 btf_show(show, "%s%s" fmt "%s%s", \
1137 btf_show_indent(show), \
1138 btf_show_name(show), \
1139 value, btf_show_delim(show), \
1140 btf_show_newline(show)); \
1141 if (show->state.depth > show->state.depth_to_show) \
1142 show->state.depth_to_show = show->state.depth; \
1146 #define btf_show_type_values(show, fmt, ...) \
1148 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1149 btf_show_name(show), \
1150 __VA_ARGS__, btf_show_delim(show), \
1151 btf_show_newline(show)); \
1152 if (show->state.depth > show->state.depth_to_show) \
1153 show->state.depth_to_show = show->state.depth; \
1156 /* How much is left to copy to safe buffer after @data? */
1157 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1159 return show->obj.head + show->obj.size - data;
1162 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1163 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1165 return data >= show->obj.data &&
1166 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1170 * If object pointed to by @data of @size falls within our safe buffer, return
1171 * the equivalent pointer to the same safe data. Assumes
1172 * copy_from_kernel_nofault() has already happened and our safe buffer is
1175 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1177 if (btf_show_obj_is_safe(show, data, size))
1178 return show->obj.safe + (data - show->obj.data);
1183 * Return a safe-to-access version of data pointed to by @data.
1184 * We do this by copying the relevant amount of information
1185 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1187 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1188 * safe copy is needed.
1190 * Otherwise we need to determine if we have the required amount
1191 * of data (determined by the @data pointer and the size of the
1192 * largest base type we can encounter (represented by
1193 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1194 * that we will be able to print some of the current object,
1195 * and if more is needed a copy will be triggered.
1196 * Some objects such as structs will not fit into the buffer;
1197 * in such cases additional copies when we iterate over their
1198 * members may be needed.
1200 * btf_show_obj_safe() is used to return a safe buffer for
1201 * btf_show_start_type(); this ensures that as we recurse into
1202 * nested types we always have safe data for the given type.
1203 * This approach is somewhat wasteful; it's possible for example
1204 * that when iterating over a large union we'll end up copying the
1205 * same data repeatedly, but the goal is safety not performance.
1206 * We use stack data as opposed to per-CPU buffers because the
1207 * iteration over a type can take some time, and preemption handling
1208 * would greatly complicate use of the safe buffer.
1210 static void *btf_show_obj_safe(struct btf_show *show,
1211 const struct btf_type *t,
1214 const struct btf_type *rt;
1215 int size_left, size;
1218 if (show->flags & BTF_SHOW_UNSAFE)
1221 rt = btf_resolve_size(show->btf, t, &size);
1223 show->state.status = PTR_ERR(rt);
1228 * Is this toplevel object? If so, set total object size and
1229 * initialize pointers. Otherwise check if we still fall within
1230 * our safe object data.
1232 if (show->state.depth == 0) {
1233 show->obj.size = size;
1234 show->obj.head = data;
1237 * If the size of the current object is > our remaining
1238 * safe buffer we _may_ need to do a new copy. However
1239 * consider the case of a nested struct; it's size pushes
1240 * us over the safe buffer limit, but showing any individual
1241 * struct members does not. In such cases, we don't need
1242 * to initiate a fresh copy yet; however we definitely need
1243 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1244 * in our buffer, regardless of the current object size.
1245 * The logic here is that as we resolve types we will
1246 * hit a base type at some point, and we need to be sure
1247 * the next chunk of data is safely available to display
1248 * that type info safely. We cannot rely on the size of
1249 * the current object here because it may be much larger
1250 * than our current buffer (e.g. task_struct is 8k).
1251 * All we want to do here is ensure that we can print the
1252 * next basic type, which we can if either
1253 * - the current type size is within the safe buffer; or
1254 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1257 safe = __btf_show_obj_safe(show, data,
1259 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1263 * We need a new copy to our safe object, either because we haven't
1264 * yet copied and are initializing safe data, or because the data
1265 * we want falls outside the boundaries of the safe object.
1268 size_left = btf_show_obj_size_left(show, data);
1269 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1270 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1271 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1273 if (!show->state.status) {
1274 show->obj.data = data;
1275 safe = show->obj.safe;
1283 * Set the type we are starting to show and return a safe data pointer
1284 * to be used for showing the associated data.
1286 static void *btf_show_start_type(struct btf_show *show,
1287 const struct btf_type *t,
1288 u32 type_id, void *data)
1290 show->state.type = t;
1291 show->state.type_id = type_id;
1292 show->state.name[0] = '\0';
1294 return btf_show_obj_safe(show, t, data);
1297 static void btf_show_end_type(struct btf_show *show)
1299 show->state.type = NULL;
1300 show->state.type_id = 0;
1301 show->state.name[0] = '\0';
1304 static void *btf_show_start_aggr_type(struct btf_show *show,
1305 const struct btf_type *t,
1306 u32 type_id, void *data)
1308 void *safe_data = btf_show_start_type(show, t, type_id, data);
1313 btf_show(show, "%s%s%s", btf_show_indent(show),
1314 btf_show_name(show),
1315 btf_show_newline(show));
1316 show->state.depth++;
1320 static void btf_show_end_aggr_type(struct btf_show *show,
1323 show->state.depth--;
1324 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1325 btf_show_delim(show), btf_show_newline(show));
1326 btf_show_end_type(show);
1329 static void btf_show_start_member(struct btf_show *show,
1330 const struct btf_member *m)
1332 show->state.member = m;
1335 static void btf_show_start_array_member(struct btf_show *show)
1337 show->state.array_member = 1;
1338 btf_show_start_member(show, NULL);
1341 static void btf_show_end_member(struct btf_show *show)
1343 show->state.member = NULL;
1346 static void btf_show_end_array_member(struct btf_show *show)
1348 show->state.array_member = 0;
1349 btf_show_end_member(show);
1352 static void *btf_show_start_array_type(struct btf_show *show,
1353 const struct btf_type *t,
1358 show->state.array_encoding = array_encoding;
1359 show->state.array_terminated = 0;
1360 return btf_show_start_aggr_type(show, t, type_id, data);
1363 static void btf_show_end_array_type(struct btf_show *show)
1365 show->state.array_encoding = 0;
1366 show->state.array_terminated = 0;
1367 btf_show_end_aggr_type(show, "]");
1370 static void *btf_show_start_struct_type(struct btf_show *show,
1371 const struct btf_type *t,
1375 return btf_show_start_aggr_type(show, t, type_id, data);
1378 static void btf_show_end_struct_type(struct btf_show *show)
1380 btf_show_end_aggr_type(show, "}");
1383 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1384 const char *fmt, ...)
1388 va_start(args, fmt);
1389 bpf_verifier_vlog(log, fmt, args);
1393 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1394 const char *fmt, ...)
1396 struct bpf_verifier_log *log = &env->log;
1399 if (!bpf_verifier_log_needed(log))
1402 va_start(args, fmt);
1403 bpf_verifier_vlog(log, fmt, args);
1407 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1408 const struct btf_type *t,
1410 const char *fmt, ...)
1412 struct bpf_verifier_log *log = &env->log;
1413 struct btf *btf = env->btf;
1416 if (!bpf_verifier_log_needed(log))
1419 if (log->level == BPF_LOG_KERNEL) {
1420 /* btf verifier prints all types it is processing via
1421 * btf_verifier_log_type(..., fmt = NULL).
1422 * Skip those prints for in-kernel BTF verification.
1427 /* Skip logging when loading module BTF with mismatches permitted */
1428 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1432 __btf_verifier_log(log, "[%u] %s %s%s",
1435 __btf_name_by_offset(btf, t->name_off),
1436 log_details ? " " : "");
1439 btf_type_ops(t)->log_details(env, t);
1442 __btf_verifier_log(log, " ");
1443 va_start(args, fmt);
1444 bpf_verifier_vlog(log, fmt, args);
1448 __btf_verifier_log(log, "\n");
1451 #define btf_verifier_log_type(env, t, ...) \
1452 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1453 #define btf_verifier_log_basic(env, t, ...) \
1454 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1457 static void btf_verifier_log_member(struct btf_verifier_env *env,
1458 const struct btf_type *struct_type,
1459 const struct btf_member *member,
1460 const char *fmt, ...)
1462 struct bpf_verifier_log *log = &env->log;
1463 struct btf *btf = env->btf;
1466 if (!bpf_verifier_log_needed(log))
1469 if (log->level == BPF_LOG_KERNEL) {
1473 /* Skip logging when loading module BTF with mismatches permitted */
1474 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1478 /* The CHECK_META phase already did a btf dump.
1480 * If member is logged again, it must hit an error in
1481 * parsing this member. It is useful to print out which
1482 * struct this member belongs to.
1484 if (env->phase != CHECK_META)
1485 btf_verifier_log_type(env, struct_type, NULL);
1487 if (btf_type_kflag(struct_type))
1488 __btf_verifier_log(log,
1489 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1490 __btf_name_by_offset(btf, member->name_off),
1492 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1493 BTF_MEMBER_BIT_OFFSET(member->offset));
1495 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1496 __btf_name_by_offset(btf, member->name_off),
1497 member->type, member->offset);
1500 __btf_verifier_log(log, " ");
1501 va_start(args, fmt);
1502 bpf_verifier_vlog(log, fmt, args);
1506 __btf_verifier_log(log, "\n");
1510 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1511 const struct btf_type *datasec_type,
1512 const struct btf_var_secinfo *vsi,
1513 const char *fmt, ...)
1515 struct bpf_verifier_log *log = &env->log;
1518 if (!bpf_verifier_log_needed(log))
1520 if (log->level == BPF_LOG_KERNEL && !fmt)
1522 if (env->phase != CHECK_META)
1523 btf_verifier_log_type(env, datasec_type, NULL);
1525 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1526 vsi->type, vsi->offset, vsi->size);
1528 __btf_verifier_log(log, " ");
1529 va_start(args, fmt);
1530 bpf_verifier_vlog(log, fmt, args);
1534 __btf_verifier_log(log, "\n");
1537 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1540 struct bpf_verifier_log *log = &env->log;
1541 const struct btf *btf = env->btf;
1542 const struct btf_header *hdr;
1544 if (!bpf_verifier_log_needed(log))
1547 if (log->level == BPF_LOG_KERNEL)
1550 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1551 __btf_verifier_log(log, "version: %u\n", hdr->version);
1552 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1553 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1554 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1555 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1556 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1557 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1558 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1561 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1563 struct btf *btf = env->btf;
1565 if (btf->types_size == btf->nr_types) {
1566 /* Expand 'types' array */
1568 struct btf_type **new_types;
1569 u32 expand_by, new_size;
1571 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1572 btf_verifier_log(env, "Exceeded max num of types");
1576 expand_by = max_t(u32, btf->types_size >> 2, 16);
1577 new_size = min_t(u32, BTF_MAX_TYPE,
1578 btf->types_size + expand_by);
1580 new_types = kvcalloc(new_size, sizeof(*new_types),
1581 GFP_KERNEL | __GFP_NOWARN);
1585 if (btf->nr_types == 0) {
1586 if (!btf->base_btf) {
1587 /* lazily init VOID type */
1588 new_types[0] = &btf_void;
1592 memcpy(new_types, btf->types,
1593 sizeof(*btf->types) * btf->nr_types);
1597 btf->types = new_types;
1598 btf->types_size = new_size;
1601 btf->types[btf->nr_types++] = t;
1606 static int btf_alloc_id(struct btf *btf)
1610 idr_preload(GFP_KERNEL);
1611 spin_lock_bh(&btf_idr_lock);
1612 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1615 spin_unlock_bh(&btf_idr_lock);
1618 if (WARN_ON_ONCE(!id))
1621 return id > 0 ? 0 : id;
1624 static void btf_free_id(struct btf *btf)
1626 unsigned long flags;
1629 * In map-in-map, calling map_delete_elem() on outer
1630 * map will call bpf_map_put on the inner map.
1631 * It will then eventually call btf_free_id()
1632 * on the inner map. Some of the map_delete_elem()
1633 * implementation may have irq disabled, so
1634 * we need to use the _irqsave() version instead
1635 * of the _bh() version.
1637 spin_lock_irqsave(&btf_idr_lock, flags);
1638 idr_remove(&btf_idr, btf->id);
1639 spin_unlock_irqrestore(&btf_idr_lock, flags);
1642 static void btf_free_kfunc_set_tab(struct btf *btf)
1644 struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1649 /* For module BTF, we directly assign the sets being registered, so
1650 * there is nothing to free except kfunc_set_tab.
1652 if (btf_is_module(btf))
1654 for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1655 kfree(tab->sets[hook]);
1658 btf->kfunc_set_tab = NULL;
1661 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1663 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1668 btf->dtor_kfunc_tab = NULL;
1671 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1677 for (i = 0; i < tab->cnt; i++)
1678 btf_record_free(tab->types[i].record);
1682 static void btf_free_struct_meta_tab(struct btf *btf)
1684 struct btf_struct_metas *tab = btf->struct_meta_tab;
1686 btf_struct_metas_free(tab);
1687 btf->struct_meta_tab = NULL;
1690 static void btf_free(struct btf *btf)
1692 btf_free_struct_meta_tab(btf);
1693 btf_free_dtor_kfunc_tab(btf);
1694 btf_free_kfunc_set_tab(btf);
1696 kvfree(btf->resolved_sizes);
1697 kvfree(btf->resolved_ids);
1702 static void btf_free_rcu(struct rcu_head *rcu)
1704 struct btf *btf = container_of(rcu, struct btf, rcu);
1709 void btf_get(struct btf *btf)
1711 refcount_inc(&btf->refcnt);
1714 void btf_put(struct btf *btf)
1716 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1718 call_rcu(&btf->rcu, btf_free_rcu);
1722 static int env_resolve_init(struct btf_verifier_env *env)
1724 struct btf *btf = env->btf;
1725 u32 nr_types = btf->nr_types;
1726 u32 *resolved_sizes = NULL;
1727 u32 *resolved_ids = NULL;
1728 u8 *visit_states = NULL;
1730 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1731 GFP_KERNEL | __GFP_NOWARN);
1732 if (!resolved_sizes)
1735 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1736 GFP_KERNEL | __GFP_NOWARN);
1740 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1741 GFP_KERNEL | __GFP_NOWARN);
1745 btf->resolved_sizes = resolved_sizes;
1746 btf->resolved_ids = resolved_ids;
1747 env->visit_states = visit_states;
1752 kvfree(resolved_sizes);
1753 kvfree(resolved_ids);
1754 kvfree(visit_states);
1758 static void btf_verifier_env_free(struct btf_verifier_env *env)
1760 kvfree(env->visit_states);
1764 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1765 const struct btf_type *next_type)
1767 switch (env->resolve_mode) {
1769 /* int, enum or void is a sink */
1770 return !btf_type_needs_resolve(next_type);
1772 /* int, enum, void, struct, array, func or func_proto is a sink
1775 return !btf_type_is_modifier(next_type) &&
1776 !btf_type_is_ptr(next_type);
1777 case RESOLVE_STRUCT_OR_ARRAY:
1778 /* int, enum, void, ptr, func or func_proto is a sink
1779 * for struct and array
1781 return !btf_type_is_modifier(next_type) &&
1782 !btf_type_is_array(next_type) &&
1783 !btf_type_is_struct(next_type);
1789 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1792 /* base BTF types should be resolved by now */
1793 if (type_id < env->btf->start_id)
1796 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1799 static int env_stack_push(struct btf_verifier_env *env,
1800 const struct btf_type *t, u32 type_id)
1802 const struct btf *btf = env->btf;
1803 struct resolve_vertex *v;
1805 if (env->top_stack == MAX_RESOLVE_DEPTH)
1808 if (type_id < btf->start_id
1809 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1812 env->visit_states[type_id - btf->start_id] = VISITED;
1814 v = &env->stack[env->top_stack++];
1816 v->type_id = type_id;
1819 if (env->resolve_mode == RESOLVE_TBD) {
1820 if (btf_type_is_ptr(t))
1821 env->resolve_mode = RESOLVE_PTR;
1822 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1823 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1829 static void env_stack_set_next_member(struct btf_verifier_env *env,
1832 env->stack[env->top_stack - 1].next_member = next_member;
1835 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1836 u32 resolved_type_id,
1839 u32 type_id = env->stack[--(env->top_stack)].type_id;
1840 struct btf *btf = env->btf;
1842 type_id -= btf->start_id; /* adjust to local type id */
1843 btf->resolved_sizes[type_id] = resolved_size;
1844 btf->resolved_ids[type_id] = resolved_type_id;
1845 env->visit_states[type_id] = RESOLVED;
1848 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1850 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1853 /* Resolve the size of a passed-in "type"
1855 * type: is an array (e.g. u32 array[x][y])
1856 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1857 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1858 * corresponds to the return type.
1860 * *elem_id: id of u32
1861 * *total_nelems: (x * y). Hence, individual elem size is
1862 * (*type_size / *total_nelems)
1863 * *type_id: id of type if it's changed within the function, 0 if not
1865 * type: is not an array (e.g. const struct X)
1866 * return type: type "struct X"
1867 * *type_size: sizeof(struct X)
1868 * *elem_type: same as return type ("struct X")
1871 * *type_id: id of type if it's changed within the function, 0 if not
1873 static const struct btf_type *
1874 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1875 u32 *type_size, const struct btf_type **elem_type,
1876 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1878 const struct btf_type *array_type = NULL;
1879 const struct btf_array *array = NULL;
1880 u32 i, size, nelems = 1, id = 0;
1882 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1883 switch (BTF_INFO_KIND(type->info)) {
1884 /* type->size can be used */
1886 case BTF_KIND_STRUCT:
1887 case BTF_KIND_UNION:
1889 case BTF_KIND_FLOAT:
1890 case BTF_KIND_ENUM64:
1895 size = sizeof(void *);
1899 case BTF_KIND_TYPEDEF:
1900 case BTF_KIND_VOLATILE:
1901 case BTF_KIND_CONST:
1902 case BTF_KIND_RESTRICT:
1903 case BTF_KIND_TYPE_TAG:
1905 type = btf_type_by_id(btf, type->type);
1908 case BTF_KIND_ARRAY:
1911 array = btf_type_array(type);
1912 if (nelems && array->nelems > U32_MAX / nelems)
1913 return ERR_PTR(-EINVAL);
1914 nelems *= array->nelems;
1915 type = btf_type_by_id(btf, array->type);
1918 /* type without size */
1920 return ERR_PTR(-EINVAL);
1924 return ERR_PTR(-EINVAL);
1927 if (nelems && size > U32_MAX / nelems)
1928 return ERR_PTR(-EINVAL);
1930 *type_size = nelems * size;
1932 *total_nelems = nelems;
1936 *elem_id = array ? array->type : 0;
1940 return array_type ? : type;
1943 const struct btf_type *
1944 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1947 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1950 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1952 while (type_id < btf->start_id)
1953 btf = btf->base_btf;
1955 return btf->resolved_ids[type_id - btf->start_id];
1958 /* The input param "type_id" must point to a needs_resolve type */
1959 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1962 *type_id = btf_resolved_type_id(btf, *type_id);
1963 return btf_type_by_id(btf, *type_id);
1966 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1968 while (type_id < btf->start_id)
1969 btf = btf->base_btf;
1971 return btf->resolved_sizes[type_id - btf->start_id];
1974 const struct btf_type *btf_type_id_size(const struct btf *btf,
1975 u32 *type_id, u32 *ret_size)
1977 const struct btf_type *size_type;
1978 u32 size_type_id = *type_id;
1981 size_type = btf_type_by_id(btf, size_type_id);
1982 if (btf_type_nosize_or_null(size_type))
1985 if (btf_type_has_size(size_type)) {
1986 size = size_type->size;
1987 } else if (btf_type_is_array(size_type)) {
1988 size = btf_resolved_type_size(btf, size_type_id);
1989 } else if (btf_type_is_ptr(size_type)) {
1990 size = sizeof(void *);
1992 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1993 !btf_type_is_var(size_type)))
1996 size_type_id = btf_resolved_type_id(btf, size_type_id);
1997 size_type = btf_type_by_id(btf, size_type_id);
1998 if (btf_type_nosize_or_null(size_type))
2000 else if (btf_type_has_size(size_type))
2001 size = size_type->size;
2002 else if (btf_type_is_array(size_type))
2003 size = btf_resolved_type_size(btf, size_type_id);
2004 else if (btf_type_is_ptr(size_type))
2005 size = sizeof(void *);
2010 *type_id = size_type_id;
2017 static int btf_df_check_member(struct btf_verifier_env *env,
2018 const struct btf_type *struct_type,
2019 const struct btf_member *member,
2020 const struct btf_type *member_type)
2022 btf_verifier_log_basic(env, struct_type,
2023 "Unsupported check_member");
2027 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2028 const struct btf_type *struct_type,
2029 const struct btf_member *member,
2030 const struct btf_type *member_type)
2032 btf_verifier_log_basic(env, struct_type,
2033 "Unsupported check_kflag_member");
2037 /* Used for ptr, array struct/union and float type members.
2038 * int, enum and modifier types have their specific callback functions.
2040 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2041 const struct btf_type *struct_type,
2042 const struct btf_member *member,
2043 const struct btf_type *member_type)
2045 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2046 btf_verifier_log_member(env, struct_type, member,
2047 "Invalid member bitfield_size");
2051 /* bitfield size is 0, so member->offset represents bit offset only.
2052 * It is safe to call non kflag check_member variants.
2054 return btf_type_ops(member_type)->check_member(env, struct_type,
2059 static int btf_df_resolve(struct btf_verifier_env *env,
2060 const struct resolve_vertex *v)
2062 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2066 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2067 u32 type_id, void *data, u8 bits_offsets,
2068 struct btf_show *show)
2070 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2073 static int btf_int_check_member(struct btf_verifier_env *env,
2074 const struct btf_type *struct_type,
2075 const struct btf_member *member,
2076 const struct btf_type *member_type)
2078 u32 int_data = btf_type_int(member_type);
2079 u32 struct_bits_off = member->offset;
2080 u32 struct_size = struct_type->size;
2084 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2085 btf_verifier_log_member(env, struct_type, member,
2086 "bits_offset exceeds U32_MAX");
2090 struct_bits_off += BTF_INT_OFFSET(int_data);
2091 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2092 nr_copy_bits = BTF_INT_BITS(int_data) +
2093 BITS_PER_BYTE_MASKED(struct_bits_off);
2095 if (nr_copy_bits > BITS_PER_U128) {
2096 btf_verifier_log_member(env, struct_type, member,
2097 "nr_copy_bits exceeds 128");
2101 if (struct_size < bytes_offset ||
2102 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2103 btf_verifier_log_member(env, struct_type, member,
2104 "Member exceeds struct_size");
2111 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2112 const struct btf_type *struct_type,
2113 const struct btf_member *member,
2114 const struct btf_type *member_type)
2116 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2117 u32 int_data = btf_type_int(member_type);
2118 u32 struct_size = struct_type->size;
2121 /* a regular int type is required for the kflag int member */
2122 if (!btf_type_int_is_regular(member_type)) {
2123 btf_verifier_log_member(env, struct_type, member,
2124 "Invalid member base type");
2128 /* check sanity of bitfield size */
2129 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2130 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2131 nr_int_data_bits = BTF_INT_BITS(int_data);
2133 /* Not a bitfield member, member offset must be at byte
2136 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2137 btf_verifier_log_member(env, struct_type, member,
2138 "Invalid member offset");
2142 nr_bits = nr_int_data_bits;
2143 } else if (nr_bits > nr_int_data_bits) {
2144 btf_verifier_log_member(env, struct_type, member,
2145 "Invalid member bitfield_size");
2149 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2150 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2151 if (nr_copy_bits > BITS_PER_U128) {
2152 btf_verifier_log_member(env, struct_type, member,
2153 "nr_copy_bits exceeds 128");
2157 if (struct_size < bytes_offset ||
2158 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2159 btf_verifier_log_member(env, struct_type, member,
2160 "Member exceeds struct_size");
2167 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2168 const struct btf_type *t,
2171 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2174 if (meta_left < meta_needed) {
2175 btf_verifier_log_basic(env, t,
2176 "meta_left:%u meta_needed:%u",
2177 meta_left, meta_needed);
2181 if (btf_type_vlen(t)) {
2182 btf_verifier_log_type(env, t, "vlen != 0");
2186 if (btf_type_kflag(t)) {
2187 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2191 int_data = btf_type_int(t);
2192 if (int_data & ~BTF_INT_MASK) {
2193 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2198 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2200 if (nr_bits > BITS_PER_U128) {
2201 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2206 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2207 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2212 * Only one of the encoding bits is allowed and it
2213 * should be sufficient for the pretty print purpose (i.e. decoding).
2214 * Multiple bits can be allowed later if it is found
2215 * to be insufficient.
2217 encoding = BTF_INT_ENCODING(int_data);
2219 encoding != BTF_INT_SIGNED &&
2220 encoding != BTF_INT_CHAR &&
2221 encoding != BTF_INT_BOOL) {
2222 btf_verifier_log_type(env, t, "Unsupported encoding");
2226 btf_verifier_log_type(env, t, NULL);
2231 static void btf_int_log(struct btf_verifier_env *env,
2232 const struct btf_type *t)
2234 int int_data = btf_type_int(t);
2236 btf_verifier_log(env,
2237 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2238 t->size, BTF_INT_OFFSET(int_data),
2239 BTF_INT_BITS(int_data),
2240 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2243 static void btf_int128_print(struct btf_show *show, void *data)
2245 /* data points to a __int128 number.
2247 * int128_num = *(__int128 *)data;
2248 * The below formulas shows what upper_num and lower_num represents:
2249 * upper_num = int128_num >> 64;
2250 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2252 u64 upper_num, lower_num;
2254 #ifdef __BIG_ENDIAN_BITFIELD
2255 upper_num = *(u64 *)data;
2256 lower_num = *(u64 *)(data + 8);
2258 upper_num = *(u64 *)(data + 8);
2259 lower_num = *(u64 *)data;
2262 btf_show_type_value(show, "0x%llx", lower_num);
2264 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2268 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2269 u16 right_shift_bits)
2271 u64 upper_num, lower_num;
2273 #ifdef __BIG_ENDIAN_BITFIELD
2274 upper_num = print_num[0];
2275 lower_num = print_num[1];
2277 upper_num = print_num[1];
2278 lower_num = print_num[0];
2281 /* shake out un-needed bits by shift/or operations */
2282 if (left_shift_bits >= 64) {
2283 upper_num = lower_num << (left_shift_bits - 64);
2286 upper_num = (upper_num << left_shift_bits) |
2287 (lower_num >> (64 - left_shift_bits));
2288 lower_num = lower_num << left_shift_bits;
2291 if (right_shift_bits >= 64) {
2292 lower_num = upper_num >> (right_shift_bits - 64);
2295 lower_num = (lower_num >> right_shift_bits) |
2296 (upper_num << (64 - right_shift_bits));
2297 upper_num = upper_num >> right_shift_bits;
2300 #ifdef __BIG_ENDIAN_BITFIELD
2301 print_num[0] = upper_num;
2302 print_num[1] = lower_num;
2304 print_num[0] = lower_num;
2305 print_num[1] = upper_num;
2309 static void btf_bitfield_show(void *data, u8 bits_offset,
2310 u8 nr_bits, struct btf_show *show)
2312 u16 left_shift_bits, right_shift_bits;
2315 u64 print_num[2] = {};
2317 nr_copy_bits = nr_bits + bits_offset;
2318 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2320 memcpy(print_num, data, nr_copy_bytes);
2322 #ifdef __BIG_ENDIAN_BITFIELD
2323 left_shift_bits = bits_offset;
2325 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2327 right_shift_bits = BITS_PER_U128 - nr_bits;
2329 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2330 btf_int128_print(show, print_num);
2334 static void btf_int_bits_show(const struct btf *btf,
2335 const struct btf_type *t,
2336 void *data, u8 bits_offset,
2337 struct btf_show *show)
2339 u32 int_data = btf_type_int(t);
2340 u8 nr_bits = BTF_INT_BITS(int_data);
2341 u8 total_bits_offset;
2344 * bits_offset is at most 7.
2345 * BTF_INT_OFFSET() cannot exceed 128 bits.
2347 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2348 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2349 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2350 btf_bitfield_show(data, bits_offset, nr_bits, show);
2353 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2354 u32 type_id, void *data, u8 bits_offset,
2355 struct btf_show *show)
2357 u32 int_data = btf_type_int(t);
2358 u8 encoding = BTF_INT_ENCODING(int_data);
2359 bool sign = encoding & BTF_INT_SIGNED;
2360 u8 nr_bits = BTF_INT_BITS(int_data);
2363 safe_data = btf_show_start_type(show, t, type_id, data);
2367 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2368 BITS_PER_BYTE_MASKED(nr_bits)) {
2369 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2375 btf_int128_print(show, safe_data);
2379 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2381 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2385 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2387 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2391 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2393 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2396 if (show->state.array_encoding == BTF_INT_CHAR) {
2397 /* check for null terminator */
2398 if (show->state.array_terminated)
2400 if (*(char *)data == '\0') {
2401 show->state.array_terminated = 1;
2404 if (isprint(*(char *)data)) {
2405 btf_show_type_value(show, "'%c'",
2406 *(char *)safe_data);
2411 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2413 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2416 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2420 btf_show_end_type(show);
2423 static const struct btf_kind_operations int_ops = {
2424 .check_meta = btf_int_check_meta,
2425 .resolve = btf_df_resolve,
2426 .check_member = btf_int_check_member,
2427 .check_kflag_member = btf_int_check_kflag_member,
2428 .log_details = btf_int_log,
2429 .show = btf_int_show,
2432 static int btf_modifier_check_member(struct btf_verifier_env *env,
2433 const struct btf_type *struct_type,
2434 const struct btf_member *member,
2435 const struct btf_type *member_type)
2437 const struct btf_type *resolved_type;
2438 u32 resolved_type_id = member->type;
2439 struct btf_member resolved_member;
2440 struct btf *btf = env->btf;
2442 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2443 if (!resolved_type) {
2444 btf_verifier_log_member(env, struct_type, member,
2449 resolved_member = *member;
2450 resolved_member.type = resolved_type_id;
2452 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2457 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2458 const struct btf_type *struct_type,
2459 const struct btf_member *member,
2460 const struct btf_type *member_type)
2462 const struct btf_type *resolved_type;
2463 u32 resolved_type_id = member->type;
2464 struct btf_member resolved_member;
2465 struct btf *btf = env->btf;
2467 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2468 if (!resolved_type) {
2469 btf_verifier_log_member(env, struct_type, member,
2474 resolved_member = *member;
2475 resolved_member.type = resolved_type_id;
2477 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2482 static int btf_ptr_check_member(struct btf_verifier_env *env,
2483 const struct btf_type *struct_type,
2484 const struct btf_member *member,
2485 const struct btf_type *member_type)
2487 u32 struct_size, struct_bits_off, bytes_offset;
2489 struct_size = struct_type->size;
2490 struct_bits_off = member->offset;
2491 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2493 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2494 btf_verifier_log_member(env, struct_type, member,
2495 "Member is not byte aligned");
2499 if (struct_size - bytes_offset < sizeof(void *)) {
2500 btf_verifier_log_member(env, struct_type, member,
2501 "Member exceeds struct_size");
2508 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2509 const struct btf_type *t,
2514 if (btf_type_vlen(t)) {
2515 btf_verifier_log_type(env, t, "vlen != 0");
2519 if (btf_type_kflag(t)) {
2520 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2524 if (!BTF_TYPE_ID_VALID(t->type)) {
2525 btf_verifier_log_type(env, t, "Invalid type_id");
2529 /* typedef/type_tag type must have a valid name, and other ref types,
2530 * volatile, const, restrict, should have a null name.
2532 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2534 !btf_name_valid_identifier(env->btf, t->name_off)) {
2535 btf_verifier_log_type(env, t, "Invalid name");
2538 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2539 value = btf_name_by_offset(env->btf, t->name_off);
2540 if (!value || !value[0]) {
2541 btf_verifier_log_type(env, t, "Invalid name");
2546 btf_verifier_log_type(env, t, "Invalid name");
2551 btf_verifier_log_type(env, t, NULL);
2556 static int btf_modifier_resolve(struct btf_verifier_env *env,
2557 const struct resolve_vertex *v)
2559 const struct btf_type *t = v->t;
2560 const struct btf_type *next_type;
2561 u32 next_type_id = t->type;
2562 struct btf *btf = env->btf;
2564 next_type = btf_type_by_id(btf, next_type_id);
2565 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2566 btf_verifier_log_type(env, v->t, "Invalid type_id");
2570 if (!env_type_is_resolve_sink(env, next_type) &&
2571 !env_type_is_resolved(env, next_type_id))
2572 return env_stack_push(env, next_type, next_type_id);
2574 /* Figure out the resolved next_type_id with size.
2575 * They will be stored in the current modifier's
2576 * resolved_ids and resolved_sizes such that it can
2577 * save us a few type-following when we use it later (e.g. in
2580 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2581 if (env_type_is_resolved(env, next_type_id))
2582 next_type = btf_type_id_resolve(btf, &next_type_id);
2584 /* "typedef void new_void", "const void"...etc */
2585 if (!btf_type_is_void(next_type) &&
2586 !btf_type_is_fwd(next_type) &&
2587 !btf_type_is_func_proto(next_type)) {
2588 btf_verifier_log_type(env, v->t, "Invalid type_id");
2593 env_stack_pop_resolved(env, next_type_id, 0);
2598 static int btf_var_resolve(struct btf_verifier_env *env,
2599 const struct resolve_vertex *v)
2601 const struct btf_type *next_type;
2602 const struct btf_type *t = v->t;
2603 u32 next_type_id = t->type;
2604 struct btf *btf = env->btf;
2606 next_type = btf_type_by_id(btf, next_type_id);
2607 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2608 btf_verifier_log_type(env, v->t, "Invalid type_id");
2612 if (!env_type_is_resolve_sink(env, next_type) &&
2613 !env_type_is_resolved(env, next_type_id))
2614 return env_stack_push(env, next_type, next_type_id);
2616 if (btf_type_is_modifier(next_type)) {
2617 const struct btf_type *resolved_type;
2618 u32 resolved_type_id;
2620 resolved_type_id = next_type_id;
2621 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2623 if (btf_type_is_ptr(resolved_type) &&
2624 !env_type_is_resolve_sink(env, resolved_type) &&
2625 !env_type_is_resolved(env, resolved_type_id))
2626 return env_stack_push(env, resolved_type,
2630 /* We must resolve to something concrete at this point, no
2631 * forward types or similar that would resolve to size of
2634 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2635 btf_verifier_log_type(env, v->t, "Invalid type_id");
2639 env_stack_pop_resolved(env, next_type_id, 0);
2644 static int btf_ptr_resolve(struct btf_verifier_env *env,
2645 const struct resolve_vertex *v)
2647 const struct btf_type *next_type;
2648 const struct btf_type *t = v->t;
2649 u32 next_type_id = t->type;
2650 struct btf *btf = env->btf;
2652 next_type = btf_type_by_id(btf, next_type_id);
2653 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2654 btf_verifier_log_type(env, v->t, "Invalid type_id");
2658 if (!env_type_is_resolve_sink(env, next_type) &&
2659 !env_type_is_resolved(env, next_type_id))
2660 return env_stack_push(env, next_type, next_type_id);
2662 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2663 * the modifier may have stopped resolving when it was resolved
2664 * to a ptr (last-resolved-ptr).
2666 * We now need to continue from the last-resolved-ptr to
2667 * ensure the last-resolved-ptr will not referring back to
2668 * the current ptr (t).
2670 if (btf_type_is_modifier(next_type)) {
2671 const struct btf_type *resolved_type;
2672 u32 resolved_type_id;
2674 resolved_type_id = next_type_id;
2675 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2677 if (btf_type_is_ptr(resolved_type) &&
2678 !env_type_is_resolve_sink(env, resolved_type) &&
2679 !env_type_is_resolved(env, resolved_type_id))
2680 return env_stack_push(env, resolved_type,
2684 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2685 if (env_type_is_resolved(env, next_type_id))
2686 next_type = btf_type_id_resolve(btf, &next_type_id);
2688 if (!btf_type_is_void(next_type) &&
2689 !btf_type_is_fwd(next_type) &&
2690 !btf_type_is_func_proto(next_type)) {
2691 btf_verifier_log_type(env, v->t, "Invalid type_id");
2696 env_stack_pop_resolved(env, next_type_id, 0);
2701 static void btf_modifier_show(const struct btf *btf,
2702 const struct btf_type *t,
2703 u32 type_id, void *data,
2704 u8 bits_offset, struct btf_show *show)
2706 if (btf->resolved_ids)
2707 t = btf_type_id_resolve(btf, &type_id);
2709 t = btf_type_skip_modifiers(btf, type_id, NULL);
2711 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2714 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2715 u32 type_id, void *data, u8 bits_offset,
2716 struct btf_show *show)
2718 t = btf_type_id_resolve(btf, &type_id);
2720 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2723 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2724 u32 type_id, void *data, u8 bits_offset,
2725 struct btf_show *show)
2729 safe_data = btf_show_start_type(show, t, type_id, data);
2733 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2734 if (show->flags & BTF_SHOW_PTR_RAW)
2735 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2737 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2738 btf_show_end_type(show);
2741 static void btf_ref_type_log(struct btf_verifier_env *env,
2742 const struct btf_type *t)
2744 btf_verifier_log(env, "type_id=%u", t->type);
2747 static struct btf_kind_operations modifier_ops = {
2748 .check_meta = btf_ref_type_check_meta,
2749 .resolve = btf_modifier_resolve,
2750 .check_member = btf_modifier_check_member,
2751 .check_kflag_member = btf_modifier_check_kflag_member,
2752 .log_details = btf_ref_type_log,
2753 .show = btf_modifier_show,
2756 static struct btf_kind_operations ptr_ops = {
2757 .check_meta = btf_ref_type_check_meta,
2758 .resolve = btf_ptr_resolve,
2759 .check_member = btf_ptr_check_member,
2760 .check_kflag_member = btf_generic_check_kflag_member,
2761 .log_details = btf_ref_type_log,
2762 .show = btf_ptr_show,
2765 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2766 const struct btf_type *t,
2769 if (btf_type_vlen(t)) {
2770 btf_verifier_log_type(env, t, "vlen != 0");
2775 btf_verifier_log_type(env, t, "type != 0");
2779 /* fwd type must have a valid name */
2781 !btf_name_valid_identifier(env->btf, t->name_off)) {
2782 btf_verifier_log_type(env, t, "Invalid name");
2786 btf_verifier_log_type(env, t, NULL);
2791 static void btf_fwd_type_log(struct btf_verifier_env *env,
2792 const struct btf_type *t)
2794 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2797 static struct btf_kind_operations fwd_ops = {
2798 .check_meta = btf_fwd_check_meta,
2799 .resolve = btf_df_resolve,
2800 .check_member = btf_df_check_member,
2801 .check_kflag_member = btf_df_check_kflag_member,
2802 .log_details = btf_fwd_type_log,
2803 .show = btf_df_show,
2806 static int btf_array_check_member(struct btf_verifier_env *env,
2807 const struct btf_type *struct_type,
2808 const struct btf_member *member,
2809 const struct btf_type *member_type)
2811 u32 struct_bits_off = member->offset;
2812 u32 struct_size, bytes_offset;
2813 u32 array_type_id, array_size;
2814 struct btf *btf = env->btf;
2816 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2817 btf_verifier_log_member(env, struct_type, member,
2818 "Member is not byte aligned");
2822 array_type_id = member->type;
2823 btf_type_id_size(btf, &array_type_id, &array_size);
2824 struct_size = struct_type->size;
2825 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2826 if (struct_size - bytes_offset < array_size) {
2827 btf_verifier_log_member(env, struct_type, member,
2828 "Member exceeds struct_size");
2835 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2836 const struct btf_type *t,
2839 const struct btf_array *array = btf_type_array(t);
2840 u32 meta_needed = sizeof(*array);
2842 if (meta_left < meta_needed) {
2843 btf_verifier_log_basic(env, t,
2844 "meta_left:%u meta_needed:%u",
2845 meta_left, meta_needed);
2849 /* array type should not have a name */
2851 btf_verifier_log_type(env, t, "Invalid name");
2855 if (btf_type_vlen(t)) {
2856 btf_verifier_log_type(env, t, "vlen != 0");
2860 if (btf_type_kflag(t)) {
2861 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2866 btf_verifier_log_type(env, t, "size != 0");
2870 /* Array elem type and index type cannot be in type void,
2871 * so !array->type and !array->index_type are not allowed.
2873 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2874 btf_verifier_log_type(env, t, "Invalid elem");
2878 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2879 btf_verifier_log_type(env, t, "Invalid index");
2883 btf_verifier_log_type(env, t, NULL);
2888 static int btf_array_resolve(struct btf_verifier_env *env,
2889 const struct resolve_vertex *v)
2891 const struct btf_array *array = btf_type_array(v->t);
2892 const struct btf_type *elem_type, *index_type;
2893 u32 elem_type_id, index_type_id;
2894 struct btf *btf = env->btf;
2897 /* Check array->index_type */
2898 index_type_id = array->index_type;
2899 index_type = btf_type_by_id(btf, index_type_id);
2900 if (btf_type_nosize_or_null(index_type) ||
2901 btf_type_is_resolve_source_only(index_type)) {
2902 btf_verifier_log_type(env, v->t, "Invalid index");
2906 if (!env_type_is_resolve_sink(env, index_type) &&
2907 !env_type_is_resolved(env, index_type_id))
2908 return env_stack_push(env, index_type, index_type_id);
2910 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2911 if (!index_type || !btf_type_is_int(index_type) ||
2912 !btf_type_int_is_regular(index_type)) {
2913 btf_verifier_log_type(env, v->t, "Invalid index");
2917 /* Check array->type */
2918 elem_type_id = array->type;
2919 elem_type = btf_type_by_id(btf, elem_type_id);
2920 if (btf_type_nosize_or_null(elem_type) ||
2921 btf_type_is_resolve_source_only(elem_type)) {
2922 btf_verifier_log_type(env, v->t,
2927 if (!env_type_is_resolve_sink(env, elem_type) &&
2928 !env_type_is_resolved(env, elem_type_id))
2929 return env_stack_push(env, elem_type, elem_type_id);
2931 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2933 btf_verifier_log_type(env, v->t, "Invalid elem");
2937 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2938 btf_verifier_log_type(env, v->t, "Invalid array of int");
2942 if (array->nelems && elem_size > U32_MAX / array->nelems) {
2943 btf_verifier_log_type(env, v->t,
2944 "Array size overflows U32_MAX");
2948 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2953 static void btf_array_log(struct btf_verifier_env *env,
2954 const struct btf_type *t)
2956 const struct btf_array *array = btf_type_array(t);
2958 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2959 array->type, array->index_type, array->nelems);
2962 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2963 u32 type_id, void *data, u8 bits_offset,
2964 struct btf_show *show)
2966 const struct btf_array *array = btf_type_array(t);
2967 const struct btf_kind_operations *elem_ops;
2968 const struct btf_type *elem_type;
2969 u32 i, elem_size = 0, elem_type_id;
2972 elem_type_id = array->type;
2973 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2974 if (elem_type && btf_type_has_size(elem_type))
2975 elem_size = elem_type->size;
2977 if (elem_type && btf_type_is_int(elem_type)) {
2978 u32 int_type = btf_type_int(elem_type);
2980 encoding = BTF_INT_ENCODING(int_type);
2983 * BTF_INT_CHAR encoding never seems to be set for
2984 * char arrays, so if size is 1 and element is
2985 * printable as a char, we'll do that.
2988 encoding = BTF_INT_CHAR;
2991 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2996 elem_ops = btf_type_ops(elem_type);
2998 for (i = 0; i < array->nelems; i++) {
3000 btf_show_start_array_member(show);
3002 elem_ops->show(btf, elem_type, elem_type_id, data,
3006 btf_show_end_array_member(show);
3008 if (show->state.array_terminated)
3012 btf_show_end_array_type(show);
3015 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3016 u32 type_id, void *data, u8 bits_offset,
3017 struct btf_show *show)
3019 const struct btf_member *m = show->state.member;
3022 * First check if any members would be shown (are non-zero).
3023 * See comments above "struct btf_show" definition for more
3024 * details on how this works at a high-level.
3026 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3027 if (!show->state.depth_check) {
3028 show->state.depth_check = show->state.depth + 1;
3029 show->state.depth_to_show = 0;
3031 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3032 show->state.member = m;
3034 if (show->state.depth_check != show->state.depth + 1)
3036 show->state.depth_check = 0;
3038 if (show->state.depth_to_show <= show->state.depth)
3041 * Reaching here indicates we have recursed and found
3042 * non-zero array member(s).
3045 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3048 static struct btf_kind_operations array_ops = {
3049 .check_meta = btf_array_check_meta,
3050 .resolve = btf_array_resolve,
3051 .check_member = btf_array_check_member,
3052 .check_kflag_member = btf_generic_check_kflag_member,
3053 .log_details = btf_array_log,
3054 .show = btf_array_show,
3057 static int btf_struct_check_member(struct btf_verifier_env *env,
3058 const struct btf_type *struct_type,
3059 const struct btf_member *member,
3060 const struct btf_type *member_type)
3062 u32 struct_bits_off = member->offset;
3063 u32 struct_size, bytes_offset;
3065 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3066 btf_verifier_log_member(env, struct_type, member,
3067 "Member is not byte aligned");
3071 struct_size = struct_type->size;
3072 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3073 if (struct_size - bytes_offset < member_type->size) {
3074 btf_verifier_log_member(env, struct_type, member,
3075 "Member exceeds struct_size");
3082 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3083 const struct btf_type *t,
3086 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3087 const struct btf_member *member;
3088 u32 meta_needed, last_offset;
3089 struct btf *btf = env->btf;
3090 u32 struct_size = t->size;
3094 meta_needed = btf_type_vlen(t) * sizeof(*member);
3095 if (meta_left < meta_needed) {
3096 btf_verifier_log_basic(env, t,
3097 "meta_left:%u meta_needed:%u",
3098 meta_left, meta_needed);
3102 /* struct type either no name or a valid one */
3104 !btf_name_valid_identifier(env->btf, t->name_off)) {
3105 btf_verifier_log_type(env, t, "Invalid name");
3109 btf_verifier_log_type(env, t, NULL);
3112 for_each_member(i, t, member) {
3113 if (!btf_name_offset_valid(btf, member->name_off)) {
3114 btf_verifier_log_member(env, t, member,
3115 "Invalid member name_offset:%u",
3120 /* struct member either no name or a valid one */
3121 if (member->name_off &&
3122 !btf_name_valid_identifier(btf, member->name_off)) {
3123 btf_verifier_log_member(env, t, member, "Invalid name");
3126 /* A member cannot be in type void */
3127 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3128 btf_verifier_log_member(env, t, member,
3133 offset = __btf_member_bit_offset(t, member);
3134 if (is_union && offset) {
3135 btf_verifier_log_member(env, t, member,
3136 "Invalid member bits_offset");
3141 * ">" instead of ">=" because the last member could be
3144 if (last_offset > offset) {
3145 btf_verifier_log_member(env, t, member,
3146 "Invalid member bits_offset");
3150 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3151 btf_verifier_log_member(env, t, member,
3152 "Member bits_offset exceeds its struct size");
3156 btf_verifier_log_member(env, t, member, NULL);
3157 last_offset = offset;
3163 static int btf_struct_resolve(struct btf_verifier_env *env,
3164 const struct resolve_vertex *v)
3166 const struct btf_member *member;
3170 /* Before continue resolving the next_member,
3171 * ensure the last member is indeed resolved to a
3172 * type with size info.
3174 if (v->next_member) {
3175 const struct btf_type *last_member_type;
3176 const struct btf_member *last_member;
3177 u32 last_member_type_id;
3179 last_member = btf_type_member(v->t) + v->next_member - 1;
3180 last_member_type_id = last_member->type;
3181 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3182 last_member_type_id)))
3185 last_member_type = btf_type_by_id(env->btf,
3186 last_member_type_id);
3187 if (btf_type_kflag(v->t))
3188 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3192 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3199 for_each_member_from(i, v->next_member, v->t, member) {
3200 u32 member_type_id = member->type;
3201 const struct btf_type *member_type = btf_type_by_id(env->btf,
3204 if (btf_type_nosize_or_null(member_type) ||
3205 btf_type_is_resolve_source_only(member_type)) {
3206 btf_verifier_log_member(env, v->t, member,
3211 if (!env_type_is_resolve_sink(env, member_type) &&
3212 !env_type_is_resolved(env, member_type_id)) {
3213 env_stack_set_next_member(env, i + 1);
3214 return env_stack_push(env, member_type, member_type_id);
3217 if (btf_type_kflag(v->t))
3218 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3222 err = btf_type_ops(member_type)->check_member(env, v->t,
3229 env_stack_pop_resolved(env, 0, 0);
3234 static void btf_struct_log(struct btf_verifier_env *env,
3235 const struct btf_type *t)
3237 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3241 BTF_FIELD_IGNORE = 0,
3242 BTF_FIELD_FOUND = 1,
3245 struct btf_field_info {
3246 enum btf_field_type type;
3253 const char *node_name;
3259 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3260 u32 off, int sz, enum btf_field_type field_type,
3261 struct btf_field_info *info)
3263 if (!__btf_type_is_struct(t))
3264 return BTF_FIELD_IGNORE;
3266 return BTF_FIELD_IGNORE;
3267 info->type = field_type;
3269 return BTF_FIELD_FOUND;
3272 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3273 u32 off, int sz, struct btf_field_info *info)
3275 enum btf_field_type type;
3278 /* Permit modifiers on the pointer itself */
3279 if (btf_type_is_volatile(t))
3280 t = btf_type_by_id(btf, t->type);
3281 /* For PTR, sz is always == 8 */
3282 if (!btf_type_is_ptr(t))
3283 return BTF_FIELD_IGNORE;
3284 t = btf_type_by_id(btf, t->type);
3286 if (!btf_type_is_type_tag(t))
3287 return BTF_FIELD_IGNORE;
3288 /* Reject extra tags */
3289 if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3291 if (!strcmp("kptr_untrusted", __btf_name_by_offset(btf, t->name_off)))
3292 type = BPF_KPTR_UNREF;
3293 else if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3294 type = BPF_KPTR_REF;
3298 /* Get the base type */
3299 t = btf_type_skip_modifiers(btf, t->type, &res_id);
3300 /* Only pointer to struct is allowed */
3301 if (!__btf_type_is_struct(t))
3306 info->kptr.type_id = res_id;
3307 return BTF_FIELD_FOUND;
3310 static const char *btf_find_decl_tag_value(const struct btf *btf,
3311 const struct btf_type *pt,
3312 int comp_idx, const char *tag_key)
3316 for (i = 1; i < btf_nr_types(btf); i++) {
3317 const struct btf_type *t = btf_type_by_id(btf, i);
3318 int len = strlen(tag_key);
3320 if (!btf_type_is_decl_tag(t))
3322 if (pt != btf_type_by_id(btf, t->type) ||
3323 btf_type_decl_tag(t)->component_idx != comp_idx)
3325 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3327 return __btf_name_by_offset(btf, t->name_off) + len;
3333 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3334 const struct btf_type *t, int comp_idx, u32 off,
3335 int sz, struct btf_field_info *info,
3336 enum btf_field_type head_type)
3338 const char *node_field_name;
3339 const char *value_type;
3342 if (!__btf_type_is_struct(t))
3343 return BTF_FIELD_IGNORE;
3345 return BTF_FIELD_IGNORE;
3346 value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3349 node_field_name = strstr(value_type, ":");
3350 if (!node_field_name)
3352 value_type = kstrndup(value_type, node_field_name - value_type, GFP_KERNEL | __GFP_NOWARN);
3355 id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3360 if (str_is_empty(node_field_name))
3362 info->type = head_type;
3364 info->graph_root.value_btf_id = id;
3365 info->graph_root.node_name = node_field_name;
3366 return BTF_FIELD_FOUND;
3369 #define field_mask_test_name(field_type, field_type_str) \
3370 if (field_mask & field_type && !strcmp(name, field_type_str)) { \
3371 type = field_type; \
3375 static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3376 int *align, int *sz)
3380 if (field_mask & BPF_SPIN_LOCK) {
3381 if (!strcmp(name, "bpf_spin_lock")) {
3382 if (*seen_mask & BPF_SPIN_LOCK)
3384 *seen_mask |= BPF_SPIN_LOCK;
3385 type = BPF_SPIN_LOCK;
3389 if (field_mask & BPF_TIMER) {
3390 if (!strcmp(name, "bpf_timer")) {
3391 if (*seen_mask & BPF_TIMER)
3393 *seen_mask |= BPF_TIMER;
3398 field_mask_test_name(BPF_LIST_HEAD, "bpf_list_head");
3399 field_mask_test_name(BPF_LIST_NODE, "bpf_list_node");
3400 field_mask_test_name(BPF_RB_ROOT, "bpf_rb_root");
3401 field_mask_test_name(BPF_RB_NODE, "bpf_rb_node");
3402 field_mask_test_name(BPF_REFCOUNT, "bpf_refcount");
3404 /* Only return BPF_KPTR when all other types with matchable names fail */
3405 if (field_mask & BPF_KPTR) {
3406 type = BPF_KPTR_REF;
3411 *sz = btf_field_type_size(type);
3412 *align = btf_field_type_align(type);
3416 #undef field_mask_test_name
3418 static int btf_find_struct_field(const struct btf *btf,
3419 const struct btf_type *t, u32 field_mask,
3420 struct btf_field_info *info, int info_cnt)
3422 int ret, idx = 0, align, sz, field_type;
3423 const struct btf_member *member;
3424 struct btf_field_info tmp;
3425 u32 i, off, seen_mask = 0;
3427 for_each_member(i, t, member) {
3428 const struct btf_type *member_type = btf_type_by_id(btf,
3431 field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3432 field_mask, &seen_mask, &align, &sz);
3433 if (field_type == 0)
3438 off = __btf_member_bit_offset(t, member);
3440 /* valid C code cannot generate such BTF */
3446 switch (field_type) {
3452 ret = btf_find_struct(btf, member_type, off, sz, field_type,
3453 idx < info_cnt ? &info[idx] : &tmp);
3457 case BPF_KPTR_UNREF:
3459 ret = btf_find_kptr(btf, member_type, off, sz,
3460 idx < info_cnt ? &info[idx] : &tmp);
3466 ret = btf_find_graph_root(btf, t, member_type,
3468 idx < info_cnt ? &info[idx] : &tmp,
3477 if (ret == BTF_FIELD_IGNORE)
3479 if (idx >= info_cnt)
3486 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3487 u32 field_mask, struct btf_field_info *info,
3490 int ret, idx = 0, align, sz, field_type;
3491 const struct btf_var_secinfo *vsi;
3492 struct btf_field_info tmp;
3493 u32 i, off, seen_mask = 0;
3495 for_each_vsi(i, t, vsi) {
3496 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3497 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3499 field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3500 field_mask, &seen_mask, &align, &sz);
3501 if (field_type == 0)
3507 if (vsi->size != sz)
3512 switch (field_type) {
3518 ret = btf_find_struct(btf, var_type, off, sz, field_type,
3519 idx < info_cnt ? &info[idx] : &tmp);
3523 case BPF_KPTR_UNREF:
3525 ret = btf_find_kptr(btf, var_type, off, sz,
3526 idx < info_cnt ? &info[idx] : &tmp);
3532 ret = btf_find_graph_root(btf, var, var_type,
3534 idx < info_cnt ? &info[idx] : &tmp,
3543 if (ret == BTF_FIELD_IGNORE)
3545 if (idx >= info_cnt)
3552 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3553 u32 field_mask, struct btf_field_info *info,
3556 if (__btf_type_is_struct(t))
3557 return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
3558 else if (btf_type_is_datasec(t))
3559 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
3563 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3564 struct btf_field_info *info)
3566 struct module *mod = NULL;
3567 const struct btf_type *t;
3568 /* If a matching btf type is found in kernel or module BTFs, kptr_ref
3569 * is that BTF, otherwise it's program BTF
3571 struct btf *kptr_btf;
3575 /* Find type in map BTF, and use it to look up the matching type
3576 * in vmlinux or module BTFs, by name and kind.
3578 t = btf_type_by_id(btf, info->kptr.type_id);
3579 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3581 if (id == -ENOENT) {
3582 /* btf_parse_kptr should only be called w/ btf = program BTF */
3583 WARN_ON_ONCE(btf_is_kernel(btf));
3585 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3586 * kptr allocated via bpf_obj_new
3588 field->kptr.dtor = NULL;
3589 id = info->kptr.type_id;
3590 kptr_btf = (struct btf *)btf;
3597 /* Find and stash the function pointer for the destruction function that
3598 * needs to be eventually invoked from the map free path.
3600 if (info->type == BPF_KPTR_REF) {
3601 const struct btf_type *dtor_func;
3602 const char *dtor_func_name;
3606 /* This call also serves as a whitelist of allowed objects that
3607 * can be used as a referenced pointer and be stored in a map at
3610 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3611 if (dtor_btf_id < 0) {
3616 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3622 if (btf_is_module(kptr_btf)) {
3623 mod = btf_try_get_module(kptr_btf);
3630 /* We already verified dtor_func to be btf_type_is_func
3631 * in register_btf_id_dtor_kfuncs.
3633 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3634 addr = kallsyms_lookup_name(dtor_func_name);
3639 field->kptr.dtor = (void *)addr;
3643 field->kptr.btf_id = id;
3644 field->kptr.btf = kptr_btf;
3645 field->kptr.module = mod;
3654 static int btf_parse_graph_root(const struct btf *btf,
3655 struct btf_field *field,
3656 struct btf_field_info *info,
3657 const char *node_type_name,
3658 size_t node_type_align)
3660 const struct btf_type *t, *n = NULL;
3661 const struct btf_member *member;
3665 t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3666 /* We've already checked that value_btf_id is a struct type. We
3667 * just need to figure out the offset of the list_node, and
3670 for_each_member(i, t, member) {
3671 if (strcmp(info->graph_root.node_name,
3672 __btf_name_by_offset(btf, member->name_off)))
3674 /* Invalid BTF, two members with same name */
3677 n = btf_type_by_id(btf, member->type);
3678 if (!__btf_type_is_struct(n))
3680 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3682 offset = __btf_member_bit_offset(n, member);
3686 if (offset % node_type_align)
3689 field->graph_root.btf = (struct btf *)btf;
3690 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3691 field->graph_root.node_offset = offset;
3698 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3699 struct btf_field_info *info)
3701 return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3702 __alignof__(struct bpf_list_node));
3705 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3706 struct btf_field_info *info)
3708 return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3709 __alignof__(struct bpf_rb_node));
3712 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3714 const struct btf_field *a = (const struct btf_field *)_a;
3715 const struct btf_field *b = (const struct btf_field *)_b;
3717 if (a->offset < b->offset)
3719 else if (a->offset > b->offset)
3724 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3725 u32 field_mask, u32 value_size)
3727 struct btf_field_info info_arr[BTF_FIELDS_MAX];
3728 u32 next_off = 0, field_type_size;
3729 struct btf_record *rec;
3732 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3734 return ERR_PTR(ret);
3739 /* This needs to be kzalloc to zero out padding and unused fields, see
3740 * comment in btf_record_equal.
3742 rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3744 return ERR_PTR(-ENOMEM);
3746 rec->spin_lock_off = -EINVAL;
3747 rec->timer_off = -EINVAL;
3748 rec->refcount_off = -EINVAL;
3749 for (i = 0; i < cnt; i++) {
3750 field_type_size = btf_field_type_size(info_arr[i].type);
3751 if (info_arr[i].off + field_type_size > value_size) {
3752 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3756 if (info_arr[i].off < next_off) {
3760 next_off = info_arr[i].off + field_type_size;
3762 rec->field_mask |= info_arr[i].type;
3763 rec->fields[i].offset = info_arr[i].off;
3764 rec->fields[i].type = info_arr[i].type;
3765 rec->fields[i].size = field_type_size;
3767 switch (info_arr[i].type) {
3769 WARN_ON_ONCE(rec->spin_lock_off >= 0);
3770 /* Cache offset for faster lookup at runtime */
3771 rec->spin_lock_off = rec->fields[i].offset;
3774 WARN_ON_ONCE(rec->timer_off >= 0);
3775 /* Cache offset for faster lookup at runtime */
3776 rec->timer_off = rec->fields[i].offset;
3779 WARN_ON_ONCE(rec->refcount_off >= 0);
3780 /* Cache offset for faster lookup at runtime */
3781 rec->refcount_off = rec->fields[i].offset;
3783 case BPF_KPTR_UNREF:
3785 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3790 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3795 ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
3809 /* bpf_{list_head, rb_node} require bpf_spin_lock */
3810 if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
3811 btf_record_has_field(rec, BPF_RB_ROOT)) && rec->spin_lock_off < 0) {
3816 if (rec->refcount_off < 0 &&
3817 btf_record_has_field(rec, BPF_LIST_NODE) &&
3818 btf_record_has_field(rec, BPF_RB_NODE)) {
3823 sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
3828 btf_record_free(rec);
3829 return ERR_PTR(ret);
3832 #define GRAPH_ROOT_MASK (BPF_LIST_HEAD | BPF_RB_ROOT)
3833 #define GRAPH_NODE_MASK (BPF_LIST_NODE | BPF_RB_NODE)
3835 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3839 /* There are three types that signify ownership of some other type:
3840 * kptr_ref, bpf_list_head, bpf_rb_root.
3841 * kptr_ref only supports storing kernel types, which can't store
3842 * references to program allocated local types.
3844 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
3845 * does not form cycles.
3847 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & GRAPH_ROOT_MASK))
3849 for (i = 0; i < rec->cnt; i++) {
3850 struct btf_struct_meta *meta;
3853 if (!(rec->fields[i].type & GRAPH_ROOT_MASK))
3855 btf_id = rec->fields[i].graph_root.value_btf_id;
3856 meta = btf_find_struct_meta(btf, btf_id);
3859 rec->fields[i].graph_root.value_rec = meta->record;
3861 /* We need to set value_rec for all root types, but no need
3862 * to check ownership cycle for a type unless it's also a
3865 if (!(rec->field_mask & GRAPH_NODE_MASK))
3868 /* We need to ensure ownership acyclicity among all types. The
3869 * proper way to do it would be to topologically sort all BTF
3870 * IDs based on the ownership edges, since there can be multiple
3871 * bpf_{list_head,rb_node} in a type. Instead, we use the
3872 * following resaoning:
3874 * - A type can only be owned by another type in user BTF if it
3875 * has a bpf_{list,rb}_node. Let's call these node types.
3876 * - A type can only _own_ another type in user BTF if it has a
3877 * bpf_{list_head,rb_root}. Let's call these root types.
3879 * We ensure that if a type is both a root and node, its
3880 * element types cannot be root types.
3882 * To ensure acyclicity:
3884 * When A is an root type but not a node, its ownership
3888 * - A is an root, e.g. has bpf_rb_root.
3889 * - B is both a root and node, e.g. has bpf_rb_node and
3891 * - C is only an root, e.g. has bpf_list_node
3893 * When A is both a root and node, some other type already
3894 * owns it in the BTF domain, hence it can not own
3895 * another root type through any of the ownership edges.
3898 * - A is both an root and node.
3899 * - B is only an node.
3901 if (meta->record->field_mask & GRAPH_ROOT_MASK)
3907 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3908 u32 type_id, void *data, u8 bits_offset,
3909 struct btf_show *show)
3911 const struct btf_member *member;
3915 safe_data = btf_show_start_struct_type(show, t, type_id, data);
3919 for_each_member(i, t, member) {
3920 const struct btf_type *member_type = btf_type_by_id(btf,
3922 const struct btf_kind_operations *ops;
3923 u32 member_offset, bitfield_size;
3927 btf_show_start_member(show, member);
3929 member_offset = __btf_member_bit_offset(t, member);
3930 bitfield_size = __btf_member_bitfield_size(t, member);
3931 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3932 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3933 if (bitfield_size) {
3934 safe_data = btf_show_start_type(show, member_type,
3936 data + bytes_offset);
3938 btf_bitfield_show(safe_data,
3940 bitfield_size, show);
3941 btf_show_end_type(show);
3943 ops = btf_type_ops(member_type);
3944 ops->show(btf, member_type, member->type,
3945 data + bytes_offset, bits8_offset, show);
3948 btf_show_end_member(show);
3951 btf_show_end_struct_type(show);
3954 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3955 u32 type_id, void *data, u8 bits_offset,
3956 struct btf_show *show)
3958 const struct btf_member *m = show->state.member;
3961 * First check if any members would be shown (are non-zero).
3962 * See comments above "struct btf_show" definition for more
3963 * details on how this works at a high-level.
3965 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3966 if (!show->state.depth_check) {
3967 show->state.depth_check = show->state.depth + 1;
3968 show->state.depth_to_show = 0;
3970 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3971 /* Restore saved member data here */
3972 show->state.member = m;
3973 if (show->state.depth_check != show->state.depth + 1)
3975 show->state.depth_check = 0;
3977 if (show->state.depth_to_show <= show->state.depth)
3980 * Reaching here indicates we have recursed and found
3981 * non-zero child values.
3985 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3988 static struct btf_kind_operations struct_ops = {
3989 .check_meta = btf_struct_check_meta,
3990 .resolve = btf_struct_resolve,
3991 .check_member = btf_struct_check_member,
3992 .check_kflag_member = btf_generic_check_kflag_member,
3993 .log_details = btf_struct_log,
3994 .show = btf_struct_show,
3997 static int btf_enum_check_member(struct btf_verifier_env *env,
3998 const struct btf_type *struct_type,
3999 const struct btf_member *member,
4000 const struct btf_type *member_type)
4002 u32 struct_bits_off = member->offset;
4003 u32 struct_size, bytes_offset;
4005 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4006 btf_verifier_log_member(env, struct_type, member,
4007 "Member is not byte aligned");
4011 struct_size = struct_type->size;
4012 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4013 if (struct_size - bytes_offset < member_type->size) {
4014 btf_verifier_log_member(env, struct_type, member,
4015 "Member exceeds struct_size");
4022 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4023 const struct btf_type *struct_type,
4024 const struct btf_member *member,
4025 const struct btf_type *member_type)
4027 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4028 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4030 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4031 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4033 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4034 btf_verifier_log_member(env, struct_type, member,
4035 "Member is not byte aligned");
4039 nr_bits = int_bitsize;
4040 } else if (nr_bits > int_bitsize) {
4041 btf_verifier_log_member(env, struct_type, member,
4042 "Invalid member bitfield_size");
4046 struct_size = struct_type->size;
4047 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4048 if (struct_size < bytes_end) {
4049 btf_verifier_log_member(env, struct_type, member,
4050 "Member exceeds struct_size");
4057 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4058 const struct btf_type *t,
4061 const struct btf_enum *enums = btf_type_enum(t);
4062 struct btf *btf = env->btf;
4063 const char *fmt_str;
4067 nr_enums = btf_type_vlen(t);
4068 meta_needed = nr_enums * sizeof(*enums);
4070 if (meta_left < meta_needed) {
4071 btf_verifier_log_basic(env, t,
4072 "meta_left:%u meta_needed:%u",
4073 meta_left, meta_needed);
4077 if (t->size > 8 || !is_power_of_2(t->size)) {
4078 btf_verifier_log_type(env, t, "Unexpected size");
4082 /* enum type either no name or a valid one */
4084 !btf_name_valid_identifier(env->btf, t->name_off)) {
4085 btf_verifier_log_type(env, t, "Invalid name");
4089 btf_verifier_log_type(env, t, NULL);
4091 for (i = 0; i < nr_enums; i++) {
4092 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4093 btf_verifier_log(env, "\tInvalid name_offset:%u",
4098 /* enum member must have a valid name */
4099 if (!enums[i].name_off ||
4100 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4101 btf_verifier_log_type(env, t, "Invalid name");
4105 if (env->log.level == BPF_LOG_KERNEL)
4107 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4108 btf_verifier_log(env, fmt_str,
4109 __btf_name_by_offset(btf, enums[i].name_off),
4116 static void btf_enum_log(struct btf_verifier_env *env,
4117 const struct btf_type *t)
4119 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4122 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4123 u32 type_id, void *data, u8 bits_offset,
4124 struct btf_show *show)
4126 const struct btf_enum *enums = btf_type_enum(t);
4127 u32 i, nr_enums = btf_type_vlen(t);
4131 safe_data = btf_show_start_type(show, t, type_id, data);
4135 v = *(int *)safe_data;
4137 for (i = 0; i < nr_enums; i++) {
4138 if (v != enums[i].val)
4141 btf_show_type_value(show, "%s",
4142 __btf_name_by_offset(btf,
4143 enums[i].name_off));
4145 btf_show_end_type(show);
4149 if (btf_type_kflag(t))
4150 btf_show_type_value(show, "%d", v);
4152 btf_show_type_value(show, "%u", v);
4153 btf_show_end_type(show);
4156 static struct btf_kind_operations enum_ops = {
4157 .check_meta = btf_enum_check_meta,
4158 .resolve = btf_df_resolve,
4159 .check_member = btf_enum_check_member,
4160 .check_kflag_member = btf_enum_check_kflag_member,
4161 .log_details = btf_enum_log,
4162 .show = btf_enum_show,
4165 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4166 const struct btf_type *t,
4169 const struct btf_enum64 *enums = btf_type_enum64(t);
4170 struct btf *btf = env->btf;
4171 const char *fmt_str;
4175 nr_enums = btf_type_vlen(t);
4176 meta_needed = nr_enums * sizeof(*enums);
4178 if (meta_left < meta_needed) {
4179 btf_verifier_log_basic(env, t,
4180 "meta_left:%u meta_needed:%u",
4181 meta_left, meta_needed);
4185 if (t->size > 8 || !is_power_of_2(t->size)) {
4186 btf_verifier_log_type(env, t, "Unexpected size");
4190 /* enum type either no name or a valid one */
4192 !btf_name_valid_identifier(env->btf, t->name_off)) {
4193 btf_verifier_log_type(env, t, "Invalid name");
4197 btf_verifier_log_type(env, t, NULL);
4199 for (i = 0; i < nr_enums; i++) {
4200 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4201 btf_verifier_log(env, "\tInvalid name_offset:%u",
4206 /* enum member must have a valid name */
4207 if (!enums[i].name_off ||
4208 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4209 btf_verifier_log_type(env, t, "Invalid name");
4213 if (env->log.level == BPF_LOG_KERNEL)
4216 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4217 btf_verifier_log(env, fmt_str,
4218 __btf_name_by_offset(btf, enums[i].name_off),
4219 btf_enum64_value(enums + i));
4225 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4226 u32 type_id, void *data, u8 bits_offset,
4227 struct btf_show *show)
4229 const struct btf_enum64 *enums = btf_type_enum64(t);
4230 u32 i, nr_enums = btf_type_vlen(t);
4234 safe_data = btf_show_start_type(show, t, type_id, data);
4238 v = *(u64 *)safe_data;
4240 for (i = 0; i < nr_enums; i++) {
4241 if (v != btf_enum64_value(enums + i))
4244 btf_show_type_value(show, "%s",
4245 __btf_name_by_offset(btf,
4246 enums[i].name_off));
4248 btf_show_end_type(show);
4252 if (btf_type_kflag(t))
4253 btf_show_type_value(show, "%lld", v);
4255 btf_show_type_value(show, "%llu", v);
4256 btf_show_end_type(show);
4259 static struct btf_kind_operations enum64_ops = {
4260 .check_meta = btf_enum64_check_meta,
4261 .resolve = btf_df_resolve,
4262 .check_member = btf_enum_check_member,
4263 .check_kflag_member = btf_enum_check_kflag_member,
4264 .log_details = btf_enum_log,
4265 .show = btf_enum64_show,
4268 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4269 const struct btf_type *t,
4272 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4274 if (meta_left < meta_needed) {
4275 btf_verifier_log_basic(env, t,
4276 "meta_left:%u meta_needed:%u",
4277 meta_left, meta_needed);
4282 btf_verifier_log_type(env, t, "Invalid name");
4286 if (btf_type_kflag(t)) {
4287 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4291 btf_verifier_log_type(env, t, NULL);
4296 static void btf_func_proto_log(struct btf_verifier_env *env,
4297 const struct btf_type *t)
4299 const struct btf_param *args = (const struct btf_param *)(t + 1);
4300 u16 nr_args = btf_type_vlen(t), i;
4302 btf_verifier_log(env, "return=%u args=(", t->type);
4304 btf_verifier_log(env, "void");
4308 if (nr_args == 1 && !args[0].type) {
4309 /* Only one vararg */
4310 btf_verifier_log(env, "vararg");
4314 btf_verifier_log(env, "%u %s", args[0].type,
4315 __btf_name_by_offset(env->btf,
4317 for (i = 1; i < nr_args - 1; i++)
4318 btf_verifier_log(env, ", %u %s", args[i].type,
4319 __btf_name_by_offset(env->btf,
4323 const struct btf_param *last_arg = &args[nr_args - 1];
4326 btf_verifier_log(env, ", %u %s", last_arg->type,
4327 __btf_name_by_offset(env->btf,
4328 last_arg->name_off));
4330 btf_verifier_log(env, ", vararg");
4334 btf_verifier_log(env, ")");
4337 static struct btf_kind_operations func_proto_ops = {
4338 .check_meta = btf_func_proto_check_meta,
4339 .resolve = btf_df_resolve,
4341 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4342 * a struct's member.
4344 * It should be a function pointer instead.
4345 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4347 * Hence, there is no btf_func_check_member().
4349 .check_member = btf_df_check_member,
4350 .check_kflag_member = btf_df_check_kflag_member,
4351 .log_details = btf_func_proto_log,
4352 .show = btf_df_show,
4355 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4356 const struct btf_type *t,
4360 !btf_name_valid_identifier(env->btf, t->name_off)) {
4361 btf_verifier_log_type(env, t, "Invalid name");
4365 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4366 btf_verifier_log_type(env, t, "Invalid func linkage");
4370 if (btf_type_kflag(t)) {
4371 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4375 btf_verifier_log_type(env, t, NULL);
4380 static int btf_func_resolve(struct btf_verifier_env *env,
4381 const struct resolve_vertex *v)
4383 const struct btf_type *t = v->t;
4384 u32 next_type_id = t->type;
4387 err = btf_func_check(env, t);
4391 env_stack_pop_resolved(env, next_type_id, 0);
4395 static struct btf_kind_operations func_ops = {
4396 .check_meta = btf_func_check_meta,
4397 .resolve = btf_func_resolve,
4398 .check_member = btf_df_check_member,
4399 .check_kflag_member = btf_df_check_kflag_member,
4400 .log_details = btf_ref_type_log,
4401 .show = btf_df_show,
4404 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4405 const struct btf_type *t,
4408 const struct btf_var *var;
4409 u32 meta_needed = sizeof(*var);
4411 if (meta_left < meta_needed) {
4412 btf_verifier_log_basic(env, t,
4413 "meta_left:%u meta_needed:%u",
4414 meta_left, meta_needed);
4418 if (btf_type_vlen(t)) {
4419 btf_verifier_log_type(env, t, "vlen != 0");
4423 if (btf_type_kflag(t)) {
4424 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4429 !__btf_name_valid(env->btf, t->name_off)) {
4430 btf_verifier_log_type(env, t, "Invalid name");
4434 /* A var cannot be in type void */
4435 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4436 btf_verifier_log_type(env, t, "Invalid type_id");
4440 var = btf_type_var(t);
4441 if (var->linkage != BTF_VAR_STATIC &&
4442 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4443 btf_verifier_log_type(env, t, "Linkage not supported");
4447 btf_verifier_log_type(env, t, NULL);
4452 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4454 const struct btf_var *var = btf_type_var(t);
4456 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4459 static const struct btf_kind_operations var_ops = {
4460 .check_meta = btf_var_check_meta,
4461 .resolve = btf_var_resolve,
4462 .check_member = btf_df_check_member,
4463 .check_kflag_member = btf_df_check_kflag_member,
4464 .log_details = btf_var_log,
4465 .show = btf_var_show,
4468 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4469 const struct btf_type *t,
4472 const struct btf_var_secinfo *vsi;
4473 u64 last_vsi_end_off = 0, sum = 0;
4476 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
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, "size == 0");
4489 if (btf_type_kflag(t)) {
4490 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4495 !btf_name_valid_section(env->btf, t->name_off)) {
4496 btf_verifier_log_type(env, t, "Invalid name");
4500 btf_verifier_log_type(env, t, NULL);
4502 for_each_vsi(i, t, vsi) {
4503 /* A var cannot be in type void */
4504 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4505 btf_verifier_log_vsi(env, t, vsi,
4510 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4511 btf_verifier_log_vsi(env, t, vsi,
4516 if (!vsi->size || vsi->size > t->size) {
4517 btf_verifier_log_vsi(env, t, vsi,
4522 last_vsi_end_off = vsi->offset + vsi->size;
4523 if (last_vsi_end_off > t->size) {
4524 btf_verifier_log_vsi(env, t, vsi,
4525 "Invalid offset+size");
4529 btf_verifier_log_vsi(env, t, vsi, NULL);
4533 if (t->size < sum) {
4534 btf_verifier_log_type(env, t, "Invalid btf_info size");
4541 static int btf_datasec_resolve(struct btf_verifier_env *env,
4542 const struct resolve_vertex *v)
4544 const struct btf_var_secinfo *vsi;
4545 struct btf *btf = env->btf;
4548 env->resolve_mode = RESOLVE_TBD;
4549 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4550 u32 var_type_id = vsi->type, type_id, type_size = 0;
4551 const struct btf_type *var_type = btf_type_by_id(env->btf,
4553 if (!var_type || !btf_type_is_var(var_type)) {
4554 btf_verifier_log_vsi(env, v->t, vsi,
4555 "Not a VAR kind member");
4559 if (!env_type_is_resolve_sink(env, var_type) &&
4560 !env_type_is_resolved(env, var_type_id)) {
4561 env_stack_set_next_member(env, i + 1);
4562 return env_stack_push(env, var_type, var_type_id);
4565 type_id = var_type->type;
4566 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4567 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4571 if (vsi->size < type_size) {
4572 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4577 env_stack_pop_resolved(env, 0, 0);
4581 static void btf_datasec_log(struct btf_verifier_env *env,
4582 const struct btf_type *t)
4584 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4587 static void btf_datasec_show(const struct btf *btf,
4588 const struct btf_type *t, u32 type_id,
4589 void *data, u8 bits_offset,
4590 struct btf_show *show)
4592 const struct btf_var_secinfo *vsi;
4593 const struct btf_type *var;
4596 if (!btf_show_start_type(show, t, type_id, data))
4599 btf_show_type_value(show, "section (\"%s\") = {",
4600 __btf_name_by_offset(btf, t->name_off));
4601 for_each_vsi(i, t, vsi) {
4602 var = btf_type_by_id(btf, vsi->type);
4604 btf_show(show, ",");
4605 btf_type_ops(var)->show(btf, var, vsi->type,
4606 data + vsi->offset, bits_offset, show);
4608 btf_show_end_type(show);
4611 static const struct btf_kind_operations datasec_ops = {
4612 .check_meta = btf_datasec_check_meta,
4613 .resolve = btf_datasec_resolve,
4614 .check_member = btf_df_check_member,
4615 .check_kflag_member = btf_df_check_kflag_member,
4616 .log_details = btf_datasec_log,
4617 .show = btf_datasec_show,
4620 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4621 const struct btf_type *t,
4624 if (btf_type_vlen(t)) {
4625 btf_verifier_log_type(env, t, "vlen != 0");
4629 if (btf_type_kflag(t)) {
4630 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4634 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4636 btf_verifier_log_type(env, t, "Invalid type_size");
4640 btf_verifier_log_type(env, t, NULL);
4645 static int btf_float_check_member(struct btf_verifier_env *env,
4646 const struct btf_type *struct_type,
4647 const struct btf_member *member,
4648 const struct btf_type *member_type)
4650 u64 start_offset_bytes;
4651 u64 end_offset_bytes;
4656 /* Different architectures have different alignment requirements, so
4657 * here we check only for the reasonable minimum. This way we ensure
4658 * that types after CO-RE can pass the kernel BTF verifier.
4660 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4661 align_bits = align_bytes * BITS_PER_BYTE;
4662 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4663 if (misalign_bits) {
4664 btf_verifier_log_member(env, struct_type, member,
4665 "Member is not properly aligned");
4669 start_offset_bytes = member->offset / BITS_PER_BYTE;
4670 end_offset_bytes = start_offset_bytes + member_type->size;
4671 if (end_offset_bytes > struct_type->size) {
4672 btf_verifier_log_member(env, struct_type, member,
4673 "Member exceeds struct_size");
4680 static void btf_float_log(struct btf_verifier_env *env,
4681 const struct btf_type *t)
4683 btf_verifier_log(env, "size=%u", t->size);
4686 static const struct btf_kind_operations float_ops = {
4687 .check_meta = btf_float_check_meta,
4688 .resolve = btf_df_resolve,
4689 .check_member = btf_float_check_member,
4690 .check_kflag_member = btf_generic_check_kflag_member,
4691 .log_details = btf_float_log,
4692 .show = btf_df_show,
4695 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4696 const struct btf_type *t,
4699 const struct btf_decl_tag *tag;
4700 u32 meta_needed = sizeof(*tag);
4704 if (meta_left < meta_needed) {
4705 btf_verifier_log_basic(env, t,
4706 "meta_left:%u meta_needed:%u",
4707 meta_left, meta_needed);
4711 value = btf_name_by_offset(env->btf, t->name_off);
4712 if (!value || !value[0]) {
4713 btf_verifier_log_type(env, t, "Invalid value");
4717 if (btf_type_vlen(t)) {
4718 btf_verifier_log_type(env, t, "vlen != 0");
4722 if (btf_type_kflag(t)) {
4723 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4727 component_idx = btf_type_decl_tag(t)->component_idx;
4728 if (component_idx < -1) {
4729 btf_verifier_log_type(env, t, "Invalid component_idx");
4733 btf_verifier_log_type(env, t, NULL);
4738 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4739 const struct resolve_vertex *v)
4741 const struct btf_type *next_type;
4742 const struct btf_type *t = v->t;
4743 u32 next_type_id = t->type;
4744 struct btf *btf = env->btf;
4748 next_type = btf_type_by_id(btf, next_type_id);
4749 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4750 btf_verifier_log_type(env, v->t, "Invalid type_id");
4754 if (!env_type_is_resolve_sink(env, next_type) &&
4755 !env_type_is_resolved(env, next_type_id))
4756 return env_stack_push(env, next_type, next_type_id);
4758 component_idx = btf_type_decl_tag(t)->component_idx;
4759 if (component_idx != -1) {
4760 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4761 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4765 if (btf_type_is_struct(next_type)) {
4766 vlen = btf_type_vlen(next_type);
4768 /* next_type should be a function */
4769 next_type = btf_type_by_id(btf, next_type->type);
4770 vlen = btf_type_vlen(next_type);
4773 if ((u32)component_idx >= vlen) {
4774 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4779 env_stack_pop_resolved(env, next_type_id, 0);
4784 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4786 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4787 btf_type_decl_tag(t)->component_idx);
4790 static const struct btf_kind_operations decl_tag_ops = {
4791 .check_meta = btf_decl_tag_check_meta,
4792 .resolve = btf_decl_tag_resolve,
4793 .check_member = btf_df_check_member,
4794 .check_kflag_member = btf_df_check_kflag_member,
4795 .log_details = btf_decl_tag_log,
4796 .show = btf_df_show,
4799 static int btf_func_proto_check(struct btf_verifier_env *env,
4800 const struct btf_type *t)
4802 const struct btf_type *ret_type;
4803 const struct btf_param *args;
4804 const struct btf *btf;
4809 args = (const struct btf_param *)(t + 1);
4810 nr_args = btf_type_vlen(t);
4812 /* Check func return type which could be "void" (t->type == 0) */
4814 u32 ret_type_id = t->type;
4816 ret_type = btf_type_by_id(btf, ret_type_id);
4818 btf_verifier_log_type(env, t, "Invalid return type");
4822 if (btf_type_is_resolve_source_only(ret_type)) {
4823 btf_verifier_log_type(env, t, "Invalid return type");
4827 if (btf_type_needs_resolve(ret_type) &&
4828 !env_type_is_resolved(env, ret_type_id)) {
4829 err = btf_resolve(env, ret_type, ret_type_id);
4834 /* Ensure the return type is a type that has a size */
4835 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4836 btf_verifier_log_type(env, t, "Invalid return type");
4844 /* Last func arg type_id could be 0 if it is a vararg */
4845 if (!args[nr_args - 1].type) {
4846 if (args[nr_args - 1].name_off) {
4847 btf_verifier_log_type(env, t, "Invalid arg#%u",
4854 for (i = 0; i < nr_args; i++) {
4855 const struct btf_type *arg_type;
4858 arg_type_id = args[i].type;
4859 arg_type = btf_type_by_id(btf, arg_type_id);
4861 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4865 if (btf_type_is_resolve_source_only(arg_type)) {
4866 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4870 if (args[i].name_off &&
4871 (!btf_name_offset_valid(btf, args[i].name_off) ||
4872 !btf_name_valid_identifier(btf, args[i].name_off))) {
4873 btf_verifier_log_type(env, t,
4874 "Invalid arg#%u", i + 1);
4878 if (btf_type_needs_resolve(arg_type) &&
4879 !env_type_is_resolved(env, arg_type_id)) {
4880 err = btf_resolve(env, arg_type, arg_type_id);
4885 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4886 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4894 static int btf_func_check(struct btf_verifier_env *env,
4895 const struct btf_type *t)
4897 const struct btf_type *proto_type;
4898 const struct btf_param *args;
4899 const struct btf *btf;
4903 proto_type = btf_type_by_id(btf, t->type);
4905 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4906 btf_verifier_log_type(env, t, "Invalid type_id");
4910 args = (const struct btf_param *)(proto_type + 1);
4911 nr_args = btf_type_vlen(proto_type);
4912 for (i = 0; i < nr_args; i++) {
4913 if (!args[i].name_off && args[i].type) {
4914 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4922 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4923 [BTF_KIND_INT] = &int_ops,
4924 [BTF_KIND_PTR] = &ptr_ops,
4925 [BTF_KIND_ARRAY] = &array_ops,
4926 [BTF_KIND_STRUCT] = &struct_ops,
4927 [BTF_KIND_UNION] = &struct_ops,
4928 [BTF_KIND_ENUM] = &enum_ops,
4929 [BTF_KIND_FWD] = &fwd_ops,
4930 [BTF_KIND_TYPEDEF] = &modifier_ops,
4931 [BTF_KIND_VOLATILE] = &modifier_ops,
4932 [BTF_KIND_CONST] = &modifier_ops,
4933 [BTF_KIND_RESTRICT] = &modifier_ops,
4934 [BTF_KIND_FUNC] = &func_ops,
4935 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4936 [BTF_KIND_VAR] = &var_ops,
4937 [BTF_KIND_DATASEC] = &datasec_ops,
4938 [BTF_KIND_FLOAT] = &float_ops,
4939 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
4940 [BTF_KIND_TYPE_TAG] = &modifier_ops,
4941 [BTF_KIND_ENUM64] = &enum64_ops,
4944 static s32 btf_check_meta(struct btf_verifier_env *env,
4945 const struct btf_type *t,
4948 u32 saved_meta_left = meta_left;
4951 if (meta_left < sizeof(*t)) {
4952 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4953 env->log_type_id, meta_left, sizeof(*t));
4956 meta_left -= sizeof(*t);
4958 if (t->info & ~BTF_INFO_MASK) {
4959 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4960 env->log_type_id, t->info);
4964 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4965 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4966 btf_verifier_log(env, "[%u] Invalid kind:%u",
4967 env->log_type_id, BTF_INFO_KIND(t->info));
4971 if (!btf_name_offset_valid(env->btf, t->name_off)) {
4972 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4973 env->log_type_id, t->name_off);
4977 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4978 if (var_meta_size < 0)
4979 return var_meta_size;
4981 meta_left -= var_meta_size;
4983 return saved_meta_left - meta_left;
4986 static int btf_check_all_metas(struct btf_verifier_env *env)
4988 struct btf *btf = env->btf;
4989 struct btf_header *hdr;
4993 cur = btf->nohdr_data + hdr->type_off;
4994 end = cur + hdr->type_len;
4996 env->log_type_id = btf->base_btf ? btf->start_id : 1;
4998 struct btf_type *t = cur;
5001 meta_size = btf_check_meta(env, t, end - cur);
5005 btf_add_type(env, t);
5013 static bool btf_resolve_valid(struct btf_verifier_env *env,
5014 const struct btf_type *t,
5017 struct btf *btf = env->btf;
5019 if (!env_type_is_resolved(env, type_id))
5022 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5023 return !btf_resolved_type_id(btf, type_id) &&
5024 !btf_resolved_type_size(btf, type_id);
5026 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5027 return btf_resolved_type_id(btf, type_id) &&
5028 !btf_resolved_type_size(btf, type_id);
5030 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5031 btf_type_is_var(t)) {
5032 t = btf_type_id_resolve(btf, &type_id);
5034 !btf_type_is_modifier(t) &&
5035 !btf_type_is_var(t) &&
5036 !btf_type_is_datasec(t);
5039 if (btf_type_is_array(t)) {
5040 const struct btf_array *array = btf_type_array(t);
5041 const struct btf_type *elem_type;
5042 u32 elem_type_id = array->type;
5045 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5046 return elem_type && !btf_type_is_modifier(elem_type) &&
5047 (array->nelems * elem_size ==
5048 btf_resolved_type_size(btf, type_id));
5054 static int btf_resolve(struct btf_verifier_env *env,
5055 const struct btf_type *t, u32 type_id)
5057 u32 save_log_type_id = env->log_type_id;
5058 const struct resolve_vertex *v;
5061 env->resolve_mode = RESOLVE_TBD;
5062 env_stack_push(env, t, type_id);
5063 while (!err && (v = env_stack_peak(env))) {
5064 env->log_type_id = v->type_id;
5065 err = btf_type_ops(v->t)->resolve(env, v);
5068 env->log_type_id = type_id;
5069 if (err == -E2BIG) {
5070 btf_verifier_log_type(env, t,
5071 "Exceeded max resolving depth:%u",
5073 } else if (err == -EEXIST) {
5074 btf_verifier_log_type(env, t, "Loop detected");
5077 /* Final sanity check */
5078 if (!err && !btf_resolve_valid(env, t, type_id)) {
5079 btf_verifier_log_type(env, t, "Invalid resolve state");
5083 env->log_type_id = save_log_type_id;
5087 static int btf_check_all_types(struct btf_verifier_env *env)
5089 struct btf *btf = env->btf;
5090 const struct btf_type *t;
5094 err = env_resolve_init(env);
5099 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5100 type_id = btf->start_id + i;
5101 t = btf_type_by_id(btf, type_id);
5103 env->log_type_id = type_id;
5104 if (btf_type_needs_resolve(t) &&
5105 !env_type_is_resolved(env, type_id)) {
5106 err = btf_resolve(env, t, type_id);
5111 if (btf_type_is_func_proto(t)) {
5112 err = btf_func_proto_check(env, t);
5121 static int btf_parse_type_sec(struct btf_verifier_env *env)
5123 const struct btf_header *hdr = &env->btf->hdr;
5126 /* Type section must align to 4 bytes */
5127 if (hdr->type_off & (sizeof(u32) - 1)) {
5128 btf_verifier_log(env, "Unaligned type_off");
5132 if (!env->btf->base_btf && !hdr->type_len) {
5133 btf_verifier_log(env, "No type found");
5137 err = btf_check_all_metas(env);
5141 return btf_check_all_types(env);
5144 static int btf_parse_str_sec(struct btf_verifier_env *env)
5146 const struct btf_header *hdr;
5147 struct btf *btf = env->btf;
5148 const char *start, *end;
5151 start = btf->nohdr_data + hdr->str_off;
5152 end = start + hdr->str_len;
5154 if (end != btf->data + btf->data_size) {
5155 btf_verifier_log(env, "String section is not at the end");
5159 btf->strings = start;
5161 if (btf->base_btf && !hdr->str_len)
5163 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5164 btf_verifier_log(env, "Invalid string section");
5167 if (!btf->base_btf && start[0]) {
5168 btf_verifier_log(env, "Invalid string section");
5175 static const size_t btf_sec_info_offset[] = {
5176 offsetof(struct btf_header, type_off),
5177 offsetof(struct btf_header, str_off),
5180 static int btf_sec_info_cmp(const void *a, const void *b)
5182 const struct btf_sec_info *x = a;
5183 const struct btf_sec_info *y = b;
5185 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5188 static int btf_check_sec_info(struct btf_verifier_env *env,
5191 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5192 u32 total, expected_total, i;
5193 const struct btf_header *hdr;
5194 const struct btf *btf;
5199 /* Populate the secs from hdr */
5200 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5201 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5202 btf_sec_info_offset[i]);
5204 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5205 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5207 /* Check for gaps and overlap among sections */
5209 expected_total = btf_data_size - hdr->hdr_len;
5210 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5211 if (expected_total < secs[i].off) {
5212 btf_verifier_log(env, "Invalid section offset");
5215 if (total < secs[i].off) {
5217 btf_verifier_log(env, "Unsupported section found");
5220 if (total > secs[i].off) {
5221 btf_verifier_log(env, "Section overlap found");
5224 if (expected_total - total < secs[i].len) {
5225 btf_verifier_log(env,
5226 "Total section length too long");
5229 total += secs[i].len;
5232 /* There is data other than hdr and known sections */
5233 if (expected_total != total) {
5234 btf_verifier_log(env, "Unsupported section found");
5241 static int btf_parse_hdr(struct btf_verifier_env *env)
5243 u32 hdr_len, hdr_copy, btf_data_size;
5244 const struct btf_header *hdr;
5248 btf_data_size = btf->data_size;
5250 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5251 btf_verifier_log(env, "hdr_len not found");
5256 hdr_len = hdr->hdr_len;
5257 if (btf_data_size < hdr_len) {
5258 btf_verifier_log(env, "btf_header not found");
5262 /* Ensure the unsupported header fields are zero */
5263 if (hdr_len > sizeof(btf->hdr)) {
5264 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5265 u8 *end = btf->data + hdr_len;
5267 for (; expected_zero < end; expected_zero++) {
5268 if (*expected_zero) {
5269 btf_verifier_log(env, "Unsupported btf_header");
5275 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5276 memcpy(&btf->hdr, btf->data, hdr_copy);
5280 btf_verifier_log_hdr(env, btf_data_size);
5282 if (hdr->magic != BTF_MAGIC) {
5283 btf_verifier_log(env, "Invalid magic");
5287 if (hdr->version != BTF_VERSION) {
5288 btf_verifier_log(env, "Unsupported version");
5293 btf_verifier_log(env, "Unsupported flags");
5297 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5298 btf_verifier_log(env, "No data");
5302 return btf_check_sec_info(env, btf_data_size);
5305 static const char *alloc_obj_fields[] = {
5314 static struct btf_struct_metas *
5315 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5318 struct btf_id_set set;
5321 u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5324 struct btf_struct_metas *tab = NULL;
5327 BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5328 BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5330 memset(&aof, 0, sizeof(aof));
5331 for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5332 /* Try to find whether this special type exists in user BTF, and
5333 * if so remember its ID so we can easily find it among members
5334 * of structs that we iterate in the next loop.
5336 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5339 aof.set.ids[aof.set.cnt++] = id;
5344 sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5346 n = btf_nr_types(btf);
5347 for (i = 1; i < n; i++) {
5348 struct btf_struct_metas *new_tab;
5349 const struct btf_member *member;
5350 struct btf_struct_meta *type;
5351 struct btf_record *record;
5352 const struct btf_type *t;
5355 t = btf_type_by_id(btf, i);
5360 if (!__btf_type_is_struct(t))
5365 for_each_member(j, t, member) {
5366 if (btf_id_set_contains(&aof.set, member->type))
5371 tab_cnt = tab ? tab->cnt : 0;
5372 new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5373 GFP_KERNEL | __GFP_NOWARN);
5382 type = &tab->types[tab->cnt];
5384 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5385 BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT, t->size);
5386 /* The record cannot be unset, treat it as an error if so */
5387 if (IS_ERR_OR_NULL(record)) {
5388 ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5391 type->record = record;
5396 btf_struct_metas_free(tab);
5397 return ERR_PTR(ret);
5400 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5402 struct btf_struct_metas *tab;
5404 BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5405 tab = btf->struct_meta_tab;
5408 return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5411 static int btf_check_type_tags(struct btf_verifier_env *env,
5412 struct btf *btf, int start_id)
5414 int i, n, good_id = start_id - 1;
5417 n = btf_nr_types(btf);
5418 for (i = start_id; i < n; i++) {
5419 const struct btf_type *t;
5420 int chain_limit = 32;
5423 t = btf_type_by_id(btf, i);
5426 if (!btf_type_is_modifier(t))
5431 in_tags = btf_type_is_type_tag(t);
5432 while (btf_type_is_modifier(t)) {
5433 if (!chain_limit--) {
5434 btf_verifier_log(env, "Max chain length or cycle detected");
5437 if (btf_type_is_type_tag(t)) {
5439 btf_verifier_log(env, "Type tags don't precede modifiers");
5442 } else if (in_tags) {
5445 if (cur_id <= good_id)
5447 /* Move to next type */
5449 t = btf_type_by_id(btf, cur_id);
5458 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5463 err = bpf_vlog_finalize(log, &log_true_size);
5465 if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5466 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5467 &log_true_size, sizeof(log_true_size)))
5473 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5475 bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5476 char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5477 struct btf_struct_metas *struct_meta_tab;
5478 struct btf_verifier_env *env = NULL;
5479 struct btf *btf = NULL;
5483 if (attr->btf_size > BTF_MAX_SIZE)
5484 return ERR_PTR(-E2BIG);
5486 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5488 return ERR_PTR(-ENOMEM);
5490 /* user could have requested verbose verifier output
5491 * and supplied buffer to store the verification trace
5493 err = bpf_vlog_init(&env->log, attr->btf_log_level,
5494 log_ubuf, attr->btf_log_size);
5498 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5505 data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5512 btf->data_size = attr->btf_size;
5514 if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5519 err = btf_parse_hdr(env);
5523 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5525 err = btf_parse_str_sec(env);
5529 err = btf_parse_type_sec(env);
5533 err = btf_check_type_tags(env, btf, 1);
5537 struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5538 if (IS_ERR(struct_meta_tab)) {
5539 err = PTR_ERR(struct_meta_tab);
5542 btf->struct_meta_tab = struct_meta_tab;
5544 if (struct_meta_tab) {
5547 for (i = 0; i < struct_meta_tab->cnt; i++) {
5548 err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5554 err = finalize_log(&env->log, uattr, uattr_size);
5558 btf_verifier_env_free(env);
5559 refcount_set(&btf->refcnt, 1);
5563 btf_free_struct_meta_tab(btf);
5565 /* overwrite err with -ENOSPC or -EFAULT */
5566 ret = finalize_log(&env->log, uattr, uattr_size);
5570 btf_verifier_env_free(env);
5573 return ERR_PTR(err);
5576 extern char __weak __start_BTF[];
5577 extern char __weak __stop_BTF[];
5578 extern struct btf *btf_vmlinux;
5580 #define BPF_MAP_TYPE(_id, _ops)
5581 #define BPF_LINK_TYPE(_id, _name)
5583 struct bpf_ctx_convert {
5584 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5585 prog_ctx_type _id##_prog; \
5586 kern_ctx_type _id##_kern;
5587 #include <linux/bpf_types.h>
5588 #undef BPF_PROG_TYPE
5590 /* 't' is written once under lock. Read many times. */
5591 const struct btf_type *t;
5594 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5596 #include <linux/bpf_types.h>
5597 #undef BPF_PROG_TYPE
5598 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5600 static u8 bpf_ctx_convert_map[] = {
5601 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5602 [_id] = __ctx_convert##_id,
5603 #include <linux/bpf_types.h>
5604 #undef BPF_PROG_TYPE
5605 0, /* avoid empty array */
5608 #undef BPF_LINK_TYPE
5610 const struct btf_member *
5611 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5612 const struct btf_type *t, enum bpf_prog_type prog_type,
5615 const struct btf_type *conv_struct;
5616 const struct btf_type *ctx_struct;
5617 const struct btf_member *ctx_type;
5618 const char *tname, *ctx_tname;
5620 conv_struct = bpf_ctx_convert.t;
5622 bpf_log(log, "btf_vmlinux is malformed\n");
5625 t = btf_type_by_id(btf, t->type);
5626 while (btf_type_is_modifier(t))
5627 t = btf_type_by_id(btf, t->type);
5628 if (!btf_type_is_struct(t)) {
5629 /* Only pointer to struct is supported for now.
5630 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5631 * is not supported yet.
5632 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5636 tname = btf_name_by_offset(btf, t->name_off);
5638 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5641 /* prog_type is valid bpf program type. No need for bounds check. */
5642 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5643 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5644 * Like 'struct __sk_buff'
5646 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5648 /* should not happen */
5651 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5653 /* should not happen */
5654 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5657 /* only compare that prog's ctx type name is the same as
5658 * kernel expects. No need to compare field by field.
5659 * It's ok for bpf prog to do:
5660 * struct __sk_buff {};
5661 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5662 * { // no fields of skb are ever used }
5664 if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5666 if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5668 if (strcmp(ctx_tname, tname)) {
5669 /* bpf_user_pt_regs_t is a typedef, so resolve it to
5670 * underlying struct and check name again
5672 if (!btf_type_is_modifier(ctx_struct))
5674 while (btf_type_is_modifier(ctx_struct))
5675 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_struct->type);
5681 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5683 const struct btf_type *t,
5684 enum bpf_prog_type prog_type,
5687 const struct btf_member *prog_ctx_type, *kern_ctx_type;
5689 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5692 kern_ctx_type = prog_ctx_type + 1;
5693 return kern_ctx_type->type;
5696 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5698 const struct btf_member *kctx_member;
5699 const struct btf_type *conv_struct;
5700 const struct btf_type *kctx_type;
5703 conv_struct = bpf_ctx_convert.t;
5704 /* get member for kernel ctx type */
5705 kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5706 kctx_type_id = kctx_member->type;
5707 kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5708 if (!btf_type_is_struct(kctx_type)) {
5709 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5713 return kctx_type_id;
5716 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5717 BTF_ID(struct, bpf_ctx_convert)
5719 struct btf *btf_parse_vmlinux(void)
5721 struct btf_verifier_env *env = NULL;
5722 struct bpf_verifier_log *log;
5723 struct btf *btf = NULL;
5726 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5728 return ERR_PTR(-ENOMEM);
5731 log->level = BPF_LOG_KERNEL;
5733 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5740 btf->data = __start_BTF;
5741 btf->data_size = __stop_BTF - __start_BTF;
5742 btf->kernel_btf = true;
5743 snprintf(btf->name, sizeof(btf->name), "vmlinux");
5745 err = btf_parse_hdr(env);
5749 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5751 err = btf_parse_str_sec(env);
5755 err = btf_check_all_metas(env);
5759 err = btf_check_type_tags(env, btf, 1);
5763 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
5764 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5766 bpf_struct_ops_init(btf, log);
5768 refcount_set(&btf->refcnt, 1);
5770 err = btf_alloc_id(btf);
5774 btf_verifier_env_free(env);
5778 btf_verifier_env_free(env);
5783 return ERR_PTR(err);
5786 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5788 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5790 struct btf_verifier_env *env = NULL;
5791 struct bpf_verifier_log *log;
5792 struct btf *btf = NULL, *base_btf;
5795 base_btf = bpf_get_btf_vmlinux();
5796 if (IS_ERR(base_btf))
5799 return ERR_PTR(-EINVAL);
5801 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5803 return ERR_PTR(-ENOMEM);
5806 log->level = BPF_LOG_KERNEL;
5808 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5815 btf->base_btf = base_btf;
5816 btf->start_id = base_btf->nr_types;
5817 btf->start_str_off = base_btf->hdr.str_len;
5818 btf->kernel_btf = true;
5819 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5821 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5826 memcpy(btf->data, data, data_size);
5827 btf->data_size = data_size;
5829 err = btf_parse_hdr(env);
5833 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5835 err = btf_parse_str_sec(env);
5839 err = btf_check_all_metas(env);
5843 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5847 btf_verifier_env_free(env);
5848 refcount_set(&btf->refcnt, 1);
5852 btf_verifier_env_free(env);
5858 return ERR_PTR(err);
5861 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5863 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5865 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5868 return tgt_prog->aux->btf;
5870 return prog->aux->attach_btf;
5873 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5875 /* skip modifiers */
5876 t = btf_type_skip_modifiers(btf, t->type, NULL);
5878 return btf_type_is_int(t);
5881 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5884 const struct btf_param *args;
5885 const struct btf_type *t;
5886 u32 offset = 0, nr_args;
5892 nr_args = btf_type_vlen(func_proto);
5893 args = (const struct btf_param *)(func_proto + 1);
5894 for (i = 0; i < nr_args; i++) {
5895 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5896 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5901 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5902 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5909 static bool prog_args_trusted(const struct bpf_prog *prog)
5911 enum bpf_attach_type atype = prog->expected_attach_type;
5913 switch (prog->type) {
5914 case BPF_PROG_TYPE_TRACING:
5915 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
5916 case BPF_PROG_TYPE_LSM:
5917 return bpf_lsm_is_trusted(prog);
5918 case BPF_PROG_TYPE_STRUCT_OPS:
5925 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5926 const struct bpf_prog *prog,
5927 struct bpf_insn_access_aux *info)
5929 const struct btf_type *t = prog->aux->attach_func_proto;
5930 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5931 struct btf *btf = bpf_prog_get_target_btf(prog);
5932 const char *tname = prog->aux->attach_func_name;
5933 struct bpf_verifier_log *log = info->log;
5934 const struct btf_param *args;
5935 const char *tag_value;
5940 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5944 arg = get_ctx_arg_idx(btf, t, off);
5945 args = (const struct btf_param *)(t + 1);
5946 /* if (t == NULL) Fall back to default BPF prog with
5947 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5949 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5950 if (prog->aux->attach_btf_trace) {
5951 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5956 if (arg > nr_args) {
5957 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5962 if (arg == nr_args) {
5963 switch (prog->expected_attach_type) {
5964 case BPF_LSM_CGROUP:
5966 case BPF_TRACE_FEXIT:
5967 /* When LSM programs are attached to void LSM hooks
5968 * they use FEXIT trampolines and when attached to
5969 * int LSM hooks, they use MODIFY_RETURN trampolines.
5971 * While the LSM programs are BPF_MODIFY_RETURN-like
5974 * if (ret_type != 'int')
5977 * is _not_ done here. This is still safe as LSM hooks
5978 * have only void and int return types.
5982 t = btf_type_by_id(btf, t->type);
5984 case BPF_MODIFY_RETURN:
5985 /* For now the BPF_MODIFY_RETURN can only be attached to
5986 * functions that return an int.
5991 t = btf_type_skip_modifiers(btf, t->type, NULL);
5992 if (!btf_type_is_small_int(t)) {
5994 "ret type %s not allowed for fmod_ret\n",
6000 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6006 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6008 t = btf_type_by_id(btf, args[arg].type);
6011 /* skip modifiers */
6012 while (btf_type_is_modifier(t))
6013 t = btf_type_by_id(btf, t->type);
6014 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6015 /* accessing a scalar */
6017 if (!btf_type_is_ptr(t)) {
6019 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6021 __btf_name_by_offset(btf, t->name_off),
6026 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6027 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6028 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6031 type = base_type(ctx_arg_info->reg_type);
6032 flag = type_flag(ctx_arg_info->reg_type);
6033 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6034 (flag & PTR_MAYBE_NULL)) {
6035 info->reg_type = ctx_arg_info->reg_type;
6041 /* This is a pointer to void.
6042 * It is the same as scalar from the verifier safety pov.
6043 * No further pointer walking is allowed.
6047 if (is_int_ptr(btf, t))
6050 /* this is a pointer to another type */
6051 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6052 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6054 if (ctx_arg_info->offset == off) {
6055 if (!ctx_arg_info->btf_id) {
6056 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6060 info->reg_type = ctx_arg_info->reg_type;
6061 info->btf = btf_vmlinux;
6062 info->btf_id = ctx_arg_info->btf_id;
6067 info->reg_type = PTR_TO_BTF_ID;
6068 if (prog_args_trusted(prog))
6069 info->reg_type |= PTR_TRUSTED;
6072 enum bpf_prog_type tgt_type;
6074 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6075 tgt_type = tgt_prog->aux->saved_dst_prog_type;
6077 tgt_type = tgt_prog->type;
6079 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6081 info->btf = btf_vmlinux;
6090 info->btf_id = t->type;
6091 t = btf_type_by_id(btf, t->type);
6093 if (btf_type_is_type_tag(t)) {
6094 tag_value = __btf_name_by_offset(btf, t->name_off);
6095 if (strcmp(tag_value, "user") == 0)
6096 info->reg_type |= MEM_USER;
6097 if (strcmp(tag_value, "percpu") == 0)
6098 info->reg_type |= MEM_PERCPU;
6101 /* skip modifiers */
6102 while (btf_type_is_modifier(t)) {
6103 info->btf_id = t->type;
6104 t = btf_type_by_id(btf, t->type);
6106 if (!btf_type_is_struct(t)) {
6108 "func '%s' arg%d type %s is not a struct\n",
6109 tname, arg, btf_type_str(t));
6112 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6113 tname, arg, info->btf_id, btf_type_str(t),
6114 __btf_name_by_offset(btf, t->name_off));
6118 enum bpf_struct_walk_result {
6125 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6126 const struct btf_type *t, int off, int size,
6127 u32 *next_btf_id, enum bpf_type_flag *flag,
6128 const char **field_name)
6130 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6131 const struct btf_type *mtype, *elem_type = NULL;
6132 const struct btf_member *member;
6133 const char *tname, *mname, *tag_value;
6134 u32 vlen, elem_id, mid;
6138 tname = __btf_name_by_offset(btf, t->name_off);
6139 if (!btf_type_is_struct(t)) {
6140 bpf_log(log, "Type '%s' is not a struct\n", tname);
6144 vlen = btf_type_vlen(t);
6145 if (off + size > t->size) {
6146 /* If the last element is a variable size array, we may
6147 * need to relax the rule.
6149 struct btf_array *array_elem;
6154 member = btf_type_member(t) + vlen - 1;
6155 mtype = btf_type_skip_modifiers(btf, member->type,
6157 if (!btf_type_is_array(mtype))
6160 array_elem = (struct btf_array *)(mtype + 1);
6161 if (array_elem->nelems != 0)
6164 moff = __btf_member_bit_offset(t, member) / 8;
6168 /* allow structure and integer */
6169 t = btf_type_skip_modifiers(btf, array_elem->type,
6172 if (btf_type_is_int(t))
6175 if (!btf_type_is_struct(t))
6178 off = (off - moff) % t->size;
6182 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6187 for_each_member(i, t, member) {
6188 /* offset of the field in bytes */
6189 moff = __btf_member_bit_offset(t, member) / 8;
6190 if (off + size <= moff)
6191 /* won't find anything, field is already too far */
6194 if (__btf_member_bitfield_size(t, member)) {
6195 u32 end_bit = __btf_member_bit_offset(t, member) +
6196 __btf_member_bitfield_size(t, member);
6198 /* off <= moff instead of off == moff because clang
6199 * does not generate a BTF member for anonymous
6200 * bitfield like the ":16" here:
6207 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6210 /* off may be accessing a following member
6214 * Doing partial access at either end of this
6215 * bitfield. Continue on this case also to
6216 * treat it as not accessing this bitfield
6217 * and eventually error out as field not
6218 * found to keep it simple.
6219 * It could be relaxed if there was a legit
6220 * partial access case later.
6225 /* In case of "off" is pointing to holes of a struct */
6229 /* type of the field */
6231 mtype = btf_type_by_id(btf, member->type);
6232 mname = __btf_name_by_offset(btf, member->name_off);
6234 mtype = __btf_resolve_size(btf, mtype, &msize,
6235 &elem_type, &elem_id, &total_nelems,
6237 if (IS_ERR(mtype)) {
6238 bpf_log(log, "field %s doesn't have size\n", mname);
6242 mtrue_end = moff + msize;
6243 if (off >= mtrue_end)
6244 /* no overlap with member, keep iterating */
6247 if (btf_type_is_array(mtype)) {
6250 /* __btf_resolve_size() above helps to
6251 * linearize a multi-dimensional array.
6253 * The logic here is treating an array
6254 * in a struct as the following way:
6257 * struct inner array[2][2];
6263 * struct inner array_elem0;
6264 * struct inner array_elem1;
6265 * struct inner array_elem2;
6266 * struct inner array_elem3;
6269 * When accessing outer->array[1][0], it moves
6270 * moff to "array_elem2", set mtype to
6271 * "struct inner", and msize also becomes
6272 * sizeof(struct inner). Then most of the
6273 * remaining logic will fall through without
6274 * caring the current member is an array or
6277 * Unlike mtype/msize/moff, mtrue_end does not
6278 * change. The naming difference ("_true") tells
6279 * that it is not always corresponding to
6280 * the current mtype/msize/moff.
6281 * It is the true end of the current
6282 * member (i.e. array in this case). That
6283 * will allow an int array to be accessed like
6285 * i.e. allow access beyond the size of
6286 * the array's element as long as it is
6287 * within the mtrue_end boundary.
6290 /* skip empty array */
6291 if (moff == mtrue_end)
6294 msize /= total_nelems;
6295 elem_idx = (off - moff) / msize;
6296 moff += elem_idx * msize;
6301 /* the 'off' we're looking for is either equal to start
6302 * of this field or inside of this struct
6304 if (btf_type_is_struct(mtype)) {
6305 if (BTF_INFO_KIND(mtype->info) == BTF_KIND_UNION &&
6306 btf_type_vlen(mtype) != 1)
6308 * walking unions yields untrusted pointers
6309 * with exception of __bpf_md_ptr and other
6310 * unions with a single member
6312 *flag |= PTR_UNTRUSTED;
6314 /* our field must be inside that union or struct */
6317 /* return if the offset matches the member offset */
6323 /* adjust offset we're looking for */
6328 if (btf_type_is_ptr(mtype)) {
6329 const struct btf_type *stype, *t;
6330 enum bpf_type_flag tmp_flag = 0;
6333 if (msize != size || off != moff) {
6335 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6336 mname, moff, tname, off, size);
6340 /* check type tag */
6341 t = btf_type_by_id(btf, mtype->type);
6342 if (btf_type_is_type_tag(t)) {
6343 tag_value = __btf_name_by_offset(btf, t->name_off);
6344 /* check __user tag */
6345 if (strcmp(tag_value, "user") == 0)
6346 tmp_flag = MEM_USER;
6347 /* check __percpu tag */
6348 if (strcmp(tag_value, "percpu") == 0)
6349 tmp_flag = MEM_PERCPU;
6350 /* check __rcu tag */
6351 if (strcmp(tag_value, "rcu") == 0)
6355 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6356 if (btf_type_is_struct(stype)) {
6360 *field_name = mname;
6365 /* Allow more flexible access within an int as long as
6366 * it is within mtrue_end.
6367 * Since mtrue_end could be the end of an array,
6368 * that also allows using an array of int as a scratch
6369 * space. e.g. skb->cb[].
6371 if (off + size > mtrue_end) {
6373 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6374 mname, mtrue_end, tname, off, size);
6380 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6384 int btf_struct_access(struct bpf_verifier_log *log,
6385 const struct bpf_reg_state *reg,
6386 int off, int size, enum bpf_access_type atype __maybe_unused,
6387 u32 *next_btf_id, enum bpf_type_flag *flag,
6388 const char **field_name)
6390 const struct btf *btf = reg->btf;
6391 enum bpf_type_flag tmp_flag = 0;
6392 const struct btf_type *t;
6393 u32 id = reg->btf_id;
6396 while (type_is_alloc(reg->type)) {
6397 struct btf_struct_meta *meta;
6398 struct btf_record *rec;
6401 meta = btf_find_struct_meta(btf, id);
6405 for (i = 0; i < rec->cnt; i++) {
6406 struct btf_field *field = &rec->fields[i];
6407 u32 offset = field->offset;
6408 if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6410 "direct access to %s is disallowed\n",
6411 btf_field_type_name(field->type));
6418 t = btf_type_by_id(btf, id);
6420 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6424 /* For local types, the destination register cannot
6425 * become a pointer again.
6427 if (type_is_alloc(reg->type))
6428 return SCALAR_VALUE;
6429 /* If we found the pointer or scalar on t+off,
6434 return PTR_TO_BTF_ID;
6436 return SCALAR_VALUE;
6438 /* We found nested struct, so continue the search
6439 * by diving in it. At this point the offset is
6440 * aligned with the new type, so set it to 0.
6442 t = btf_type_by_id(btf, id);
6446 /* It's either error or unknown return value..
6449 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6458 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6459 * the same. Trivial ID check is not enough due to module BTFs, because we can
6460 * end up with two different module BTFs, but IDs point to the common type in
6463 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6464 const struct btf *btf2, u32 id2)
6470 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6473 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6474 const struct btf *btf, u32 id, int off,
6475 const struct btf *need_btf, u32 need_type_id,
6478 const struct btf_type *type;
6479 enum bpf_type_flag flag;
6482 /* Are we already done? */
6483 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6485 /* In case of strict type match, we do not walk struct, the top level
6486 * type match must succeed. When strict is true, off should have already
6492 type = btf_type_by_id(btf, id);
6495 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6496 if (err != WALK_STRUCT)
6499 /* We found nested struct object. If it matches
6500 * the requested ID, we're done. Otherwise let's
6501 * continue the search with offset 0 in the new
6504 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6512 static int __get_type_size(struct btf *btf, u32 btf_id,
6513 const struct btf_type **ret_type)
6515 const struct btf_type *t;
6517 *ret_type = btf_type_by_id(btf, 0);
6521 t = btf_type_by_id(btf, btf_id);
6522 while (t && btf_type_is_modifier(t))
6523 t = btf_type_by_id(btf, t->type);
6527 if (btf_type_is_ptr(t))
6528 /* kernel size of pointer. Not BPF's size of pointer*/
6529 return sizeof(void *);
6530 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6535 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6539 if (__btf_type_is_struct(t))
6540 flags |= BTF_FMODEL_STRUCT_ARG;
6541 if (btf_type_is_signed_int(t))
6542 flags |= BTF_FMODEL_SIGNED_ARG;
6547 int btf_distill_func_proto(struct bpf_verifier_log *log,
6549 const struct btf_type *func,
6551 struct btf_func_model *m)
6553 const struct btf_param *args;
6554 const struct btf_type *t;
6559 /* BTF function prototype doesn't match the verifier types.
6560 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6562 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6564 m->arg_flags[i] = 0;
6568 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6571 args = (const struct btf_param *)(func + 1);
6572 nargs = btf_type_vlen(func);
6573 if (nargs > MAX_BPF_FUNC_ARGS) {
6575 "The function %s has %d arguments. Too many.\n",
6579 ret = __get_type_size(btf, func->type, &t);
6580 if (ret < 0 || __btf_type_is_struct(t)) {
6582 "The function %s return type %s is unsupported.\n",
6583 tname, btf_type_str(t));
6587 m->ret_flags = __get_type_fmodel_flags(t);
6589 for (i = 0; i < nargs; i++) {
6590 if (i == nargs - 1 && args[i].type == 0) {
6592 "The function %s with variable args is unsupported.\n",
6596 ret = __get_type_size(btf, args[i].type, &t);
6598 /* No support of struct argument size greater than 16 bytes */
6599 if (ret < 0 || ret > 16) {
6601 "The function %s arg%d type %s is unsupported.\n",
6602 tname, i, btf_type_str(t));
6607 "The function %s has malformed void argument.\n",
6611 m->arg_size[i] = ret;
6612 m->arg_flags[i] = __get_type_fmodel_flags(t);
6618 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6619 * t1 points to BTF_KIND_FUNC in btf1
6620 * t2 points to BTF_KIND_FUNC in btf2
6622 * EINVAL - function prototype mismatch
6623 * EFAULT - verifier bug
6624 * 0 - 99% match. The last 1% is validated by the verifier.
6626 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6627 struct btf *btf1, const struct btf_type *t1,
6628 struct btf *btf2, const struct btf_type *t2)
6630 const struct btf_param *args1, *args2;
6631 const char *fn1, *fn2, *s1, *s2;
6632 u32 nargs1, nargs2, i;
6634 fn1 = btf_name_by_offset(btf1, t1->name_off);
6635 fn2 = btf_name_by_offset(btf2, t2->name_off);
6637 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6638 bpf_log(log, "%s() is not a global function\n", fn1);
6641 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6642 bpf_log(log, "%s() is not a global function\n", fn2);
6646 t1 = btf_type_by_id(btf1, t1->type);
6647 if (!t1 || !btf_type_is_func_proto(t1))
6649 t2 = btf_type_by_id(btf2, t2->type);
6650 if (!t2 || !btf_type_is_func_proto(t2))
6653 args1 = (const struct btf_param *)(t1 + 1);
6654 nargs1 = btf_type_vlen(t1);
6655 args2 = (const struct btf_param *)(t2 + 1);
6656 nargs2 = btf_type_vlen(t2);
6658 if (nargs1 != nargs2) {
6659 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6660 fn1, nargs1, fn2, nargs2);
6664 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6665 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6666 if (t1->info != t2->info) {
6668 "Return type %s of %s() doesn't match type %s of %s()\n",
6669 btf_type_str(t1), fn1,
6670 btf_type_str(t2), fn2);
6674 for (i = 0; i < nargs1; i++) {
6675 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6676 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6678 if (t1->info != t2->info) {
6679 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6680 i, fn1, btf_type_str(t1),
6681 fn2, btf_type_str(t2));
6684 if (btf_type_has_size(t1) && t1->size != t2->size) {
6686 "arg%d in %s() has size %d while %s() has %d\n",
6692 /* global functions are validated with scalars and pointers
6693 * to context only. And only global functions can be replaced.
6694 * Hence type check only those types.
6696 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6698 if (!btf_type_is_ptr(t1)) {
6700 "arg%d in %s() has unrecognized type\n",
6704 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6705 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6706 if (!btf_type_is_struct(t1)) {
6708 "arg%d in %s() is not a pointer to context\n",
6712 if (!btf_type_is_struct(t2)) {
6714 "arg%d in %s() is not a pointer to context\n",
6718 /* This is an optional check to make program writing easier.
6719 * Compare names of structs and report an error to the user.
6720 * btf_prepare_func_args() already checked that t2 struct
6721 * is a context type. btf_prepare_func_args() will check
6722 * later that t1 struct is a context type as well.
6724 s1 = btf_name_by_offset(btf1, t1->name_off);
6725 s2 = btf_name_by_offset(btf2, t2->name_off);
6726 if (strcmp(s1, s2)) {
6728 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6729 i, fn1, s1, fn2, s2);
6736 /* Compare BTFs of given program with BTF of target program */
6737 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
6738 struct btf *btf2, const struct btf_type *t2)
6740 struct btf *btf1 = prog->aux->btf;
6741 const struct btf_type *t1;
6744 if (!prog->aux->func_info) {
6745 bpf_log(log, "Program extension requires BTF\n");
6749 btf_id = prog->aux->func_info[0].type_id;
6753 t1 = btf_type_by_id(btf1, btf_id);
6754 if (!t1 || !btf_type_is_func(t1))
6757 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
6760 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6761 const struct btf *btf, u32 func_id,
6762 struct bpf_reg_state *regs,
6764 bool processing_call)
6766 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6767 struct bpf_verifier_log *log = &env->log;
6768 const char *func_name, *ref_tname;
6769 const struct btf_type *t, *ref_t;
6770 const struct btf_param *args;
6771 u32 i, nargs, ref_id;
6774 t = btf_type_by_id(btf, func_id);
6775 if (!t || !btf_type_is_func(t)) {
6776 /* These checks were already done by the verifier while loading
6777 * struct bpf_func_info or in add_kfunc_call().
6779 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6783 func_name = btf_name_by_offset(btf, t->name_off);
6785 t = btf_type_by_id(btf, t->type);
6786 if (!t || !btf_type_is_func_proto(t)) {
6787 bpf_log(log, "Invalid BTF of func %s\n", func_name);
6790 args = (const struct btf_param *)(t + 1);
6791 nargs = btf_type_vlen(t);
6792 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6793 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6794 MAX_BPF_FUNC_REG_ARGS);
6798 /* check that BTF function arguments match actual types that the
6801 for (i = 0; i < nargs; i++) {
6802 enum bpf_arg_type arg_type = ARG_DONTCARE;
6804 struct bpf_reg_state *reg = ®s[regno];
6806 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6807 if (btf_type_is_scalar(t)) {
6808 if (reg->type == SCALAR_VALUE)
6810 bpf_log(log, "R%d is not a scalar\n", regno);
6814 if (!btf_type_is_ptr(t)) {
6815 bpf_log(log, "Unrecognized arg#%d type %s\n",
6816 i, btf_type_str(t));
6820 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6821 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6823 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6827 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6828 /* If function expects ctx type in BTF check that caller
6829 * is passing PTR_TO_CTX.
6831 if (reg->type != PTR_TO_CTX) {
6833 "arg#%d expected pointer to ctx, but got %s\n",
6834 i, btf_type_str(t));
6837 } else if (ptr_to_mem_ok && processing_call) {
6838 const struct btf_type *resolve_ret;
6841 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6842 if (IS_ERR(resolve_ret)) {
6844 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6845 i, btf_type_str(ref_t), ref_tname,
6846 PTR_ERR(resolve_ret));
6850 if (check_mem_reg(env, reg, regno, type_size))
6853 bpf_log(log, "reg type unsupported for arg#%d function %s#%d\n", i,
6854 func_name, func_id);
6862 /* Compare BTF of a function declaration with given bpf_reg_state.
6864 * EFAULT - there is a verifier bug. Abort verification.
6865 * EINVAL - there is a type mismatch or BTF is not available.
6866 * 0 - BTF matches with what bpf_reg_state expects.
6867 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6869 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6870 struct bpf_reg_state *regs)
6872 struct bpf_prog *prog = env->prog;
6873 struct btf *btf = prog->aux->btf;
6878 if (!prog->aux->func_info)
6881 btf_id = prog->aux->func_info[subprog].type_id;
6885 if (prog->aux->func_info_aux[subprog].unreliable)
6888 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6889 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, false);
6891 /* Compiler optimizations can remove arguments from static functions
6892 * or mismatched type can be passed into a global function.
6893 * In such cases mark the function as unreliable from BTF point of view.
6896 prog->aux->func_info_aux[subprog].unreliable = true;
6900 /* Compare BTF of a function call with given bpf_reg_state.
6902 * EFAULT - there is a verifier bug. Abort verification.
6903 * EINVAL - there is a type mismatch or BTF is not available.
6904 * 0 - BTF matches with what bpf_reg_state expects.
6905 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6907 * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6908 * because btf_check_func_arg_match() is still doing both. Once that
6909 * function is split in 2, we can call from here btf_check_subprog_arg_match()
6910 * first, and then treat the calling part in a new code path.
6912 int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6913 struct bpf_reg_state *regs)
6915 struct bpf_prog *prog = env->prog;
6916 struct btf *btf = prog->aux->btf;
6921 if (!prog->aux->func_info)
6924 btf_id = prog->aux->func_info[subprog].type_id;
6928 if (prog->aux->func_info_aux[subprog].unreliable)
6931 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6932 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, true);
6934 /* Compiler optimizations can remove arguments from static functions
6935 * or mismatched type can be passed into a global function.
6936 * In such cases mark the function as unreliable from BTF point of view.
6939 prog->aux->func_info_aux[subprog].unreliable = true;
6943 /* Convert BTF of a function into bpf_reg_state if possible
6945 * EFAULT - there is a verifier bug. Abort verification.
6946 * EINVAL - cannot convert BTF.
6947 * 0 - Successfully converted BTF into bpf_reg_state
6948 * (either PTR_TO_CTX or SCALAR_VALUE).
6950 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6951 struct bpf_reg_state *regs)
6953 struct bpf_verifier_log *log = &env->log;
6954 struct bpf_prog *prog = env->prog;
6955 enum bpf_prog_type prog_type = prog->type;
6956 struct btf *btf = prog->aux->btf;
6957 const struct btf_param *args;
6958 const struct btf_type *t, *ref_t;
6959 u32 i, nargs, btf_id;
6962 if (!prog->aux->func_info ||
6963 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6964 bpf_log(log, "Verifier bug\n");
6968 btf_id = prog->aux->func_info[subprog].type_id;
6970 bpf_log(log, "Global functions need valid BTF\n");
6974 t = btf_type_by_id(btf, btf_id);
6975 if (!t || !btf_type_is_func(t)) {
6976 /* These checks were already done by the verifier while loading
6977 * struct bpf_func_info
6979 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6983 tname = btf_name_by_offset(btf, t->name_off);
6985 if (log->level & BPF_LOG_LEVEL)
6986 bpf_log(log, "Validating %s() func#%d...\n",
6989 if (prog->aux->func_info_aux[subprog].unreliable) {
6990 bpf_log(log, "Verifier bug in function %s()\n", tname);
6993 if (prog_type == BPF_PROG_TYPE_EXT)
6994 prog_type = prog->aux->dst_prog->type;
6996 t = btf_type_by_id(btf, t->type);
6997 if (!t || !btf_type_is_func_proto(t)) {
6998 bpf_log(log, "Invalid type of function %s()\n", tname);
7001 args = (const struct btf_param *)(t + 1);
7002 nargs = btf_type_vlen(t);
7003 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7004 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7005 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7008 /* check that function returns int */
7009 t = btf_type_by_id(btf, t->type);
7010 while (btf_type_is_modifier(t))
7011 t = btf_type_by_id(btf, t->type);
7012 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7014 "Global function %s() doesn't return scalar. Only those are supported.\n",
7018 /* Convert BTF function arguments into verifier types.
7019 * Only PTR_TO_CTX and SCALAR are supported atm.
7021 for (i = 0; i < nargs; i++) {
7022 struct bpf_reg_state *reg = ®s[i + 1];
7024 t = btf_type_by_id(btf, args[i].type);
7025 while (btf_type_is_modifier(t))
7026 t = btf_type_by_id(btf, t->type);
7027 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7028 reg->type = SCALAR_VALUE;
7031 if (btf_type_is_ptr(t)) {
7032 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
7033 reg->type = PTR_TO_CTX;
7037 t = btf_type_skip_modifiers(btf, t->type, NULL);
7039 ref_t = btf_resolve_size(btf, t, ®->mem_size);
7040 if (IS_ERR(ref_t)) {
7042 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7043 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7048 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
7049 reg->id = ++env->id_gen;
7053 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7054 i, btf_type_str(t), tname);
7060 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7061 struct btf_show *show)
7063 const struct btf_type *t = btf_type_by_id(btf, type_id);
7066 memset(&show->state, 0, sizeof(show->state));
7067 memset(&show->obj, 0, sizeof(show->obj));
7069 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7072 static void btf_seq_show(struct btf_show *show, const char *fmt,
7075 seq_vprintf((struct seq_file *)show->target, fmt, args);
7078 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7079 void *obj, struct seq_file *m, u64 flags)
7081 struct btf_show sseq;
7084 sseq.showfn = btf_seq_show;
7087 btf_type_show(btf, type_id, obj, &sseq);
7089 return sseq.state.status;
7092 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7095 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7096 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7097 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7100 struct btf_show_snprintf {
7101 struct btf_show show;
7102 int len_left; /* space left in string */
7103 int len; /* length we would have written */
7106 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7109 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7112 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7115 ssnprintf->len_left = 0;
7116 ssnprintf->len = len;
7117 } else if (len >= ssnprintf->len_left) {
7118 /* no space, drive on to get length we would have written */
7119 ssnprintf->len_left = 0;
7120 ssnprintf->len += len;
7122 ssnprintf->len_left -= len;
7123 ssnprintf->len += len;
7124 show->target += len;
7128 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7129 char *buf, int len, u64 flags)
7131 struct btf_show_snprintf ssnprintf;
7133 ssnprintf.show.target = buf;
7134 ssnprintf.show.flags = flags;
7135 ssnprintf.show.showfn = btf_snprintf_show;
7136 ssnprintf.len_left = len;
7139 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7141 /* If we encountered an error, return it. */
7142 if (ssnprintf.show.state.status)
7143 return ssnprintf.show.state.status;
7145 /* Otherwise return length we would have written */
7146 return ssnprintf.len;
7149 #ifdef CONFIG_PROC_FS
7150 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7152 const struct btf *btf = filp->private_data;
7154 seq_printf(m, "btf_id:\t%u\n", btf->id);
7158 static int btf_release(struct inode *inode, struct file *filp)
7160 btf_put(filp->private_data);
7164 const struct file_operations btf_fops = {
7165 #ifdef CONFIG_PROC_FS
7166 .show_fdinfo = bpf_btf_show_fdinfo,
7168 .release = btf_release,
7171 static int __btf_new_fd(struct btf *btf)
7173 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7176 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7181 btf = btf_parse(attr, uattr, uattr_size);
7183 return PTR_ERR(btf);
7185 ret = btf_alloc_id(btf);
7192 * The BTF ID is published to the userspace.
7193 * All BTF free must go through call_rcu() from
7194 * now on (i.e. free by calling btf_put()).
7197 ret = __btf_new_fd(btf);
7204 struct btf *btf_get_by_fd(int fd)
7212 return ERR_PTR(-EBADF);
7214 if (f.file->f_op != &btf_fops) {
7216 return ERR_PTR(-EINVAL);
7219 btf = f.file->private_data;
7220 refcount_inc(&btf->refcnt);
7226 int btf_get_info_by_fd(const struct btf *btf,
7227 const union bpf_attr *attr,
7228 union bpf_attr __user *uattr)
7230 struct bpf_btf_info __user *uinfo;
7231 struct bpf_btf_info info;
7232 u32 info_copy, btf_copy;
7235 u32 uinfo_len, uname_len, name_len;
7238 uinfo = u64_to_user_ptr(attr->info.info);
7239 uinfo_len = attr->info.info_len;
7241 info_copy = min_t(u32, uinfo_len, sizeof(info));
7242 memset(&info, 0, sizeof(info));
7243 if (copy_from_user(&info, uinfo, info_copy))
7247 ubtf = u64_to_user_ptr(info.btf);
7248 btf_copy = min_t(u32, btf->data_size, info.btf_size);
7249 if (copy_to_user(ubtf, btf->data, btf_copy))
7251 info.btf_size = btf->data_size;
7253 info.kernel_btf = btf->kernel_btf;
7255 uname = u64_to_user_ptr(info.name);
7256 uname_len = info.name_len;
7257 if (!uname ^ !uname_len)
7260 name_len = strlen(btf->name);
7261 info.name_len = name_len;
7264 if (uname_len >= name_len + 1) {
7265 if (copy_to_user(uname, btf->name, name_len + 1))
7270 if (copy_to_user(uname, btf->name, uname_len - 1))
7272 if (put_user(zero, uname + uname_len - 1))
7274 /* let user-space know about too short buffer */
7279 if (copy_to_user(uinfo, &info, info_copy) ||
7280 put_user(info_copy, &uattr->info.info_len))
7286 int btf_get_fd_by_id(u32 id)
7292 btf = idr_find(&btf_idr, id);
7293 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7294 btf = ERR_PTR(-ENOENT);
7298 return PTR_ERR(btf);
7300 fd = __btf_new_fd(btf);
7307 u32 btf_obj_id(const struct btf *btf)
7312 bool btf_is_kernel(const struct btf *btf)
7314 return btf->kernel_btf;
7317 bool btf_is_module(const struct btf *btf)
7319 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7323 BTF_MODULE_F_LIVE = (1 << 0),
7326 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7328 struct list_head list;
7329 struct module *module;
7331 struct bin_attribute *sysfs_attr;
7335 static LIST_HEAD(btf_modules);
7336 static DEFINE_MUTEX(btf_module_mutex);
7339 btf_module_read(struct file *file, struct kobject *kobj,
7340 struct bin_attribute *bin_attr,
7341 char *buf, loff_t off, size_t len)
7343 const struct btf *btf = bin_attr->private;
7345 memcpy(buf, btf->data + off, len);
7349 static void purge_cand_cache(struct btf *btf);
7351 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7354 struct btf_module *btf_mod, *tmp;
7355 struct module *mod = module;
7359 if (mod->btf_data_size == 0 ||
7360 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7361 op != MODULE_STATE_GOING))
7365 case MODULE_STATE_COMING:
7366 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7371 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7374 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7375 pr_warn("failed to validate module [%s] BTF: %ld\n",
7376 mod->name, PTR_ERR(btf));
7379 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7383 err = btf_alloc_id(btf);
7390 purge_cand_cache(NULL);
7391 mutex_lock(&btf_module_mutex);
7392 btf_mod->module = module;
7394 list_add(&btf_mod->list, &btf_modules);
7395 mutex_unlock(&btf_module_mutex);
7397 if (IS_ENABLED(CONFIG_SYSFS)) {
7398 struct bin_attribute *attr;
7400 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7404 sysfs_bin_attr_init(attr);
7405 attr->attr.name = btf->name;
7406 attr->attr.mode = 0444;
7407 attr->size = btf->data_size;
7408 attr->private = btf;
7409 attr->read = btf_module_read;
7411 err = sysfs_create_bin_file(btf_kobj, attr);
7413 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7420 btf_mod->sysfs_attr = attr;
7424 case MODULE_STATE_LIVE:
7425 mutex_lock(&btf_module_mutex);
7426 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7427 if (btf_mod->module != module)
7430 btf_mod->flags |= BTF_MODULE_F_LIVE;
7433 mutex_unlock(&btf_module_mutex);
7435 case MODULE_STATE_GOING:
7436 mutex_lock(&btf_module_mutex);
7437 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7438 if (btf_mod->module != module)
7441 list_del(&btf_mod->list);
7442 if (btf_mod->sysfs_attr)
7443 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7444 purge_cand_cache(btf_mod->btf);
7445 btf_put(btf_mod->btf);
7446 kfree(btf_mod->sysfs_attr);
7450 mutex_unlock(&btf_module_mutex);
7454 return notifier_from_errno(err);
7457 static struct notifier_block btf_module_nb = {
7458 .notifier_call = btf_module_notify,
7461 static int __init btf_module_init(void)
7463 register_module_notifier(&btf_module_nb);
7467 fs_initcall(btf_module_init);
7468 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7470 struct module *btf_try_get_module(const struct btf *btf)
7472 struct module *res = NULL;
7473 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7474 struct btf_module *btf_mod, *tmp;
7476 mutex_lock(&btf_module_mutex);
7477 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7478 if (btf_mod->btf != btf)
7481 /* We must only consider module whose __init routine has
7482 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7483 * which is set from the notifier callback for
7484 * MODULE_STATE_LIVE.
7486 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7487 res = btf_mod->module;
7491 mutex_unlock(&btf_module_mutex);
7497 /* Returns struct btf corresponding to the struct module.
7498 * This function can return NULL or ERR_PTR.
7500 static struct btf *btf_get_module_btf(const struct module *module)
7502 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7503 struct btf_module *btf_mod, *tmp;
7505 struct btf *btf = NULL;
7508 btf = bpf_get_btf_vmlinux();
7509 if (!IS_ERR_OR_NULL(btf))
7514 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7515 mutex_lock(&btf_module_mutex);
7516 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7517 if (btf_mod->module != module)
7520 btf_get(btf_mod->btf);
7524 mutex_unlock(&btf_module_mutex);
7530 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7532 struct btf *btf = NULL;
7539 if (name_sz <= 1 || name[name_sz - 1])
7542 ret = bpf_find_btf_id(name, kind, &btf);
7543 if (ret > 0 && btf_is_module(btf)) {
7544 btf_obj_fd = __btf_new_fd(btf);
7545 if (btf_obj_fd < 0) {
7549 return ret | (((u64)btf_obj_fd) << 32);
7556 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7557 .func = bpf_btf_find_by_name_kind,
7559 .ret_type = RET_INTEGER,
7560 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
7561 .arg2_type = ARG_CONST_SIZE,
7562 .arg3_type = ARG_ANYTHING,
7563 .arg4_type = ARG_ANYTHING,
7566 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7567 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7568 BTF_TRACING_TYPE_xxx
7569 #undef BTF_TRACING_TYPE
7571 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
7572 const struct btf_type *func, u32 func_flags)
7574 u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7575 const char *name, *sfx, *iter_name;
7576 const struct btf_param *arg;
7577 const struct btf_type *t;
7581 /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
7582 if (!flags || (flags & (flags - 1)))
7585 /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
7586 nr_args = btf_type_vlen(func);
7590 arg = &btf_params(func)[0];
7591 t = btf_type_skip_modifiers(btf, arg->type, NULL);
7592 if (!t || !btf_type_is_ptr(t))
7594 t = btf_type_skip_modifiers(btf, t->type, NULL);
7595 if (!t || !__btf_type_is_struct(t))
7598 name = btf_name_by_offset(btf, t->name_off);
7599 if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
7602 /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
7603 * fit nicely in stack slots
7605 if (t->size == 0 || (t->size % 8))
7608 /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
7611 iter_name = name + sizeof(ITER_PREFIX) - 1;
7612 if (flags & KF_ITER_NEW)
7614 else if (flags & KF_ITER_NEXT)
7616 else /* (flags & KF_ITER_DESTROY) */
7619 snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
7620 if (strcmp(func_name, exp_name))
7623 /* only iter constructor should have extra arguments */
7624 if (!(flags & KF_ITER_NEW) && nr_args != 1)
7627 if (flags & KF_ITER_NEXT) {
7628 /* bpf_iter_<type>_next() should return pointer */
7629 t = btf_type_skip_modifiers(btf, func->type, NULL);
7630 if (!t || !btf_type_is_ptr(t))
7634 if (flags & KF_ITER_DESTROY) {
7635 /* bpf_iter_<type>_destroy() should return void */
7636 t = btf_type_by_id(btf, func->type);
7637 if (!t || !btf_type_is_void(t))
7644 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
7646 const struct btf_type *func;
7647 const char *func_name;
7650 /* any kfunc should be FUNC -> FUNC_PROTO */
7651 func = btf_type_by_id(btf, func_id);
7652 if (!func || !btf_type_is_func(func))
7655 /* sanity check kfunc name */
7656 func_name = btf_name_by_offset(btf, func->name_off);
7657 if (!func_name || !func_name[0])
7660 func = btf_type_by_id(btf, func->type);
7661 if (!func || !btf_type_is_func_proto(func))
7664 if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
7665 err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
7673 /* Kernel Function (kfunc) BTF ID set registration API */
7675 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7676 const struct btf_kfunc_id_set *kset)
7678 struct btf_kfunc_hook_filter *hook_filter;
7679 struct btf_id_set8 *add_set = kset->set;
7680 bool vmlinux_set = !btf_is_module(btf);
7681 bool add_filter = !!kset->filter;
7682 struct btf_kfunc_set_tab *tab;
7683 struct btf_id_set8 *set;
7687 if (hook >= BTF_KFUNC_HOOK_MAX) {
7695 tab = btf->kfunc_set_tab;
7697 if (tab && add_filter) {
7700 hook_filter = &tab->hook_filters[hook];
7701 for (i = 0; i < hook_filter->nr_filters; i++) {
7702 if (hook_filter->filters[i] == kset->filter) {
7708 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
7715 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7718 btf->kfunc_set_tab = tab;
7721 set = tab->sets[hook];
7722 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7725 if (WARN_ON_ONCE(set && !vmlinux_set)) {
7730 /* We don't need to allocate, concatenate, and sort module sets, because
7731 * only one is allowed per hook. Hence, we can directly assign the
7732 * pointer and return.
7735 tab->sets[hook] = add_set;
7739 /* In case of vmlinux sets, there may be more than one set being
7740 * registered per hook. To create a unified set, we allocate a new set
7741 * and concatenate all individual sets being registered. While each set
7742 * is individually sorted, they may become unsorted when concatenated,
7743 * hence re-sorting the final set again is required to make binary
7744 * searching the set using btf_id_set8_contains function work.
7746 set_cnt = set ? set->cnt : 0;
7748 if (set_cnt > U32_MAX - add_set->cnt) {
7753 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7759 set = krealloc(tab->sets[hook],
7760 offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
7761 GFP_KERNEL | __GFP_NOWARN);
7767 /* For newly allocated set, initialize set->cnt to 0 */
7768 if (!tab->sets[hook])
7770 tab->sets[hook] = set;
7772 /* Concatenate the two sets */
7773 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
7774 set->cnt += add_set->cnt;
7776 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
7780 hook_filter = &tab->hook_filters[hook];
7781 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
7785 btf_free_kfunc_set_tab(btf);
7789 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
7790 enum btf_kfunc_hook hook,
7792 const struct bpf_prog *prog)
7794 struct btf_kfunc_hook_filter *hook_filter;
7795 struct btf_id_set8 *set;
7798 if (hook >= BTF_KFUNC_HOOK_MAX)
7800 if (!btf->kfunc_set_tab)
7802 hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
7803 for (i = 0; i < hook_filter->nr_filters; i++) {
7804 if (hook_filter->filters[i](prog, kfunc_btf_id))
7807 set = btf->kfunc_set_tab->sets[hook];
7810 id = btf_id_set8_contains(set, kfunc_btf_id);
7813 /* The flags for BTF ID are located next to it */
7817 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7819 switch (prog_type) {
7820 case BPF_PROG_TYPE_UNSPEC:
7821 return BTF_KFUNC_HOOK_COMMON;
7822 case BPF_PROG_TYPE_XDP:
7823 return BTF_KFUNC_HOOK_XDP;
7824 case BPF_PROG_TYPE_SCHED_CLS:
7825 return BTF_KFUNC_HOOK_TC;
7826 case BPF_PROG_TYPE_STRUCT_OPS:
7827 return BTF_KFUNC_HOOK_STRUCT_OPS;
7828 case BPF_PROG_TYPE_TRACING:
7829 case BPF_PROG_TYPE_LSM:
7830 return BTF_KFUNC_HOOK_TRACING;
7831 case BPF_PROG_TYPE_SYSCALL:
7832 return BTF_KFUNC_HOOK_SYSCALL;
7833 case BPF_PROG_TYPE_CGROUP_SKB:
7834 return BTF_KFUNC_HOOK_CGROUP_SKB;
7835 case BPF_PROG_TYPE_SCHED_ACT:
7836 return BTF_KFUNC_HOOK_SCHED_ACT;
7837 case BPF_PROG_TYPE_SK_SKB:
7838 return BTF_KFUNC_HOOK_SK_SKB;
7839 case BPF_PROG_TYPE_SOCKET_FILTER:
7840 return BTF_KFUNC_HOOK_SOCKET_FILTER;
7841 case BPF_PROG_TYPE_LWT_OUT:
7842 case BPF_PROG_TYPE_LWT_IN:
7843 case BPF_PROG_TYPE_LWT_XMIT:
7844 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
7845 return BTF_KFUNC_HOOK_LWT;
7846 case BPF_PROG_TYPE_NETFILTER:
7847 return BTF_KFUNC_HOOK_NETFILTER;
7849 return BTF_KFUNC_HOOK_MAX;
7854 * Reference to the module (obtained using btf_try_get_module) corresponding to
7855 * the struct btf *MUST* be held when calling this function from verifier
7856 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7857 * keeping the reference for the duration of the call provides the necessary
7858 * protection for looking up a well-formed btf->kfunc_set_tab.
7860 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
7862 const struct bpf_prog *prog)
7864 enum bpf_prog_type prog_type = resolve_prog_type(prog);
7865 enum btf_kfunc_hook hook;
7868 kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
7872 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7873 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
7876 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
7877 const struct bpf_prog *prog)
7879 return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
7882 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
7883 const struct btf_kfunc_id_set *kset)
7888 btf = btf_get_module_btf(kset->owner);
7890 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7891 pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7894 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
7895 pr_warn("missing module BTF, cannot register kfuncs\n");
7899 return PTR_ERR(btf);
7901 for (i = 0; i < kset->set->cnt; i++) {
7902 ret = btf_check_kfunc_protos(btf, kset->set->pairs[i].id,
7903 kset->set->pairs[i].flags);
7908 ret = btf_populate_kfunc_set(btf, hook, kset);
7915 /* This function must be invoked only from initcalls/module init functions */
7916 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7917 const struct btf_kfunc_id_set *kset)
7919 enum btf_kfunc_hook hook;
7921 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7922 return __register_btf_kfunc_id_set(hook, kset);
7924 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7926 /* This function must be invoked only from initcalls/module init functions */
7927 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
7929 return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
7931 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
7933 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7935 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7936 struct btf_id_dtor_kfunc *dtor;
7940 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7941 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7943 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7944 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7947 return dtor->kfunc_btf_id;
7950 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7952 const struct btf_type *dtor_func, *dtor_func_proto, *t;
7953 const struct btf_param *args;
7957 for (i = 0; i < cnt; i++) {
7958 dtor_btf_id = dtors[i].kfunc_btf_id;
7960 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7961 if (!dtor_func || !btf_type_is_func(dtor_func))
7964 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7965 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7968 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7969 t = btf_type_by_id(btf, dtor_func_proto->type);
7970 if (!t || !btf_type_is_void(t))
7973 nr_args = btf_type_vlen(dtor_func_proto);
7976 args = btf_params(dtor_func_proto);
7977 t = btf_type_by_id(btf, args[0].type);
7978 /* Allow any pointer type, as width on targets Linux supports
7979 * will be same for all pointer types (i.e. sizeof(void *))
7981 if (!t || !btf_type_is_ptr(t))
7987 /* This function must be invoked only from initcalls/module init functions */
7988 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7989 struct module *owner)
7991 struct btf_id_dtor_kfunc_tab *tab;
7996 btf = btf_get_module_btf(owner);
7998 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7999 pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
8002 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
8003 pr_err("missing module BTF, cannot register dtor kfuncs\n");
8009 return PTR_ERR(btf);
8011 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8012 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8017 /* Ensure that the prototype of dtor kfuncs being registered is sane */
8018 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8022 tab = btf->dtor_kfunc_tab;
8023 /* Only one call allowed for modules */
8024 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8029 tab_cnt = tab ? tab->cnt : 0;
8030 if (tab_cnt > U32_MAX - add_cnt) {
8034 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8035 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8040 tab = krealloc(btf->dtor_kfunc_tab,
8041 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
8042 GFP_KERNEL | __GFP_NOWARN);
8048 if (!btf->dtor_kfunc_tab)
8050 btf->dtor_kfunc_tab = tab;
8052 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8053 tab->cnt += add_cnt;
8055 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8059 btf_free_dtor_kfunc_tab(btf);
8063 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8065 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8067 /* Check local and target types for compatibility. This check is used for
8068 * type-based CO-RE relocations and follow slightly different rules than
8069 * field-based relocations. This function assumes that root types were already
8070 * checked for name match. Beyond that initial root-level name check, names
8071 * are completely ignored. Compatibility rules are as follows:
8072 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8073 * kind should match for local and target types (i.e., STRUCT is not
8074 * compatible with UNION);
8075 * - for ENUMs/ENUM64s, the size is ignored;
8076 * - for INT, size and signedness are ignored;
8077 * - for ARRAY, dimensionality is ignored, element types are checked for
8078 * compatibility recursively;
8079 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
8080 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8081 * - FUNC_PROTOs are compatible if they have compatible signature: same
8082 * number of input args and compatible return and argument types.
8083 * These rules are not set in stone and probably will be adjusted as we get
8084 * more experience with using BPF CO-RE relocations.
8086 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8087 const struct btf *targ_btf, __u32 targ_id)
8089 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8090 MAX_TYPES_ARE_COMPAT_DEPTH);
8093 #define MAX_TYPES_MATCH_DEPTH 2
8095 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8096 const struct btf *targ_btf, u32 targ_id)
8098 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8099 MAX_TYPES_MATCH_DEPTH);
8102 static bool bpf_core_is_flavor_sep(const char *s)
8104 /* check X___Y name pattern, where X and Y are not underscores */
8105 return s[0] != '_' && /* X */
8106 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
8107 s[4] != '_'; /* Y */
8110 size_t bpf_core_essential_name_len(const char *name)
8112 size_t n = strlen(name);
8115 for (i = n - 5; i >= 0; i--) {
8116 if (bpf_core_is_flavor_sep(name + i))
8122 struct bpf_cand_cache {
8128 const struct btf *btf;
8133 static void bpf_free_cands(struct bpf_cand_cache *cands)
8136 /* empty candidate array was allocated on stack */
8141 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8147 #define VMLINUX_CAND_CACHE_SIZE 31
8148 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8150 #define MODULE_CAND_CACHE_SIZE 31
8151 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8153 static DEFINE_MUTEX(cand_cache_mutex);
8155 static void __print_cand_cache(struct bpf_verifier_log *log,
8156 struct bpf_cand_cache **cache,
8159 struct bpf_cand_cache *cc;
8162 for (i = 0; i < cache_size; i++) {
8166 bpf_log(log, "[%d]%s(", i, cc->name);
8167 for (j = 0; j < cc->cnt; j++) {
8168 bpf_log(log, "%d", cc->cands[j].id);
8169 if (j < cc->cnt - 1)
8172 bpf_log(log, "), ");
8176 static void print_cand_cache(struct bpf_verifier_log *log)
8178 mutex_lock(&cand_cache_mutex);
8179 bpf_log(log, "vmlinux_cand_cache:");
8180 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8181 bpf_log(log, "\nmodule_cand_cache:");
8182 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8184 mutex_unlock(&cand_cache_mutex);
8187 static u32 hash_cands(struct bpf_cand_cache *cands)
8189 return jhash(cands->name, cands->name_len, 0);
8192 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8193 struct bpf_cand_cache **cache,
8196 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8198 if (cc && cc->name_len == cands->name_len &&
8199 !strncmp(cc->name, cands->name, cands->name_len))
8204 static size_t sizeof_cands(int cnt)
8206 return offsetof(struct bpf_cand_cache, cands[cnt]);
8209 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8210 struct bpf_cand_cache **cache,
8213 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8216 bpf_free_cands_from_cache(*cc);
8219 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8221 bpf_free_cands(cands);
8222 return ERR_PTR(-ENOMEM);
8224 /* strdup the name, since it will stay in cache.
8225 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8227 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8228 bpf_free_cands(cands);
8229 if (!new_cands->name) {
8231 return ERR_PTR(-ENOMEM);
8237 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8238 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8241 struct bpf_cand_cache *cc;
8244 for (i = 0; i < cache_size; i++) {
8249 /* when new module is loaded purge all of module_cand_cache,
8250 * since new module might have candidates with the name
8251 * that matches cached cands.
8253 bpf_free_cands_from_cache(cc);
8257 /* when module is unloaded purge cache entries
8258 * that match module's btf
8260 for (j = 0; j < cc->cnt; j++)
8261 if (cc->cands[j].btf == btf) {
8262 bpf_free_cands_from_cache(cc);
8270 static void purge_cand_cache(struct btf *btf)
8272 mutex_lock(&cand_cache_mutex);
8273 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8274 mutex_unlock(&cand_cache_mutex);
8278 static struct bpf_cand_cache *
8279 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8282 struct bpf_cand_cache *new_cands;
8283 const struct btf_type *t;
8284 const char *targ_name;
8285 size_t targ_essent_len;
8288 n = btf_nr_types(targ_btf);
8289 for (i = targ_start_id; i < n; i++) {
8290 t = btf_type_by_id(targ_btf, i);
8291 if (btf_kind(t) != cands->kind)
8294 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8298 /* the resched point is before strncmp to make sure that search
8299 * for non-existing name will have a chance to schedule().
8303 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8306 targ_essent_len = bpf_core_essential_name_len(targ_name);
8307 if (targ_essent_len != cands->name_len)
8310 /* most of the time there is only one candidate for a given kind+name pair */
8311 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8313 bpf_free_cands(cands);
8314 return ERR_PTR(-ENOMEM);
8317 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8318 bpf_free_cands(cands);
8320 cands->cands[cands->cnt].btf = targ_btf;
8321 cands->cands[cands->cnt].id = i;
8327 static struct bpf_cand_cache *
8328 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8330 struct bpf_cand_cache *cands, *cc, local_cand = {};
8331 const struct btf *local_btf = ctx->btf;
8332 const struct btf_type *local_type;
8333 const struct btf *main_btf;
8334 size_t local_essent_len;
8335 struct btf *mod_btf;
8339 main_btf = bpf_get_btf_vmlinux();
8340 if (IS_ERR(main_btf))
8341 return ERR_CAST(main_btf);
8343 return ERR_PTR(-EINVAL);
8345 local_type = btf_type_by_id(local_btf, local_type_id);
8347 return ERR_PTR(-EINVAL);
8349 name = btf_name_by_offset(local_btf, local_type->name_off);
8350 if (str_is_empty(name))
8351 return ERR_PTR(-EINVAL);
8352 local_essent_len = bpf_core_essential_name_len(name);
8354 cands = &local_cand;
8356 cands->kind = btf_kind(local_type);
8357 cands->name_len = local_essent_len;
8359 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8360 /* cands is a pointer to stack here */
8367 /* Attempt to find target candidates in vmlinux BTF first */
8368 cands = bpf_core_add_cands(cands, main_btf, 1);
8370 return ERR_CAST(cands);
8372 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8374 /* populate cache even when cands->cnt == 0 */
8375 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8377 return ERR_CAST(cc);
8379 /* if vmlinux BTF has any candidate, don't go for module BTFs */
8384 /* cands is a pointer to stack here and cands->cnt == 0 */
8385 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8387 /* if cache has it return it even if cc->cnt == 0 */
8390 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8391 spin_lock_bh(&btf_idr_lock);
8392 idr_for_each_entry(&btf_idr, mod_btf, id) {
8393 if (!btf_is_module(mod_btf))
8395 /* linear search could be slow hence unlock/lock
8396 * the IDR to avoiding holding it for too long
8399 spin_unlock_bh(&btf_idr_lock);
8400 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8403 return ERR_CAST(cands);
8404 spin_lock_bh(&btf_idr_lock);
8406 spin_unlock_bh(&btf_idr_lock);
8407 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8408 * or pointer to stack if cands->cnd == 0.
8409 * Copy it into the cache even when cands->cnt == 0 and
8410 * return the result.
8412 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8415 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8416 int relo_idx, void *insn)
8418 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8419 struct bpf_core_cand_list cands = {};
8420 struct bpf_core_relo_res targ_res;
8421 struct bpf_core_spec *specs;
8424 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8425 * into arrays of btf_ids of struct fields and array indices.
8427 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8432 struct bpf_cand_cache *cc;
8435 mutex_lock(&cand_cache_mutex);
8436 cc = bpf_core_find_cands(ctx, relo->type_id);
8438 bpf_log(ctx->log, "target candidate search failed for %d\n",
8444 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8450 for (i = 0; i < cc->cnt; i++) {
8452 "CO-RE relocating %s %s: found target candidate [%d]\n",
8453 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8454 cands.cands[i].btf = cc->cands[i].btf;
8455 cands.cands[i].id = cc->cands[i].id;
8457 cands.len = cc->cnt;
8458 /* cand_cache_mutex needs to span the cache lookup and
8459 * copy of btf pointer into bpf_core_cand_list,
8460 * since module can be unloaded while bpf_core_calc_relo_insn
8461 * is working with module's btf.
8465 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8470 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8477 mutex_unlock(&cand_cache_mutex);
8478 if (ctx->log->level & BPF_LOG_LEVEL2)
8479 print_cand_cache(ctx->log);
8484 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8485 const struct bpf_reg_state *reg,
8486 const char *field_name, u32 btf_id, const char *suffix)
8488 struct btf *btf = reg->btf;
8489 const struct btf_type *walk_type, *safe_type;
8491 char safe_tname[64];
8493 const struct btf_member *member;
8496 walk_type = btf_type_by_id(btf, reg->btf_id);
8500 tname = btf_name_by_offset(btf, walk_type->name_off);
8502 ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8506 safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8510 safe_type = btf_type_by_id(btf, safe_id);
8514 for_each_member(i, safe_type, member) {
8515 const char *m_name = __btf_name_by_offset(btf, member->name_off);
8516 const struct btf_type *mtype = btf_type_by_id(btf, member->type);
8519 if (!btf_type_is_ptr(mtype))
8522 btf_type_skip_modifiers(btf, mtype->type, &id);
8523 /* If we match on both type and name, the field is considered trusted. */
8524 if (btf_id == id && !strcmp(field_name, m_name))
8531 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8532 const struct btf *reg_btf, u32 reg_id,
8533 const struct btf *arg_btf, u32 arg_id)
8535 const char *reg_name, *arg_name, *search_needle;
8536 const struct btf_type *reg_type, *arg_type;
8537 int reg_len, arg_len, cmp_len;
8538 size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8540 reg_type = btf_type_by_id(reg_btf, reg_id);
8544 arg_type = btf_type_by_id(arg_btf, arg_id);
8548 reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8549 arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8551 reg_len = strlen(reg_name);
8552 arg_len = strlen(arg_name);
8554 /* Exactly one of the two type names may be suffixed with ___init, so
8555 * if the strings are the same size, they can't possibly be no-cast
8556 * aliases of one another. If you have two of the same type names, e.g.
8557 * they're both nf_conn___init, it would be improper to return true
8558 * because they are _not_ no-cast aliases, they are the same type.
8560 if (reg_len == arg_len)
8563 /* Either of the two names must be the other name, suffixed with ___init. */
8564 if ((reg_len != arg_len + pattern_len) &&
8565 (arg_len != reg_len + pattern_len))
8568 if (reg_len < arg_len) {
8569 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8572 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8579 /* ___init suffix must come at the end of the name */
8580 if (*(search_needle + pattern_len) != '\0')
8583 return !strncmp(reg_name, arg_name, cmp_len);