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 "../tools/lib/bpf/relo_core.h"
31 /* BTF (BPF Type Format) is the meta data format which describes
32 * the data types of BPF program/map. Hence, it basically focus
33 * on the C programming language which the modern BPF is primary
38 * The BTF data is stored under the ".BTF" ELF section
42 * Each 'struct btf_type' object describes a C data type.
43 * Depending on the type it is describing, a 'struct btf_type'
44 * object may be followed by more data. F.e.
45 * To describe an array, 'struct btf_type' is followed by
48 * 'struct btf_type' and any extra data following it are
53 * The BTF type section contains a list of 'struct btf_type' objects.
54 * Each one describes a C type. Recall from the above section
55 * that a 'struct btf_type' object could be immediately followed by extra
56 * data in order to describe some particular C types.
60 * Each btf_type object is identified by a type_id. The type_id
61 * is implicitly implied by the location of the btf_type object in
62 * the BTF type section. The first one has type_id 1. The second
63 * one has type_id 2...etc. Hence, an earlier btf_type has
66 * A btf_type object may refer to another btf_type object by using
67 * type_id (i.e. the "type" in the "struct btf_type").
69 * NOTE that we cannot assume any reference-order.
70 * A btf_type object can refer to an earlier btf_type object
71 * but it can also refer to a later btf_type object.
73 * For example, to describe "const void *". A btf_type
74 * object describing "const" may refer to another btf_type
75 * object describing "void *". This type-reference is done
76 * by specifying type_id:
78 * [1] CONST (anon) type_id=2
79 * [2] PTR (anon) type_id=0
81 * The above is the btf_verifier debug log:
82 * - Each line started with "[?]" is a btf_type object
83 * - [?] is the type_id of the btf_type object.
84 * - CONST/PTR is the BTF_KIND_XXX
85 * - "(anon)" is the name of the type. It just
86 * happens that CONST and PTR has no name.
87 * - type_id=XXX is the 'u32 type' in btf_type
89 * NOTE: "void" has type_id 0
93 * The BTF string section contains the names used by the type section.
94 * Each string is referred by an "offset" from the beginning of the
97 * Each string is '\0' terminated.
99 * The first character in the string section must be '\0'
100 * which is used to mean 'anonymous'. Some btf_type may not
106 * To verify BTF data, two passes are needed.
110 * The first pass is to collect all btf_type objects to
111 * an array: "btf->types".
113 * Depending on the C type that a btf_type is describing,
114 * a btf_type may be followed by extra data. We don't know
115 * how many btf_type is there, and more importantly we don't
116 * know where each btf_type is located in the type section.
118 * Without knowing the location of each type_id, most verifications
119 * cannot be done. e.g. an earlier btf_type may refer to a later
120 * btf_type (recall the "const void *" above), so we cannot
121 * check this type-reference in the first pass.
123 * In the first pass, it still does some verifications (e.g.
124 * checking the name is a valid offset to the string section).
128 * The main focus is to resolve a btf_type that is referring
131 * We have to ensure the referring type:
132 * 1) does exist in the BTF (i.e. in btf->types[])
133 * 2) does not cause a loop:
142 * btf_type_needs_resolve() decides if a btf_type needs
145 * The needs_resolve type implements the "resolve()" ops which
146 * essentially does a DFS and detects backedge.
148 * During resolve (or DFS), different C types have different
149 * "RESOLVED" conditions.
151 * When resolving a BTF_KIND_STRUCT, we need to resolve all its
152 * members because a member is always referring to another
153 * type. A struct's member can be treated as "RESOLVED" if
154 * it is referring to a BTF_KIND_PTR. Otherwise, the
155 * following valid C struct would be rejected:
162 * When resolving a BTF_KIND_PTR, it needs to keep resolving if
163 * it is referring to another BTF_KIND_PTR. Otherwise, we cannot
164 * detect a pointer loop, e.g.:
165 * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
167 * +-----------------------------------------+
171 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
172 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
173 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
174 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
175 #define BITS_ROUNDUP_BYTES(bits) \
176 (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
178 #define BTF_INFO_MASK 0x9f00ffff
179 #define BTF_INT_MASK 0x0fffffff
180 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
181 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
183 /* 16MB for 64k structs and each has 16 members and
184 * a few MB spaces for the string section.
185 * The hard limit is S32_MAX.
187 #define BTF_MAX_SIZE (16 * 1024 * 1024)
189 #define for_each_member_from(i, from, struct_type, member) \
190 for (i = from, member = btf_type_member(struct_type) + from; \
191 i < btf_type_vlen(struct_type); \
194 #define for_each_vsi_from(i, from, struct_type, member) \
195 for (i = from, member = btf_type_var_secinfo(struct_type) + from; \
196 i < btf_type_vlen(struct_type); \
200 DEFINE_SPINLOCK(btf_idr_lock);
202 enum btf_kfunc_hook {
203 BTF_KFUNC_HOOK_COMMON,
206 BTF_KFUNC_HOOK_STRUCT_OPS,
207 BTF_KFUNC_HOOK_TRACING,
208 BTF_KFUNC_HOOK_SYSCALL,
209 BTF_KFUNC_HOOK_FMODRET,
210 BTF_KFUNC_HOOK_CGROUP_SKB,
211 BTF_KFUNC_HOOK_SCHED_ACT,
212 BTF_KFUNC_HOOK_SK_SKB,
213 BTF_KFUNC_HOOK_SOCKET_FILTER,
219 BTF_KFUNC_SET_MAX_CNT = 256,
220 BTF_DTOR_KFUNC_MAX_CNT = 256,
223 struct btf_kfunc_set_tab {
224 struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
227 struct btf_id_dtor_kfunc_tab {
229 struct btf_id_dtor_kfunc dtors[];
234 struct btf_type **types;
239 struct btf_header hdr;
240 u32 nr_types; /* includes VOID for base BTF */
246 struct btf_kfunc_set_tab *kfunc_set_tab;
247 struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
248 struct btf_struct_metas *struct_meta_tab;
250 /* split BTF support */
251 struct btf *base_btf;
252 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
253 u32 start_str_off; /* first string offset (0 for base BTF) */
254 char name[MODULE_NAME_LEN];
258 enum verifier_phase {
263 struct resolve_vertex {
264 const struct btf_type *t;
276 RESOLVE_TBD, /* To Be Determined */
277 RESOLVE_PTR, /* Resolving for Pointer */
278 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
283 #define MAX_RESOLVE_DEPTH 32
285 struct btf_sec_info {
290 struct btf_verifier_env {
293 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
294 struct bpf_verifier_log log;
297 enum verifier_phase phase;
298 enum resolve_mode resolve_mode;
301 static const char * const btf_kind_str[NR_BTF_KINDS] = {
302 [BTF_KIND_UNKN] = "UNKNOWN",
303 [BTF_KIND_INT] = "INT",
304 [BTF_KIND_PTR] = "PTR",
305 [BTF_KIND_ARRAY] = "ARRAY",
306 [BTF_KIND_STRUCT] = "STRUCT",
307 [BTF_KIND_UNION] = "UNION",
308 [BTF_KIND_ENUM] = "ENUM",
309 [BTF_KIND_FWD] = "FWD",
310 [BTF_KIND_TYPEDEF] = "TYPEDEF",
311 [BTF_KIND_VOLATILE] = "VOLATILE",
312 [BTF_KIND_CONST] = "CONST",
313 [BTF_KIND_RESTRICT] = "RESTRICT",
314 [BTF_KIND_FUNC] = "FUNC",
315 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
316 [BTF_KIND_VAR] = "VAR",
317 [BTF_KIND_DATASEC] = "DATASEC",
318 [BTF_KIND_FLOAT] = "FLOAT",
319 [BTF_KIND_DECL_TAG] = "DECL_TAG",
320 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
321 [BTF_KIND_ENUM64] = "ENUM64",
324 const char *btf_type_str(const struct btf_type *t)
326 return btf_kind_str[BTF_INFO_KIND(t->info)];
329 /* Chunk size we use in safe copy of data to be shown. */
330 #define BTF_SHOW_OBJ_SAFE_SIZE 32
333 * This is the maximum size of a base type value (equivalent to a
334 * 128-bit int); if we are at the end of our safe buffer and have
335 * less than 16 bytes space we can't be assured of being able
336 * to copy the next type safely, so in such cases we will initiate
339 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
342 #define BTF_SHOW_NAME_SIZE 80
345 * The suffix of a type that indicates it cannot alias another type when
346 * comparing BTF IDs for kfunc invocations.
348 #define NOCAST_ALIAS_SUFFIX "___init"
351 * Common data to all BTF show operations. Private show functions can add
352 * their own data to a structure containing a struct btf_show and consult it
353 * in the show callback. See btf_type_show() below.
355 * One challenge with showing nested data is we want to skip 0-valued
356 * data, but in order to figure out whether a nested object is all zeros
357 * we need to walk through it. As a result, we need to make two passes
358 * when handling structs, unions and arrays; the first path simply looks
359 * for nonzero data, while the second actually does the display. The first
360 * pass is signalled by show->state.depth_check being set, and if we
361 * encounter a non-zero value we set show->state.depth_to_show to
362 * the depth at which we encountered it. When we have completed the
363 * first pass, we will know if anything needs to be displayed if
364 * depth_to_show > depth. See btf_[struct,array]_show() for the
365 * implementation of this.
367 * Another problem is we want to ensure the data for display is safe to
368 * access. To support this, the anonymous "struct {} obj" tracks the data
369 * object and our safe copy of it. We copy portions of the data needed
370 * to the object "copy" buffer, but because its size is limited to
371 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
372 * traverse larger objects for display.
374 * The various data type show functions all start with a call to
375 * btf_show_start_type() which returns a pointer to the safe copy
376 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
377 * raw data itself). btf_show_obj_safe() is responsible for
378 * using copy_from_kernel_nofault() to update the safe data if necessary
379 * as we traverse the object's data. skbuff-like semantics are
382 * - obj.head points to the start of the toplevel object for display
383 * - obj.size is the size of the toplevel object
384 * - obj.data points to the current point in the original data at
385 * which our safe data starts. obj.data will advance as we copy
386 * portions of the data.
388 * In most cases a single copy will suffice, but larger data structures
389 * such as "struct task_struct" will require many copies. The logic in
390 * btf_show_obj_safe() handles the logic that determines if a new
391 * copy_from_kernel_nofault() is needed.
395 void *target; /* target of show operation (seq file, buffer) */
396 void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
397 const struct btf *btf;
398 /* below are used during iteration */
407 int status; /* non-zero for error */
408 const struct btf_type *type;
409 const struct btf_member *member;
410 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
416 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
420 struct btf_kind_operations {
421 s32 (*check_meta)(struct btf_verifier_env *env,
422 const struct btf_type *t,
424 int (*resolve)(struct btf_verifier_env *env,
425 const struct resolve_vertex *v);
426 int (*check_member)(struct btf_verifier_env *env,
427 const struct btf_type *struct_type,
428 const struct btf_member *member,
429 const struct btf_type *member_type);
430 int (*check_kflag_member)(struct btf_verifier_env *env,
431 const struct btf_type *struct_type,
432 const struct btf_member *member,
433 const struct btf_type *member_type);
434 void (*log_details)(struct btf_verifier_env *env,
435 const struct btf_type *t);
436 void (*show)(const struct btf *btf, const struct btf_type *t,
437 u32 type_id, void *data, u8 bits_offsets,
438 struct btf_show *show);
441 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
442 static struct btf_type btf_void;
444 static int btf_resolve(struct btf_verifier_env *env,
445 const struct btf_type *t, u32 type_id);
447 static int btf_func_check(struct btf_verifier_env *env,
448 const struct btf_type *t);
450 static bool btf_type_is_modifier(const struct btf_type *t)
452 /* Some of them is not strictly a C modifier
453 * but they are grouped into the same bucket
455 * A type (t) that refers to another
456 * type through t->type AND its size cannot
457 * be determined without following the t->type.
459 * ptr does not fall into this bucket
460 * because its size is always sizeof(void *).
462 switch (BTF_INFO_KIND(t->info)) {
463 case BTF_KIND_TYPEDEF:
464 case BTF_KIND_VOLATILE:
466 case BTF_KIND_RESTRICT:
467 case BTF_KIND_TYPE_TAG:
474 bool btf_type_is_void(const struct btf_type *t)
476 return t == &btf_void;
479 static bool btf_type_is_fwd(const struct btf_type *t)
481 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
484 static bool btf_type_nosize(const struct btf_type *t)
486 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
487 btf_type_is_func(t) || btf_type_is_func_proto(t);
490 static bool btf_type_nosize_or_null(const struct btf_type *t)
492 return !t || btf_type_nosize(t);
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_is_decl_tag_target(const struct btf_type *t)
507 return btf_type_is_func(t) || btf_type_is_struct(t) ||
508 btf_type_is_var(t) || btf_type_is_typedef(t);
511 u32 btf_nr_types(const struct btf *btf)
516 total += btf->nr_types;
523 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
525 const struct btf_type *t;
529 total = btf_nr_types(btf);
530 for (i = 1; i < total; i++) {
531 t = btf_type_by_id(btf, i);
532 if (BTF_INFO_KIND(t->info) != kind)
535 tname = btf_name_by_offset(btf, t->name_off);
536 if (!strcmp(tname, name))
543 static s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
549 btf = bpf_get_btf_vmlinux();
555 ret = btf_find_by_name_kind(btf, name, kind);
556 /* ret is never zero, since btf_find_by_name_kind returns
557 * positive btf_id or negative error.
565 /* If name is not found in vmlinux's BTF then search in module's BTFs */
566 spin_lock_bh(&btf_idr_lock);
567 idr_for_each_entry(&btf_idr, btf, id) {
568 if (!btf_is_module(btf))
570 /* linear search could be slow hence unlock/lock
571 * the IDR to avoiding holding it for too long
574 spin_unlock_bh(&btf_idr_lock);
575 ret = btf_find_by_name_kind(btf, name, kind);
580 spin_lock_bh(&btf_idr_lock);
583 spin_unlock_bh(&btf_idr_lock);
587 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
590 const struct btf_type *t = btf_type_by_id(btf, id);
592 while (btf_type_is_modifier(t)) {
594 t = btf_type_by_id(btf, t->type);
603 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
606 const struct btf_type *t;
608 t = btf_type_skip_modifiers(btf, id, NULL);
609 if (!btf_type_is_ptr(t))
612 return btf_type_skip_modifiers(btf, t->type, res_id);
615 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
618 const struct btf_type *ptype;
620 ptype = btf_type_resolve_ptr(btf, id, res_id);
621 if (ptype && btf_type_is_func_proto(ptype))
627 /* Types that act only as a source, not sink or intermediate
628 * type when resolving.
630 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
632 return btf_type_is_var(t) ||
633 btf_type_is_decl_tag(t) ||
634 btf_type_is_datasec(t);
637 /* What types need to be resolved?
639 * btf_type_is_modifier() is an obvious one.
641 * btf_type_is_struct() because its member refers to
642 * another type (through member->type).
644 * btf_type_is_var() because the variable refers to
645 * another type. btf_type_is_datasec() holds multiple
646 * btf_type_is_var() types that need resolving.
648 * btf_type_is_array() because its element (array->type)
649 * refers to another type. Array can be thought of a
650 * special case of struct while array just has the same
651 * member-type repeated by array->nelems of times.
653 static bool btf_type_needs_resolve(const struct btf_type *t)
655 return btf_type_is_modifier(t) ||
656 btf_type_is_ptr(t) ||
657 btf_type_is_struct(t) ||
658 btf_type_is_array(t) ||
659 btf_type_is_var(t) ||
660 btf_type_is_func(t) ||
661 btf_type_is_decl_tag(t) ||
662 btf_type_is_datasec(t);
665 /* t->size can be used */
666 static bool btf_type_has_size(const struct btf_type *t)
668 switch (BTF_INFO_KIND(t->info)) {
670 case BTF_KIND_STRUCT:
673 case BTF_KIND_DATASEC:
675 case BTF_KIND_ENUM64:
682 static const char *btf_int_encoding_str(u8 encoding)
686 else if (encoding == BTF_INT_SIGNED)
688 else if (encoding == BTF_INT_CHAR)
690 else if (encoding == BTF_INT_BOOL)
696 static u32 btf_type_int(const struct btf_type *t)
698 return *(u32 *)(t + 1);
701 static const struct btf_array *btf_type_array(const struct btf_type *t)
703 return (const struct btf_array *)(t + 1);
706 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
708 return (const struct btf_enum *)(t + 1);
711 static const struct btf_var *btf_type_var(const struct btf_type *t)
713 return (const struct btf_var *)(t + 1);
716 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
718 return (const struct btf_decl_tag *)(t + 1);
721 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
723 return (const struct btf_enum64 *)(t + 1);
726 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
728 return kind_ops[BTF_INFO_KIND(t->info)];
731 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
733 if (!BTF_STR_OFFSET_VALID(offset))
736 while (offset < btf->start_str_off)
739 offset -= btf->start_str_off;
740 return offset < btf->hdr.str_len;
743 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
745 if ((first ? !isalpha(c) :
748 ((c == '.' && !dot_ok) ||
754 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
756 while (offset < btf->start_str_off)
759 offset -= btf->start_str_off;
760 if (offset < btf->hdr.str_len)
761 return &btf->strings[offset];
766 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
768 /* offset must be valid */
769 const char *src = btf_str_by_offset(btf, offset);
770 const char *src_limit;
772 if (!__btf_name_char_ok(*src, true, dot_ok))
775 /* set a limit on identifier length */
776 src_limit = src + KSYM_NAME_LEN;
778 while (*src && src < src_limit) {
779 if (!__btf_name_char_ok(*src, false, dot_ok))
787 /* Only C-style identifier is permitted. This can be relaxed if
790 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
792 return __btf_name_valid(btf, offset, false);
795 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
797 return __btf_name_valid(btf, offset, true);
800 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
807 name = btf_str_by_offset(btf, offset);
808 return name ?: "(invalid-name-offset)";
811 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
813 return btf_str_by_offset(btf, offset);
816 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
818 while (type_id < btf->start_id)
821 type_id -= btf->start_id;
822 if (type_id >= btf->nr_types)
824 return btf->types[type_id];
826 EXPORT_SYMBOL_GPL(btf_type_by_id);
829 * Regular int is not a bit field and it must be either
830 * u8/u16/u32/u64 or __int128.
832 static bool btf_type_int_is_regular(const struct btf_type *t)
834 u8 nr_bits, nr_bytes;
837 int_data = btf_type_int(t);
838 nr_bits = BTF_INT_BITS(int_data);
839 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
840 if (BITS_PER_BYTE_MASKED(nr_bits) ||
841 BTF_INT_OFFSET(int_data) ||
842 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
843 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
844 nr_bytes != (2 * sizeof(u64)))) {
852 * Check that given struct member is a regular int with expected
855 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
856 const struct btf_member *m,
857 u32 expected_offset, u32 expected_size)
859 const struct btf_type *t;
864 t = btf_type_id_size(btf, &id, NULL);
865 if (!t || !btf_type_is_int(t))
868 int_data = btf_type_int(t);
869 nr_bits = BTF_INT_BITS(int_data);
870 if (btf_type_kflag(s)) {
871 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
872 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
874 /* if kflag set, int should be a regular int and
875 * bit offset should be at byte boundary.
877 return !bitfield_size &&
878 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
879 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
882 if (BTF_INT_OFFSET(int_data) ||
883 BITS_PER_BYTE_MASKED(m->offset) ||
884 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
885 BITS_PER_BYTE_MASKED(nr_bits) ||
886 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
892 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
893 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
896 const struct btf_type *t = btf_type_by_id(btf, id);
898 while (btf_type_is_modifier(t) &&
899 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
900 t = btf_type_by_id(btf, t->type);
906 #define BTF_SHOW_MAX_ITER 10
908 #define BTF_KIND_BIT(kind) (1ULL << kind)
911 * Populate show->state.name with type name information.
912 * Format of type name is
914 * [.member_name = ] (type_name)
916 static const char *btf_show_name(struct btf_show *show)
918 /* BTF_MAX_ITER array suffixes "[]" */
919 const char *array_suffixes = "[][][][][][][][][][]";
920 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
921 /* BTF_MAX_ITER pointer suffixes "*" */
922 const char *ptr_suffixes = "**********";
923 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
924 const char *name = NULL, *prefix = "", *parens = "";
925 const struct btf_member *m = show->state.member;
926 const struct btf_type *t;
927 const struct btf_array *array;
928 u32 id = show->state.type_id;
929 const char *member = NULL;
930 bool show_member = false;
934 show->state.name[0] = '\0';
937 * Don't show type name if we're showing an array member;
938 * in that case we show the array type so don't need to repeat
939 * ourselves for each member.
941 if (show->state.array_member)
944 /* Retrieve member name, if any. */
946 member = btf_name_by_offset(show->btf, m->name_off);
947 show_member = strlen(member) > 0;
952 * Start with type_id, as we have resolved the struct btf_type *
953 * via btf_modifier_show() past the parent typedef to the child
954 * struct, int etc it is defined as. In such cases, the type_id
955 * still represents the starting type while the struct btf_type *
956 * in our show->state points at the resolved type of the typedef.
958 t = btf_type_by_id(show->btf, id);
963 * The goal here is to build up the right number of pointer and
964 * array suffixes while ensuring the type name for a typedef
965 * is represented. Along the way we accumulate a list of
966 * BTF kinds we have encountered, since these will inform later
967 * display; for example, pointer types will not require an
968 * opening "{" for struct, we will just display the pointer value.
970 * We also want to accumulate the right number of pointer or array
971 * indices in the format string while iterating until we get to
972 * the typedef/pointee/array member target type.
974 * We start by pointing at the end of pointer and array suffix
975 * strings; as we accumulate pointers and arrays we move the pointer
976 * or array string backwards so it will show the expected number of
977 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
978 * and/or arrays and typedefs are supported as a precaution.
980 * We also want to get typedef name while proceeding to resolve
981 * type it points to so that we can add parentheses if it is a
982 * "typedef struct" etc.
984 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
986 switch (BTF_INFO_KIND(t->info)) {
987 case BTF_KIND_TYPEDEF:
989 name = btf_name_by_offset(show->btf,
991 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
995 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
999 array = btf_type_array(t);
1000 if (array_suffix > array_suffixes)
1005 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1006 if (ptr_suffix > ptr_suffixes)
1016 t = btf_type_skip_qualifiers(show->btf, id);
1018 /* We may not be able to represent this type; bail to be safe */
1019 if (i == BTF_SHOW_MAX_ITER)
1023 name = btf_name_by_offset(show->btf, t->name_off);
1025 switch (BTF_INFO_KIND(t->info)) {
1026 case BTF_KIND_STRUCT:
1027 case BTF_KIND_UNION:
1028 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1030 /* if it's an array of struct/union, parens is already set */
1031 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1035 case BTF_KIND_ENUM64:
1042 /* pointer does not require parens */
1043 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1045 /* typedef does not require struct/union/enum prefix */
1046 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1052 /* Even if we don't want type name info, we want parentheses etc */
1053 if (show->flags & BTF_SHOW_NONAME)
1054 snprintf(show->state.name, sizeof(show->state.name), "%s",
1057 snprintf(show->state.name, sizeof(show->state.name),
1058 "%s%s%s(%s%s%s%s%s%s)%s",
1059 /* first 3 strings comprise ".member = " */
1060 show_member ? "." : "",
1061 show_member ? member : "",
1062 show_member ? " = " : "",
1063 /* ...next is our prefix (struct, enum, etc) */
1065 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1066 /* ...this is the type name itself */
1068 /* ...suffixed by the appropriate '*', '[]' suffixes */
1069 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1070 array_suffix, parens);
1072 return show->state.name;
1075 static const char *__btf_show_indent(struct btf_show *show)
1077 const char *indents = " ";
1078 const char *indent = &indents[strlen(indents)];
1080 if ((indent - show->state.depth) >= indents)
1081 return indent - show->state.depth;
1085 static const char *btf_show_indent(struct btf_show *show)
1087 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1090 static const char *btf_show_newline(struct btf_show *show)
1092 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1095 static const char *btf_show_delim(struct btf_show *show)
1097 if (show->state.depth == 0)
1100 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1101 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1107 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1111 if (!show->state.depth_check) {
1112 va_start(args, fmt);
1113 show->showfn(show, fmt, args);
1118 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1119 * format specifiers to the format specifier passed in; these do the work of
1120 * adding indentation, delimiters etc while the caller simply has to specify
1121 * the type value(s) in the format specifier + value(s).
1123 #define btf_show_type_value(show, fmt, value) \
1125 if ((value) != (__typeof__(value))0 || \
1126 (show->flags & BTF_SHOW_ZERO) || \
1127 show->state.depth == 0) { \
1128 btf_show(show, "%s%s" fmt "%s%s", \
1129 btf_show_indent(show), \
1130 btf_show_name(show), \
1131 value, btf_show_delim(show), \
1132 btf_show_newline(show)); \
1133 if (show->state.depth > show->state.depth_to_show) \
1134 show->state.depth_to_show = show->state.depth; \
1138 #define btf_show_type_values(show, fmt, ...) \
1140 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1141 btf_show_name(show), \
1142 __VA_ARGS__, btf_show_delim(show), \
1143 btf_show_newline(show)); \
1144 if (show->state.depth > show->state.depth_to_show) \
1145 show->state.depth_to_show = show->state.depth; \
1148 /* How much is left to copy to safe buffer after @data? */
1149 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1151 return show->obj.head + show->obj.size - data;
1154 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1155 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1157 return data >= show->obj.data &&
1158 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1162 * If object pointed to by @data of @size falls within our safe buffer, return
1163 * the equivalent pointer to the same safe data. Assumes
1164 * copy_from_kernel_nofault() has already happened and our safe buffer is
1167 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1169 if (btf_show_obj_is_safe(show, data, size))
1170 return show->obj.safe + (data - show->obj.data);
1175 * Return a safe-to-access version of data pointed to by @data.
1176 * We do this by copying the relevant amount of information
1177 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1179 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1180 * safe copy is needed.
1182 * Otherwise we need to determine if we have the required amount
1183 * of data (determined by the @data pointer and the size of the
1184 * largest base type we can encounter (represented by
1185 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1186 * that we will be able to print some of the current object,
1187 * and if more is needed a copy will be triggered.
1188 * Some objects such as structs will not fit into the buffer;
1189 * in such cases additional copies when we iterate over their
1190 * members may be needed.
1192 * btf_show_obj_safe() is used to return a safe buffer for
1193 * btf_show_start_type(); this ensures that as we recurse into
1194 * nested types we always have safe data for the given type.
1195 * This approach is somewhat wasteful; it's possible for example
1196 * that when iterating over a large union we'll end up copying the
1197 * same data repeatedly, but the goal is safety not performance.
1198 * We use stack data as opposed to per-CPU buffers because the
1199 * iteration over a type can take some time, and preemption handling
1200 * would greatly complicate use of the safe buffer.
1202 static void *btf_show_obj_safe(struct btf_show *show,
1203 const struct btf_type *t,
1206 const struct btf_type *rt;
1207 int size_left, size;
1210 if (show->flags & BTF_SHOW_UNSAFE)
1213 rt = btf_resolve_size(show->btf, t, &size);
1215 show->state.status = PTR_ERR(rt);
1220 * Is this toplevel object? If so, set total object size and
1221 * initialize pointers. Otherwise check if we still fall within
1222 * our safe object data.
1224 if (show->state.depth == 0) {
1225 show->obj.size = size;
1226 show->obj.head = data;
1229 * If the size of the current object is > our remaining
1230 * safe buffer we _may_ need to do a new copy. However
1231 * consider the case of a nested struct; it's size pushes
1232 * us over the safe buffer limit, but showing any individual
1233 * struct members does not. In such cases, we don't need
1234 * to initiate a fresh copy yet; however we definitely need
1235 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1236 * in our buffer, regardless of the current object size.
1237 * The logic here is that as we resolve types we will
1238 * hit a base type at some point, and we need to be sure
1239 * the next chunk of data is safely available to display
1240 * that type info safely. We cannot rely on the size of
1241 * the current object here because it may be much larger
1242 * than our current buffer (e.g. task_struct is 8k).
1243 * All we want to do here is ensure that we can print the
1244 * next basic type, which we can if either
1245 * - the current type size is within the safe buffer; or
1246 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1249 safe = __btf_show_obj_safe(show, data,
1251 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1255 * We need a new copy to our safe object, either because we haven't
1256 * yet copied and are initializing safe data, or because the data
1257 * we want falls outside the boundaries of the safe object.
1260 size_left = btf_show_obj_size_left(show, data);
1261 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1262 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1263 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1265 if (!show->state.status) {
1266 show->obj.data = data;
1267 safe = show->obj.safe;
1275 * Set the type we are starting to show and return a safe data pointer
1276 * to be used for showing the associated data.
1278 static void *btf_show_start_type(struct btf_show *show,
1279 const struct btf_type *t,
1280 u32 type_id, void *data)
1282 show->state.type = t;
1283 show->state.type_id = type_id;
1284 show->state.name[0] = '\0';
1286 return btf_show_obj_safe(show, t, data);
1289 static void btf_show_end_type(struct btf_show *show)
1291 show->state.type = NULL;
1292 show->state.type_id = 0;
1293 show->state.name[0] = '\0';
1296 static void *btf_show_start_aggr_type(struct btf_show *show,
1297 const struct btf_type *t,
1298 u32 type_id, void *data)
1300 void *safe_data = btf_show_start_type(show, t, type_id, data);
1305 btf_show(show, "%s%s%s", btf_show_indent(show),
1306 btf_show_name(show),
1307 btf_show_newline(show));
1308 show->state.depth++;
1312 static void btf_show_end_aggr_type(struct btf_show *show,
1315 show->state.depth--;
1316 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1317 btf_show_delim(show), btf_show_newline(show));
1318 btf_show_end_type(show);
1321 static void btf_show_start_member(struct btf_show *show,
1322 const struct btf_member *m)
1324 show->state.member = m;
1327 static void btf_show_start_array_member(struct btf_show *show)
1329 show->state.array_member = 1;
1330 btf_show_start_member(show, NULL);
1333 static void btf_show_end_member(struct btf_show *show)
1335 show->state.member = NULL;
1338 static void btf_show_end_array_member(struct btf_show *show)
1340 show->state.array_member = 0;
1341 btf_show_end_member(show);
1344 static void *btf_show_start_array_type(struct btf_show *show,
1345 const struct btf_type *t,
1350 show->state.array_encoding = array_encoding;
1351 show->state.array_terminated = 0;
1352 return btf_show_start_aggr_type(show, t, type_id, data);
1355 static void btf_show_end_array_type(struct btf_show *show)
1357 show->state.array_encoding = 0;
1358 show->state.array_terminated = 0;
1359 btf_show_end_aggr_type(show, "]");
1362 static void *btf_show_start_struct_type(struct btf_show *show,
1363 const struct btf_type *t,
1367 return btf_show_start_aggr_type(show, t, type_id, data);
1370 static void btf_show_end_struct_type(struct btf_show *show)
1372 btf_show_end_aggr_type(show, "}");
1375 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1376 const char *fmt, ...)
1380 va_start(args, fmt);
1381 bpf_verifier_vlog(log, fmt, args);
1385 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1386 const char *fmt, ...)
1388 struct bpf_verifier_log *log = &env->log;
1391 if (!bpf_verifier_log_needed(log))
1394 va_start(args, fmt);
1395 bpf_verifier_vlog(log, fmt, args);
1399 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1400 const struct btf_type *t,
1402 const char *fmt, ...)
1404 struct bpf_verifier_log *log = &env->log;
1405 struct btf *btf = env->btf;
1408 if (!bpf_verifier_log_needed(log))
1411 if (log->level == BPF_LOG_KERNEL) {
1412 /* btf verifier prints all types it is processing via
1413 * btf_verifier_log_type(..., fmt = NULL).
1414 * Skip those prints for in-kernel BTF verification.
1419 /* Skip logging when loading module BTF with mismatches permitted */
1420 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1424 __btf_verifier_log(log, "[%u] %s %s%s",
1427 __btf_name_by_offset(btf, t->name_off),
1428 log_details ? " " : "");
1431 btf_type_ops(t)->log_details(env, t);
1434 __btf_verifier_log(log, " ");
1435 va_start(args, fmt);
1436 bpf_verifier_vlog(log, fmt, args);
1440 __btf_verifier_log(log, "\n");
1443 #define btf_verifier_log_type(env, t, ...) \
1444 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1445 #define btf_verifier_log_basic(env, t, ...) \
1446 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1449 static void btf_verifier_log_member(struct btf_verifier_env *env,
1450 const struct btf_type *struct_type,
1451 const struct btf_member *member,
1452 const char *fmt, ...)
1454 struct bpf_verifier_log *log = &env->log;
1455 struct btf *btf = env->btf;
1458 if (!bpf_verifier_log_needed(log))
1461 if (log->level == BPF_LOG_KERNEL) {
1465 /* Skip logging when loading module BTF with mismatches permitted */
1466 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1470 /* The CHECK_META phase already did a btf dump.
1472 * If member is logged again, it must hit an error in
1473 * parsing this member. It is useful to print out which
1474 * struct this member belongs to.
1476 if (env->phase != CHECK_META)
1477 btf_verifier_log_type(env, struct_type, NULL);
1479 if (btf_type_kflag(struct_type))
1480 __btf_verifier_log(log,
1481 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1482 __btf_name_by_offset(btf, member->name_off),
1484 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1485 BTF_MEMBER_BIT_OFFSET(member->offset));
1487 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1488 __btf_name_by_offset(btf, member->name_off),
1489 member->type, member->offset);
1492 __btf_verifier_log(log, " ");
1493 va_start(args, fmt);
1494 bpf_verifier_vlog(log, fmt, args);
1498 __btf_verifier_log(log, "\n");
1502 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1503 const struct btf_type *datasec_type,
1504 const struct btf_var_secinfo *vsi,
1505 const char *fmt, ...)
1507 struct bpf_verifier_log *log = &env->log;
1510 if (!bpf_verifier_log_needed(log))
1512 if (log->level == BPF_LOG_KERNEL && !fmt)
1514 if (env->phase != CHECK_META)
1515 btf_verifier_log_type(env, datasec_type, NULL);
1517 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1518 vsi->type, vsi->offset, vsi->size);
1520 __btf_verifier_log(log, " ");
1521 va_start(args, fmt);
1522 bpf_verifier_vlog(log, fmt, args);
1526 __btf_verifier_log(log, "\n");
1529 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1532 struct bpf_verifier_log *log = &env->log;
1533 const struct btf *btf = env->btf;
1534 const struct btf_header *hdr;
1536 if (!bpf_verifier_log_needed(log))
1539 if (log->level == BPF_LOG_KERNEL)
1542 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1543 __btf_verifier_log(log, "version: %u\n", hdr->version);
1544 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1545 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1546 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1547 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1548 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1549 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1550 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1553 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1555 struct btf *btf = env->btf;
1557 if (btf->types_size == btf->nr_types) {
1558 /* Expand 'types' array */
1560 struct btf_type **new_types;
1561 u32 expand_by, new_size;
1563 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1564 btf_verifier_log(env, "Exceeded max num of types");
1568 expand_by = max_t(u32, btf->types_size >> 2, 16);
1569 new_size = min_t(u32, BTF_MAX_TYPE,
1570 btf->types_size + expand_by);
1572 new_types = kvcalloc(new_size, sizeof(*new_types),
1573 GFP_KERNEL | __GFP_NOWARN);
1577 if (btf->nr_types == 0) {
1578 if (!btf->base_btf) {
1579 /* lazily init VOID type */
1580 new_types[0] = &btf_void;
1584 memcpy(new_types, btf->types,
1585 sizeof(*btf->types) * btf->nr_types);
1589 btf->types = new_types;
1590 btf->types_size = new_size;
1593 btf->types[btf->nr_types++] = t;
1598 static int btf_alloc_id(struct btf *btf)
1602 idr_preload(GFP_KERNEL);
1603 spin_lock_bh(&btf_idr_lock);
1604 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1607 spin_unlock_bh(&btf_idr_lock);
1610 if (WARN_ON_ONCE(!id))
1613 return id > 0 ? 0 : id;
1616 static void btf_free_id(struct btf *btf)
1618 unsigned long flags;
1621 * In map-in-map, calling map_delete_elem() on outer
1622 * map will call bpf_map_put on the inner map.
1623 * It will then eventually call btf_free_id()
1624 * on the inner map. Some of the map_delete_elem()
1625 * implementation may have irq disabled, so
1626 * we need to use the _irqsave() version instead
1627 * of the _bh() version.
1629 spin_lock_irqsave(&btf_idr_lock, flags);
1630 idr_remove(&btf_idr, btf->id);
1631 spin_unlock_irqrestore(&btf_idr_lock, flags);
1634 static void btf_free_kfunc_set_tab(struct btf *btf)
1636 struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1641 /* For module BTF, we directly assign the sets being registered, so
1642 * there is nothing to free except kfunc_set_tab.
1644 if (btf_is_module(btf))
1646 for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1647 kfree(tab->sets[hook]);
1650 btf->kfunc_set_tab = NULL;
1653 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1655 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1660 btf->dtor_kfunc_tab = NULL;
1663 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1669 for (i = 0; i < tab->cnt; i++) {
1670 btf_record_free(tab->types[i].record);
1671 kfree(tab->types[i].field_offs);
1676 static void btf_free_struct_meta_tab(struct btf *btf)
1678 struct btf_struct_metas *tab = btf->struct_meta_tab;
1680 btf_struct_metas_free(tab);
1681 btf->struct_meta_tab = NULL;
1684 static void btf_free(struct btf *btf)
1686 btf_free_struct_meta_tab(btf);
1687 btf_free_dtor_kfunc_tab(btf);
1688 btf_free_kfunc_set_tab(btf);
1690 kvfree(btf->resolved_sizes);
1691 kvfree(btf->resolved_ids);
1696 static void btf_free_rcu(struct rcu_head *rcu)
1698 struct btf *btf = container_of(rcu, struct btf, rcu);
1703 void btf_get(struct btf *btf)
1705 refcount_inc(&btf->refcnt);
1708 void btf_put(struct btf *btf)
1710 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1712 call_rcu(&btf->rcu, btf_free_rcu);
1716 static int env_resolve_init(struct btf_verifier_env *env)
1718 struct btf *btf = env->btf;
1719 u32 nr_types = btf->nr_types;
1720 u32 *resolved_sizes = NULL;
1721 u32 *resolved_ids = NULL;
1722 u8 *visit_states = NULL;
1724 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1725 GFP_KERNEL | __GFP_NOWARN);
1726 if (!resolved_sizes)
1729 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1730 GFP_KERNEL | __GFP_NOWARN);
1734 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1735 GFP_KERNEL | __GFP_NOWARN);
1739 btf->resolved_sizes = resolved_sizes;
1740 btf->resolved_ids = resolved_ids;
1741 env->visit_states = visit_states;
1746 kvfree(resolved_sizes);
1747 kvfree(resolved_ids);
1748 kvfree(visit_states);
1752 static void btf_verifier_env_free(struct btf_verifier_env *env)
1754 kvfree(env->visit_states);
1758 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1759 const struct btf_type *next_type)
1761 switch (env->resolve_mode) {
1763 /* int, enum or void is a sink */
1764 return !btf_type_needs_resolve(next_type);
1766 /* int, enum, void, struct, array, func or func_proto is a sink
1769 return !btf_type_is_modifier(next_type) &&
1770 !btf_type_is_ptr(next_type);
1771 case RESOLVE_STRUCT_OR_ARRAY:
1772 /* int, enum, void, ptr, func or func_proto is a sink
1773 * for struct and array
1775 return !btf_type_is_modifier(next_type) &&
1776 !btf_type_is_array(next_type) &&
1777 !btf_type_is_struct(next_type);
1783 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1786 /* base BTF types should be resolved by now */
1787 if (type_id < env->btf->start_id)
1790 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1793 static int env_stack_push(struct btf_verifier_env *env,
1794 const struct btf_type *t, u32 type_id)
1796 const struct btf *btf = env->btf;
1797 struct resolve_vertex *v;
1799 if (env->top_stack == MAX_RESOLVE_DEPTH)
1802 if (type_id < btf->start_id
1803 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1806 env->visit_states[type_id - btf->start_id] = VISITED;
1808 v = &env->stack[env->top_stack++];
1810 v->type_id = type_id;
1813 if (env->resolve_mode == RESOLVE_TBD) {
1814 if (btf_type_is_ptr(t))
1815 env->resolve_mode = RESOLVE_PTR;
1816 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1817 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1823 static void env_stack_set_next_member(struct btf_verifier_env *env,
1826 env->stack[env->top_stack - 1].next_member = next_member;
1829 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1830 u32 resolved_type_id,
1833 u32 type_id = env->stack[--(env->top_stack)].type_id;
1834 struct btf *btf = env->btf;
1836 type_id -= btf->start_id; /* adjust to local type id */
1837 btf->resolved_sizes[type_id] = resolved_size;
1838 btf->resolved_ids[type_id] = resolved_type_id;
1839 env->visit_states[type_id] = RESOLVED;
1842 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1844 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1847 /* Resolve the size of a passed-in "type"
1849 * type: is an array (e.g. u32 array[x][y])
1850 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1851 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1852 * corresponds to the return type.
1854 * *elem_id: id of u32
1855 * *total_nelems: (x * y). Hence, individual elem size is
1856 * (*type_size / *total_nelems)
1857 * *type_id: id of type if it's changed within the function, 0 if not
1859 * type: is not an array (e.g. const struct X)
1860 * return type: type "struct X"
1861 * *type_size: sizeof(struct X)
1862 * *elem_type: same as return type ("struct X")
1865 * *type_id: id of type if it's changed within the function, 0 if not
1867 static const struct btf_type *
1868 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1869 u32 *type_size, const struct btf_type **elem_type,
1870 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1872 const struct btf_type *array_type = NULL;
1873 const struct btf_array *array = NULL;
1874 u32 i, size, nelems = 1, id = 0;
1876 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1877 switch (BTF_INFO_KIND(type->info)) {
1878 /* type->size can be used */
1880 case BTF_KIND_STRUCT:
1881 case BTF_KIND_UNION:
1883 case BTF_KIND_FLOAT:
1884 case BTF_KIND_ENUM64:
1889 size = sizeof(void *);
1893 case BTF_KIND_TYPEDEF:
1894 case BTF_KIND_VOLATILE:
1895 case BTF_KIND_CONST:
1896 case BTF_KIND_RESTRICT:
1897 case BTF_KIND_TYPE_TAG:
1899 type = btf_type_by_id(btf, type->type);
1902 case BTF_KIND_ARRAY:
1905 array = btf_type_array(type);
1906 if (nelems && array->nelems > U32_MAX / nelems)
1907 return ERR_PTR(-EINVAL);
1908 nelems *= array->nelems;
1909 type = btf_type_by_id(btf, array->type);
1912 /* type without size */
1914 return ERR_PTR(-EINVAL);
1918 return ERR_PTR(-EINVAL);
1921 if (nelems && size > U32_MAX / nelems)
1922 return ERR_PTR(-EINVAL);
1924 *type_size = nelems * size;
1926 *total_nelems = nelems;
1930 *elem_id = array ? array->type : 0;
1934 return array_type ? : type;
1937 const struct btf_type *
1938 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1941 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1944 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1946 while (type_id < btf->start_id)
1947 btf = btf->base_btf;
1949 return btf->resolved_ids[type_id - btf->start_id];
1952 /* The input param "type_id" must point to a needs_resolve type */
1953 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1956 *type_id = btf_resolved_type_id(btf, *type_id);
1957 return btf_type_by_id(btf, *type_id);
1960 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1962 while (type_id < btf->start_id)
1963 btf = btf->base_btf;
1965 return btf->resolved_sizes[type_id - btf->start_id];
1968 const struct btf_type *btf_type_id_size(const struct btf *btf,
1969 u32 *type_id, u32 *ret_size)
1971 const struct btf_type *size_type;
1972 u32 size_type_id = *type_id;
1975 size_type = btf_type_by_id(btf, size_type_id);
1976 if (btf_type_nosize_or_null(size_type))
1979 if (btf_type_has_size(size_type)) {
1980 size = size_type->size;
1981 } else if (btf_type_is_array(size_type)) {
1982 size = btf_resolved_type_size(btf, size_type_id);
1983 } else if (btf_type_is_ptr(size_type)) {
1984 size = sizeof(void *);
1986 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1987 !btf_type_is_var(size_type)))
1990 size_type_id = btf_resolved_type_id(btf, size_type_id);
1991 size_type = btf_type_by_id(btf, size_type_id);
1992 if (btf_type_nosize_or_null(size_type))
1994 else if (btf_type_has_size(size_type))
1995 size = size_type->size;
1996 else if (btf_type_is_array(size_type))
1997 size = btf_resolved_type_size(btf, size_type_id);
1998 else if (btf_type_is_ptr(size_type))
1999 size = sizeof(void *);
2004 *type_id = size_type_id;
2011 static int btf_df_check_member(struct btf_verifier_env *env,
2012 const struct btf_type *struct_type,
2013 const struct btf_member *member,
2014 const struct btf_type *member_type)
2016 btf_verifier_log_basic(env, struct_type,
2017 "Unsupported check_member");
2021 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2022 const struct btf_type *struct_type,
2023 const struct btf_member *member,
2024 const struct btf_type *member_type)
2026 btf_verifier_log_basic(env, struct_type,
2027 "Unsupported check_kflag_member");
2031 /* Used for ptr, array struct/union and float type members.
2032 * int, enum and modifier types have their specific callback functions.
2034 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2035 const struct btf_type *struct_type,
2036 const struct btf_member *member,
2037 const struct btf_type *member_type)
2039 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2040 btf_verifier_log_member(env, struct_type, member,
2041 "Invalid member bitfield_size");
2045 /* bitfield size is 0, so member->offset represents bit offset only.
2046 * It is safe to call non kflag check_member variants.
2048 return btf_type_ops(member_type)->check_member(env, struct_type,
2053 static int btf_df_resolve(struct btf_verifier_env *env,
2054 const struct resolve_vertex *v)
2056 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2060 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2061 u32 type_id, void *data, u8 bits_offsets,
2062 struct btf_show *show)
2064 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2067 static int btf_int_check_member(struct btf_verifier_env *env,
2068 const struct btf_type *struct_type,
2069 const struct btf_member *member,
2070 const struct btf_type *member_type)
2072 u32 int_data = btf_type_int(member_type);
2073 u32 struct_bits_off = member->offset;
2074 u32 struct_size = struct_type->size;
2078 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2079 btf_verifier_log_member(env, struct_type, member,
2080 "bits_offset exceeds U32_MAX");
2084 struct_bits_off += BTF_INT_OFFSET(int_data);
2085 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2086 nr_copy_bits = BTF_INT_BITS(int_data) +
2087 BITS_PER_BYTE_MASKED(struct_bits_off);
2089 if (nr_copy_bits > BITS_PER_U128) {
2090 btf_verifier_log_member(env, struct_type, member,
2091 "nr_copy_bits exceeds 128");
2095 if (struct_size < bytes_offset ||
2096 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2097 btf_verifier_log_member(env, struct_type, member,
2098 "Member exceeds struct_size");
2105 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2106 const struct btf_type *struct_type,
2107 const struct btf_member *member,
2108 const struct btf_type *member_type)
2110 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2111 u32 int_data = btf_type_int(member_type);
2112 u32 struct_size = struct_type->size;
2115 /* a regular int type is required for the kflag int member */
2116 if (!btf_type_int_is_regular(member_type)) {
2117 btf_verifier_log_member(env, struct_type, member,
2118 "Invalid member base type");
2122 /* check sanity of bitfield size */
2123 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2124 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2125 nr_int_data_bits = BTF_INT_BITS(int_data);
2127 /* Not a bitfield member, member offset must be at byte
2130 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2131 btf_verifier_log_member(env, struct_type, member,
2132 "Invalid member offset");
2136 nr_bits = nr_int_data_bits;
2137 } else if (nr_bits > nr_int_data_bits) {
2138 btf_verifier_log_member(env, struct_type, member,
2139 "Invalid member bitfield_size");
2143 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2144 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2145 if (nr_copy_bits > BITS_PER_U128) {
2146 btf_verifier_log_member(env, struct_type, member,
2147 "nr_copy_bits exceeds 128");
2151 if (struct_size < bytes_offset ||
2152 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2153 btf_verifier_log_member(env, struct_type, member,
2154 "Member exceeds struct_size");
2161 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2162 const struct btf_type *t,
2165 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2168 if (meta_left < meta_needed) {
2169 btf_verifier_log_basic(env, t,
2170 "meta_left:%u meta_needed:%u",
2171 meta_left, meta_needed);
2175 if (btf_type_vlen(t)) {
2176 btf_verifier_log_type(env, t, "vlen != 0");
2180 if (btf_type_kflag(t)) {
2181 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2185 int_data = btf_type_int(t);
2186 if (int_data & ~BTF_INT_MASK) {
2187 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2192 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2194 if (nr_bits > BITS_PER_U128) {
2195 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2200 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2201 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2206 * Only one of the encoding bits is allowed and it
2207 * should be sufficient for the pretty print purpose (i.e. decoding).
2208 * Multiple bits can be allowed later if it is found
2209 * to be insufficient.
2211 encoding = BTF_INT_ENCODING(int_data);
2213 encoding != BTF_INT_SIGNED &&
2214 encoding != BTF_INT_CHAR &&
2215 encoding != BTF_INT_BOOL) {
2216 btf_verifier_log_type(env, t, "Unsupported encoding");
2220 btf_verifier_log_type(env, t, NULL);
2225 static void btf_int_log(struct btf_verifier_env *env,
2226 const struct btf_type *t)
2228 int int_data = btf_type_int(t);
2230 btf_verifier_log(env,
2231 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2232 t->size, BTF_INT_OFFSET(int_data),
2233 BTF_INT_BITS(int_data),
2234 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2237 static void btf_int128_print(struct btf_show *show, void *data)
2239 /* data points to a __int128 number.
2241 * int128_num = *(__int128 *)data;
2242 * The below formulas shows what upper_num and lower_num represents:
2243 * upper_num = int128_num >> 64;
2244 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2246 u64 upper_num, lower_num;
2248 #ifdef __BIG_ENDIAN_BITFIELD
2249 upper_num = *(u64 *)data;
2250 lower_num = *(u64 *)(data + 8);
2252 upper_num = *(u64 *)(data + 8);
2253 lower_num = *(u64 *)data;
2256 btf_show_type_value(show, "0x%llx", lower_num);
2258 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2262 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2263 u16 right_shift_bits)
2265 u64 upper_num, lower_num;
2267 #ifdef __BIG_ENDIAN_BITFIELD
2268 upper_num = print_num[0];
2269 lower_num = print_num[1];
2271 upper_num = print_num[1];
2272 lower_num = print_num[0];
2275 /* shake out un-needed bits by shift/or operations */
2276 if (left_shift_bits >= 64) {
2277 upper_num = lower_num << (left_shift_bits - 64);
2280 upper_num = (upper_num << left_shift_bits) |
2281 (lower_num >> (64 - left_shift_bits));
2282 lower_num = lower_num << left_shift_bits;
2285 if (right_shift_bits >= 64) {
2286 lower_num = upper_num >> (right_shift_bits - 64);
2289 lower_num = (lower_num >> right_shift_bits) |
2290 (upper_num << (64 - right_shift_bits));
2291 upper_num = upper_num >> right_shift_bits;
2294 #ifdef __BIG_ENDIAN_BITFIELD
2295 print_num[0] = upper_num;
2296 print_num[1] = lower_num;
2298 print_num[0] = lower_num;
2299 print_num[1] = upper_num;
2303 static void btf_bitfield_show(void *data, u8 bits_offset,
2304 u8 nr_bits, struct btf_show *show)
2306 u16 left_shift_bits, right_shift_bits;
2309 u64 print_num[2] = {};
2311 nr_copy_bits = nr_bits + bits_offset;
2312 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2314 memcpy(print_num, data, nr_copy_bytes);
2316 #ifdef __BIG_ENDIAN_BITFIELD
2317 left_shift_bits = bits_offset;
2319 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2321 right_shift_bits = BITS_PER_U128 - nr_bits;
2323 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2324 btf_int128_print(show, print_num);
2328 static void btf_int_bits_show(const struct btf *btf,
2329 const struct btf_type *t,
2330 void *data, u8 bits_offset,
2331 struct btf_show *show)
2333 u32 int_data = btf_type_int(t);
2334 u8 nr_bits = BTF_INT_BITS(int_data);
2335 u8 total_bits_offset;
2338 * bits_offset is at most 7.
2339 * BTF_INT_OFFSET() cannot exceed 128 bits.
2341 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2342 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2343 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2344 btf_bitfield_show(data, bits_offset, nr_bits, show);
2347 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2348 u32 type_id, void *data, u8 bits_offset,
2349 struct btf_show *show)
2351 u32 int_data = btf_type_int(t);
2352 u8 encoding = BTF_INT_ENCODING(int_data);
2353 bool sign = encoding & BTF_INT_SIGNED;
2354 u8 nr_bits = BTF_INT_BITS(int_data);
2357 safe_data = btf_show_start_type(show, t, type_id, data);
2361 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2362 BITS_PER_BYTE_MASKED(nr_bits)) {
2363 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2369 btf_int128_print(show, safe_data);
2373 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2375 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2379 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2381 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2385 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2387 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2390 if (show->state.array_encoding == BTF_INT_CHAR) {
2391 /* check for null terminator */
2392 if (show->state.array_terminated)
2394 if (*(char *)data == '\0') {
2395 show->state.array_terminated = 1;
2398 if (isprint(*(char *)data)) {
2399 btf_show_type_value(show, "'%c'",
2400 *(char *)safe_data);
2405 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2407 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2410 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2414 btf_show_end_type(show);
2417 static const struct btf_kind_operations int_ops = {
2418 .check_meta = btf_int_check_meta,
2419 .resolve = btf_df_resolve,
2420 .check_member = btf_int_check_member,
2421 .check_kflag_member = btf_int_check_kflag_member,
2422 .log_details = btf_int_log,
2423 .show = btf_int_show,
2426 static int btf_modifier_check_member(struct btf_verifier_env *env,
2427 const struct btf_type *struct_type,
2428 const struct btf_member *member,
2429 const struct btf_type *member_type)
2431 const struct btf_type *resolved_type;
2432 u32 resolved_type_id = member->type;
2433 struct btf_member resolved_member;
2434 struct btf *btf = env->btf;
2436 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2437 if (!resolved_type) {
2438 btf_verifier_log_member(env, struct_type, member,
2443 resolved_member = *member;
2444 resolved_member.type = resolved_type_id;
2446 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2451 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2452 const struct btf_type *struct_type,
2453 const struct btf_member *member,
2454 const struct btf_type *member_type)
2456 const struct btf_type *resolved_type;
2457 u32 resolved_type_id = member->type;
2458 struct btf_member resolved_member;
2459 struct btf *btf = env->btf;
2461 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2462 if (!resolved_type) {
2463 btf_verifier_log_member(env, struct_type, member,
2468 resolved_member = *member;
2469 resolved_member.type = resolved_type_id;
2471 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2476 static int btf_ptr_check_member(struct btf_verifier_env *env,
2477 const struct btf_type *struct_type,
2478 const struct btf_member *member,
2479 const struct btf_type *member_type)
2481 u32 struct_size, struct_bits_off, bytes_offset;
2483 struct_size = struct_type->size;
2484 struct_bits_off = member->offset;
2485 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2487 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2488 btf_verifier_log_member(env, struct_type, member,
2489 "Member is not byte aligned");
2493 if (struct_size - bytes_offset < sizeof(void *)) {
2494 btf_verifier_log_member(env, struct_type, member,
2495 "Member exceeds struct_size");
2502 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2503 const struct btf_type *t,
2508 if (btf_type_vlen(t)) {
2509 btf_verifier_log_type(env, t, "vlen != 0");
2513 if (btf_type_kflag(t)) {
2514 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2518 if (!BTF_TYPE_ID_VALID(t->type)) {
2519 btf_verifier_log_type(env, t, "Invalid type_id");
2523 /* typedef/type_tag type must have a valid name, and other ref types,
2524 * volatile, const, restrict, should have a null name.
2526 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2528 !btf_name_valid_identifier(env->btf, t->name_off)) {
2529 btf_verifier_log_type(env, t, "Invalid name");
2532 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2533 value = btf_name_by_offset(env->btf, t->name_off);
2534 if (!value || !value[0]) {
2535 btf_verifier_log_type(env, t, "Invalid name");
2540 btf_verifier_log_type(env, t, "Invalid name");
2545 btf_verifier_log_type(env, t, NULL);
2550 static int btf_modifier_resolve(struct btf_verifier_env *env,
2551 const struct resolve_vertex *v)
2553 const struct btf_type *t = v->t;
2554 const struct btf_type *next_type;
2555 u32 next_type_id = t->type;
2556 struct btf *btf = env->btf;
2558 next_type = btf_type_by_id(btf, next_type_id);
2559 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2560 btf_verifier_log_type(env, v->t, "Invalid type_id");
2564 if (!env_type_is_resolve_sink(env, next_type) &&
2565 !env_type_is_resolved(env, next_type_id))
2566 return env_stack_push(env, next_type, next_type_id);
2568 /* Figure out the resolved next_type_id with size.
2569 * They will be stored in the current modifier's
2570 * resolved_ids and resolved_sizes such that it can
2571 * save us a few type-following when we use it later (e.g. in
2574 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2575 if (env_type_is_resolved(env, next_type_id))
2576 next_type = btf_type_id_resolve(btf, &next_type_id);
2578 /* "typedef void new_void", "const void"...etc */
2579 if (!btf_type_is_void(next_type) &&
2580 !btf_type_is_fwd(next_type) &&
2581 !btf_type_is_func_proto(next_type)) {
2582 btf_verifier_log_type(env, v->t, "Invalid type_id");
2587 env_stack_pop_resolved(env, next_type_id, 0);
2592 static int btf_var_resolve(struct btf_verifier_env *env,
2593 const struct resolve_vertex *v)
2595 const struct btf_type *next_type;
2596 const struct btf_type *t = v->t;
2597 u32 next_type_id = t->type;
2598 struct btf *btf = env->btf;
2600 next_type = btf_type_by_id(btf, next_type_id);
2601 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2602 btf_verifier_log_type(env, v->t, "Invalid type_id");
2606 if (!env_type_is_resolve_sink(env, next_type) &&
2607 !env_type_is_resolved(env, next_type_id))
2608 return env_stack_push(env, next_type, next_type_id);
2610 if (btf_type_is_modifier(next_type)) {
2611 const struct btf_type *resolved_type;
2612 u32 resolved_type_id;
2614 resolved_type_id = next_type_id;
2615 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2617 if (btf_type_is_ptr(resolved_type) &&
2618 !env_type_is_resolve_sink(env, resolved_type) &&
2619 !env_type_is_resolved(env, resolved_type_id))
2620 return env_stack_push(env, resolved_type,
2624 /* We must resolve to something concrete at this point, no
2625 * forward types or similar that would resolve to size of
2628 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2629 btf_verifier_log_type(env, v->t, "Invalid type_id");
2633 env_stack_pop_resolved(env, next_type_id, 0);
2638 static int btf_ptr_resolve(struct btf_verifier_env *env,
2639 const struct resolve_vertex *v)
2641 const struct btf_type *next_type;
2642 const struct btf_type *t = v->t;
2643 u32 next_type_id = t->type;
2644 struct btf *btf = env->btf;
2646 next_type = btf_type_by_id(btf, next_type_id);
2647 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2648 btf_verifier_log_type(env, v->t, "Invalid type_id");
2652 if (!env_type_is_resolve_sink(env, next_type) &&
2653 !env_type_is_resolved(env, next_type_id))
2654 return env_stack_push(env, next_type, next_type_id);
2656 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2657 * the modifier may have stopped resolving when it was resolved
2658 * to a ptr (last-resolved-ptr).
2660 * We now need to continue from the last-resolved-ptr to
2661 * ensure the last-resolved-ptr will not referring back to
2662 * the current ptr (t).
2664 if (btf_type_is_modifier(next_type)) {
2665 const struct btf_type *resolved_type;
2666 u32 resolved_type_id;
2668 resolved_type_id = next_type_id;
2669 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2671 if (btf_type_is_ptr(resolved_type) &&
2672 !env_type_is_resolve_sink(env, resolved_type) &&
2673 !env_type_is_resolved(env, resolved_type_id))
2674 return env_stack_push(env, resolved_type,
2678 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2679 if (env_type_is_resolved(env, next_type_id))
2680 next_type = btf_type_id_resolve(btf, &next_type_id);
2682 if (!btf_type_is_void(next_type) &&
2683 !btf_type_is_fwd(next_type) &&
2684 !btf_type_is_func_proto(next_type)) {
2685 btf_verifier_log_type(env, v->t, "Invalid type_id");
2690 env_stack_pop_resolved(env, next_type_id, 0);
2695 static void btf_modifier_show(const struct btf *btf,
2696 const struct btf_type *t,
2697 u32 type_id, void *data,
2698 u8 bits_offset, struct btf_show *show)
2700 if (btf->resolved_ids)
2701 t = btf_type_id_resolve(btf, &type_id);
2703 t = btf_type_skip_modifiers(btf, type_id, NULL);
2705 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2708 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2709 u32 type_id, void *data, u8 bits_offset,
2710 struct btf_show *show)
2712 t = btf_type_id_resolve(btf, &type_id);
2714 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2717 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2718 u32 type_id, void *data, u8 bits_offset,
2719 struct btf_show *show)
2723 safe_data = btf_show_start_type(show, t, type_id, data);
2727 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2728 if (show->flags & BTF_SHOW_PTR_RAW)
2729 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2731 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2732 btf_show_end_type(show);
2735 static void btf_ref_type_log(struct btf_verifier_env *env,
2736 const struct btf_type *t)
2738 btf_verifier_log(env, "type_id=%u", t->type);
2741 static struct btf_kind_operations modifier_ops = {
2742 .check_meta = btf_ref_type_check_meta,
2743 .resolve = btf_modifier_resolve,
2744 .check_member = btf_modifier_check_member,
2745 .check_kflag_member = btf_modifier_check_kflag_member,
2746 .log_details = btf_ref_type_log,
2747 .show = btf_modifier_show,
2750 static struct btf_kind_operations ptr_ops = {
2751 .check_meta = btf_ref_type_check_meta,
2752 .resolve = btf_ptr_resolve,
2753 .check_member = btf_ptr_check_member,
2754 .check_kflag_member = btf_generic_check_kflag_member,
2755 .log_details = btf_ref_type_log,
2756 .show = btf_ptr_show,
2759 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2760 const struct btf_type *t,
2763 if (btf_type_vlen(t)) {
2764 btf_verifier_log_type(env, t, "vlen != 0");
2769 btf_verifier_log_type(env, t, "type != 0");
2773 /* fwd type must have a valid name */
2775 !btf_name_valid_identifier(env->btf, t->name_off)) {
2776 btf_verifier_log_type(env, t, "Invalid name");
2780 btf_verifier_log_type(env, t, NULL);
2785 static void btf_fwd_type_log(struct btf_verifier_env *env,
2786 const struct btf_type *t)
2788 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2791 static struct btf_kind_operations fwd_ops = {
2792 .check_meta = btf_fwd_check_meta,
2793 .resolve = btf_df_resolve,
2794 .check_member = btf_df_check_member,
2795 .check_kflag_member = btf_df_check_kflag_member,
2796 .log_details = btf_fwd_type_log,
2797 .show = btf_df_show,
2800 static int btf_array_check_member(struct btf_verifier_env *env,
2801 const struct btf_type *struct_type,
2802 const struct btf_member *member,
2803 const struct btf_type *member_type)
2805 u32 struct_bits_off = member->offset;
2806 u32 struct_size, bytes_offset;
2807 u32 array_type_id, array_size;
2808 struct btf *btf = env->btf;
2810 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2811 btf_verifier_log_member(env, struct_type, member,
2812 "Member is not byte aligned");
2816 array_type_id = member->type;
2817 btf_type_id_size(btf, &array_type_id, &array_size);
2818 struct_size = struct_type->size;
2819 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2820 if (struct_size - bytes_offset < array_size) {
2821 btf_verifier_log_member(env, struct_type, member,
2822 "Member exceeds struct_size");
2829 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2830 const struct btf_type *t,
2833 const struct btf_array *array = btf_type_array(t);
2834 u32 meta_needed = sizeof(*array);
2836 if (meta_left < meta_needed) {
2837 btf_verifier_log_basic(env, t,
2838 "meta_left:%u meta_needed:%u",
2839 meta_left, meta_needed);
2843 /* array type should not have a name */
2845 btf_verifier_log_type(env, t, "Invalid name");
2849 if (btf_type_vlen(t)) {
2850 btf_verifier_log_type(env, t, "vlen != 0");
2854 if (btf_type_kflag(t)) {
2855 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2860 btf_verifier_log_type(env, t, "size != 0");
2864 /* Array elem type and index type cannot be in type void,
2865 * so !array->type and !array->index_type are not allowed.
2867 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2868 btf_verifier_log_type(env, t, "Invalid elem");
2872 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2873 btf_verifier_log_type(env, t, "Invalid index");
2877 btf_verifier_log_type(env, t, NULL);
2882 static int btf_array_resolve(struct btf_verifier_env *env,
2883 const struct resolve_vertex *v)
2885 const struct btf_array *array = btf_type_array(v->t);
2886 const struct btf_type *elem_type, *index_type;
2887 u32 elem_type_id, index_type_id;
2888 struct btf *btf = env->btf;
2891 /* Check array->index_type */
2892 index_type_id = array->index_type;
2893 index_type = btf_type_by_id(btf, index_type_id);
2894 if (btf_type_nosize_or_null(index_type) ||
2895 btf_type_is_resolve_source_only(index_type)) {
2896 btf_verifier_log_type(env, v->t, "Invalid index");
2900 if (!env_type_is_resolve_sink(env, index_type) &&
2901 !env_type_is_resolved(env, index_type_id))
2902 return env_stack_push(env, index_type, index_type_id);
2904 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2905 if (!index_type || !btf_type_is_int(index_type) ||
2906 !btf_type_int_is_regular(index_type)) {
2907 btf_verifier_log_type(env, v->t, "Invalid index");
2911 /* Check array->type */
2912 elem_type_id = array->type;
2913 elem_type = btf_type_by_id(btf, elem_type_id);
2914 if (btf_type_nosize_or_null(elem_type) ||
2915 btf_type_is_resolve_source_only(elem_type)) {
2916 btf_verifier_log_type(env, v->t,
2921 if (!env_type_is_resolve_sink(env, elem_type) &&
2922 !env_type_is_resolved(env, elem_type_id))
2923 return env_stack_push(env, elem_type, elem_type_id);
2925 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2927 btf_verifier_log_type(env, v->t, "Invalid elem");
2931 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2932 btf_verifier_log_type(env, v->t, "Invalid array of int");
2936 if (array->nelems && elem_size > U32_MAX / array->nelems) {
2937 btf_verifier_log_type(env, v->t,
2938 "Array size overflows U32_MAX");
2942 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2947 static void btf_array_log(struct btf_verifier_env *env,
2948 const struct btf_type *t)
2950 const struct btf_array *array = btf_type_array(t);
2952 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2953 array->type, array->index_type, array->nelems);
2956 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2957 u32 type_id, void *data, u8 bits_offset,
2958 struct btf_show *show)
2960 const struct btf_array *array = btf_type_array(t);
2961 const struct btf_kind_operations *elem_ops;
2962 const struct btf_type *elem_type;
2963 u32 i, elem_size = 0, elem_type_id;
2966 elem_type_id = array->type;
2967 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2968 if (elem_type && btf_type_has_size(elem_type))
2969 elem_size = elem_type->size;
2971 if (elem_type && btf_type_is_int(elem_type)) {
2972 u32 int_type = btf_type_int(elem_type);
2974 encoding = BTF_INT_ENCODING(int_type);
2977 * BTF_INT_CHAR encoding never seems to be set for
2978 * char arrays, so if size is 1 and element is
2979 * printable as a char, we'll do that.
2982 encoding = BTF_INT_CHAR;
2985 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2990 elem_ops = btf_type_ops(elem_type);
2992 for (i = 0; i < array->nelems; i++) {
2994 btf_show_start_array_member(show);
2996 elem_ops->show(btf, elem_type, elem_type_id, data,
3000 btf_show_end_array_member(show);
3002 if (show->state.array_terminated)
3006 btf_show_end_array_type(show);
3009 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3010 u32 type_id, void *data, u8 bits_offset,
3011 struct btf_show *show)
3013 const struct btf_member *m = show->state.member;
3016 * First check if any members would be shown (are non-zero).
3017 * See comments above "struct btf_show" definition for more
3018 * details on how this works at a high-level.
3020 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3021 if (!show->state.depth_check) {
3022 show->state.depth_check = show->state.depth + 1;
3023 show->state.depth_to_show = 0;
3025 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3026 show->state.member = m;
3028 if (show->state.depth_check != show->state.depth + 1)
3030 show->state.depth_check = 0;
3032 if (show->state.depth_to_show <= show->state.depth)
3035 * Reaching here indicates we have recursed and found
3036 * non-zero array member(s).
3039 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3042 static struct btf_kind_operations array_ops = {
3043 .check_meta = btf_array_check_meta,
3044 .resolve = btf_array_resolve,
3045 .check_member = btf_array_check_member,
3046 .check_kflag_member = btf_generic_check_kflag_member,
3047 .log_details = btf_array_log,
3048 .show = btf_array_show,
3051 static int btf_struct_check_member(struct btf_verifier_env *env,
3052 const struct btf_type *struct_type,
3053 const struct btf_member *member,
3054 const struct btf_type *member_type)
3056 u32 struct_bits_off = member->offset;
3057 u32 struct_size, bytes_offset;
3059 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3060 btf_verifier_log_member(env, struct_type, member,
3061 "Member is not byte aligned");
3065 struct_size = struct_type->size;
3066 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3067 if (struct_size - bytes_offset < member_type->size) {
3068 btf_verifier_log_member(env, struct_type, member,
3069 "Member exceeds struct_size");
3076 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3077 const struct btf_type *t,
3080 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3081 const struct btf_member *member;
3082 u32 meta_needed, last_offset;
3083 struct btf *btf = env->btf;
3084 u32 struct_size = t->size;
3088 meta_needed = btf_type_vlen(t) * sizeof(*member);
3089 if (meta_left < meta_needed) {
3090 btf_verifier_log_basic(env, t,
3091 "meta_left:%u meta_needed:%u",
3092 meta_left, meta_needed);
3096 /* struct type either no name or a valid one */
3098 !btf_name_valid_identifier(env->btf, t->name_off)) {
3099 btf_verifier_log_type(env, t, "Invalid name");
3103 btf_verifier_log_type(env, t, NULL);
3106 for_each_member(i, t, member) {
3107 if (!btf_name_offset_valid(btf, member->name_off)) {
3108 btf_verifier_log_member(env, t, member,
3109 "Invalid member name_offset:%u",
3114 /* struct member either no name or a valid one */
3115 if (member->name_off &&
3116 !btf_name_valid_identifier(btf, member->name_off)) {
3117 btf_verifier_log_member(env, t, member, "Invalid name");
3120 /* A member cannot be in type void */
3121 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3122 btf_verifier_log_member(env, t, member,
3127 offset = __btf_member_bit_offset(t, member);
3128 if (is_union && offset) {
3129 btf_verifier_log_member(env, t, member,
3130 "Invalid member bits_offset");
3135 * ">" instead of ">=" because the last member could be
3138 if (last_offset > offset) {
3139 btf_verifier_log_member(env, t, member,
3140 "Invalid member bits_offset");
3144 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3145 btf_verifier_log_member(env, t, member,
3146 "Member bits_offset exceeds its struct size");
3150 btf_verifier_log_member(env, t, member, NULL);
3151 last_offset = offset;
3157 static int btf_struct_resolve(struct btf_verifier_env *env,
3158 const struct resolve_vertex *v)
3160 const struct btf_member *member;
3164 /* Before continue resolving the next_member,
3165 * ensure the last member is indeed resolved to a
3166 * type with size info.
3168 if (v->next_member) {
3169 const struct btf_type *last_member_type;
3170 const struct btf_member *last_member;
3171 u32 last_member_type_id;
3173 last_member = btf_type_member(v->t) + v->next_member - 1;
3174 last_member_type_id = last_member->type;
3175 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3176 last_member_type_id)))
3179 last_member_type = btf_type_by_id(env->btf,
3180 last_member_type_id);
3181 if (btf_type_kflag(v->t))
3182 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3186 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3193 for_each_member_from(i, v->next_member, v->t, member) {
3194 u32 member_type_id = member->type;
3195 const struct btf_type *member_type = btf_type_by_id(env->btf,
3198 if (btf_type_nosize_or_null(member_type) ||
3199 btf_type_is_resolve_source_only(member_type)) {
3200 btf_verifier_log_member(env, v->t, member,
3205 if (!env_type_is_resolve_sink(env, member_type) &&
3206 !env_type_is_resolved(env, member_type_id)) {
3207 env_stack_set_next_member(env, i + 1);
3208 return env_stack_push(env, member_type, member_type_id);
3211 if (btf_type_kflag(v->t))
3212 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3216 err = btf_type_ops(member_type)->check_member(env, v->t,
3223 env_stack_pop_resolved(env, 0, 0);
3228 static void btf_struct_log(struct btf_verifier_env *env,
3229 const struct btf_type *t)
3231 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3234 enum btf_field_info_type {
3235 BTF_FIELD_SPIN_LOCK,
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");
3403 /* Only return BPF_KPTR when all other types with matchable names fail */
3404 if (field_mask & BPF_KPTR) {
3405 type = BPF_KPTR_REF;
3410 *sz = btf_field_type_size(type);
3411 *align = btf_field_type_align(type);
3415 #undef field_mask_test_name
3417 static int btf_find_struct_field(const struct btf *btf,
3418 const struct btf_type *t, u32 field_mask,
3419 struct btf_field_info *info, int info_cnt)
3421 int ret, idx = 0, align, sz, field_type;
3422 const struct btf_member *member;
3423 struct btf_field_info tmp;
3424 u32 i, off, seen_mask = 0;
3426 for_each_member(i, t, member) {
3427 const struct btf_type *member_type = btf_type_by_id(btf,
3430 field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3431 field_mask, &seen_mask, &align, &sz);
3432 if (field_type == 0)
3437 off = __btf_member_bit_offset(t, member);
3439 /* valid C code cannot generate such BTF */
3445 switch (field_type) {
3450 ret = btf_find_struct(btf, member_type, off, sz, field_type,
3451 idx < info_cnt ? &info[idx] : &tmp);
3455 case BPF_KPTR_UNREF:
3457 ret = btf_find_kptr(btf, member_type, off, sz,
3458 idx < info_cnt ? &info[idx] : &tmp);
3464 ret = btf_find_graph_root(btf, t, member_type,
3466 idx < info_cnt ? &info[idx] : &tmp,
3475 if (ret == BTF_FIELD_IGNORE)
3477 if (idx >= info_cnt)
3484 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3485 u32 field_mask, struct btf_field_info *info,
3488 int ret, idx = 0, align, sz, field_type;
3489 const struct btf_var_secinfo *vsi;
3490 struct btf_field_info tmp;
3491 u32 i, off, seen_mask = 0;
3493 for_each_vsi(i, t, vsi) {
3494 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3495 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3497 field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3498 field_mask, &seen_mask, &align, &sz);
3499 if (field_type == 0)
3505 if (vsi->size != sz)
3510 switch (field_type) {
3515 ret = btf_find_struct(btf, var_type, off, sz, field_type,
3516 idx < info_cnt ? &info[idx] : &tmp);
3520 case BPF_KPTR_UNREF:
3522 ret = btf_find_kptr(btf, var_type, off, sz,
3523 idx < info_cnt ? &info[idx] : &tmp);
3529 ret = btf_find_graph_root(btf, var, var_type,
3531 idx < info_cnt ? &info[idx] : &tmp,
3540 if (ret == BTF_FIELD_IGNORE)
3542 if (idx >= info_cnt)
3549 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3550 u32 field_mask, struct btf_field_info *info,
3553 if (__btf_type_is_struct(t))
3554 return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
3555 else if (btf_type_is_datasec(t))
3556 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
3560 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3561 struct btf_field_info *info)
3563 struct module *mod = NULL;
3564 const struct btf_type *t;
3565 struct btf *kernel_btf;
3569 /* Find type in map BTF, and use it to look up the matching type
3570 * in vmlinux or module BTFs, by name and kind.
3572 t = btf_type_by_id(btf, info->kptr.type_id);
3573 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3578 /* Find and stash the function pointer for the destruction function that
3579 * needs to be eventually invoked from the map free path.
3581 if (info->type == BPF_KPTR_REF) {
3582 const struct btf_type *dtor_func;
3583 const char *dtor_func_name;
3587 /* This call also serves as a whitelist of allowed objects that
3588 * can be used as a referenced pointer and be stored in a map at
3591 dtor_btf_id = btf_find_dtor_kfunc(kernel_btf, id);
3592 if (dtor_btf_id < 0) {
3597 dtor_func = btf_type_by_id(kernel_btf, dtor_btf_id);
3603 if (btf_is_module(kernel_btf)) {
3604 mod = btf_try_get_module(kernel_btf);
3611 /* We already verified dtor_func to be btf_type_is_func
3612 * in register_btf_id_dtor_kfuncs.
3614 dtor_func_name = __btf_name_by_offset(kernel_btf, dtor_func->name_off);
3615 addr = kallsyms_lookup_name(dtor_func_name);
3620 field->kptr.dtor = (void *)addr;
3623 field->kptr.btf_id = id;
3624 field->kptr.btf = kernel_btf;
3625 field->kptr.module = mod;
3630 btf_put(kernel_btf);
3634 static int btf_parse_graph_root(const struct btf *btf,
3635 struct btf_field *field,
3636 struct btf_field_info *info,
3637 const char *node_type_name,
3638 size_t node_type_align)
3640 const struct btf_type *t, *n = NULL;
3641 const struct btf_member *member;
3645 t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3646 /* We've already checked that value_btf_id is a struct type. We
3647 * just need to figure out the offset of the list_node, and
3650 for_each_member(i, t, member) {
3651 if (strcmp(info->graph_root.node_name,
3652 __btf_name_by_offset(btf, member->name_off)))
3654 /* Invalid BTF, two members with same name */
3657 n = btf_type_by_id(btf, member->type);
3658 if (!__btf_type_is_struct(n))
3660 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3662 offset = __btf_member_bit_offset(n, member);
3666 if (offset % node_type_align)
3669 field->graph_root.btf = (struct btf *)btf;
3670 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3671 field->graph_root.node_offset = offset;
3678 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3679 struct btf_field_info *info)
3681 return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3682 __alignof__(struct bpf_list_node));
3685 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3686 struct btf_field_info *info)
3688 return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3689 __alignof__(struct bpf_rb_node));
3692 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3693 u32 field_mask, u32 value_size)
3695 struct btf_field_info info_arr[BTF_FIELDS_MAX];
3696 struct btf_record *rec;
3700 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3702 return ERR_PTR(ret);
3707 /* This needs to be kzalloc to zero out padding and unused fields, see
3708 * comment in btf_record_equal.
3710 rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3712 return ERR_PTR(-ENOMEM);
3714 rec->spin_lock_off = -EINVAL;
3715 rec->timer_off = -EINVAL;
3716 for (i = 0; i < cnt; i++) {
3717 if (info_arr[i].off + btf_field_type_size(info_arr[i].type) > value_size) {
3718 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3722 if (info_arr[i].off < next_off) {
3726 next_off = info_arr[i].off + btf_field_type_size(info_arr[i].type);
3728 rec->field_mask |= info_arr[i].type;
3729 rec->fields[i].offset = info_arr[i].off;
3730 rec->fields[i].type = info_arr[i].type;
3732 switch (info_arr[i].type) {
3734 WARN_ON_ONCE(rec->spin_lock_off >= 0);
3735 /* Cache offset for faster lookup at runtime */
3736 rec->spin_lock_off = rec->fields[i].offset;
3739 WARN_ON_ONCE(rec->timer_off >= 0);
3740 /* Cache offset for faster lookup at runtime */
3741 rec->timer_off = rec->fields[i].offset;
3743 case BPF_KPTR_UNREF:
3745 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3750 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3755 ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
3769 /* bpf_{list_head, rb_node} require bpf_spin_lock */
3770 if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
3771 btf_record_has_field(rec, BPF_RB_ROOT)) && rec->spin_lock_off < 0) {
3776 /* need collection identity for non-owning refs before allowing this
3778 * Consider a node type w/ both list and rb_node fields:
3780 * struct bpf_list_node l;
3781 * struct bpf_rb_node r;
3785 * struct node *n = bpf_obj_new(....);
3786 * bpf_list_push_front(&list_head, &n->l);
3787 * bpf_rbtree_remove(&rb_root, &n->r);
3789 * It should not be possible to rbtree_remove the node since it hasn't
3790 * been added to a tree. But push_front converts n to a non-owning
3791 * reference, and rbtree_remove accepts the non-owning reference to
3792 * a type w/ bpf_rb_node field.
3794 if (btf_record_has_field(rec, BPF_LIST_NODE) &&
3795 btf_record_has_field(rec, BPF_RB_NODE)) {
3802 btf_record_free(rec);
3803 return ERR_PTR(ret);
3806 #define GRAPH_ROOT_MASK (BPF_LIST_HEAD | BPF_RB_ROOT)
3807 #define GRAPH_NODE_MASK (BPF_LIST_NODE | BPF_RB_NODE)
3809 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3813 /* There are three types that signify ownership of some other type:
3814 * kptr_ref, bpf_list_head, bpf_rb_root.
3815 * kptr_ref only supports storing kernel types, which can't store
3816 * references to program allocated local types.
3818 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
3819 * does not form cycles.
3821 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & GRAPH_ROOT_MASK))
3823 for (i = 0; i < rec->cnt; i++) {
3824 struct btf_struct_meta *meta;
3827 if (!(rec->fields[i].type & GRAPH_ROOT_MASK))
3829 btf_id = rec->fields[i].graph_root.value_btf_id;
3830 meta = btf_find_struct_meta(btf, btf_id);
3833 rec->fields[i].graph_root.value_rec = meta->record;
3835 /* We need to set value_rec for all root types, but no need
3836 * to check ownership cycle for a type unless it's also a
3839 if (!(rec->field_mask & GRAPH_NODE_MASK))
3842 /* We need to ensure ownership acyclicity among all types. The
3843 * proper way to do it would be to topologically sort all BTF
3844 * IDs based on the ownership edges, since there can be multiple
3845 * bpf_{list_head,rb_node} in a type. Instead, we use the
3846 * following resaoning:
3848 * - A type can only be owned by another type in user BTF if it
3849 * has a bpf_{list,rb}_node. Let's call these node types.
3850 * - A type can only _own_ another type in user BTF if it has a
3851 * bpf_{list_head,rb_root}. Let's call these root types.
3853 * We ensure that if a type is both a root and node, its
3854 * element types cannot be root types.
3856 * To ensure acyclicity:
3858 * When A is an root type but not a node, its ownership
3862 * - A is an root, e.g. has bpf_rb_root.
3863 * - B is both a root and node, e.g. has bpf_rb_node and
3865 * - C is only an root, e.g. has bpf_list_node
3867 * When A is both a root and node, some other type already
3868 * owns it in the BTF domain, hence it can not own
3869 * another root type through any of the ownership edges.
3872 * - A is both an root and node.
3873 * - B is only an node.
3875 if (meta->record->field_mask & GRAPH_ROOT_MASK)
3881 static int btf_field_offs_cmp(const void *_a, const void *_b, const void *priv)
3883 const u32 a = *(const u32 *)_a;
3884 const u32 b = *(const u32 *)_b;
3893 static void btf_field_offs_swap(void *_a, void *_b, int size, const void *priv)
3895 struct btf_field_offs *foffs = (void *)priv;
3896 u32 *off_base = foffs->field_off;
3897 u32 *a = _a, *b = _b;
3900 sz_a = foffs->field_sz + (a - off_base);
3901 sz_b = foffs->field_sz + (b - off_base);
3907 struct btf_field_offs *btf_parse_field_offs(struct btf_record *rec)
3909 struct btf_field_offs *foffs;
3913 BUILD_BUG_ON(ARRAY_SIZE(foffs->field_off) != ARRAY_SIZE(foffs->field_sz));
3914 if (IS_ERR_OR_NULL(rec))
3917 foffs = kzalloc(sizeof(*foffs), GFP_KERNEL | __GFP_NOWARN);
3919 return ERR_PTR(-ENOMEM);
3921 off = foffs->field_off;
3922 sz = foffs->field_sz;
3923 for (i = 0; i < rec->cnt; i++) {
3924 off[i] = rec->fields[i].offset;
3925 sz[i] = btf_field_type_size(rec->fields[i].type);
3927 foffs->cnt = rec->cnt;
3929 if (foffs->cnt == 1)
3931 sort_r(foffs->field_off, foffs->cnt, sizeof(foffs->field_off[0]),
3932 btf_field_offs_cmp, btf_field_offs_swap, foffs);
3936 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3937 u32 type_id, void *data, u8 bits_offset,
3938 struct btf_show *show)
3940 const struct btf_member *member;
3944 safe_data = btf_show_start_struct_type(show, t, type_id, data);
3948 for_each_member(i, t, member) {
3949 const struct btf_type *member_type = btf_type_by_id(btf,
3951 const struct btf_kind_operations *ops;
3952 u32 member_offset, bitfield_size;
3956 btf_show_start_member(show, member);
3958 member_offset = __btf_member_bit_offset(t, member);
3959 bitfield_size = __btf_member_bitfield_size(t, member);
3960 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3961 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3962 if (bitfield_size) {
3963 safe_data = btf_show_start_type(show, member_type,
3965 data + bytes_offset);
3967 btf_bitfield_show(safe_data,
3969 bitfield_size, show);
3970 btf_show_end_type(show);
3972 ops = btf_type_ops(member_type);
3973 ops->show(btf, member_type, member->type,
3974 data + bytes_offset, bits8_offset, show);
3977 btf_show_end_member(show);
3980 btf_show_end_struct_type(show);
3983 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3984 u32 type_id, void *data, u8 bits_offset,
3985 struct btf_show *show)
3987 const struct btf_member *m = show->state.member;
3990 * First check if any members would be shown (are non-zero).
3991 * See comments above "struct btf_show" definition for more
3992 * details on how this works at a high-level.
3994 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3995 if (!show->state.depth_check) {
3996 show->state.depth_check = show->state.depth + 1;
3997 show->state.depth_to_show = 0;
3999 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4000 /* Restore saved member data here */
4001 show->state.member = m;
4002 if (show->state.depth_check != show->state.depth + 1)
4004 show->state.depth_check = 0;
4006 if (show->state.depth_to_show <= show->state.depth)
4009 * Reaching here indicates we have recursed and found
4010 * non-zero child values.
4014 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4017 static struct btf_kind_operations struct_ops = {
4018 .check_meta = btf_struct_check_meta,
4019 .resolve = btf_struct_resolve,
4020 .check_member = btf_struct_check_member,
4021 .check_kflag_member = btf_generic_check_kflag_member,
4022 .log_details = btf_struct_log,
4023 .show = btf_struct_show,
4026 static int btf_enum_check_member(struct btf_verifier_env *env,
4027 const struct btf_type *struct_type,
4028 const struct btf_member *member,
4029 const struct btf_type *member_type)
4031 u32 struct_bits_off = member->offset;
4032 u32 struct_size, bytes_offset;
4034 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4035 btf_verifier_log_member(env, struct_type, member,
4036 "Member is not byte aligned");
4040 struct_size = struct_type->size;
4041 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4042 if (struct_size - bytes_offset < member_type->size) {
4043 btf_verifier_log_member(env, struct_type, member,
4044 "Member exceeds struct_size");
4051 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4052 const struct btf_type *struct_type,
4053 const struct btf_member *member,
4054 const struct btf_type *member_type)
4056 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4057 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4059 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4060 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4062 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4063 btf_verifier_log_member(env, struct_type, member,
4064 "Member is not byte aligned");
4068 nr_bits = int_bitsize;
4069 } else if (nr_bits > int_bitsize) {
4070 btf_verifier_log_member(env, struct_type, member,
4071 "Invalid member bitfield_size");
4075 struct_size = struct_type->size;
4076 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4077 if (struct_size < bytes_end) {
4078 btf_verifier_log_member(env, struct_type, member,
4079 "Member exceeds struct_size");
4086 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4087 const struct btf_type *t,
4090 const struct btf_enum *enums = btf_type_enum(t);
4091 struct btf *btf = env->btf;
4092 const char *fmt_str;
4096 nr_enums = btf_type_vlen(t);
4097 meta_needed = nr_enums * sizeof(*enums);
4099 if (meta_left < meta_needed) {
4100 btf_verifier_log_basic(env, t,
4101 "meta_left:%u meta_needed:%u",
4102 meta_left, meta_needed);
4106 if (t->size > 8 || !is_power_of_2(t->size)) {
4107 btf_verifier_log_type(env, t, "Unexpected size");
4111 /* enum type either no name or a valid one */
4113 !btf_name_valid_identifier(env->btf, t->name_off)) {
4114 btf_verifier_log_type(env, t, "Invalid name");
4118 btf_verifier_log_type(env, t, NULL);
4120 for (i = 0; i < nr_enums; i++) {
4121 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4122 btf_verifier_log(env, "\tInvalid name_offset:%u",
4127 /* enum member must have a valid name */
4128 if (!enums[i].name_off ||
4129 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4130 btf_verifier_log_type(env, t, "Invalid name");
4134 if (env->log.level == BPF_LOG_KERNEL)
4136 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4137 btf_verifier_log(env, fmt_str,
4138 __btf_name_by_offset(btf, enums[i].name_off),
4145 static void btf_enum_log(struct btf_verifier_env *env,
4146 const struct btf_type *t)
4148 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4151 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4152 u32 type_id, void *data, u8 bits_offset,
4153 struct btf_show *show)
4155 const struct btf_enum *enums = btf_type_enum(t);
4156 u32 i, nr_enums = btf_type_vlen(t);
4160 safe_data = btf_show_start_type(show, t, type_id, data);
4164 v = *(int *)safe_data;
4166 for (i = 0; i < nr_enums; i++) {
4167 if (v != enums[i].val)
4170 btf_show_type_value(show, "%s",
4171 __btf_name_by_offset(btf,
4172 enums[i].name_off));
4174 btf_show_end_type(show);
4178 if (btf_type_kflag(t))
4179 btf_show_type_value(show, "%d", v);
4181 btf_show_type_value(show, "%u", v);
4182 btf_show_end_type(show);
4185 static struct btf_kind_operations enum_ops = {
4186 .check_meta = btf_enum_check_meta,
4187 .resolve = btf_df_resolve,
4188 .check_member = btf_enum_check_member,
4189 .check_kflag_member = btf_enum_check_kflag_member,
4190 .log_details = btf_enum_log,
4191 .show = btf_enum_show,
4194 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4195 const struct btf_type *t,
4198 const struct btf_enum64 *enums = btf_type_enum64(t);
4199 struct btf *btf = env->btf;
4200 const char *fmt_str;
4204 nr_enums = btf_type_vlen(t);
4205 meta_needed = nr_enums * sizeof(*enums);
4207 if (meta_left < meta_needed) {
4208 btf_verifier_log_basic(env, t,
4209 "meta_left:%u meta_needed:%u",
4210 meta_left, meta_needed);
4214 if (t->size > 8 || !is_power_of_2(t->size)) {
4215 btf_verifier_log_type(env, t, "Unexpected size");
4219 /* enum type either no name or a valid one */
4221 !btf_name_valid_identifier(env->btf, t->name_off)) {
4222 btf_verifier_log_type(env, t, "Invalid name");
4226 btf_verifier_log_type(env, t, NULL);
4228 for (i = 0; i < nr_enums; i++) {
4229 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4230 btf_verifier_log(env, "\tInvalid name_offset:%u",
4235 /* enum member must have a valid name */
4236 if (!enums[i].name_off ||
4237 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4238 btf_verifier_log_type(env, t, "Invalid name");
4242 if (env->log.level == BPF_LOG_KERNEL)
4245 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4246 btf_verifier_log(env, fmt_str,
4247 __btf_name_by_offset(btf, enums[i].name_off),
4248 btf_enum64_value(enums + i));
4254 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4255 u32 type_id, void *data, u8 bits_offset,
4256 struct btf_show *show)
4258 const struct btf_enum64 *enums = btf_type_enum64(t);
4259 u32 i, nr_enums = btf_type_vlen(t);
4263 safe_data = btf_show_start_type(show, t, type_id, data);
4267 v = *(u64 *)safe_data;
4269 for (i = 0; i < nr_enums; i++) {
4270 if (v != btf_enum64_value(enums + i))
4273 btf_show_type_value(show, "%s",
4274 __btf_name_by_offset(btf,
4275 enums[i].name_off));
4277 btf_show_end_type(show);
4281 if (btf_type_kflag(t))
4282 btf_show_type_value(show, "%lld", v);
4284 btf_show_type_value(show, "%llu", v);
4285 btf_show_end_type(show);
4288 static struct btf_kind_operations enum64_ops = {
4289 .check_meta = btf_enum64_check_meta,
4290 .resolve = btf_df_resolve,
4291 .check_member = btf_enum_check_member,
4292 .check_kflag_member = btf_enum_check_kflag_member,
4293 .log_details = btf_enum_log,
4294 .show = btf_enum64_show,
4297 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4298 const struct btf_type *t,
4301 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4303 if (meta_left < meta_needed) {
4304 btf_verifier_log_basic(env, t,
4305 "meta_left:%u meta_needed:%u",
4306 meta_left, meta_needed);
4311 btf_verifier_log_type(env, t, "Invalid name");
4315 if (btf_type_kflag(t)) {
4316 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4320 btf_verifier_log_type(env, t, NULL);
4325 static void btf_func_proto_log(struct btf_verifier_env *env,
4326 const struct btf_type *t)
4328 const struct btf_param *args = (const struct btf_param *)(t + 1);
4329 u16 nr_args = btf_type_vlen(t), i;
4331 btf_verifier_log(env, "return=%u args=(", t->type);
4333 btf_verifier_log(env, "void");
4337 if (nr_args == 1 && !args[0].type) {
4338 /* Only one vararg */
4339 btf_verifier_log(env, "vararg");
4343 btf_verifier_log(env, "%u %s", args[0].type,
4344 __btf_name_by_offset(env->btf,
4346 for (i = 1; i < nr_args - 1; i++)
4347 btf_verifier_log(env, ", %u %s", args[i].type,
4348 __btf_name_by_offset(env->btf,
4352 const struct btf_param *last_arg = &args[nr_args - 1];
4355 btf_verifier_log(env, ", %u %s", last_arg->type,
4356 __btf_name_by_offset(env->btf,
4357 last_arg->name_off));
4359 btf_verifier_log(env, ", vararg");
4363 btf_verifier_log(env, ")");
4366 static struct btf_kind_operations func_proto_ops = {
4367 .check_meta = btf_func_proto_check_meta,
4368 .resolve = btf_df_resolve,
4370 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4371 * a struct's member.
4373 * It should be a function pointer instead.
4374 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4376 * Hence, there is no btf_func_check_member().
4378 .check_member = btf_df_check_member,
4379 .check_kflag_member = btf_df_check_kflag_member,
4380 .log_details = btf_func_proto_log,
4381 .show = btf_df_show,
4384 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4385 const struct btf_type *t,
4389 !btf_name_valid_identifier(env->btf, t->name_off)) {
4390 btf_verifier_log_type(env, t, "Invalid name");
4394 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4395 btf_verifier_log_type(env, t, "Invalid func linkage");
4399 if (btf_type_kflag(t)) {
4400 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4404 btf_verifier_log_type(env, t, NULL);
4409 static int btf_func_resolve(struct btf_verifier_env *env,
4410 const struct resolve_vertex *v)
4412 const struct btf_type *t = v->t;
4413 u32 next_type_id = t->type;
4416 err = btf_func_check(env, t);
4420 env_stack_pop_resolved(env, next_type_id, 0);
4424 static struct btf_kind_operations func_ops = {
4425 .check_meta = btf_func_check_meta,
4426 .resolve = btf_func_resolve,
4427 .check_member = btf_df_check_member,
4428 .check_kflag_member = btf_df_check_kflag_member,
4429 .log_details = btf_ref_type_log,
4430 .show = btf_df_show,
4433 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4434 const struct btf_type *t,
4437 const struct btf_var *var;
4438 u32 meta_needed = sizeof(*var);
4440 if (meta_left < meta_needed) {
4441 btf_verifier_log_basic(env, t,
4442 "meta_left:%u meta_needed:%u",
4443 meta_left, meta_needed);
4447 if (btf_type_vlen(t)) {
4448 btf_verifier_log_type(env, t, "vlen != 0");
4452 if (btf_type_kflag(t)) {
4453 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4458 !__btf_name_valid(env->btf, t->name_off, true)) {
4459 btf_verifier_log_type(env, t, "Invalid name");
4463 /* A var cannot be in type void */
4464 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4465 btf_verifier_log_type(env, t, "Invalid type_id");
4469 var = btf_type_var(t);
4470 if (var->linkage != BTF_VAR_STATIC &&
4471 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4472 btf_verifier_log_type(env, t, "Linkage not supported");
4476 btf_verifier_log_type(env, t, NULL);
4481 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4483 const struct btf_var *var = btf_type_var(t);
4485 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4488 static const struct btf_kind_operations var_ops = {
4489 .check_meta = btf_var_check_meta,
4490 .resolve = btf_var_resolve,
4491 .check_member = btf_df_check_member,
4492 .check_kflag_member = btf_df_check_kflag_member,
4493 .log_details = btf_var_log,
4494 .show = btf_var_show,
4497 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4498 const struct btf_type *t,
4501 const struct btf_var_secinfo *vsi;
4502 u64 last_vsi_end_off = 0, sum = 0;
4505 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4506 if (meta_left < meta_needed) {
4507 btf_verifier_log_basic(env, t,
4508 "meta_left:%u meta_needed:%u",
4509 meta_left, meta_needed);
4514 btf_verifier_log_type(env, t, "size == 0");
4518 if (btf_type_kflag(t)) {
4519 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4524 !btf_name_valid_section(env->btf, t->name_off)) {
4525 btf_verifier_log_type(env, t, "Invalid name");
4529 btf_verifier_log_type(env, t, NULL);
4531 for_each_vsi(i, t, vsi) {
4532 /* A var cannot be in type void */
4533 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4534 btf_verifier_log_vsi(env, t, vsi,
4539 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4540 btf_verifier_log_vsi(env, t, vsi,
4545 if (!vsi->size || vsi->size > t->size) {
4546 btf_verifier_log_vsi(env, t, vsi,
4551 last_vsi_end_off = vsi->offset + vsi->size;
4552 if (last_vsi_end_off > t->size) {
4553 btf_verifier_log_vsi(env, t, vsi,
4554 "Invalid offset+size");
4558 btf_verifier_log_vsi(env, t, vsi, NULL);
4562 if (t->size < sum) {
4563 btf_verifier_log_type(env, t, "Invalid btf_info size");
4570 static int btf_datasec_resolve(struct btf_verifier_env *env,
4571 const struct resolve_vertex *v)
4573 const struct btf_var_secinfo *vsi;
4574 struct btf *btf = env->btf;
4577 env->resolve_mode = RESOLVE_TBD;
4578 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4579 u32 var_type_id = vsi->type, type_id, type_size = 0;
4580 const struct btf_type *var_type = btf_type_by_id(env->btf,
4582 if (!var_type || !btf_type_is_var(var_type)) {
4583 btf_verifier_log_vsi(env, v->t, vsi,
4584 "Not a VAR kind member");
4588 if (!env_type_is_resolve_sink(env, var_type) &&
4589 !env_type_is_resolved(env, var_type_id)) {
4590 env_stack_set_next_member(env, i + 1);
4591 return env_stack_push(env, var_type, var_type_id);
4594 type_id = var_type->type;
4595 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4596 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4600 if (vsi->size < type_size) {
4601 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4606 env_stack_pop_resolved(env, 0, 0);
4610 static void btf_datasec_log(struct btf_verifier_env *env,
4611 const struct btf_type *t)
4613 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4616 static void btf_datasec_show(const struct btf *btf,
4617 const struct btf_type *t, u32 type_id,
4618 void *data, u8 bits_offset,
4619 struct btf_show *show)
4621 const struct btf_var_secinfo *vsi;
4622 const struct btf_type *var;
4625 if (!btf_show_start_type(show, t, type_id, data))
4628 btf_show_type_value(show, "section (\"%s\") = {",
4629 __btf_name_by_offset(btf, t->name_off));
4630 for_each_vsi(i, t, vsi) {
4631 var = btf_type_by_id(btf, vsi->type);
4633 btf_show(show, ",");
4634 btf_type_ops(var)->show(btf, var, vsi->type,
4635 data + vsi->offset, bits_offset, show);
4637 btf_show_end_type(show);
4640 static const struct btf_kind_operations datasec_ops = {
4641 .check_meta = btf_datasec_check_meta,
4642 .resolve = btf_datasec_resolve,
4643 .check_member = btf_df_check_member,
4644 .check_kflag_member = btf_df_check_kflag_member,
4645 .log_details = btf_datasec_log,
4646 .show = btf_datasec_show,
4649 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4650 const struct btf_type *t,
4653 if (btf_type_vlen(t)) {
4654 btf_verifier_log_type(env, t, "vlen != 0");
4658 if (btf_type_kflag(t)) {
4659 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4663 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4665 btf_verifier_log_type(env, t, "Invalid type_size");
4669 btf_verifier_log_type(env, t, NULL);
4674 static int btf_float_check_member(struct btf_verifier_env *env,
4675 const struct btf_type *struct_type,
4676 const struct btf_member *member,
4677 const struct btf_type *member_type)
4679 u64 start_offset_bytes;
4680 u64 end_offset_bytes;
4685 /* Different architectures have different alignment requirements, so
4686 * here we check only for the reasonable minimum. This way we ensure
4687 * that types after CO-RE can pass the kernel BTF verifier.
4689 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4690 align_bits = align_bytes * BITS_PER_BYTE;
4691 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4692 if (misalign_bits) {
4693 btf_verifier_log_member(env, struct_type, member,
4694 "Member is not properly aligned");
4698 start_offset_bytes = member->offset / BITS_PER_BYTE;
4699 end_offset_bytes = start_offset_bytes + member_type->size;
4700 if (end_offset_bytes > struct_type->size) {
4701 btf_verifier_log_member(env, struct_type, member,
4702 "Member exceeds struct_size");
4709 static void btf_float_log(struct btf_verifier_env *env,
4710 const struct btf_type *t)
4712 btf_verifier_log(env, "size=%u", t->size);
4715 static const struct btf_kind_operations float_ops = {
4716 .check_meta = btf_float_check_meta,
4717 .resolve = btf_df_resolve,
4718 .check_member = btf_float_check_member,
4719 .check_kflag_member = btf_generic_check_kflag_member,
4720 .log_details = btf_float_log,
4721 .show = btf_df_show,
4724 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4725 const struct btf_type *t,
4728 const struct btf_decl_tag *tag;
4729 u32 meta_needed = sizeof(*tag);
4733 if (meta_left < meta_needed) {
4734 btf_verifier_log_basic(env, t,
4735 "meta_left:%u meta_needed:%u",
4736 meta_left, meta_needed);
4740 value = btf_name_by_offset(env->btf, t->name_off);
4741 if (!value || !value[0]) {
4742 btf_verifier_log_type(env, t, "Invalid value");
4746 if (btf_type_vlen(t)) {
4747 btf_verifier_log_type(env, t, "vlen != 0");
4751 if (btf_type_kflag(t)) {
4752 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4756 component_idx = btf_type_decl_tag(t)->component_idx;
4757 if (component_idx < -1) {
4758 btf_verifier_log_type(env, t, "Invalid component_idx");
4762 btf_verifier_log_type(env, t, NULL);
4767 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4768 const struct resolve_vertex *v)
4770 const struct btf_type *next_type;
4771 const struct btf_type *t = v->t;
4772 u32 next_type_id = t->type;
4773 struct btf *btf = env->btf;
4777 next_type = btf_type_by_id(btf, next_type_id);
4778 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4779 btf_verifier_log_type(env, v->t, "Invalid type_id");
4783 if (!env_type_is_resolve_sink(env, next_type) &&
4784 !env_type_is_resolved(env, next_type_id))
4785 return env_stack_push(env, next_type, next_type_id);
4787 component_idx = btf_type_decl_tag(t)->component_idx;
4788 if (component_idx != -1) {
4789 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4790 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4794 if (btf_type_is_struct(next_type)) {
4795 vlen = btf_type_vlen(next_type);
4797 /* next_type should be a function */
4798 next_type = btf_type_by_id(btf, next_type->type);
4799 vlen = btf_type_vlen(next_type);
4802 if ((u32)component_idx >= vlen) {
4803 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4808 env_stack_pop_resolved(env, next_type_id, 0);
4813 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4815 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4816 btf_type_decl_tag(t)->component_idx);
4819 static const struct btf_kind_operations decl_tag_ops = {
4820 .check_meta = btf_decl_tag_check_meta,
4821 .resolve = btf_decl_tag_resolve,
4822 .check_member = btf_df_check_member,
4823 .check_kflag_member = btf_df_check_kflag_member,
4824 .log_details = btf_decl_tag_log,
4825 .show = btf_df_show,
4828 static int btf_func_proto_check(struct btf_verifier_env *env,
4829 const struct btf_type *t)
4831 const struct btf_type *ret_type;
4832 const struct btf_param *args;
4833 const struct btf *btf;
4838 args = (const struct btf_param *)(t + 1);
4839 nr_args = btf_type_vlen(t);
4841 /* Check func return type which could be "void" (t->type == 0) */
4843 u32 ret_type_id = t->type;
4845 ret_type = btf_type_by_id(btf, ret_type_id);
4847 btf_verifier_log_type(env, t, "Invalid return type");
4851 if (btf_type_is_resolve_source_only(ret_type)) {
4852 btf_verifier_log_type(env, t, "Invalid return type");
4856 if (btf_type_needs_resolve(ret_type) &&
4857 !env_type_is_resolved(env, ret_type_id)) {
4858 err = btf_resolve(env, ret_type, ret_type_id);
4863 /* Ensure the return type is a type that has a size */
4864 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4865 btf_verifier_log_type(env, t, "Invalid return type");
4873 /* Last func arg type_id could be 0 if it is a vararg */
4874 if (!args[nr_args - 1].type) {
4875 if (args[nr_args - 1].name_off) {
4876 btf_verifier_log_type(env, t, "Invalid arg#%u",
4883 for (i = 0; i < nr_args; i++) {
4884 const struct btf_type *arg_type;
4887 arg_type_id = args[i].type;
4888 arg_type = btf_type_by_id(btf, arg_type_id);
4890 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4894 if (btf_type_is_resolve_source_only(arg_type)) {
4895 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4899 if (args[i].name_off &&
4900 (!btf_name_offset_valid(btf, args[i].name_off) ||
4901 !btf_name_valid_identifier(btf, args[i].name_off))) {
4902 btf_verifier_log_type(env, t,
4903 "Invalid arg#%u", i + 1);
4907 if (btf_type_needs_resolve(arg_type) &&
4908 !env_type_is_resolved(env, arg_type_id)) {
4909 err = btf_resolve(env, arg_type, arg_type_id);
4914 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4915 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4923 static int btf_func_check(struct btf_verifier_env *env,
4924 const struct btf_type *t)
4926 const struct btf_type *proto_type;
4927 const struct btf_param *args;
4928 const struct btf *btf;
4932 proto_type = btf_type_by_id(btf, t->type);
4934 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4935 btf_verifier_log_type(env, t, "Invalid type_id");
4939 args = (const struct btf_param *)(proto_type + 1);
4940 nr_args = btf_type_vlen(proto_type);
4941 for (i = 0; i < nr_args; i++) {
4942 if (!args[i].name_off && args[i].type) {
4943 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4951 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4952 [BTF_KIND_INT] = &int_ops,
4953 [BTF_KIND_PTR] = &ptr_ops,
4954 [BTF_KIND_ARRAY] = &array_ops,
4955 [BTF_KIND_STRUCT] = &struct_ops,
4956 [BTF_KIND_UNION] = &struct_ops,
4957 [BTF_KIND_ENUM] = &enum_ops,
4958 [BTF_KIND_FWD] = &fwd_ops,
4959 [BTF_KIND_TYPEDEF] = &modifier_ops,
4960 [BTF_KIND_VOLATILE] = &modifier_ops,
4961 [BTF_KIND_CONST] = &modifier_ops,
4962 [BTF_KIND_RESTRICT] = &modifier_ops,
4963 [BTF_KIND_FUNC] = &func_ops,
4964 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4965 [BTF_KIND_VAR] = &var_ops,
4966 [BTF_KIND_DATASEC] = &datasec_ops,
4967 [BTF_KIND_FLOAT] = &float_ops,
4968 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
4969 [BTF_KIND_TYPE_TAG] = &modifier_ops,
4970 [BTF_KIND_ENUM64] = &enum64_ops,
4973 static s32 btf_check_meta(struct btf_verifier_env *env,
4974 const struct btf_type *t,
4977 u32 saved_meta_left = meta_left;
4980 if (meta_left < sizeof(*t)) {
4981 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4982 env->log_type_id, meta_left, sizeof(*t));
4985 meta_left -= sizeof(*t);
4987 if (t->info & ~BTF_INFO_MASK) {
4988 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4989 env->log_type_id, t->info);
4993 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4994 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4995 btf_verifier_log(env, "[%u] Invalid kind:%u",
4996 env->log_type_id, BTF_INFO_KIND(t->info));
5000 if (!btf_name_offset_valid(env->btf, t->name_off)) {
5001 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5002 env->log_type_id, t->name_off);
5006 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5007 if (var_meta_size < 0)
5008 return var_meta_size;
5010 meta_left -= var_meta_size;
5012 return saved_meta_left - meta_left;
5015 static int btf_check_all_metas(struct btf_verifier_env *env)
5017 struct btf *btf = env->btf;
5018 struct btf_header *hdr;
5022 cur = btf->nohdr_data + hdr->type_off;
5023 end = cur + hdr->type_len;
5025 env->log_type_id = btf->base_btf ? btf->start_id : 1;
5027 struct btf_type *t = cur;
5030 meta_size = btf_check_meta(env, t, end - cur);
5034 btf_add_type(env, t);
5042 static bool btf_resolve_valid(struct btf_verifier_env *env,
5043 const struct btf_type *t,
5046 struct btf *btf = env->btf;
5048 if (!env_type_is_resolved(env, type_id))
5051 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5052 return !btf_resolved_type_id(btf, type_id) &&
5053 !btf_resolved_type_size(btf, type_id);
5055 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5056 return btf_resolved_type_id(btf, type_id) &&
5057 !btf_resolved_type_size(btf, type_id);
5059 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5060 btf_type_is_var(t)) {
5061 t = btf_type_id_resolve(btf, &type_id);
5063 !btf_type_is_modifier(t) &&
5064 !btf_type_is_var(t) &&
5065 !btf_type_is_datasec(t);
5068 if (btf_type_is_array(t)) {
5069 const struct btf_array *array = btf_type_array(t);
5070 const struct btf_type *elem_type;
5071 u32 elem_type_id = array->type;
5074 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5075 return elem_type && !btf_type_is_modifier(elem_type) &&
5076 (array->nelems * elem_size ==
5077 btf_resolved_type_size(btf, type_id));
5083 static int btf_resolve(struct btf_verifier_env *env,
5084 const struct btf_type *t, u32 type_id)
5086 u32 save_log_type_id = env->log_type_id;
5087 const struct resolve_vertex *v;
5090 env->resolve_mode = RESOLVE_TBD;
5091 env_stack_push(env, t, type_id);
5092 while (!err && (v = env_stack_peak(env))) {
5093 env->log_type_id = v->type_id;
5094 err = btf_type_ops(v->t)->resolve(env, v);
5097 env->log_type_id = type_id;
5098 if (err == -E2BIG) {
5099 btf_verifier_log_type(env, t,
5100 "Exceeded max resolving depth:%u",
5102 } else if (err == -EEXIST) {
5103 btf_verifier_log_type(env, t, "Loop detected");
5106 /* Final sanity check */
5107 if (!err && !btf_resolve_valid(env, t, type_id)) {
5108 btf_verifier_log_type(env, t, "Invalid resolve state");
5112 env->log_type_id = save_log_type_id;
5116 static int btf_check_all_types(struct btf_verifier_env *env)
5118 struct btf *btf = env->btf;
5119 const struct btf_type *t;
5123 err = env_resolve_init(env);
5128 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5129 type_id = btf->start_id + i;
5130 t = btf_type_by_id(btf, type_id);
5132 env->log_type_id = type_id;
5133 if (btf_type_needs_resolve(t) &&
5134 !env_type_is_resolved(env, type_id)) {
5135 err = btf_resolve(env, t, type_id);
5140 if (btf_type_is_func_proto(t)) {
5141 err = btf_func_proto_check(env, t);
5150 static int btf_parse_type_sec(struct btf_verifier_env *env)
5152 const struct btf_header *hdr = &env->btf->hdr;
5155 /* Type section must align to 4 bytes */
5156 if (hdr->type_off & (sizeof(u32) - 1)) {
5157 btf_verifier_log(env, "Unaligned type_off");
5161 if (!env->btf->base_btf && !hdr->type_len) {
5162 btf_verifier_log(env, "No type found");
5166 err = btf_check_all_metas(env);
5170 return btf_check_all_types(env);
5173 static int btf_parse_str_sec(struct btf_verifier_env *env)
5175 const struct btf_header *hdr;
5176 struct btf *btf = env->btf;
5177 const char *start, *end;
5180 start = btf->nohdr_data + hdr->str_off;
5181 end = start + hdr->str_len;
5183 if (end != btf->data + btf->data_size) {
5184 btf_verifier_log(env, "String section is not at the end");
5188 btf->strings = start;
5190 if (btf->base_btf && !hdr->str_len)
5192 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5193 btf_verifier_log(env, "Invalid string section");
5196 if (!btf->base_btf && start[0]) {
5197 btf_verifier_log(env, "Invalid string section");
5204 static const size_t btf_sec_info_offset[] = {
5205 offsetof(struct btf_header, type_off),
5206 offsetof(struct btf_header, str_off),
5209 static int btf_sec_info_cmp(const void *a, const void *b)
5211 const struct btf_sec_info *x = a;
5212 const struct btf_sec_info *y = b;
5214 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5217 static int btf_check_sec_info(struct btf_verifier_env *env,
5220 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5221 u32 total, expected_total, i;
5222 const struct btf_header *hdr;
5223 const struct btf *btf;
5228 /* Populate the secs from hdr */
5229 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5230 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5231 btf_sec_info_offset[i]);
5233 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5234 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5236 /* Check for gaps and overlap among sections */
5238 expected_total = btf_data_size - hdr->hdr_len;
5239 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5240 if (expected_total < secs[i].off) {
5241 btf_verifier_log(env, "Invalid section offset");
5244 if (total < secs[i].off) {
5246 btf_verifier_log(env, "Unsupported section found");
5249 if (total > secs[i].off) {
5250 btf_verifier_log(env, "Section overlap found");
5253 if (expected_total - total < secs[i].len) {
5254 btf_verifier_log(env,
5255 "Total section length too long");
5258 total += secs[i].len;
5261 /* There is data other than hdr and known sections */
5262 if (expected_total != total) {
5263 btf_verifier_log(env, "Unsupported section found");
5270 static int btf_parse_hdr(struct btf_verifier_env *env)
5272 u32 hdr_len, hdr_copy, btf_data_size;
5273 const struct btf_header *hdr;
5277 btf_data_size = btf->data_size;
5279 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5280 btf_verifier_log(env, "hdr_len not found");
5285 hdr_len = hdr->hdr_len;
5286 if (btf_data_size < hdr_len) {
5287 btf_verifier_log(env, "btf_header not found");
5291 /* Ensure the unsupported header fields are zero */
5292 if (hdr_len > sizeof(btf->hdr)) {
5293 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5294 u8 *end = btf->data + hdr_len;
5296 for (; expected_zero < end; expected_zero++) {
5297 if (*expected_zero) {
5298 btf_verifier_log(env, "Unsupported btf_header");
5304 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5305 memcpy(&btf->hdr, btf->data, hdr_copy);
5309 btf_verifier_log_hdr(env, btf_data_size);
5311 if (hdr->magic != BTF_MAGIC) {
5312 btf_verifier_log(env, "Invalid magic");
5316 if (hdr->version != BTF_VERSION) {
5317 btf_verifier_log(env, "Unsupported version");
5322 btf_verifier_log(env, "Unsupported flags");
5326 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5327 btf_verifier_log(env, "No data");
5331 return btf_check_sec_info(env, btf_data_size);
5334 static const char *alloc_obj_fields[] = {
5342 static struct btf_struct_metas *
5343 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5346 struct btf_id_set set;
5349 u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5352 struct btf_struct_metas *tab = NULL;
5355 BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5356 BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5358 memset(&aof, 0, sizeof(aof));
5359 for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5360 /* Try to find whether this special type exists in user BTF, and
5361 * if so remember its ID so we can easily find it among members
5362 * of structs that we iterate in the next loop.
5364 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5367 aof.set.ids[aof.set.cnt++] = id;
5372 sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5374 n = btf_nr_types(btf);
5375 for (i = 1; i < n; i++) {
5376 struct btf_struct_metas *new_tab;
5377 const struct btf_member *member;
5378 struct btf_field_offs *foffs;
5379 struct btf_struct_meta *type;
5380 struct btf_record *record;
5381 const struct btf_type *t;
5384 t = btf_type_by_id(btf, i);
5389 if (!__btf_type_is_struct(t))
5394 for_each_member(j, t, member) {
5395 if (btf_id_set_contains(&aof.set, member->type))
5400 tab_cnt = tab ? tab->cnt : 0;
5401 new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5402 GFP_KERNEL | __GFP_NOWARN);
5411 type = &tab->types[tab->cnt];
5413 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5414 BPF_RB_ROOT | BPF_RB_NODE, t->size);
5415 /* The record cannot be unset, treat it as an error if so */
5416 if (IS_ERR_OR_NULL(record)) {
5417 ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5420 foffs = btf_parse_field_offs(record);
5421 /* We need the field_offs to be valid for a valid record,
5422 * either both should be set or both should be unset.
5424 if (IS_ERR_OR_NULL(foffs)) {
5425 btf_record_free(record);
5429 type->record = record;
5430 type->field_offs = foffs;
5435 btf_struct_metas_free(tab);
5436 return ERR_PTR(ret);
5439 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5441 struct btf_struct_metas *tab;
5443 BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5444 tab = btf->struct_meta_tab;
5447 return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5450 static int btf_check_type_tags(struct btf_verifier_env *env,
5451 struct btf *btf, int start_id)
5453 int i, n, good_id = start_id - 1;
5456 n = btf_nr_types(btf);
5457 for (i = start_id; i < n; i++) {
5458 const struct btf_type *t;
5459 int chain_limit = 32;
5462 t = btf_type_by_id(btf, i);
5465 if (!btf_type_is_modifier(t))
5470 in_tags = btf_type_is_type_tag(t);
5471 while (btf_type_is_modifier(t)) {
5472 if (!chain_limit--) {
5473 btf_verifier_log(env, "Max chain length or cycle detected");
5476 if (btf_type_is_type_tag(t)) {
5478 btf_verifier_log(env, "Type tags don't precede modifiers");
5481 } else if (in_tags) {
5484 if (cur_id <= good_id)
5486 /* Move to next type */
5488 t = btf_type_by_id(btf, cur_id);
5497 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
5498 u32 log_level, char __user *log_ubuf, u32 log_size)
5500 struct btf_struct_metas *struct_meta_tab;
5501 struct btf_verifier_env *env = NULL;
5502 struct bpf_verifier_log *log;
5503 struct btf *btf = NULL;
5507 if (btf_data_size > BTF_MAX_SIZE)
5508 return ERR_PTR(-E2BIG);
5510 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5512 return ERR_PTR(-ENOMEM);
5515 if (log_level || log_ubuf || log_size) {
5516 /* user requested verbose verifier output
5517 * and supplied buffer to store the verification trace
5519 log->level = log_level;
5520 log->ubuf = log_ubuf;
5521 log->len_total = log_size;
5523 /* log attributes have to be sane */
5524 if (!bpf_verifier_log_attr_valid(log)) {
5530 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5537 data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
5544 btf->data_size = btf_data_size;
5546 if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
5551 err = btf_parse_hdr(env);
5555 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5557 err = btf_parse_str_sec(env);
5561 err = btf_parse_type_sec(env);
5565 err = btf_check_type_tags(env, btf, 1);
5569 struct_meta_tab = btf_parse_struct_metas(log, btf);
5570 if (IS_ERR(struct_meta_tab)) {
5571 err = PTR_ERR(struct_meta_tab);
5574 btf->struct_meta_tab = struct_meta_tab;
5576 if (struct_meta_tab) {
5579 for (i = 0; i < struct_meta_tab->cnt; i++) {
5580 err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5586 if (log->level && bpf_verifier_log_full(log)) {
5591 btf_verifier_env_free(env);
5592 refcount_set(&btf->refcnt, 1);
5596 btf_free_struct_meta_tab(btf);
5598 btf_verifier_env_free(env);
5601 return ERR_PTR(err);
5604 extern char __weak __start_BTF[];
5605 extern char __weak __stop_BTF[];
5606 extern struct btf *btf_vmlinux;
5608 #define BPF_MAP_TYPE(_id, _ops)
5609 #define BPF_LINK_TYPE(_id, _name)
5611 struct bpf_ctx_convert {
5612 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5613 prog_ctx_type _id##_prog; \
5614 kern_ctx_type _id##_kern;
5615 #include <linux/bpf_types.h>
5616 #undef BPF_PROG_TYPE
5618 /* 't' is written once under lock. Read many times. */
5619 const struct btf_type *t;
5622 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5624 #include <linux/bpf_types.h>
5625 #undef BPF_PROG_TYPE
5626 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5628 static u8 bpf_ctx_convert_map[] = {
5629 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5630 [_id] = __ctx_convert##_id,
5631 #include <linux/bpf_types.h>
5632 #undef BPF_PROG_TYPE
5633 0, /* avoid empty array */
5636 #undef BPF_LINK_TYPE
5638 const struct btf_member *
5639 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5640 const struct btf_type *t, enum bpf_prog_type prog_type,
5643 const struct btf_type *conv_struct;
5644 const struct btf_type *ctx_struct;
5645 const struct btf_member *ctx_type;
5646 const char *tname, *ctx_tname;
5648 conv_struct = bpf_ctx_convert.t;
5650 bpf_log(log, "btf_vmlinux is malformed\n");
5653 t = btf_type_by_id(btf, t->type);
5654 while (btf_type_is_modifier(t))
5655 t = btf_type_by_id(btf, t->type);
5656 if (!btf_type_is_struct(t)) {
5657 /* Only pointer to struct is supported for now.
5658 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5659 * is not supported yet.
5660 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5664 tname = btf_name_by_offset(btf, t->name_off);
5666 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5669 /* prog_type is valid bpf program type. No need for bounds check. */
5670 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5671 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5672 * Like 'struct __sk_buff'
5674 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5676 /* should not happen */
5679 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5681 /* should not happen */
5682 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5685 /* only compare that prog's ctx type name is the same as
5686 * kernel expects. No need to compare field by field.
5687 * It's ok for bpf prog to do:
5688 * struct __sk_buff {};
5689 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5690 * { // no fields of skb are ever used }
5692 if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5694 if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5696 if (strcmp(ctx_tname, tname)) {
5697 /* bpf_user_pt_regs_t is a typedef, so resolve it to
5698 * underlying struct and check name again
5700 if (!btf_type_is_modifier(ctx_struct))
5702 while (btf_type_is_modifier(ctx_struct))
5703 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_struct->type);
5709 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5711 const struct btf_type *t,
5712 enum bpf_prog_type prog_type,
5715 const struct btf_member *prog_ctx_type, *kern_ctx_type;
5717 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5720 kern_ctx_type = prog_ctx_type + 1;
5721 return kern_ctx_type->type;
5724 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5726 const struct btf_member *kctx_member;
5727 const struct btf_type *conv_struct;
5728 const struct btf_type *kctx_type;
5731 conv_struct = bpf_ctx_convert.t;
5732 /* get member for kernel ctx type */
5733 kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5734 kctx_type_id = kctx_member->type;
5735 kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5736 if (!btf_type_is_struct(kctx_type)) {
5737 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5741 return kctx_type_id;
5744 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5745 BTF_ID(struct, bpf_ctx_convert)
5747 struct btf *btf_parse_vmlinux(void)
5749 struct btf_verifier_env *env = NULL;
5750 struct bpf_verifier_log *log;
5751 struct btf *btf = NULL;
5754 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5756 return ERR_PTR(-ENOMEM);
5759 log->level = BPF_LOG_KERNEL;
5761 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5768 btf->data = __start_BTF;
5769 btf->data_size = __stop_BTF - __start_BTF;
5770 btf->kernel_btf = true;
5771 snprintf(btf->name, sizeof(btf->name), "vmlinux");
5773 err = btf_parse_hdr(env);
5777 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5779 err = btf_parse_str_sec(env);
5783 err = btf_check_all_metas(env);
5787 err = btf_check_type_tags(env, btf, 1);
5791 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
5792 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5794 bpf_struct_ops_init(btf, log);
5796 refcount_set(&btf->refcnt, 1);
5798 err = btf_alloc_id(btf);
5802 btf_verifier_env_free(env);
5806 btf_verifier_env_free(env);
5811 return ERR_PTR(err);
5814 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5816 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5818 struct btf_verifier_env *env = NULL;
5819 struct bpf_verifier_log *log;
5820 struct btf *btf = NULL, *base_btf;
5823 base_btf = bpf_get_btf_vmlinux();
5824 if (IS_ERR(base_btf))
5827 return ERR_PTR(-EINVAL);
5829 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5831 return ERR_PTR(-ENOMEM);
5834 log->level = BPF_LOG_KERNEL;
5836 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5843 btf->base_btf = base_btf;
5844 btf->start_id = base_btf->nr_types;
5845 btf->start_str_off = base_btf->hdr.str_len;
5846 btf->kernel_btf = true;
5847 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5849 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5854 memcpy(btf->data, data, data_size);
5855 btf->data_size = data_size;
5857 err = btf_parse_hdr(env);
5861 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5863 err = btf_parse_str_sec(env);
5867 err = btf_check_all_metas(env);
5871 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5875 btf_verifier_env_free(env);
5876 refcount_set(&btf->refcnt, 1);
5880 btf_verifier_env_free(env);
5886 return ERR_PTR(err);
5889 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5891 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5893 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5896 return tgt_prog->aux->btf;
5898 return prog->aux->attach_btf;
5901 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5903 /* t comes in already as a pointer */
5904 t = btf_type_by_id(btf, t->type);
5907 if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5908 t = btf_type_by_id(btf, t->type);
5910 return btf_type_is_int(t);
5913 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5916 const struct btf_param *args;
5917 const struct btf_type *t;
5918 u32 offset = 0, nr_args;
5924 nr_args = btf_type_vlen(func_proto);
5925 args = (const struct btf_param *)(func_proto + 1);
5926 for (i = 0; i < nr_args; i++) {
5927 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5928 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5933 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5934 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5941 static bool prog_args_trusted(const struct bpf_prog *prog)
5943 enum bpf_attach_type atype = prog->expected_attach_type;
5945 switch (prog->type) {
5946 case BPF_PROG_TYPE_TRACING:
5947 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
5948 case BPF_PROG_TYPE_LSM:
5949 return bpf_lsm_is_trusted(prog);
5950 case BPF_PROG_TYPE_STRUCT_OPS:
5957 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5958 const struct bpf_prog *prog,
5959 struct bpf_insn_access_aux *info)
5961 const struct btf_type *t = prog->aux->attach_func_proto;
5962 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5963 struct btf *btf = bpf_prog_get_target_btf(prog);
5964 const char *tname = prog->aux->attach_func_name;
5965 struct bpf_verifier_log *log = info->log;
5966 const struct btf_param *args;
5967 const char *tag_value;
5972 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5976 arg = get_ctx_arg_idx(btf, t, off);
5977 args = (const struct btf_param *)(t + 1);
5978 /* if (t == NULL) Fall back to default BPF prog with
5979 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5981 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5982 if (prog->aux->attach_btf_trace) {
5983 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5988 if (arg > nr_args) {
5989 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5994 if (arg == nr_args) {
5995 switch (prog->expected_attach_type) {
5996 case BPF_LSM_CGROUP:
5998 case BPF_TRACE_FEXIT:
5999 /* When LSM programs are attached to void LSM hooks
6000 * they use FEXIT trampolines and when attached to
6001 * int LSM hooks, they use MODIFY_RETURN trampolines.
6003 * While the LSM programs are BPF_MODIFY_RETURN-like
6006 * if (ret_type != 'int')
6009 * is _not_ done here. This is still safe as LSM hooks
6010 * have only void and int return types.
6014 t = btf_type_by_id(btf, t->type);
6016 case BPF_MODIFY_RETURN:
6017 /* For now the BPF_MODIFY_RETURN can only be attached to
6018 * functions that return an int.
6023 t = btf_type_skip_modifiers(btf, t->type, NULL);
6024 if (!btf_type_is_small_int(t)) {
6026 "ret type %s not allowed for fmod_ret\n",
6032 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6038 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6040 t = btf_type_by_id(btf, args[arg].type);
6043 /* skip modifiers */
6044 while (btf_type_is_modifier(t))
6045 t = btf_type_by_id(btf, t->type);
6046 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6047 /* accessing a scalar */
6049 if (!btf_type_is_ptr(t)) {
6051 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6053 __btf_name_by_offset(btf, t->name_off),
6058 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6059 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6060 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6063 type = base_type(ctx_arg_info->reg_type);
6064 flag = type_flag(ctx_arg_info->reg_type);
6065 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6066 (flag & PTR_MAYBE_NULL)) {
6067 info->reg_type = ctx_arg_info->reg_type;
6073 /* This is a pointer to void.
6074 * It is the same as scalar from the verifier safety pov.
6075 * No further pointer walking is allowed.
6079 if (is_int_ptr(btf, t))
6082 /* this is a pointer to another type */
6083 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6084 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6086 if (ctx_arg_info->offset == off) {
6087 if (!ctx_arg_info->btf_id) {
6088 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6092 info->reg_type = ctx_arg_info->reg_type;
6093 info->btf = btf_vmlinux;
6094 info->btf_id = ctx_arg_info->btf_id;
6099 info->reg_type = PTR_TO_BTF_ID;
6100 if (prog_args_trusted(prog))
6101 info->reg_type |= PTR_TRUSTED;
6104 enum bpf_prog_type tgt_type;
6106 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6107 tgt_type = tgt_prog->aux->saved_dst_prog_type;
6109 tgt_type = tgt_prog->type;
6111 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6113 info->btf = btf_vmlinux;
6122 info->btf_id = t->type;
6123 t = btf_type_by_id(btf, t->type);
6125 if (btf_type_is_type_tag(t)) {
6126 tag_value = __btf_name_by_offset(btf, t->name_off);
6127 if (strcmp(tag_value, "user") == 0)
6128 info->reg_type |= MEM_USER;
6129 if (strcmp(tag_value, "percpu") == 0)
6130 info->reg_type |= MEM_PERCPU;
6133 /* skip modifiers */
6134 while (btf_type_is_modifier(t)) {
6135 info->btf_id = t->type;
6136 t = btf_type_by_id(btf, t->type);
6138 if (!btf_type_is_struct(t)) {
6140 "func '%s' arg%d type %s is not a struct\n",
6141 tname, arg, btf_type_str(t));
6144 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6145 tname, arg, info->btf_id, btf_type_str(t),
6146 __btf_name_by_offset(btf, t->name_off));
6150 enum bpf_struct_walk_result {
6157 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6158 const struct btf_type *t, int off, int size,
6159 u32 *next_btf_id, enum bpf_type_flag *flag)
6161 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6162 const struct btf_type *mtype, *elem_type = NULL;
6163 const struct btf_member *member;
6164 const char *tname, *mname, *tag_value;
6165 u32 vlen, elem_id, mid;
6169 tname = __btf_name_by_offset(btf, t->name_off);
6170 if (!btf_type_is_struct(t)) {
6171 bpf_log(log, "Type '%s' is not a struct\n", tname);
6175 vlen = btf_type_vlen(t);
6176 if (off + size > t->size) {
6177 /* If the last element is a variable size array, we may
6178 * need to relax the rule.
6180 struct btf_array *array_elem;
6185 member = btf_type_member(t) + vlen - 1;
6186 mtype = btf_type_skip_modifiers(btf, member->type,
6188 if (!btf_type_is_array(mtype))
6191 array_elem = (struct btf_array *)(mtype + 1);
6192 if (array_elem->nelems != 0)
6195 moff = __btf_member_bit_offset(t, member) / 8;
6199 /* Only allow structure for now, can be relaxed for
6200 * other types later.
6202 t = btf_type_skip_modifiers(btf, array_elem->type,
6204 if (!btf_type_is_struct(t))
6207 off = (off - moff) % t->size;
6211 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6216 for_each_member(i, t, member) {
6217 /* offset of the field in bytes */
6218 moff = __btf_member_bit_offset(t, member) / 8;
6219 if (off + size <= moff)
6220 /* won't find anything, field is already too far */
6223 if (__btf_member_bitfield_size(t, member)) {
6224 u32 end_bit = __btf_member_bit_offset(t, member) +
6225 __btf_member_bitfield_size(t, member);
6227 /* off <= moff instead of off == moff because clang
6228 * does not generate a BTF member for anonymous
6229 * bitfield like the ":16" here:
6236 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6239 /* off may be accessing a following member
6243 * Doing partial access at either end of this
6244 * bitfield. Continue on this case also to
6245 * treat it as not accessing this bitfield
6246 * and eventually error out as field not
6247 * found to keep it simple.
6248 * It could be relaxed if there was a legit
6249 * partial access case later.
6254 /* In case of "off" is pointing to holes of a struct */
6258 /* type of the field */
6260 mtype = btf_type_by_id(btf, member->type);
6261 mname = __btf_name_by_offset(btf, member->name_off);
6263 mtype = __btf_resolve_size(btf, mtype, &msize,
6264 &elem_type, &elem_id, &total_nelems,
6266 if (IS_ERR(mtype)) {
6267 bpf_log(log, "field %s doesn't have size\n", mname);
6271 mtrue_end = moff + msize;
6272 if (off >= mtrue_end)
6273 /* no overlap with member, keep iterating */
6276 if (btf_type_is_array(mtype)) {
6279 /* __btf_resolve_size() above helps to
6280 * linearize a multi-dimensional array.
6282 * The logic here is treating an array
6283 * in a struct as the following way:
6286 * struct inner array[2][2];
6292 * struct inner array_elem0;
6293 * struct inner array_elem1;
6294 * struct inner array_elem2;
6295 * struct inner array_elem3;
6298 * When accessing outer->array[1][0], it moves
6299 * moff to "array_elem2", set mtype to
6300 * "struct inner", and msize also becomes
6301 * sizeof(struct inner). Then most of the
6302 * remaining logic will fall through without
6303 * caring the current member is an array or
6306 * Unlike mtype/msize/moff, mtrue_end does not
6307 * change. The naming difference ("_true") tells
6308 * that it is not always corresponding to
6309 * the current mtype/msize/moff.
6310 * It is the true end of the current
6311 * member (i.e. array in this case). That
6312 * will allow an int array to be accessed like
6314 * i.e. allow access beyond the size of
6315 * the array's element as long as it is
6316 * within the mtrue_end boundary.
6319 /* skip empty array */
6320 if (moff == mtrue_end)
6323 msize /= total_nelems;
6324 elem_idx = (off - moff) / msize;
6325 moff += elem_idx * msize;
6330 /* the 'off' we're looking for is either equal to start
6331 * of this field or inside of this struct
6333 if (btf_type_is_struct(mtype)) {
6334 if (BTF_INFO_KIND(mtype->info) == BTF_KIND_UNION &&
6335 btf_type_vlen(mtype) != 1)
6337 * walking unions yields untrusted pointers
6338 * with exception of __bpf_md_ptr and other
6339 * unions with a single member
6341 *flag |= PTR_UNTRUSTED;
6343 /* our field must be inside that union or struct */
6346 /* return if the offset matches the member offset */
6352 /* adjust offset we're looking for */
6357 if (btf_type_is_ptr(mtype)) {
6358 const struct btf_type *stype, *t;
6359 enum bpf_type_flag tmp_flag = 0;
6362 if (msize != size || off != moff) {
6364 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6365 mname, moff, tname, off, size);
6369 /* check type tag */
6370 t = btf_type_by_id(btf, mtype->type);
6371 if (btf_type_is_type_tag(t)) {
6372 tag_value = __btf_name_by_offset(btf, t->name_off);
6373 /* check __user tag */
6374 if (strcmp(tag_value, "user") == 0)
6375 tmp_flag = MEM_USER;
6376 /* check __percpu tag */
6377 if (strcmp(tag_value, "percpu") == 0)
6378 tmp_flag = MEM_PERCPU;
6379 /* check __rcu tag */
6380 if (strcmp(tag_value, "rcu") == 0)
6384 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6385 if (btf_type_is_struct(stype)) {
6392 /* Allow more flexible access within an int as long as
6393 * it is within mtrue_end.
6394 * Since mtrue_end could be the end of an array,
6395 * that also allows using an array of int as a scratch
6396 * space. e.g. skb->cb[].
6398 if (off + size > mtrue_end) {
6400 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6401 mname, mtrue_end, tname, off, size);
6407 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6411 int btf_struct_access(struct bpf_verifier_log *log,
6412 const struct bpf_reg_state *reg,
6413 int off, int size, enum bpf_access_type atype __maybe_unused,
6414 u32 *next_btf_id, enum bpf_type_flag *flag)
6416 const struct btf *btf = reg->btf;
6417 enum bpf_type_flag tmp_flag = 0;
6418 const struct btf_type *t;
6419 u32 id = reg->btf_id;
6422 while (type_is_alloc(reg->type)) {
6423 struct btf_struct_meta *meta;
6424 struct btf_record *rec;
6427 meta = btf_find_struct_meta(btf, id);
6431 for (i = 0; i < rec->cnt; i++) {
6432 struct btf_field *field = &rec->fields[i];
6433 u32 offset = field->offset;
6434 if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6436 "direct access to %s is disallowed\n",
6437 btf_field_type_name(field->type));
6444 t = btf_type_by_id(btf, id);
6446 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
6450 /* For local types, the destination register cannot
6451 * become a pointer again.
6453 if (type_is_alloc(reg->type))
6454 return SCALAR_VALUE;
6455 /* If we found the pointer or scalar on t+off,
6460 return PTR_TO_BTF_ID;
6462 return SCALAR_VALUE;
6464 /* We found nested struct, so continue the search
6465 * by diving in it. At this point the offset is
6466 * aligned with the new type, so set it to 0.
6468 t = btf_type_by_id(btf, id);
6472 /* It's either error or unknown return value..
6475 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6484 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6485 * the same. Trivial ID check is not enough due to module BTFs, because we can
6486 * end up with two different module BTFs, but IDs point to the common type in
6489 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6490 const struct btf *btf2, u32 id2)
6496 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6499 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6500 const struct btf *btf, u32 id, int off,
6501 const struct btf *need_btf, u32 need_type_id,
6504 const struct btf_type *type;
6505 enum bpf_type_flag flag;
6508 /* Are we already done? */
6509 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6511 /* In case of strict type match, we do not walk struct, the top level
6512 * type match must succeed. When strict is true, off should have already
6518 type = btf_type_by_id(btf, id);
6521 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
6522 if (err != WALK_STRUCT)
6525 /* We found nested struct object. If it matches
6526 * the requested ID, we're done. Otherwise let's
6527 * continue the search with offset 0 in the new
6530 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6538 static int __get_type_size(struct btf *btf, u32 btf_id,
6539 const struct btf_type **ret_type)
6541 const struct btf_type *t;
6543 *ret_type = btf_type_by_id(btf, 0);
6547 t = btf_type_by_id(btf, btf_id);
6548 while (t && btf_type_is_modifier(t))
6549 t = btf_type_by_id(btf, t->type);
6553 if (btf_type_is_ptr(t))
6554 /* kernel size of pointer. Not BPF's size of pointer*/
6555 return sizeof(void *);
6556 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6561 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6565 if (__btf_type_is_struct(t))
6566 flags |= BTF_FMODEL_STRUCT_ARG;
6567 if (btf_type_is_signed_int(t))
6568 flags |= BTF_FMODEL_SIGNED_ARG;
6573 int btf_distill_func_proto(struct bpf_verifier_log *log,
6575 const struct btf_type *func,
6577 struct btf_func_model *m)
6579 const struct btf_param *args;
6580 const struct btf_type *t;
6585 /* BTF function prototype doesn't match the verifier types.
6586 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6588 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6590 m->arg_flags[i] = 0;
6594 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6597 args = (const struct btf_param *)(func + 1);
6598 nargs = btf_type_vlen(func);
6599 if (nargs > MAX_BPF_FUNC_ARGS) {
6601 "The function %s has %d arguments. Too many.\n",
6605 ret = __get_type_size(btf, func->type, &t);
6606 if (ret < 0 || __btf_type_is_struct(t)) {
6608 "The function %s return type %s is unsupported.\n",
6609 tname, btf_type_str(t));
6613 m->ret_flags = __get_type_fmodel_flags(t);
6615 for (i = 0; i < nargs; i++) {
6616 if (i == nargs - 1 && args[i].type == 0) {
6618 "The function %s with variable args is unsupported.\n",
6622 ret = __get_type_size(btf, args[i].type, &t);
6624 /* No support of struct argument size greater than 16 bytes */
6625 if (ret < 0 || ret > 16) {
6627 "The function %s arg%d type %s is unsupported.\n",
6628 tname, i, btf_type_str(t));
6633 "The function %s has malformed void argument.\n",
6637 m->arg_size[i] = ret;
6638 m->arg_flags[i] = __get_type_fmodel_flags(t);
6644 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6645 * t1 points to BTF_KIND_FUNC in btf1
6646 * t2 points to BTF_KIND_FUNC in btf2
6648 * EINVAL - function prototype mismatch
6649 * EFAULT - verifier bug
6650 * 0 - 99% match. The last 1% is validated by the verifier.
6652 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6653 struct btf *btf1, const struct btf_type *t1,
6654 struct btf *btf2, const struct btf_type *t2)
6656 const struct btf_param *args1, *args2;
6657 const char *fn1, *fn2, *s1, *s2;
6658 u32 nargs1, nargs2, i;
6660 fn1 = btf_name_by_offset(btf1, t1->name_off);
6661 fn2 = btf_name_by_offset(btf2, t2->name_off);
6663 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6664 bpf_log(log, "%s() is not a global function\n", fn1);
6667 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6668 bpf_log(log, "%s() is not a global function\n", fn2);
6672 t1 = btf_type_by_id(btf1, t1->type);
6673 if (!t1 || !btf_type_is_func_proto(t1))
6675 t2 = btf_type_by_id(btf2, t2->type);
6676 if (!t2 || !btf_type_is_func_proto(t2))
6679 args1 = (const struct btf_param *)(t1 + 1);
6680 nargs1 = btf_type_vlen(t1);
6681 args2 = (const struct btf_param *)(t2 + 1);
6682 nargs2 = btf_type_vlen(t2);
6684 if (nargs1 != nargs2) {
6685 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6686 fn1, nargs1, fn2, nargs2);
6690 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6691 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6692 if (t1->info != t2->info) {
6694 "Return type %s of %s() doesn't match type %s of %s()\n",
6695 btf_type_str(t1), fn1,
6696 btf_type_str(t2), fn2);
6700 for (i = 0; i < nargs1; i++) {
6701 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6702 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6704 if (t1->info != t2->info) {
6705 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6706 i, fn1, btf_type_str(t1),
6707 fn2, btf_type_str(t2));
6710 if (btf_type_has_size(t1) && t1->size != t2->size) {
6712 "arg%d in %s() has size %d while %s() has %d\n",
6718 /* global functions are validated with scalars and pointers
6719 * to context only. And only global functions can be replaced.
6720 * Hence type check only those types.
6722 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6724 if (!btf_type_is_ptr(t1)) {
6726 "arg%d in %s() has unrecognized type\n",
6730 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6731 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6732 if (!btf_type_is_struct(t1)) {
6734 "arg%d in %s() is not a pointer to context\n",
6738 if (!btf_type_is_struct(t2)) {
6740 "arg%d in %s() is not a pointer to context\n",
6744 /* This is an optional check to make program writing easier.
6745 * Compare names of structs and report an error to the user.
6746 * btf_prepare_func_args() already checked that t2 struct
6747 * is a context type. btf_prepare_func_args() will check
6748 * later that t1 struct is a context type as well.
6750 s1 = btf_name_by_offset(btf1, t1->name_off);
6751 s2 = btf_name_by_offset(btf2, t2->name_off);
6752 if (strcmp(s1, s2)) {
6754 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6755 i, fn1, s1, fn2, s2);
6762 /* Compare BTFs of given program with BTF of target program */
6763 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
6764 struct btf *btf2, const struct btf_type *t2)
6766 struct btf *btf1 = prog->aux->btf;
6767 const struct btf_type *t1;
6770 if (!prog->aux->func_info) {
6771 bpf_log(log, "Program extension requires BTF\n");
6775 btf_id = prog->aux->func_info[0].type_id;
6779 t1 = btf_type_by_id(btf1, btf_id);
6780 if (!t1 || !btf_type_is_func(t1))
6783 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
6786 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6787 const struct btf *btf, u32 func_id,
6788 struct bpf_reg_state *regs,
6790 bool processing_call)
6792 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6793 struct bpf_verifier_log *log = &env->log;
6794 const char *func_name, *ref_tname;
6795 const struct btf_type *t, *ref_t;
6796 const struct btf_param *args;
6797 u32 i, nargs, ref_id;
6800 t = btf_type_by_id(btf, func_id);
6801 if (!t || !btf_type_is_func(t)) {
6802 /* These checks were already done by the verifier while loading
6803 * struct bpf_func_info or in add_kfunc_call().
6805 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6809 func_name = btf_name_by_offset(btf, t->name_off);
6811 t = btf_type_by_id(btf, t->type);
6812 if (!t || !btf_type_is_func_proto(t)) {
6813 bpf_log(log, "Invalid BTF of func %s\n", func_name);
6816 args = (const struct btf_param *)(t + 1);
6817 nargs = btf_type_vlen(t);
6818 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6819 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6820 MAX_BPF_FUNC_REG_ARGS);
6824 /* check that BTF function arguments match actual types that the
6827 for (i = 0; i < nargs; i++) {
6828 enum bpf_arg_type arg_type = ARG_DONTCARE;
6830 struct bpf_reg_state *reg = ®s[regno];
6832 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6833 if (btf_type_is_scalar(t)) {
6834 if (reg->type == SCALAR_VALUE)
6836 bpf_log(log, "R%d is not a scalar\n", regno);
6840 if (!btf_type_is_ptr(t)) {
6841 bpf_log(log, "Unrecognized arg#%d type %s\n",
6842 i, btf_type_str(t));
6846 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6847 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6849 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6853 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6854 /* If function expects ctx type in BTF check that caller
6855 * is passing PTR_TO_CTX.
6857 if (reg->type != PTR_TO_CTX) {
6859 "arg#%d expected pointer to ctx, but got %s\n",
6860 i, btf_type_str(t));
6863 } else if (ptr_to_mem_ok && processing_call) {
6864 const struct btf_type *resolve_ret;
6867 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6868 if (IS_ERR(resolve_ret)) {
6870 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6871 i, btf_type_str(ref_t), ref_tname,
6872 PTR_ERR(resolve_ret));
6876 if (check_mem_reg(env, reg, regno, type_size))
6879 bpf_log(log, "reg type unsupported for arg#%d function %s#%d\n", i,
6880 func_name, func_id);
6888 /* Compare BTF of a function declaration with given bpf_reg_state.
6890 * EFAULT - there is a verifier bug. Abort verification.
6891 * EINVAL - there is a type mismatch or BTF is not available.
6892 * 0 - BTF matches with what bpf_reg_state expects.
6893 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6895 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6896 struct bpf_reg_state *regs)
6898 struct bpf_prog *prog = env->prog;
6899 struct btf *btf = prog->aux->btf;
6904 if (!prog->aux->func_info)
6907 btf_id = prog->aux->func_info[subprog].type_id;
6911 if (prog->aux->func_info_aux[subprog].unreliable)
6914 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6915 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, false);
6917 /* Compiler optimizations can remove arguments from static functions
6918 * or mismatched type can be passed into a global function.
6919 * In such cases mark the function as unreliable from BTF point of view.
6922 prog->aux->func_info_aux[subprog].unreliable = true;
6926 /* Compare BTF of a function call with given bpf_reg_state.
6928 * EFAULT - there is a verifier bug. Abort verification.
6929 * EINVAL - there is a type mismatch or BTF is not available.
6930 * 0 - BTF matches with what bpf_reg_state expects.
6931 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6933 * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6934 * because btf_check_func_arg_match() is still doing both. Once that
6935 * function is split in 2, we can call from here btf_check_subprog_arg_match()
6936 * first, and then treat the calling part in a new code path.
6938 int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6939 struct bpf_reg_state *regs)
6941 struct bpf_prog *prog = env->prog;
6942 struct btf *btf = prog->aux->btf;
6947 if (!prog->aux->func_info)
6950 btf_id = prog->aux->func_info[subprog].type_id;
6954 if (prog->aux->func_info_aux[subprog].unreliable)
6957 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6958 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, true);
6960 /* Compiler optimizations can remove arguments from static functions
6961 * or mismatched type can be passed into a global function.
6962 * In such cases mark the function as unreliable from BTF point of view.
6965 prog->aux->func_info_aux[subprog].unreliable = true;
6969 /* Convert BTF of a function into bpf_reg_state if possible
6971 * EFAULT - there is a verifier bug. Abort verification.
6972 * EINVAL - cannot convert BTF.
6973 * 0 - Successfully converted BTF into bpf_reg_state
6974 * (either PTR_TO_CTX or SCALAR_VALUE).
6976 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6977 struct bpf_reg_state *regs)
6979 struct bpf_verifier_log *log = &env->log;
6980 struct bpf_prog *prog = env->prog;
6981 enum bpf_prog_type prog_type = prog->type;
6982 struct btf *btf = prog->aux->btf;
6983 const struct btf_param *args;
6984 const struct btf_type *t, *ref_t;
6985 u32 i, nargs, btf_id;
6988 if (!prog->aux->func_info ||
6989 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6990 bpf_log(log, "Verifier bug\n");
6994 btf_id = prog->aux->func_info[subprog].type_id;
6996 bpf_log(log, "Global functions need valid BTF\n");
7000 t = btf_type_by_id(btf, btf_id);
7001 if (!t || !btf_type_is_func(t)) {
7002 /* These checks were already done by the verifier while loading
7003 * struct bpf_func_info
7005 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7009 tname = btf_name_by_offset(btf, t->name_off);
7011 if (log->level & BPF_LOG_LEVEL)
7012 bpf_log(log, "Validating %s() func#%d...\n",
7015 if (prog->aux->func_info_aux[subprog].unreliable) {
7016 bpf_log(log, "Verifier bug in function %s()\n", tname);
7019 if (prog_type == BPF_PROG_TYPE_EXT)
7020 prog_type = prog->aux->dst_prog->type;
7022 t = btf_type_by_id(btf, t->type);
7023 if (!t || !btf_type_is_func_proto(t)) {
7024 bpf_log(log, "Invalid type of function %s()\n", tname);
7027 args = (const struct btf_param *)(t + 1);
7028 nargs = btf_type_vlen(t);
7029 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7030 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7031 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7034 /* check that function returns int */
7035 t = btf_type_by_id(btf, t->type);
7036 while (btf_type_is_modifier(t))
7037 t = btf_type_by_id(btf, t->type);
7038 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7040 "Global function %s() doesn't return scalar. Only those are supported.\n",
7044 /* Convert BTF function arguments into verifier types.
7045 * Only PTR_TO_CTX and SCALAR are supported atm.
7047 for (i = 0; i < nargs; i++) {
7048 struct bpf_reg_state *reg = ®s[i + 1];
7050 t = btf_type_by_id(btf, args[i].type);
7051 while (btf_type_is_modifier(t))
7052 t = btf_type_by_id(btf, t->type);
7053 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7054 reg->type = SCALAR_VALUE;
7057 if (btf_type_is_ptr(t)) {
7058 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
7059 reg->type = PTR_TO_CTX;
7063 t = btf_type_skip_modifiers(btf, t->type, NULL);
7065 ref_t = btf_resolve_size(btf, t, ®->mem_size);
7066 if (IS_ERR(ref_t)) {
7068 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7069 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7074 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
7075 reg->id = ++env->id_gen;
7079 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7080 i, btf_type_str(t), tname);
7086 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7087 struct btf_show *show)
7089 const struct btf_type *t = btf_type_by_id(btf, type_id);
7092 memset(&show->state, 0, sizeof(show->state));
7093 memset(&show->obj, 0, sizeof(show->obj));
7095 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7098 static void btf_seq_show(struct btf_show *show, const char *fmt,
7101 seq_vprintf((struct seq_file *)show->target, fmt, args);
7104 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7105 void *obj, struct seq_file *m, u64 flags)
7107 struct btf_show sseq;
7110 sseq.showfn = btf_seq_show;
7113 btf_type_show(btf, type_id, obj, &sseq);
7115 return sseq.state.status;
7118 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7121 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7122 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7123 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7126 struct btf_show_snprintf {
7127 struct btf_show show;
7128 int len_left; /* space left in string */
7129 int len; /* length we would have written */
7132 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7135 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7138 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7141 ssnprintf->len_left = 0;
7142 ssnprintf->len = len;
7143 } else if (len >= ssnprintf->len_left) {
7144 /* no space, drive on to get length we would have written */
7145 ssnprintf->len_left = 0;
7146 ssnprintf->len += len;
7148 ssnprintf->len_left -= len;
7149 ssnprintf->len += len;
7150 show->target += len;
7154 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7155 char *buf, int len, u64 flags)
7157 struct btf_show_snprintf ssnprintf;
7159 ssnprintf.show.target = buf;
7160 ssnprintf.show.flags = flags;
7161 ssnprintf.show.showfn = btf_snprintf_show;
7162 ssnprintf.len_left = len;
7165 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7167 /* If we encountered an error, return it. */
7168 if (ssnprintf.show.state.status)
7169 return ssnprintf.show.state.status;
7171 /* Otherwise return length we would have written */
7172 return ssnprintf.len;
7175 #ifdef CONFIG_PROC_FS
7176 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7178 const struct btf *btf = filp->private_data;
7180 seq_printf(m, "btf_id:\t%u\n", btf->id);
7184 static int btf_release(struct inode *inode, struct file *filp)
7186 btf_put(filp->private_data);
7190 const struct file_operations btf_fops = {
7191 #ifdef CONFIG_PROC_FS
7192 .show_fdinfo = bpf_btf_show_fdinfo,
7194 .release = btf_release,
7197 static int __btf_new_fd(struct btf *btf)
7199 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7202 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
7207 btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
7208 attr->btf_size, attr->btf_log_level,
7209 u64_to_user_ptr(attr->btf_log_buf),
7210 attr->btf_log_size);
7212 return PTR_ERR(btf);
7214 ret = btf_alloc_id(btf);
7221 * The BTF ID is published to the userspace.
7222 * All BTF free must go through call_rcu() from
7223 * now on (i.e. free by calling btf_put()).
7226 ret = __btf_new_fd(btf);
7233 struct btf *btf_get_by_fd(int fd)
7241 return ERR_PTR(-EBADF);
7243 if (f.file->f_op != &btf_fops) {
7245 return ERR_PTR(-EINVAL);
7248 btf = f.file->private_data;
7249 refcount_inc(&btf->refcnt);
7255 int btf_get_info_by_fd(const struct btf *btf,
7256 const union bpf_attr *attr,
7257 union bpf_attr __user *uattr)
7259 struct bpf_btf_info __user *uinfo;
7260 struct bpf_btf_info info;
7261 u32 info_copy, btf_copy;
7264 u32 uinfo_len, uname_len, name_len;
7267 uinfo = u64_to_user_ptr(attr->info.info);
7268 uinfo_len = attr->info.info_len;
7270 info_copy = min_t(u32, uinfo_len, sizeof(info));
7271 memset(&info, 0, sizeof(info));
7272 if (copy_from_user(&info, uinfo, info_copy))
7276 ubtf = u64_to_user_ptr(info.btf);
7277 btf_copy = min_t(u32, btf->data_size, info.btf_size);
7278 if (copy_to_user(ubtf, btf->data, btf_copy))
7280 info.btf_size = btf->data_size;
7282 info.kernel_btf = btf->kernel_btf;
7284 uname = u64_to_user_ptr(info.name);
7285 uname_len = info.name_len;
7286 if (!uname ^ !uname_len)
7289 name_len = strlen(btf->name);
7290 info.name_len = name_len;
7293 if (uname_len >= name_len + 1) {
7294 if (copy_to_user(uname, btf->name, name_len + 1))
7299 if (copy_to_user(uname, btf->name, uname_len - 1))
7301 if (put_user(zero, uname + uname_len - 1))
7303 /* let user-space know about too short buffer */
7308 if (copy_to_user(uinfo, &info, info_copy) ||
7309 put_user(info_copy, &uattr->info.info_len))
7315 int btf_get_fd_by_id(u32 id)
7321 btf = idr_find(&btf_idr, id);
7322 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7323 btf = ERR_PTR(-ENOENT);
7327 return PTR_ERR(btf);
7329 fd = __btf_new_fd(btf);
7336 u32 btf_obj_id(const struct btf *btf)
7341 bool btf_is_kernel(const struct btf *btf)
7343 return btf->kernel_btf;
7346 bool btf_is_module(const struct btf *btf)
7348 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7352 BTF_MODULE_F_LIVE = (1 << 0),
7355 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7357 struct list_head list;
7358 struct module *module;
7360 struct bin_attribute *sysfs_attr;
7364 static LIST_HEAD(btf_modules);
7365 static DEFINE_MUTEX(btf_module_mutex);
7368 btf_module_read(struct file *file, struct kobject *kobj,
7369 struct bin_attribute *bin_attr,
7370 char *buf, loff_t off, size_t len)
7372 const struct btf *btf = bin_attr->private;
7374 memcpy(buf, btf->data + off, len);
7378 static void purge_cand_cache(struct btf *btf);
7380 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7383 struct btf_module *btf_mod, *tmp;
7384 struct module *mod = module;
7388 if (mod->btf_data_size == 0 ||
7389 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7390 op != MODULE_STATE_GOING))
7394 case MODULE_STATE_COMING:
7395 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7400 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7403 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7404 pr_warn("failed to validate module [%s] BTF: %ld\n",
7405 mod->name, PTR_ERR(btf));
7408 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7412 err = btf_alloc_id(btf);
7419 purge_cand_cache(NULL);
7420 mutex_lock(&btf_module_mutex);
7421 btf_mod->module = module;
7423 list_add(&btf_mod->list, &btf_modules);
7424 mutex_unlock(&btf_module_mutex);
7426 if (IS_ENABLED(CONFIG_SYSFS)) {
7427 struct bin_attribute *attr;
7429 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7433 sysfs_bin_attr_init(attr);
7434 attr->attr.name = btf->name;
7435 attr->attr.mode = 0444;
7436 attr->size = btf->data_size;
7437 attr->private = btf;
7438 attr->read = btf_module_read;
7440 err = sysfs_create_bin_file(btf_kobj, attr);
7442 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7449 btf_mod->sysfs_attr = attr;
7453 case MODULE_STATE_LIVE:
7454 mutex_lock(&btf_module_mutex);
7455 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7456 if (btf_mod->module != module)
7459 btf_mod->flags |= BTF_MODULE_F_LIVE;
7462 mutex_unlock(&btf_module_mutex);
7464 case MODULE_STATE_GOING:
7465 mutex_lock(&btf_module_mutex);
7466 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7467 if (btf_mod->module != module)
7470 list_del(&btf_mod->list);
7471 if (btf_mod->sysfs_attr)
7472 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7473 purge_cand_cache(btf_mod->btf);
7474 btf_put(btf_mod->btf);
7475 kfree(btf_mod->sysfs_attr);
7479 mutex_unlock(&btf_module_mutex);
7483 return notifier_from_errno(err);
7486 static struct notifier_block btf_module_nb = {
7487 .notifier_call = btf_module_notify,
7490 static int __init btf_module_init(void)
7492 register_module_notifier(&btf_module_nb);
7496 fs_initcall(btf_module_init);
7497 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7499 struct module *btf_try_get_module(const struct btf *btf)
7501 struct module *res = NULL;
7502 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7503 struct btf_module *btf_mod, *tmp;
7505 mutex_lock(&btf_module_mutex);
7506 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7507 if (btf_mod->btf != btf)
7510 /* We must only consider module whose __init routine has
7511 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7512 * which is set from the notifier callback for
7513 * MODULE_STATE_LIVE.
7515 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7516 res = btf_mod->module;
7520 mutex_unlock(&btf_module_mutex);
7526 /* Returns struct btf corresponding to the struct module.
7527 * This function can return NULL or ERR_PTR.
7529 static struct btf *btf_get_module_btf(const struct module *module)
7531 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7532 struct btf_module *btf_mod, *tmp;
7534 struct btf *btf = NULL;
7537 btf = bpf_get_btf_vmlinux();
7538 if (!IS_ERR_OR_NULL(btf))
7543 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7544 mutex_lock(&btf_module_mutex);
7545 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7546 if (btf_mod->module != module)
7549 btf_get(btf_mod->btf);
7553 mutex_unlock(&btf_module_mutex);
7559 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7561 struct btf *btf = NULL;
7568 if (name_sz <= 1 || name[name_sz - 1])
7571 ret = bpf_find_btf_id(name, kind, &btf);
7572 if (ret > 0 && btf_is_module(btf)) {
7573 btf_obj_fd = __btf_new_fd(btf);
7574 if (btf_obj_fd < 0) {
7578 return ret | (((u64)btf_obj_fd) << 32);
7585 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7586 .func = bpf_btf_find_by_name_kind,
7588 .ret_type = RET_INTEGER,
7589 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
7590 .arg2_type = ARG_CONST_SIZE,
7591 .arg3_type = ARG_ANYTHING,
7592 .arg4_type = ARG_ANYTHING,
7595 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7596 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7597 BTF_TRACING_TYPE_xxx
7598 #undef BTF_TRACING_TYPE
7600 /* Kernel Function (kfunc) BTF ID set registration API */
7602 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7603 struct btf_id_set8 *add_set)
7605 bool vmlinux_set = !btf_is_module(btf);
7606 struct btf_kfunc_set_tab *tab;
7607 struct btf_id_set8 *set;
7611 if (hook >= BTF_KFUNC_HOOK_MAX) {
7619 tab = btf->kfunc_set_tab;
7621 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7624 btf->kfunc_set_tab = tab;
7627 set = tab->sets[hook];
7628 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7631 if (WARN_ON_ONCE(set && !vmlinux_set)) {
7636 /* We don't need to allocate, concatenate, and sort module sets, because
7637 * only one is allowed per hook. Hence, we can directly assign the
7638 * pointer and return.
7641 tab->sets[hook] = add_set;
7645 /* In case of vmlinux sets, there may be more than one set being
7646 * registered per hook. To create a unified set, we allocate a new set
7647 * and concatenate all individual sets being registered. While each set
7648 * is individually sorted, they may become unsorted when concatenated,
7649 * hence re-sorting the final set again is required to make binary
7650 * searching the set using btf_id_set8_contains function work.
7652 set_cnt = set ? set->cnt : 0;
7654 if (set_cnt > U32_MAX - add_set->cnt) {
7659 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7665 set = krealloc(tab->sets[hook],
7666 offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
7667 GFP_KERNEL | __GFP_NOWARN);
7673 /* For newly allocated set, initialize set->cnt to 0 */
7674 if (!tab->sets[hook])
7676 tab->sets[hook] = set;
7678 /* Concatenate the two sets */
7679 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
7680 set->cnt += add_set->cnt;
7682 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
7686 btf_free_kfunc_set_tab(btf);
7690 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
7691 enum btf_kfunc_hook hook,
7694 struct btf_id_set8 *set;
7697 if (hook >= BTF_KFUNC_HOOK_MAX)
7699 if (!btf->kfunc_set_tab)
7701 set = btf->kfunc_set_tab->sets[hook];
7704 id = btf_id_set8_contains(set, kfunc_btf_id);
7707 /* The flags for BTF ID are located next to it */
7711 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7713 switch (prog_type) {
7714 case BPF_PROG_TYPE_UNSPEC:
7715 return BTF_KFUNC_HOOK_COMMON;
7716 case BPF_PROG_TYPE_XDP:
7717 return BTF_KFUNC_HOOK_XDP;
7718 case BPF_PROG_TYPE_SCHED_CLS:
7719 return BTF_KFUNC_HOOK_TC;
7720 case BPF_PROG_TYPE_STRUCT_OPS:
7721 return BTF_KFUNC_HOOK_STRUCT_OPS;
7722 case BPF_PROG_TYPE_TRACING:
7723 case BPF_PROG_TYPE_LSM:
7724 return BTF_KFUNC_HOOK_TRACING;
7725 case BPF_PROG_TYPE_SYSCALL:
7726 return BTF_KFUNC_HOOK_SYSCALL;
7727 case BPF_PROG_TYPE_CGROUP_SKB:
7728 return BTF_KFUNC_HOOK_CGROUP_SKB;
7729 case BPF_PROG_TYPE_SCHED_ACT:
7730 return BTF_KFUNC_HOOK_SCHED_ACT;
7731 case BPF_PROG_TYPE_SK_SKB:
7732 return BTF_KFUNC_HOOK_SK_SKB;
7733 case BPF_PROG_TYPE_SOCKET_FILTER:
7734 return BTF_KFUNC_HOOK_SOCKET_FILTER;
7735 case BPF_PROG_TYPE_LWT_OUT:
7736 case BPF_PROG_TYPE_LWT_IN:
7737 case BPF_PROG_TYPE_LWT_XMIT:
7738 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
7739 return BTF_KFUNC_HOOK_LWT;
7741 return BTF_KFUNC_HOOK_MAX;
7746 * Reference to the module (obtained using btf_try_get_module) corresponding to
7747 * the struct btf *MUST* be held when calling this function from verifier
7748 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7749 * keeping the reference for the duration of the call provides the necessary
7750 * protection for looking up a well-formed btf->kfunc_set_tab.
7752 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
7753 enum bpf_prog_type prog_type,
7756 enum btf_kfunc_hook hook;
7759 kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
7763 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7764 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
7767 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id)
7769 return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
7772 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
7773 const struct btf_kfunc_id_set *kset)
7778 btf = btf_get_module_btf(kset->owner);
7780 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7781 pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7784 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7785 pr_err("missing module BTF, cannot register kfuncs\n");
7791 return PTR_ERR(btf);
7793 ret = btf_populate_kfunc_set(btf, hook, kset->set);
7798 /* This function must be invoked only from initcalls/module init functions */
7799 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7800 const struct btf_kfunc_id_set *kset)
7802 enum btf_kfunc_hook hook;
7804 hook = bpf_prog_type_to_kfunc_hook(prog_type);
7805 return __register_btf_kfunc_id_set(hook, kset);
7807 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7809 /* This function must be invoked only from initcalls/module init functions */
7810 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
7812 return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
7814 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
7816 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7818 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7819 struct btf_id_dtor_kfunc *dtor;
7823 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7824 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7826 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7827 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7830 return dtor->kfunc_btf_id;
7833 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7835 const struct btf_type *dtor_func, *dtor_func_proto, *t;
7836 const struct btf_param *args;
7840 for (i = 0; i < cnt; i++) {
7841 dtor_btf_id = dtors[i].kfunc_btf_id;
7843 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7844 if (!dtor_func || !btf_type_is_func(dtor_func))
7847 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7848 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7851 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7852 t = btf_type_by_id(btf, dtor_func_proto->type);
7853 if (!t || !btf_type_is_void(t))
7856 nr_args = btf_type_vlen(dtor_func_proto);
7859 args = btf_params(dtor_func_proto);
7860 t = btf_type_by_id(btf, args[0].type);
7861 /* Allow any pointer type, as width on targets Linux supports
7862 * will be same for all pointer types (i.e. sizeof(void *))
7864 if (!t || !btf_type_is_ptr(t))
7870 /* This function must be invoked only from initcalls/module init functions */
7871 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7872 struct module *owner)
7874 struct btf_id_dtor_kfunc_tab *tab;
7879 btf = btf_get_module_btf(owner);
7881 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7882 pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7885 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7886 pr_err("missing module BTF, cannot register dtor kfuncs\n");
7892 return PTR_ERR(btf);
7894 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7895 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7900 /* Ensure that the prototype of dtor kfuncs being registered is sane */
7901 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7905 tab = btf->dtor_kfunc_tab;
7906 /* Only one call allowed for modules */
7907 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7912 tab_cnt = tab ? tab->cnt : 0;
7913 if (tab_cnt > U32_MAX - add_cnt) {
7917 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7918 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7923 tab = krealloc(btf->dtor_kfunc_tab,
7924 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7925 GFP_KERNEL | __GFP_NOWARN);
7931 if (!btf->dtor_kfunc_tab)
7933 btf->dtor_kfunc_tab = tab;
7935 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7936 tab->cnt += add_cnt;
7938 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7942 btf_free_dtor_kfunc_tab(btf);
7946 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7948 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
7950 /* Check local and target types for compatibility. This check is used for
7951 * type-based CO-RE relocations and follow slightly different rules than
7952 * field-based relocations. This function assumes that root types were already
7953 * checked for name match. Beyond that initial root-level name check, names
7954 * are completely ignored. Compatibility rules are as follows:
7955 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
7956 * kind should match for local and target types (i.e., STRUCT is not
7957 * compatible with UNION);
7958 * - for ENUMs/ENUM64s, the size is ignored;
7959 * - for INT, size and signedness are ignored;
7960 * - for ARRAY, dimensionality is ignored, element types are checked for
7961 * compatibility recursively;
7962 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
7963 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7964 * - FUNC_PROTOs are compatible if they have compatible signature: same
7965 * number of input args and compatible return and argument types.
7966 * These rules are not set in stone and probably will be adjusted as we get
7967 * more experience with using BPF CO-RE relocations.
7969 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7970 const struct btf *targ_btf, __u32 targ_id)
7972 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
7973 MAX_TYPES_ARE_COMPAT_DEPTH);
7976 #define MAX_TYPES_MATCH_DEPTH 2
7978 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
7979 const struct btf *targ_btf, u32 targ_id)
7981 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
7982 MAX_TYPES_MATCH_DEPTH);
7985 static bool bpf_core_is_flavor_sep(const char *s)
7987 /* check X___Y name pattern, where X and Y are not underscores */
7988 return s[0] != '_' && /* X */
7989 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
7990 s[4] != '_'; /* Y */
7993 size_t bpf_core_essential_name_len(const char *name)
7995 size_t n = strlen(name);
7998 for (i = n - 5; i >= 0; i--) {
7999 if (bpf_core_is_flavor_sep(name + i))
8005 struct bpf_cand_cache {
8011 const struct btf *btf;
8016 static void bpf_free_cands(struct bpf_cand_cache *cands)
8019 /* empty candidate array was allocated on stack */
8024 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8030 #define VMLINUX_CAND_CACHE_SIZE 31
8031 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8033 #define MODULE_CAND_CACHE_SIZE 31
8034 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8036 static DEFINE_MUTEX(cand_cache_mutex);
8038 static void __print_cand_cache(struct bpf_verifier_log *log,
8039 struct bpf_cand_cache **cache,
8042 struct bpf_cand_cache *cc;
8045 for (i = 0; i < cache_size; i++) {
8049 bpf_log(log, "[%d]%s(", i, cc->name);
8050 for (j = 0; j < cc->cnt; j++) {
8051 bpf_log(log, "%d", cc->cands[j].id);
8052 if (j < cc->cnt - 1)
8055 bpf_log(log, "), ");
8059 static void print_cand_cache(struct bpf_verifier_log *log)
8061 mutex_lock(&cand_cache_mutex);
8062 bpf_log(log, "vmlinux_cand_cache:");
8063 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8064 bpf_log(log, "\nmodule_cand_cache:");
8065 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8067 mutex_unlock(&cand_cache_mutex);
8070 static u32 hash_cands(struct bpf_cand_cache *cands)
8072 return jhash(cands->name, cands->name_len, 0);
8075 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8076 struct bpf_cand_cache **cache,
8079 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8081 if (cc && cc->name_len == cands->name_len &&
8082 !strncmp(cc->name, cands->name, cands->name_len))
8087 static size_t sizeof_cands(int cnt)
8089 return offsetof(struct bpf_cand_cache, cands[cnt]);
8092 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8093 struct bpf_cand_cache **cache,
8096 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8099 bpf_free_cands_from_cache(*cc);
8102 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8104 bpf_free_cands(cands);
8105 return ERR_PTR(-ENOMEM);
8107 /* strdup the name, since it will stay in cache.
8108 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8110 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8111 bpf_free_cands(cands);
8112 if (!new_cands->name) {
8114 return ERR_PTR(-ENOMEM);
8120 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8121 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8124 struct bpf_cand_cache *cc;
8127 for (i = 0; i < cache_size; i++) {
8132 /* when new module is loaded purge all of module_cand_cache,
8133 * since new module might have candidates with the name
8134 * that matches cached cands.
8136 bpf_free_cands_from_cache(cc);
8140 /* when module is unloaded purge cache entries
8141 * that match module's btf
8143 for (j = 0; j < cc->cnt; j++)
8144 if (cc->cands[j].btf == btf) {
8145 bpf_free_cands_from_cache(cc);
8153 static void purge_cand_cache(struct btf *btf)
8155 mutex_lock(&cand_cache_mutex);
8156 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8157 mutex_unlock(&cand_cache_mutex);
8161 static struct bpf_cand_cache *
8162 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8165 struct bpf_cand_cache *new_cands;
8166 const struct btf_type *t;
8167 const char *targ_name;
8168 size_t targ_essent_len;
8171 n = btf_nr_types(targ_btf);
8172 for (i = targ_start_id; i < n; i++) {
8173 t = btf_type_by_id(targ_btf, i);
8174 if (btf_kind(t) != cands->kind)
8177 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8181 /* the resched point is before strncmp to make sure that search
8182 * for non-existing name will have a chance to schedule().
8186 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8189 targ_essent_len = bpf_core_essential_name_len(targ_name);
8190 if (targ_essent_len != cands->name_len)
8193 /* most of the time there is only one candidate for a given kind+name pair */
8194 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8196 bpf_free_cands(cands);
8197 return ERR_PTR(-ENOMEM);
8200 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8201 bpf_free_cands(cands);
8203 cands->cands[cands->cnt].btf = targ_btf;
8204 cands->cands[cands->cnt].id = i;
8210 static struct bpf_cand_cache *
8211 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8213 struct bpf_cand_cache *cands, *cc, local_cand = {};
8214 const struct btf *local_btf = ctx->btf;
8215 const struct btf_type *local_type;
8216 const struct btf *main_btf;
8217 size_t local_essent_len;
8218 struct btf *mod_btf;
8222 main_btf = bpf_get_btf_vmlinux();
8223 if (IS_ERR(main_btf))
8224 return ERR_CAST(main_btf);
8226 return ERR_PTR(-EINVAL);
8228 local_type = btf_type_by_id(local_btf, local_type_id);
8230 return ERR_PTR(-EINVAL);
8232 name = btf_name_by_offset(local_btf, local_type->name_off);
8233 if (str_is_empty(name))
8234 return ERR_PTR(-EINVAL);
8235 local_essent_len = bpf_core_essential_name_len(name);
8237 cands = &local_cand;
8239 cands->kind = btf_kind(local_type);
8240 cands->name_len = local_essent_len;
8242 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8243 /* cands is a pointer to stack here */
8250 /* Attempt to find target candidates in vmlinux BTF first */
8251 cands = bpf_core_add_cands(cands, main_btf, 1);
8253 return ERR_CAST(cands);
8255 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8257 /* populate cache even when cands->cnt == 0 */
8258 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8260 return ERR_CAST(cc);
8262 /* if vmlinux BTF has any candidate, don't go for module BTFs */
8267 /* cands is a pointer to stack here and cands->cnt == 0 */
8268 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8270 /* if cache has it return it even if cc->cnt == 0 */
8273 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8274 spin_lock_bh(&btf_idr_lock);
8275 idr_for_each_entry(&btf_idr, mod_btf, id) {
8276 if (!btf_is_module(mod_btf))
8278 /* linear search could be slow hence unlock/lock
8279 * the IDR to avoiding holding it for too long
8282 spin_unlock_bh(&btf_idr_lock);
8283 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8284 if (IS_ERR(cands)) {
8286 return ERR_CAST(cands);
8288 spin_lock_bh(&btf_idr_lock);
8291 spin_unlock_bh(&btf_idr_lock);
8292 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8293 * or pointer to stack if cands->cnd == 0.
8294 * Copy it into the cache even when cands->cnt == 0 and
8295 * return the result.
8297 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8300 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8301 int relo_idx, void *insn)
8303 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8304 struct bpf_core_cand_list cands = {};
8305 struct bpf_core_relo_res targ_res;
8306 struct bpf_core_spec *specs;
8309 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8310 * into arrays of btf_ids of struct fields and array indices.
8312 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8317 struct bpf_cand_cache *cc;
8320 mutex_lock(&cand_cache_mutex);
8321 cc = bpf_core_find_cands(ctx, relo->type_id);
8323 bpf_log(ctx->log, "target candidate search failed for %d\n",
8329 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8335 for (i = 0; i < cc->cnt; i++) {
8337 "CO-RE relocating %s %s: found target candidate [%d]\n",
8338 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8339 cands.cands[i].btf = cc->cands[i].btf;
8340 cands.cands[i].id = cc->cands[i].id;
8342 cands.len = cc->cnt;
8343 /* cand_cache_mutex needs to span the cache lookup and
8344 * copy of btf pointer into bpf_core_cand_list,
8345 * since module can be unloaded while bpf_core_calc_relo_insn
8346 * is working with module's btf.
8350 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8355 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8362 mutex_unlock(&cand_cache_mutex);
8363 if (ctx->log->level & BPF_LOG_LEVEL2)
8364 print_cand_cache(ctx->log);
8369 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8370 const struct bpf_reg_state *reg,
8371 int off, const char *suffix)
8373 struct btf *btf = reg->btf;
8374 const struct btf_type *walk_type, *safe_type;
8376 char safe_tname[64];
8378 const struct btf_member *member, *m_walk = NULL;
8380 const char *walk_name;
8382 walk_type = btf_type_by_id(btf, reg->btf_id);
8386 tname = btf_name_by_offset(btf, walk_type->name_off);
8388 ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8392 safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8396 safe_type = btf_type_by_id(btf, safe_id);
8400 for_each_member(i, walk_type, member) {
8403 /* We're looking for the PTR_TO_BTF_ID member in the struct
8404 * type we're walking which matches the specified offset.
8405 * Below, we'll iterate over the fields in the safe variant of
8406 * the struct and see if any of them has a matching type /
8409 moff = __btf_member_bit_offset(walk_type, member) / 8;
8418 walk_name = __btf_name_by_offset(btf, m_walk->name_off);
8419 for_each_member(i, safe_type, member) {
8420 const char *m_name = __btf_name_by_offset(btf, member->name_off);
8422 /* If we match on both type and name, the field is considered trusted. */
8423 if (m_walk->type == member->type && !strcmp(walk_name, m_name))
8430 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8431 const struct btf *reg_btf, u32 reg_id,
8432 const struct btf *arg_btf, u32 arg_id)
8434 const char *reg_name, *arg_name, *search_needle;
8435 const struct btf_type *reg_type, *arg_type;
8436 int reg_len, arg_len, cmp_len;
8437 size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8439 reg_type = btf_type_by_id(reg_btf, reg_id);
8443 arg_type = btf_type_by_id(arg_btf, arg_id);
8447 reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8448 arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8450 reg_len = strlen(reg_name);
8451 arg_len = strlen(arg_name);
8453 /* Exactly one of the two type names may be suffixed with ___init, so
8454 * if the strings are the same size, they can't possibly be no-cast
8455 * aliases of one another. If you have two of the same type names, e.g.
8456 * they're both nf_conn___init, it would be improper to return true
8457 * because they are _not_ no-cast aliases, they are the same type.
8459 if (reg_len == arg_len)
8462 /* Either of the two names must be the other name, suffixed with ___init. */
8463 if ((reg_len != arg_len + pattern_len) &&
8464 (arg_len != reg_len + pattern_len))
8467 if (reg_len < arg_len) {
8468 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8471 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8478 /* ___init suffix must come at the end of the name */
8479 if (*(search_needle + pattern_len) != '\0')
8482 return !strncmp(reg_name, arg_name, cmp_len);