1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018 Facebook */
4 #include <uapi/linux/btf.h>
5 #include <uapi/linux/bpf.h>
6 #include <uapi/linux/bpf_perf_event.h>
7 #include <uapi/linux/types.h>
8 #include <linux/seq_file.h>
9 #include <linux/compiler.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/file.h>
15 #include <linux/uaccess.h>
16 #include <linux/kernel.h>
17 #include <linux/idr.h>
18 #include <linux/sort.h>
19 #include <linux/bpf_verifier.h>
20 #include <linux/btf.h>
21 #include <linux/btf_ids.h>
22 #include <linux/bpf.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/skmsg.h>
25 #include <linux/perf_event.h>
26 #include <linux/bsearch.h>
27 #include <linux/kobject.h>
28 #include <linux/sysfs.h>
30 #include <net/netfilter/nf_bpf_link.h>
34 #include "../tools/lib/bpf/relo_core.h"
36 /* BTF (BPF Type Format) is the meta data format which describes
37 * the data types of BPF program/map. Hence, it basically focus
38 * on the C programming language which the modern BPF is primary
43 * The BTF data is stored under the ".BTF" ELF section
47 * Each 'struct btf_type' object describes a C data type.
48 * Depending on the type it is describing, a 'struct btf_type'
49 * object may be followed by more data. F.e.
50 * To describe an array, 'struct btf_type' is followed by
53 * 'struct btf_type' and any extra data following it are
58 * The BTF type section contains a list of 'struct btf_type' objects.
59 * Each one describes a C type. Recall from the above section
60 * that a 'struct btf_type' object could be immediately followed by extra
61 * data in order to describe some particular C types.
65 * Each btf_type object is identified by a type_id. The type_id
66 * is implicitly implied by the location of the btf_type object in
67 * the BTF type section. The first one has type_id 1. The second
68 * one has type_id 2...etc. Hence, an earlier btf_type has
71 * A btf_type object may refer to another btf_type object by using
72 * type_id (i.e. the "type" in the "struct btf_type").
74 * NOTE that we cannot assume any reference-order.
75 * A btf_type object can refer to an earlier btf_type object
76 * but it can also refer to a later btf_type object.
78 * For example, to describe "const void *". A btf_type
79 * object describing "const" may refer to another btf_type
80 * object describing "void *". This type-reference is done
81 * by specifying type_id:
83 * [1] CONST (anon) type_id=2
84 * [2] PTR (anon) type_id=0
86 * The above is the btf_verifier debug log:
87 * - Each line started with "[?]" is a btf_type object
88 * - [?] is the type_id of the btf_type object.
89 * - CONST/PTR is the BTF_KIND_XXX
90 * - "(anon)" is the name of the type. It just
91 * happens that CONST and PTR has no name.
92 * - type_id=XXX is the 'u32 type' in btf_type
94 * NOTE: "void" has type_id 0
98 * The BTF string section contains the names used by the type section.
99 * Each string is referred by an "offset" from the beginning of the
102 * Each string is '\0' terminated.
104 * The first character in the string section must be '\0'
105 * which is used to mean 'anonymous'. Some btf_type may not
111 * To verify BTF data, two passes are needed.
115 * The first pass is to collect all btf_type objects to
116 * an array: "btf->types".
118 * Depending on the C type that a btf_type is describing,
119 * a btf_type may be followed by extra data. We don't know
120 * how many btf_type is there, and more importantly we don't
121 * know where each btf_type is located in the type section.
123 * Without knowing the location of each type_id, most verifications
124 * cannot be done. e.g. an earlier btf_type may refer to a later
125 * btf_type (recall the "const void *" above), so we cannot
126 * check this type-reference in the first pass.
128 * In the first pass, it still does some verifications (e.g.
129 * checking the name is a valid offset to the string section).
133 * The main focus is to resolve a btf_type that is referring
136 * We have to ensure the referring type:
137 * 1) does exist in the BTF (i.e. in btf->types[])
138 * 2) does not cause a loop:
147 * btf_type_needs_resolve() decides if a btf_type needs
150 * The needs_resolve type implements the "resolve()" ops which
151 * essentially does a DFS and detects backedge.
153 * During resolve (or DFS), different C types have different
154 * "RESOLVED" conditions.
156 * When resolving a BTF_KIND_STRUCT, we need to resolve all its
157 * members because a member is always referring to another
158 * type. A struct's member can be treated as "RESOLVED" if
159 * it is referring to a BTF_KIND_PTR. Otherwise, the
160 * following valid C struct would be rejected:
167 * When resolving a BTF_KIND_PTR, it needs to keep resolving if
168 * it is referring to another BTF_KIND_PTR. Otherwise, we cannot
169 * detect a pointer loop, e.g.:
170 * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
172 * +-----------------------------------------+
176 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
177 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
178 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
179 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
180 #define BITS_ROUNDUP_BYTES(bits) \
181 (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
183 #define BTF_INFO_MASK 0x9f00ffff
184 #define BTF_INT_MASK 0x0fffffff
185 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
186 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
188 /* 16MB for 64k structs and each has 16 members and
189 * a few MB spaces for the string section.
190 * The hard limit is S32_MAX.
192 #define BTF_MAX_SIZE (16 * 1024 * 1024)
194 #define for_each_member_from(i, from, struct_type, member) \
195 for (i = from, member = btf_type_member(struct_type) + from; \
196 i < btf_type_vlen(struct_type); \
199 #define for_each_vsi_from(i, from, struct_type, member) \
200 for (i = from, member = btf_type_var_secinfo(struct_type) + from; \
201 i < btf_type_vlen(struct_type); \
205 DEFINE_SPINLOCK(btf_idr_lock);
207 enum btf_kfunc_hook {
208 BTF_KFUNC_HOOK_COMMON,
211 BTF_KFUNC_HOOK_STRUCT_OPS,
212 BTF_KFUNC_HOOK_TRACING,
213 BTF_KFUNC_HOOK_SYSCALL,
214 BTF_KFUNC_HOOK_FMODRET,
215 BTF_KFUNC_HOOK_CGROUP_SKB,
216 BTF_KFUNC_HOOK_SCHED_ACT,
217 BTF_KFUNC_HOOK_SK_SKB,
218 BTF_KFUNC_HOOK_SOCKET_FILTER,
220 BTF_KFUNC_HOOK_NETFILTER,
221 BTF_KFUNC_HOOK_KPROBE,
226 BTF_KFUNC_SET_MAX_CNT = 256,
227 BTF_DTOR_KFUNC_MAX_CNT = 256,
228 BTF_KFUNC_FILTER_MAX_CNT = 16,
231 struct btf_kfunc_hook_filter {
232 btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
236 struct btf_kfunc_set_tab {
237 struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
238 struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
241 struct btf_id_dtor_kfunc_tab {
243 struct btf_id_dtor_kfunc dtors[];
246 struct btf_struct_ops_tab {
249 struct bpf_struct_ops_desc ops[];
254 struct btf_type **types;
259 struct btf_header hdr;
260 u32 nr_types; /* includes VOID for base BTF */
266 struct btf_kfunc_set_tab *kfunc_set_tab;
267 struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
268 struct btf_struct_metas *struct_meta_tab;
269 struct btf_struct_ops_tab *struct_ops_tab;
271 /* split BTF support */
272 struct btf *base_btf;
273 u32 start_id; /* first type ID in this BTF (0 for base BTF) */
274 u32 start_str_off; /* first string offset (0 for base BTF) */
275 char name[MODULE_NAME_LEN];
279 enum verifier_phase {
284 struct resolve_vertex {
285 const struct btf_type *t;
297 RESOLVE_TBD, /* To Be Determined */
298 RESOLVE_PTR, /* Resolving for Pointer */
299 RESOLVE_STRUCT_OR_ARRAY, /* Resolving for struct/union
304 #define MAX_RESOLVE_DEPTH 32
306 struct btf_sec_info {
311 struct btf_verifier_env {
314 struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
315 struct bpf_verifier_log log;
318 enum verifier_phase phase;
319 enum resolve_mode resolve_mode;
322 static const char * const btf_kind_str[NR_BTF_KINDS] = {
323 [BTF_KIND_UNKN] = "UNKNOWN",
324 [BTF_KIND_INT] = "INT",
325 [BTF_KIND_PTR] = "PTR",
326 [BTF_KIND_ARRAY] = "ARRAY",
327 [BTF_KIND_STRUCT] = "STRUCT",
328 [BTF_KIND_UNION] = "UNION",
329 [BTF_KIND_ENUM] = "ENUM",
330 [BTF_KIND_FWD] = "FWD",
331 [BTF_KIND_TYPEDEF] = "TYPEDEF",
332 [BTF_KIND_VOLATILE] = "VOLATILE",
333 [BTF_KIND_CONST] = "CONST",
334 [BTF_KIND_RESTRICT] = "RESTRICT",
335 [BTF_KIND_FUNC] = "FUNC",
336 [BTF_KIND_FUNC_PROTO] = "FUNC_PROTO",
337 [BTF_KIND_VAR] = "VAR",
338 [BTF_KIND_DATASEC] = "DATASEC",
339 [BTF_KIND_FLOAT] = "FLOAT",
340 [BTF_KIND_DECL_TAG] = "DECL_TAG",
341 [BTF_KIND_TYPE_TAG] = "TYPE_TAG",
342 [BTF_KIND_ENUM64] = "ENUM64",
345 const char *btf_type_str(const struct btf_type *t)
347 return btf_kind_str[BTF_INFO_KIND(t->info)];
350 /* Chunk size we use in safe copy of data to be shown. */
351 #define BTF_SHOW_OBJ_SAFE_SIZE 32
354 * This is the maximum size of a base type value (equivalent to a
355 * 128-bit int); if we are at the end of our safe buffer and have
356 * less than 16 bytes space we can't be assured of being able
357 * to copy the next type safely, so in such cases we will initiate
360 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE 16
363 #define BTF_SHOW_NAME_SIZE 80
366 * The suffix of a type that indicates it cannot alias another type when
367 * comparing BTF IDs for kfunc invocations.
369 #define NOCAST_ALIAS_SUFFIX "___init"
372 * Common data to all BTF show operations. Private show functions can add
373 * their own data to a structure containing a struct btf_show and consult it
374 * in the show callback. See btf_type_show() below.
376 * One challenge with showing nested data is we want to skip 0-valued
377 * data, but in order to figure out whether a nested object is all zeros
378 * we need to walk through it. As a result, we need to make two passes
379 * when handling structs, unions and arrays; the first path simply looks
380 * for nonzero data, while the second actually does the display. The first
381 * pass is signalled by show->state.depth_check being set, and if we
382 * encounter a non-zero value we set show->state.depth_to_show to
383 * the depth at which we encountered it. When we have completed the
384 * first pass, we will know if anything needs to be displayed if
385 * depth_to_show > depth. See btf_[struct,array]_show() for the
386 * implementation of this.
388 * Another problem is we want to ensure the data for display is safe to
389 * access. To support this, the anonymous "struct {} obj" tracks the data
390 * object and our safe copy of it. We copy portions of the data needed
391 * to the object "copy" buffer, but because its size is limited to
392 * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
393 * traverse larger objects for display.
395 * The various data type show functions all start with a call to
396 * btf_show_start_type() which returns a pointer to the safe copy
397 * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
398 * raw data itself). btf_show_obj_safe() is responsible for
399 * using copy_from_kernel_nofault() to update the safe data if necessary
400 * as we traverse the object's data. skbuff-like semantics are
403 * - obj.head points to the start of the toplevel object for display
404 * - obj.size is the size of the toplevel object
405 * - obj.data points to the current point in the original data at
406 * which our safe data starts. obj.data will advance as we copy
407 * portions of the data.
409 * In most cases a single copy will suffice, but larger data structures
410 * such as "struct task_struct" will require many copies. The logic in
411 * btf_show_obj_safe() handles the logic that determines if a new
412 * copy_from_kernel_nofault() is needed.
416 void *target; /* target of show operation (seq file, buffer) */
417 void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
418 const struct btf *btf;
419 /* below are used during iteration */
428 int status; /* non-zero for error */
429 const struct btf_type *type;
430 const struct btf_member *member;
431 char name[BTF_SHOW_NAME_SIZE]; /* space for member name/type */
437 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
441 struct btf_kind_operations {
442 s32 (*check_meta)(struct btf_verifier_env *env,
443 const struct btf_type *t,
445 int (*resolve)(struct btf_verifier_env *env,
446 const struct resolve_vertex *v);
447 int (*check_member)(struct btf_verifier_env *env,
448 const struct btf_type *struct_type,
449 const struct btf_member *member,
450 const struct btf_type *member_type);
451 int (*check_kflag_member)(struct btf_verifier_env *env,
452 const struct btf_type *struct_type,
453 const struct btf_member *member,
454 const struct btf_type *member_type);
455 void (*log_details)(struct btf_verifier_env *env,
456 const struct btf_type *t);
457 void (*show)(const struct btf *btf, const struct btf_type *t,
458 u32 type_id, void *data, u8 bits_offsets,
459 struct btf_show *show);
462 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
463 static struct btf_type btf_void;
465 static int btf_resolve(struct btf_verifier_env *env,
466 const struct btf_type *t, u32 type_id);
468 static int btf_func_check(struct btf_verifier_env *env,
469 const struct btf_type *t);
471 static bool btf_type_is_modifier(const struct btf_type *t)
473 /* Some of them is not strictly a C modifier
474 * but they are grouped into the same bucket
476 * A type (t) that refers to another
477 * type through t->type AND its size cannot
478 * be determined without following the t->type.
480 * ptr does not fall into this bucket
481 * because its size is always sizeof(void *).
483 switch (BTF_INFO_KIND(t->info)) {
484 case BTF_KIND_TYPEDEF:
485 case BTF_KIND_VOLATILE:
487 case BTF_KIND_RESTRICT:
488 case BTF_KIND_TYPE_TAG:
495 bool btf_type_is_void(const struct btf_type *t)
497 return t == &btf_void;
500 static bool btf_type_is_fwd(const struct btf_type *t)
502 return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
505 static bool btf_type_is_datasec(const struct btf_type *t)
507 return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
510 static bool btf_type_is_decl_tag(const struct btf_type *t)
512 return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
515 static bool btf_type_nosize(const struct btf_type *t)
517 return btf_type_is_void(t) || btf_type_is_fwd(t) ||
518 btf_type_is_func(t) || btf_type_is_func_proto(t) ||
519 btf_type_is_decl_tag(t);
522 static bool btf_type_nosize_or_null(const struct btf_type *t)
524 return !t || btf_type_nosize(t);
527 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
529 return btf_type_is_func(t) || btf_type_is_struct(t) ||
530 btf_type_is_var(t) || btf_type_is_typedef(t);
533 u32 btf_nr_types(const struct btf *btf)
538 total += btf->nr_types;
545 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
547 const struct btf_type *t;
551 total = btf_nr_types(btf);
552 for (i = 1; i < total; i++) {
553 t = btf_type_by_id(btf, i);
554 if (BTF_INFO_KIND(t->info) != kind)
557 tname = btf_name_by_offset(btf, t->name_off);
558 if (!strcmp(tname, name))
565 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
571 btf = bpf_get_btf_vmlinux();
577 ret = btf_find_by_name_kind(btf, name, kind);
578 /* ret is never zero, since btf_find_by_name_kind returns
579 * positive btf_id or negative error.
587 /* If name is not found in vmlinux's BTF then search in module's BTFs */
588 spin_lock_bh(&btf_idr_lock);
589 idr_for_each_entry(&btf_idr, btf, id) {
590 if (!btf_is_module(btf))
592 /* linear search could be slow hence unlock/lock
593 * the IDR to avoiding holding it for too long
596 spin_unlock_bh(&btf_idr_lock);
597 ret = btf_find_by_name_kind(btf, name, kind);
603 spin_lock_bh(&btf_idr_lock);
605 spin_unlock_bh(&btf_idr_lock);
609 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
612 const struct btf_type *t = btf_type_by_id(btf, id);
614 while (btf_type_is_modifier(t)) {
616 t = btf_type_by_id(btf, t->type);
625 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
628 const struct btf_type *t;
630 t = btf_type_skip_modifiers(btf, id, NULL);
631 if (!btf_type_is_ptr(t))
634 return btf_type_skip_modifiers(btf, t->type, res_id);
637 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
640 const struct btf_type *ptype;
642 ptype = btf_type_resolve_ptr(btf, id, res_id);
643 if (ptype && btf_type_is_func_proto(ptype))
649 /* Types that act only as a source, not sink or intermediate
650 * type when resolving.
652 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
654 return btf_type_is_var(t) ||
655 btf_type_is_decl_tag(t) ||
656 btf_type_is_datasec(t);
659 /* What types need to be resolved?
661 * btf_type_is_modifier() is an obvious one.
663 * btf_type_is_struct() because its member refers to
664 * another type (through member->type).
666 * btf_type_is_var() because the variable refers to
667 * another type. btf_type_is_datasec() holds multiple
668 * btf_type_is_var() types that need resolving.
670 * btf_type_is_array() because its element (array->type)
671 * refers to another type. Array can be thought of a
672 * special case of struct while array just has the same
673 * member-type repeated by array->nelems of times.
675 static bool btf_type_needs_resolve(const struct btf_type *t)
677 return btf_type_is_modifier(t) ||
678 btf_type_is_ptr(t) ||
679 btf_type_is_struct(t) ||
680 btf_type_is_array(t) ||
681 btf_type_is_var(t) ||
682 btf_type_is_func(t) ||
683 btf_type_is_decl_tag(t) ||
684 btf_type_is_datasec(t);
687 /* t->size can be used */
688 static bool btf_type_has_size(const struct btf_type *t)
690 switch (BTF_INFO_KIND(t->info)) {
692 case BTF_KIND_STRUCT:
695 case BTF_KIND_DATASEC:
697 case BTF_KIND_ENUM64:
704 static const char *btf_int_encoding_str(u8 encoding)
708 else if (encoding == BTF_INT_SIGNED)
710 else if (encoding == BTF_INT_CHAR)
712 else if (encoding == BTF_INT_BOOL)
718 static u32 btf_type_int(const struct btf_type *t)
720 return *(u32 *)(t + 1);
723 static const struct btf_array *btf_type_array(const struct btf_type *t)
725 return (const struct btf_array *)(t + 1);
728 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
730 return (const struct btf_enum *)(t + 1);
733 static const struct btf_var *btf_type_var(const struct btf_type *t)
735 return (const struct btf_var *)(t + 1);
738 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
740 return (const struct btf_decl_tag *)(t + 1);
743 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
745 return (const struct btf_enum64 *)(t + 1);
748 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
750 return kind_ops[BTF_INFO_KIND(t->info)];
753 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
755 if (!BTF_STR_OFFSET_VALID(offset))
758 while (offset < btf->start_str_off)
761 offset -= btf->start_str_off;
762 return offset < btf->hdr.str_len;
765 static bool __btf_name_char_ok(char c, bool first)
767 if ((first ? !isalpha(c) :
775 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
777 while (offset < btf->start_str_off)
780 offset -= btf->start_str_off;
781 if (offset < btf->hdr.str_len)
782 return &btf->strings[offset];
787 static bool __btf_name_valid(const struct btf *btf, u32 offset)
789 /* offset must be valid */
790 const char *src = btf_str_by_offset(btf, offset);
791 const char *src_limit;
793 if (!__btf_name_char_ok(*src, true))
796 /* set a limit on identifier length */
797 src_limit = src + KSYM_NAME_LEN;
799 while (*src && src < src_limit) {
800 if (!__btf_name_char_ok(*src, false))
808 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
810 return __btf_name_valid(btf, offset);
813 /* Allow any printable character in DATASEC names */
814 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
816 /* offset must be valid */
817 const char *src = btf_str_by_offset(btf, offset);
818 const char *src_limit;
820 /* set a limit on identifier length */
821 src_limit = src + KSYM_NAME_LEN;
823 while (*src && src < src_limit) {
832 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
839 name = btf_str_by_offset(btf, offset);
840 return name ?: "(invalid-name-offset)";
843 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
845 return btf_str_by_offset(btf, offset);
848 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
850 while (type_id < btf->start_id)
853 type_id -= btf->start_id;
854 if (type_id >= btf->nr_types)
856 return btf->types[type_id];
858 EXPORT_SYMBOL_GPL(btf_type_by_id);
861 * Regular int is not a bit field and it must be either
862 * u8/u16/u32/u64 or __int128.
864 static bool btf_type_int_is_regular(const struct btf_type *t)
866 u8 nr_bits, nr_bytes;
869 int_data = btf_type_int(t);
870 nr_bits = BTF_INT_BITS(int_data);
871 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
872 if (BITS_PER_BYTE_MASKED(nr_bits) ||
873 BTF_INT_OFFSET(int_data) ||
874 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
875 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
876 nr_bytes != (2 * sizeof(u64)))) {
884 * Check that given struct member is a regular int with expected
887 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
888 const struct btf_member *m,
889 u32 expected_offset, u32 expected_size)
891 const struct btf_type *t;
896 t = btf_type_id_size(btf, &id, NULL);
897 if (!t || !btf_type_is_int(t))
900 int_data = btf_type_int(t);
901 nr_bits = BTF_INT_BITS(int_data);
902 if (btf_type_kflag(s)) {
903 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
904 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
906 /* if kflag set, int should be a regular int and
907 * bit offset should be at byte boundary.
909 return !bitfield_size &&
910 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
911 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
914 if (BTF_INT_OFFSET(int_data) ||
915 BITS_PER_BYTE_MASKED(m->offset) ||
916 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
917 BITS_PER_BYTE_MASKED(nr_bits) ||
918 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
924 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
925 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
928 const struct btf_type *t = btf_type_by_id(btf, id);
930 while (btf_type_is_modifier(t) &&
931 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
932 t = btf_type_by_id(btf, t->type);
938 #define BTF_SHOW_MAX_ITER 10
940 #define BTF_KIND_BIT(kind) (1ULL << kind)
943 * Populate show->state.name with type name information.
944 * Format of type name is
946 * [.member_name = ] (type_name)
948 static const char *btf_show_name(struct btf_show *show)
950 /* BTF_MAX_ITER array suffixes "[]" */
951 const char *array_suffixes = "[][][][][][][][][][]";
952 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
953 /* BTF_MAX_ITER pointer suffixes "*" */
954 const char *ptr_suffixes = "**********";
955 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
956 const char *name = NULL, *prefix = "", *parens = "";
957 const struct btf_member *m = show->state.member;
958 const struct btf_type *t;
959 const struct btf_array *array;
960 u32 id = show->state.type_id;
961 const char *member = NULL;
962 bool show_member = false;
966 show->state.name[0] = '\0';
969 * Don't show type name if we're showing an array member;
970 * in that case we show the array type so don't need to repeat
971 * ourselves for each member.
973 if (show->state.array_member)
976 /* Retrieve member name, if any. */
978 member = btf_name_by_offset(show->btf, m->name_off);
979 show_member = strlen(member) > 0;
984 * Start with type_id, as we have resolved the struct btf_type *
985 * via btf_modifier_show() past the parent typedef to the child
986 * struct, int etc it is defined as. In such cases, the type_id
987 * still represents the starting type while the struct btf_type *
988 * in our show->state points at the resolved type of the typedef.
990 t = btf_type_by_id(show->btf, id);
995 * The goal here is to build up the right number of pointer and
996 * array suffixes while ensuring the type name for a typedef
997 * is represented. Along the way we accumulate a list of
998 * BTF kinds we have encountered, since these will inform later
999 * display; for example, pointer types will not require an
1000 * opening "{" for struct, we will just display the pointer value.
1002 * We also want to accumulate the right number of pointer or array
1003 * indices in the format string while iterating until we get to
1004 * the typedef/pointee/array member target type.
1006 * We start by pointing at the end of pointer and array suffix
1007 * strings; as we accumulate pointers and arrays we move the pointer
1008 * or array string backwards so it will show the expected number of
1009 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
1010 * and/or arrays and typedefs are supported as a precaution.
1012 * We also want to get typedef name while proceeding to resolve
1013 * type it points to so that we can add parentheses if it is a
1014 * "typedef struct" etc.
1016 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1018 switch (BTF_INFO_KIND(t->info)) {
1019 case BTF_KIND_TYPEDEF:
1021 name = btf_name_by_offset(show->btf,
1023 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1026 case BTF_KIND_ARRAY:
1027 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1031 array = btf_type_array(t);
1032 if (array_suffix > array_suffixes)
1037 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1038 if (ptr_suffix > ptr_suffixes)
1048 t = btf_type_skip_qualifiers(show->btf, id);
1050 /* We may not be able to represent this type; bail to be safe */
1051 if (i == BTF_SHOW_MAX_ITER)
1055 name = btf_name_by_offset(show->btf, t->name_off);
1057 switch (BTF_INFO_KIND(t->info)) {
1058 case BTF_KIND_STRUCT:
1059 case BTF_KIND_UNION:
1060 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1062 /* if it's an array of struct/union, parens is already set */
1063 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1067 case BTF_KIND_ENUM64:
1074 /* pointer does not require parens */
1075 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1077 /* typedef does not require struct/union/enum prefix */
1078 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1084 /* Even if we don't want type name info, we want parentheses etc */
1085 if (show->flags & BTF_SHOW_NONAME)
1086 snprintf(show->state.name, sizeof(show->state.name), "%s",
1089 snprintf(show->state.name, sizeof(show->state.name),
1090 "%s%s%s(%s%s%s%s%s%s)%s",
1091 /* first 3 strings comprise ".member = " */
1092 show_member ? "." : "",
1093 show_member ? member : "",
1094 show_member ? " = " : "",
1095 /* ...next is our prefix (struct, enum, etc) */
1097 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1098 /* ...this is the type name itself */
1100 /* ...suffixed by the appropriate '*', '[]' suffixes */
1101 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1102 array_suffix, parens);
1104 return show->state.name;
1107 static const char *__btf_show_indent(struct btf_show *show)
1109 const char *indents = " ";
1110 const char *indent = &indents[strlen(indents)];
1112 if ((indent - show->state.depth) >= indents)
1113 return indent - show->state.depth;
1117 static const char *btf_show_indent(struct btf_show *show)
1119 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1122 static const char *btf_show_newline(struct btf_show *show)
1124 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1127 static const char *btf_show_delim(struct btf_show *show)
1129 if (show->state.depth == 0)
1132 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1133 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1139 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1143 if (!show->state.depth_check) {
1144 va_start(args, fmt);
1145 show->showfn(show, fmt, args);
1150 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1151 * format specifiers to the format specifier passed in; these do the work of
1152 * adding indentation, delimiters etc while the caller simply has to specify
1153 * the type value(s) in the format specifier + value(s).
1155 #define btf_show_type_value(show, fmt, value) \
1157 if ((value) != (__typeof__(value))0 || \
1158 (show->flags & BTF_SHOW_ZERO) || \
1159 show->state.depth == 0) { \
1160 btf_show(show, "%s%s" fmt "%s%s", \
1161 btf_show_indent(show), \
1162 btf_show_name(show), \
1163 value, btf_show_delim(show), \
1164 btf_show_newline(show)); \
1165 if (show->state.depth > show->state.depth_to_show) \
1166 show->state.depth_to_show = show->state.depth; \
1170 #define btf_show_type_values(show, fmt, ...) \
1172 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1173 btf_show_name(show), \
1174 __VA_ARGS__, btf_show_delim(show), \
1175 btf_show_newline(show)); \
1176 if (show->state.depth > show->state.depth_to_show) \
1177 show->state.depth_to_show = show->state.depth; \
1180 /* How much is left to copy to safe buffer after @data? */
1181 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1183 return show->obj.head + show->obj.size - data;
1186 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1187 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1189 return data >= show->obj.data &&
1190 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1194 * If object pointed to by @data of @size falls within our safe buffer, return
1195 * the equivalent pointer to the same safe data. Assumes
1196 * copy_from_kernel_nofault() has already happened and our safe buffer is
1199 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1201 if (btf_show_obj_is_safe(show, data, size))
1202 return show->obj.safe + (data - show->obj.data);
1207 * Return a safe-to-access version of data pointed to by @data.
1208 * We do this by copying the relevant amount of information
1209 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1211 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1212 * safe copy is needed.
1214 * Otherwise we need to determine if we have the required amount
1215 * of data (determined by the @data pointer and the size of the
1216 * largest base type we can encounter (represented by
1217 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1218 * that we will be able to print some of the current object,
1219 * and if more is needed a copy will be triggered.
1220 * Some objects such as structs will not fit into the buffer;
1221 * in such cases additional copies when we iterate over their
1222 * members may be needed.
1224 * btf_show_obj_safe() is used to return a safe buffer for
1225 * btf_show_start_type(); this ensures that as we recurse into
1226 * nested types we always have safe data for the given type.
1227 * This approach is somewhat wasteful; it's possible for example
1228 * that when iterating over a large union we'll end up copying the
1229 * same data repeatedly, but the goal is safety not performance.
1230 * We use stack data as opposed to per-CPU buffers because the
1231 * iteration over a type can take some time, and preemption handling
1232 * would greatly complicate use of the safe buffer.
1234 static void *btf_show_obj_safe(struct btf_show *show,
1235 const struct btf_type *t,
1238 const struct btf_type *rt;
1239 int size_left, size;
1242 if (show->flags & BTF_SHOW_UNSAFE)
1245 rt = btf_resolve_size(show->btf, t, &size);
1247 show->state.status = PTR_ERR(rt);
1252 * Is this toplevel object? If so, set total object size and
1253 * initialize pointers. Otherwise check if we still fall within
1254 * our safe object data.
1256 if (show->state.depth == 0) {
1257 show->obj.size = size;
1258 show->obj.head = data;
1261 * If the size of the current object is > our remaining
1262 * safe buffer we _may_ need to do a new copy. However
1263 * consider the case of a nested struct; it's size pushes
1264 * us over the safe buffer limit, but showing any individual
1265 * struct members does not. In such cases, we don't need
1266 * to initiate a fresh copy yet; however we definitely need
1267 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1268 * in our buffer, regardless of the current object size.
1269 * The logic here is that as we resolve types we will
1270 * hit a base type at some point, and we need to be sure
1271 * the next chunk of data is safely available to display
1272 * that type info safely. We cannot rely on the size of
1273 * the current object here because it may be much larger
1274 * than our current buffer (e.g. task_struct is 8k).
1275 * All we want to do here is ensure that we can print the
1276 * next basic type, which we can if either
1277 * - the current type size is within the safe buffer; or
1278 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1281 safe = __btf_show_obj_safe(show, data,
1283 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1287 * We need a new copy to our safe object, either because we haven't
1288 * yet copied and are initializing safe data, or because the data
1289 * we want falls outside the boundaries of the safe object.
1292 size_left = btf_show_obj_size_left(show, data);
1293 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1294 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1295 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1297 if (!show->state.status) {
1298 show->obj.data = data;
1299 safe = show->obj.safe;
1307 * Set the type we are starting to show and return a safe data pointer
1308 * to be used for showing the associated data.
1310 static void *btf_show_start_type(struct btf_show *show,
1311 const struct btf_type *t,
1312 u32 type_id, void *data)
1314 show->state.type = t;
1315 show->state.type_id = type_id;
1316 show->state.name[0] = '\0';
1318 return btf_show_obj_safe(show, t, data);
1321 static void btf_show_end_type(struct btf_show *show)
1323 show->state.type = NULL;
1324 show->state.type_id = 0;
1325 show->state.name[0] = '\0';
1328 static void *btf_show_start_aggr_type(struct btf_show *show,
1329 const struct btf_type *t,
1330 u32 type_id, void *data)
1332 void *safe_data = btf_show_start_type(show, t, type_id, data);
1337 btf_show(show, "%s%s%s", btf_show_indent(show),
1338 btf_show_name(show),
1339 btf_show_newline(show));
1340 show->state.depth++;
1344 static void btf_show_end_aggr_type(struct btf_show *show,
1347 show->state.depth--;
1348 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1349 btf_show_delim(show), btf_show_newline(show));
1350 btf_show_end_type(show);
1353 static void btf_show_start_member(struct btf_show *show,
1354 const struct btf_member *m)
1356 show->state.member = m;
1359 static void btf_show_start_array_member(struct btf_show *show)
1361 show->state.array_member = 1;
1362 btf_show_start_member(show, NULL);
1365 static void btf_show_end_member(struct btf_show *show)
1367 show->state.member = NULL;
1370 static void btf_show_end_array_member(struct btf_show *show)
1372 show->state.array_member = 0;
1373 btf_show_end_member(show);
1376 static void *btf_show_start_array_type(struct btf_show *show,
1377 const struct btf_type *t,
1382 show->state.array_encoding = array_encoding;
1383 show->state.array_terminated = 0;
1384 return btf_show_start_aggr_type(show, t, type_id, data);
1387 static void btf_show_end_array_type(struct btf_show *show)
1389 show->state.array_encoding = 0;
1390 show->state.array_terminated = 0;
1391 btf_show_end_aggr_type(show, "]");
1394 static void *btf_show_start_struct_type(struct btf_show *show,
1395 const struct btf_type *t,
1399 return btf_show_start_aggr_type(show, t, type_id, data);
1402 static void btf_show_end_struct_type(struct btf_show *show)
1404 btf_show_end_aggr_type(show, "}");
1407 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1408 const char *fmt, ...)
1412 va_start(args, fmt);
1413 bpf_verifier_vlog(log, fmt, args);
1417 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1418 const char *fmt, ...)
1420 struct bpf_verifier_log *log = &env->log;
1423 if (!bpf_verifier_log_needed(log))
1426 va_start(args, fmt);
1427 bpf_verifier_vlog(log, fmt, args);
1431 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1432 const struct btf_type *t,
1434 const char *fmt, ...)
1436 struct bpf_verifier_log *log = &env->log;
1437 struct btf *btf = env->btf;
1440 if (!bpf_verifier_log_needed(log))
1443 if (log->level == BPF_LOG_KERNEL) {
1444 /* btf verifier prints all types it is processing via
1445 * btf_verifier_log_type(..., fmt = NULL).
1446 * Skip those prints for in-kernel BTF verification.
1451 /* Skip logging when loading module BTF with mismatches permitted */
1452 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1456 __btf_verifier_log(log, "[%u] %s %s%s",
1459 __btf_name_by_offset(btf, t->name_off),
1460 log_details ? " " : "");
1463 btf_type_ops(t)->log_details(env, t);
1466 __btf_verifier_log(log, " ");
1467 va_start(args, fmt);
1468 bpf_verifier_vlog(log, fmt, args);
1472 __btf_verifier_log(log, "\n");
1475 #define btf_verifier_log_type(env, t, ...) \
1476 __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1477 #define btf_verifier_log_basic(env, t, ...) \
1478 __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1481 static void btf_verifier_log_member(struct btf_verifier_env *env,
1482 const struct btf_type *struct_type,
1483 const struct btf_member *member,
1484 const char *fmt, ...)
1486 struct bpf_verifier_log *log = &env->log;
1487 struct btf *btf = env->btf;
1490 if (!bpf_verifier_log_needed(log))
1493 if (log->level == BPF_LOG_KERNEL) {
1497 /* Skip logging when loading module BTF with mismatches permitted */
1498 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1502 /* The CHECK_META phase already did a btf dump.
1504 * If member is logged again, it must hit an error in
1505 * parsing this member. It is useful to print out which
1506 * struct this member belongs to.
1508 if (env->phase != CHECK_META)
1509 btf_verifier_log_type(env, struct_type, NULL);
1511 if (btf_type_kflag(struct_type))
1512 __btf_verifier_log(log,
1513 "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1514 __btf_name_by_offset(btf, member->name_off),
1516 BTF_MEMBER_BITFIELD_SIZE(member->offset),
1517 BTF_MEMBER_BIT_OFFSET(member->offset));
1519 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1520 __btf_name_by_offset(btf, member->name_off),
1521 member->type, member->offset);
1524 __btf_verifier_log(log, " ");
1525 va_start(args, fmt);
1526 bpf_verifier_vlog(log, fmt, args);
1530 __btf_verifier_log(log, "\n");
1534 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1535 const struct btf_type *datasec_type,
1536 const struct btf_var_secinfo *vsi,
1537 const char *fmt, ...)
1539 struct bpf_verifier_log *log = &env->log;
1542 if (!bpf_verifier_log_needed(log))
1544 if (log->level == BPF_LOG_KERNEL && !fmt)
1546 if (env->phase != CHECK_META)
1547 btf_verifier_log_type(env, datasec_type, NULL);
1549 __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1550 vsi->type, vsi->offset, vsi->size);
1552 __btf_verifier_log(log, " ");
1553 va_start(args, fmt);
1554 bpf_verifier_vlog(log, fmt, args);
1558 __btf_verifier_log(log, "\n");
1561 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1564 struct bpf_verifier_log *log = &env->log;
1565 const struct btf *btf = env->btf;
1566 const struct btf_header *hdr;
1568 if (!bpf_verifier_log_needed(log))
1571 if (log->level == BPF_LOG_KERNEL)
1574 __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1575 __btf_verifier_log(log, "version: %u\n", hdr->version);
1576 __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1577 __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1578 __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1579 __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1580 __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1581 __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1582 __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1585 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1587 struct btf *btf = env->btf;
1589 if (btf->types_size == btf->nr_types) {
1590 /* Expand 'types' array */
1592 struct btf_type **new_types;
1593 u32 expand_by, new_size;
1595 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1596 btf_verifier_log(env, "Exceeded max num of types");
1600 expand_by = max_t(u32, btf->types_size >> 2, 16);
1601 new_size = min_t(u32, BTF_MAX_TYPE,
1602 btf->types_size + expand_by);
1604 new_types = kvcalloc(new_size, sizeof(*new_types),
1605 GFP_KERNEL | __GFP_NOWARN);
1609 if (btf->nr_types == 0) {
1610 if (!btf->base_btf) {
1611 /* lazily init VOID type */
1612 new_types[0] = &btf_void;
1616 memcpy(new_types, btf->types,
1617 sizeof(*btf->types) * btf->nr_types);
1621 btf->types = new_types;
1622 btf->types_size = new_size;
1625 btf->types[btf->nr_types++] = t;
1630 static int btf_alloc_id(struct btf *btf)
1634 idr_preload(GFP_KERNEL);
1635 spin_lock_bh(&btf_idr_lock);
1636 id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1639 spin_unlock_bh(&btf_idr_lock);
1642 if (WARN_ON_ONCE(!id))
1645 return id > 0 ? 0 : id;
1648 static void btf_free_id(struct btf *btf)
1650 unsigned long flags;
1653 * In map-in-map, calling map_delete_elem() on outer
1654 * map will call bpf_map_put on the inner map.
1655 * It will then eventually call btf_free_id()
1656 * on the inner map. Some of the map_delete_elem()
1657 * implementation may have irq disabled, so
1658 * we need to use the _irqsave() version instead
1659 * of the _bh() version.
1661 spin_lock_irqsave(&btf_idr_lock, flags);
1662 idr_remove(&btf_idr, btf->id);
1663 spin_unlock_irqrestore(&btf_idr_lock, flags);
1666 static void btf_free_kfunc_set_tab(struct btf *btf)
1668 struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1673 /* For module BTF, we directly assign the sets being registered, so
1674 * there is nothing to free except kfunc_set_tab.
1676 if (btf_is_module(btf))
1678 for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1679 kfree(tab->sets[hook]);
1682 btf->kfunc_set_tab = NULL;
1685 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1687 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1692 btf->dtor_kfunc_tab = NULL;
1695 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1701 for (i = 0; i < tab->cnt; i++)
1702 btf_record_free(tab->types[i].record);
1706 static void btf_free_struct_meta_tab(struct btf *btf)
1708 struct btf_struct_metas *tab = btf->struct_meta_tab;
1710 btf_struct_metas_free(tab);
1711 btf->struct_meta_tab = NULL;
1714 static void btf_free_struct_ops_tab(struct btf *btf)
1716 struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1722 for (i = 0; i < tab->cnt; i++)
1723 bpf_struct_ops_desc_release(&tab->ops[i]);
1726 btf->struct_ops_tab = NULL;
1729 static void btf_free(struct btf *btf)
1731 btf_free_struct_meta_tab(btf);
1732 btf_free_dtor_kfunc_tab(btf);
1733 btf_free_kfunc_set_tab(btf);
1734 btf_free_struct_ops_tab(btf);
1736 kvfree(btf->resolved_sizes);
1737 kvfree(btf->resolved_ids);
1742 static void btf_free_rcu(struct rcu_head *rcu)
1744 struct btf *btf = container_of(rcu, struct btf, rcu);
1749 const char *btf_get_name(const struct btf *btf)
1754 void btf_get(struct btf *btf)
1756 refcount_inc(&btf->refcnt);
1759 void btf_put(struct btf *btf)
1761 if (btf && refcount_dec_and_test(&btf->refcnt)) {
1763 call_rcu(&btf->rcu, btf_free_rcu);
1767 static int env_resolve_init(struct btf_verifier_env *env)
1769 struct btf *btf = env->btf;
1770 u32 nr_types = btf->nr_types;
1771 u32 *resolved_sizes = NULL;
1772 u32 *resolved_ids = NULL;
1773 u8 *visit_states = NULL;
1775 resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1776 GFP_KERNEL | __GFP_NOWARN);
1777 if (!resolved_sizes)
1780 resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1781 GFP_KERNEL | __GFP_NOWARN);
1785 visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1786 GFP_KERNEL | __GFP_NOWARN);
1790 btf->resolved_sizes = resolved_sizes;
1791 btf->resolved_ids = resolved_ids;
1792 env->visit_states = visit_states;
1797 kvfree(resolved_sizes);
1798 kvfree(resolved_ids);
1799 kvfree(visit_states);
1803 static void btf_verifier_env_free(struct btf_verifier_env *env)
1805 kvfree(env->visit_states);
1809 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1810 const struct btf_type *next_type)
1812 switch (env->resolve_mode) {
1814 /* int, enum or void is a sink */
1815 return !btf_type_needs_resolve(next_type);
1817 /* int, enum, void, struct, array, func or func_proto is a sink
1820 return !btf_type_is_modifier(next_type) &&
1821 !btf_type_is_ptr(next_type);
1822 case RESOLVE_STRUCT_OR_ARRAY:
1823 /* int, enum, void, ptr, func or func_proto is a sink
1824 * for struct and array
1826 return !btf_type_is_modifier(next_type) &&
1827 !btf_type_is_array(next_type) &&
1828 !btf_type_is_struct(next_type);
1834 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1837 /* base BTF types should be resolved by now */
1838 if (type_id < env->btf->start_id)
1841 return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1844 static int env_stack_push(struct btf_verifier_env *env,
1845 const struct btf_type *t, u32 type_id)
1847 const struct btf *btf = env->btf;
1848 struct resolve_vertex *v;
1850 if (env->top_stack == MAX_RESOLVE_DEPTH)
1853 if (type_id < btf->start_id
1854 || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1857 env->visit_states[type_id - btf->start_id] = VISITED;
1859 v = &env->stack[env->top_stack++];
1861 v->type_id = type_id;
1864 if (env->resolve_mode == RESOLVE_TBD) {
1865 if (btf_type_is_ptr(t))
1866 env->resolve_mode = RESOLVE_PTR;
1867 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1868 env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1874 static void env_stack_set_next_member(struct btf_verifier_env *env,
1877 env->stack[env->top_stack - 1].next_member = next_member;
1880 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1881 u32 resolved_type_id,
1884 u32 type_id = env->stack[--(env->top_stack)].type_id;
1885 struct btf *btf = env->btf;
1887 type_id -= btf->start_id; /* adjust to local type id */
1888 btf->resolved_sizes[type_id] = resolved_size;
1889 btf->resolved_ids[type_id] = resolved_type_id;
1890 env->visit_states[type_id] = RESOLVED;
1893 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1895 return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1898 /* Resolve the size of a passed-in "type"
1900 * type: is an array (e.g. u32 array[x][y])
1901 * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1902 * *type_size: (x * y * sizeof(u32)). Hence, *type_size always
1903 * corresponds to the return type.
1905 * *elem_id: id of u32
1906 * *total_nelems: (x * y). Hence, individual elem size is
1907 * (*type_size / *total_nelems)
1908 * *type_id: id of type if it's changed within the function, 0 if not
1910 * type: is not an array (e.g. const struct X)
1911 * return type: type "struct X"
1912 * *type_size: sizeof(struct X)
1913 * *elem_type: same as return type ("struct X")
1916 * *type_id: id of type if it's changed within the function, 0 if not
1918 static const struct btf_type *
1919 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1920 u32 *type_size, const struct btf_type **elem_type,
1921 u32 *elem_id, u32 *total_nelems, u32 *type_id)
1923 const struct btf_type *array_type = NULL;
1924 const struct btf_array *array = NULL;
1925 u32 i, size, nelems = 1, id = 0;
1927 for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1928 switch (BTF_INFO_KIND(type->info)) {
1929 /* type->size can be used */
1931 case BTF_KIND_STRUCT:
1932 case BTF_KIND_UNION:
1934 case BTF_KIND_FLOAT:
1935 case BTF_KIND_ENUM64:
1940 size = sizeof(void *);
1944 case BTF_KIND_TYPEDEF:
1945 case BTF_KIND_VOLATILE:
1946 case BTF_KIND_CONST:
1947 case BTF_KIND_RESTRICT:
1948 case BTF_KIND_TYPE_TAG:
1950 type = btf_type_by_id(btf, type->type);
1953 case BTF_KIND_ARRAY:
1956 array = btf_type_array(type);
1957 if (nelems && array->nelems > U32_MAX / nelems)
1958 return ERR_PTR(-EINVAL);
1959 nelems *= array->nelems;
1960 type = btf_type_by_id(btf, array->type);
1963 /* type without size */
1965 return ERR_PTR(-EINVAL);
1969 return ERR_PTR(-EINVAL);
1972 if (nelems && size > U32_MAX / nelems)
1973 return ERR_PTR(-EINVAL);
1975 *type_size = nelems * size;
1977 *total_nelems = nelems;
1981 *elem_id = array ? array->type : 0;
1985 return array_type ? : type;
1988 const struct btf_type *
1989 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1992 return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1995 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1997 while (type_id < btf->start_id)
1998 btf = btf->base_btf;
2000 return btf->resolved_ids[type_id - btf->start_id];
2003 /* The input param "type_id" must point to a needs_resolve type */
2004 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
2007 *type_id = btf_resolved_type_id(btf, *type_id);
2008 return btf_type_by_id(btf, *type_id);
2011 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2013 while (type_id < btf->start_id)
2014 btf = btf->base_btf;
2016 return btf->resolved_sizes[type_id - btf->start_id];
2019 const struct btf_type *btf_type_id_size(const struct btf *btf,
2020 u32 *type_id, u32 *ret_size)
2022 const struct btf_type *size_type;
2023 u32 size_type_id = *type_id;
2026 size_type = btf_type_by_id(btf, size_type_id);
2027 if (btf_type_nosize_or_null(size_type))
2030 if (btf_type_has_size(size_type)) {
2031 size = size_type->size;
2032 } else if (btf_type_is_array(size_type)) {
2033 size = btf_resolved_type_size(btf, size_type_id);
2034 } else if (btf_type_is_ptr(size_type)) {
2035 size = sizeof(void *);
2037 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2038 !btf_type_is_var(size_type)))
2041 size_type_id = btf_resolved_type_id(btf, size_type_id);
2042 size_type = btf_type_by_id(btf, size_type_id);
2043 if (btf_type_nosize_or_null(size_type))
2045 else if (btf_type_has_size(size_type))
2046 size = size_type->size;
2047 else if (btf_type_is_array(size_type))
2048 size = btf_resolved_type_size(btf, size_type_id);
2049 else if (btf_type_is_ptr(size_type))
2050 size = sizeof(void *);
2055 *type_id = size_type_id;
2062 static int btf_df_check_member(struct btf_verifier_env *env,
2063 const struct btf_type *struct_type,
2064 const struct btf_member *member,
2065 const struct btf_type *member_type)
2067 btf_verifier_log_basic(env, struct_type,
2068 "Unsupported check_member");
2072 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2073 const struct btf_type *struct_type,
2074 const struct btf_member *member,
2075 const struct btf_type *member_type)
2077 btf_verifier_log_basic(env, struct_type,
2078 "Unsupported check_kflag_member");
2082 /* Used for ptr, array struct/union and float type members.
2083 * int, enum and modifier types have their specific callback functions.
2085 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2086 const struct btf_type *struct_type,
2087 const struct btf_member *member,
2088 const struct btf_type *member_type)
2090 if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2091 btf_verifier_log_member(env, struct_type, member,
2092 "Invalid member bitfield_size");
2096 /* bitfield size is 0, so member->offset represents bit offset only.
2097 * It is safe to call non kflag check_member variants.
2099 return btf_type_ops(member_type)->check_member(env, struct_type,
2104 static int btf_df_resolve(struct btf_verifier_env *env,
2105 const struct resolve_vertex *v)
2107 btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2111 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2112 u32 type_id, void *data, u8 bits_offsets,
2113 struct btf_show *show)
2115 btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2118 static int btf_int_check_member(struct btf_verifier_env *env,
2119 const struct btf_type *struct_type,
2120 const struct btf_member *member,
2121 const struct btf_type *member_type)
2123 u32 int_data = btf_type_int(member_type);
2124 u32 struct_bits_off = member->offset;
2125 u32 struct_size = struct_type->size;
2129 if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2130 btf_verifier_log_member(env, struct_type, member,
2131 "bits_offset exceeds U32_MAX");
2135 struct_bits_off += BTF_INT_OFFSET(int_data);
2136 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2137 nr_copy_bits = BTF_INT_BITS(int_data) +
2138 BITS_PER_BYTE_MASKED(struct_bits_off);
2140 if (nr_copy_bits > BITS_PER_U128) {
2141 btf_verifier_log_member(env, struct_type, member,
2142 "nr_copy_bits exceeds 128");
2146 if (struct_size < bytes_offset ||
2147 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2148 btf_verifier_log_member(env, struct_type, member,
2149 "Member exceeds struct_size");
2156 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2157 const struct btf_type *struct_type,
2158 const struct btf_member *member,
2159 const struct btf_type *member_type)
2161 u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2162 u32 int_data = btf_type_int(member_type);
2163 u32 struct_size = struct_type->size;
2166 /* a regular int type is required for the kflag int member */
2167 if (!btf_type_int_is_regular(member_type)) {
2168 btf_verifier_log_member(env, struct_type, member,
2169 "Invalid member base type");
2173 /* check sanity of bitfield size */
2174 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2175 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2176 nr_int_data_bits = BTF_INT_BITS(int_data);
2178 /* Not a bitfield member, member offset must be at byte
2181 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2182 btf_verifier_log_member(env, struct_type, member,
2183 "Invalid member offset");
2187 nr_bits = nr_int_data_bits;
2188 } else if (nr_bits > nr_int_data_bits) {
2189 btf_verifier_log_member(env, struct_type, member,
2190 "Invalid member bitfield_size");
2194 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2195 nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2196 if (nr_copy_bits > BITS_PER_U128) {
2197 btf_verifier_log_member(env, struct_type, member,
2198 "nr_copy_bits exceeds 128");
2202 if (struct_size < bytes_offset ||
2203 struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2204 btf_verifier_log_member(env, struct_type, member,
2205 "Member exceeds struct_size");
2212 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2213 const struct btf_type *t,
2216 u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2219 if (meta_left < meta_needed) {
2220 btf_verifier_log_basic(env, t,
2221 "meta_left:%u meta_needed:%u",
2222 meta_left, meta_needed);
2226 if (btf_type_vlen(t)) {
2227 btf_verifier_log_type(env, t, "vlen != 0");
2231 if (btf_type_kflag(t)) {
2232 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2236 int_data = btf_type_int(t);
2237 if (int_data & ~BTF_INT_MASK) {
2238 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2243 nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2245 if (nr_bits > BITS_PER_U128) {
2246 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2251 if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2252 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2257 * Only one of the encoding bits is allowed and it
2258 * should be sufficient for the pretty print purpose (i.e. decoding).
2259 * Multiple bits can be allowed later if it is found
2260 * to be insufficient.
2262 encoding = BTF_INT_ENCODING(int_data);
2264 encoding != BTF_INT_SIGNED &&
2265 encoding != BTF_INT_CHAR &&
2266 encoding != BTF_INT_BOOL) {
2267 btf_verifier_log_type(env, t, "Unsupported encoding");
2271 btf_verifier_log_type(env, t, NULL);
2276 static void btf_int_log(struct btf_verifier_env *env,
2277 const struct btf_type *t)
2279 int int_data = btf_type_int(t);
2281 btf_verifier_log(env,
2282 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2283 t->size, BTF_INT_OFFSET(int_data),
2284 BTF_INT_BITS(int_data),
2285 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2288 static void btf_int128_print(struct btf_show *show, void *data)
2290 /* data points to a __int128 number.
2292 * int128_num = *(__int128 *)data;
2293 * The below formulas shows what upper_num and lower_num represents:
2294 * upper_num = int128_num >> 64;
2295 * lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2297 u64 upper_num, lower_num;
2299 #ifdef __BIG_ENDIAN_BITFIELD
2300 upper_num = *(u64 *)data;
2301 lower_num = *(u64 *)(data + 8);
2303 upper_num = *(u64 *)(data + 8);
2304 lower_num = *(u64 *)data;
2307 btf_show_type_value(show, "0x%llx", lower_num);
2309 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2313 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2314 u16 right_shift_bits)
2316 u64 upper_num, lower_num;
2318 #ifdef __BIG_ENDIAN_BITFIELD
2319 upper_num = print_num[0];
2320 lower_num = print_num[1];
2322 upper_num = print_num[1];
2323 lower_num = print_num[0];
2326 /* shake out un-needed bits by shift/or operations */
2327 if (left_shift_bits >= 64) {
2328 upper_num = lower_num << (left_shift_bits - 64);
2331 upper_num = (upper_num << left_shift_bits) |
2332 (lower_num >> (64 - left_shift_bits));
2333 lower_num = lower_num << left_shift_bits;
2336 if (right_shift_bits >= 64) {
2337 lower_num = upper_num >> (right_shift_bits - 64);
2340 lower_num = (lower_num >> right_shift_bits) |
2341 (upper_num << (64 - right_shift_bits));
2342 upper_num = upper_num >> right_shift_bits;
2345 #ifdef __BIG_ENDIAN_BITFIELD
2346 print_num[0] = upper_num;
2347 print_num[1] = lower_num;
2349 print_num[0] = lower_num;
2350 print_num[1] = upper_num;
2354 static void btf_bitfield_show(void *data, u8 bits_offset,
2355 u8 nr_bits, struct btf_show *show)
2357 u16 left_shift_bits, right_shift_bits;
2360 u64 print_num[2] = {};
2362 nr_copy_bits = nr_bits + bits_offset;
2363 nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2365 memcpy(print_num, data, nr_copy_bytes);
2367 #ifdef __BIG_ENDIAN_BITFIELD
2368 left_shift_bits = bits_offset;
2370 left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2372 right_shift_bits = BITS_PER_U128 - nr_bits;
2374 btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2375 btf_int128_print(show, print_num);
2379 static void btf_int_bits_show(const struct btf *btf,
2380 const struct btf_type *t,
2381 void *data, u8 bits_offset,
2382 struct btf_show *show)
2384 u32 int_data = btf_type_int(t);
2385 u8 nr_bits = BTF_INT_BITS(int_data);
2386 u8 total_bits_offset;
2389 * bits_offset is at most 7.
2390 * BTF_INT_OFFSET() cannot exceed 128 bits.
2392 total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2393 data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2394 bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2395 btf_bitfield_show(data, bits_offset, nr_bits, show);
2398 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2399 u32 type_id, void *data, u8 bits_offset,
2400 struct btf_show *show)
2402 u32 int_data = btf_type_int(t);
2403 u8 encoding = BTF_INT_ENCODING(int_data);
2404 bool sign = encoding & BTF_INT_SIGNED;
2405 u8 nr_bits = BTF_INT_BITS(int_data);
2408 safe_data = btf_show_start_type(show, t, type_id, data);
2412 if (bits_offset || BTF_INT_OFFSET(int_data) ||
2413 BITS_PER_BYTE_MASKED(nr_bits)) {
2414 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2420 btf_int128_print(show, safe_data);
2424 btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2426 btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2430 btf_show_type_value(show, "%d", *(s32 *)safe_data);
2432 btf_show_type_value(show, "%u", *(u32 *)safe_data);
2436 btf_show_type_value(show, "%d", *(s16 *)safe_data);
2438 btf_show_type_value(show, "%u", *(u16 *)safe_data);
2441 if (show->state.array_encoding == BTF_INT_CHAR) {
2442 /* check for null terminator */
2443 if (show->state.array_terminated)
2445 if (*(char *)data == '\0') {
2446 show->state.array_terminated = 1;
2449 if (isprint(*(char *)data)) {
2450 btf_show_type_value(show, "'%c'",
2451 *(char *)safe_data);
2456 btf_show_type_value(show, "%d", *(s8 *)safe_data);
2458 btf_show_type_value(show, "%u", *(u8 *)safe_data);
2461 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2465 btf_show_end_type(show);
2468 static const struct btf_kind_operations int_ops = {
2469 .check_meta = btf_int_check_meta,
2470 .resolve = btf_df_resolve,
2471 .check_member = btf_int_check_member,
2472 .check_kflag_member = btf_int_check_kflag_member,
2473 .log_details = btf_int_log,
2474 .show = btf_int_show,
2477 static int btf_modifier_check_member(struct btf_verifier_env *env,
2478 const struct btf_type *struct_type,
2479 const struct btf_member *member,
2480 const struct btf_type *member_type)
2482 const struct btf_type *resolved_type;
2483 u32 resolved_type_id = member->type;
2484 struct btf_member resolved_member;
2485 struct btf *btf = env->btf;
2487 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2488 if (!resolved_type) {
2489 btf_verifier_log_member(env, struct_type, member,
2494 resolved_member = *member;
2495 resolved_member.type = resolved_type_id;
2497 return btf_type_ops(resolved_type)->check_member(env, struct_type,
2502 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2503 const struct btf_type *struct_type,
2504 const struct btf_member *member,
2505 const struct btf_type *member_type)
2507 const struct btf_type *resolved_type;
2508 u32 resolved_type_id = member->type;
2509 struct btf_member resolved_member;
2510 struct btf *btf = env->btf;
2512 resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2513 if (!resolved_type) {
2514 btf_verifier_log_member(env, struct_type, member,
2519 resolved_member = *member;
2520 resolved_member.type = resolved_type_id;
2522 return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2527 static int btf_ptr_check_member(struct btf_verifier_env *env,
2528 const struct btf_type *struct_type,
2529 const struct btf_member *member,
2530 const struct btf_type *member_type)
2532 u32 struct_size, struct_bits_off, bytes_offset;
2534 struct_size = struct_type->size;
2535 struct_bits_off = member->offset;
2536 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2538 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2539 btf_verifier_log_member(env, struct_type, member,
2540 "Member is not byte aligned");
2544 if (struct_size - bytes_offset < sizeof(void *)) {
2545 btf_verifier_log_member(env, struct_type, member,
2546 "Member exceeds struct_size");
2553 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2554 const struct btf_type *t,
2559 if (btf_type_vlen(t)) {
2560 btf_verifier_log_type(env, t, "vlen != 0");
2564 if (btf_type_kflag(t)) {
2565 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2569 if (!BTF_TYPE_ID_VALID(t->type)) {
2570 btf_verifier_log_type(env, t, "Invalid type_id");
2574 /* typedef/type_tag type must have a valid name, and other ref types,
2575 * volatile, const, restrict, should have a null name.
2577 if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2579 !btf_name_valid_identifier(env->btf, t->name_off)) {
2580 btf_verifier_log_type(env, t, "Invalid name");
2583 } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2584 value = btf_name_by_offset(env->btf, t->name_off);
2585 if (!value || !value[0]) {
2586 btf_verifier_log_type(env, t, "Invalid name");
2591 btf_verifier_log_type(env, t, "Invalid name");
2596 btf_verifier_log_type(env, t, NULL);
2601 static int btf_modifier_resolve(struct btf_verifier_env *env,
2602 const struct resolve_vertex *v)
2604 const struct btf_type *t = v->t;
2605 const struct btf_type *next_type;
2606 u32 next_type_id = t->type;
2607 struct btf *btf = env->btf;
2609 next_type = btf_type_by_id(btf, next_type_id);
2610 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2611 btf_verifier_log_type(env, v->t, "Invalid type_id");
2615 if (!env_type_is_resolve_sink(env, next_type) &&
2616 !env_type_is_resolved(env, next_type_id))
2617 return env_stack_push(env, next_type, next_type_id);
2619 /* Figure out the resolved next_type_id with size.
2620 * They will be stored in the current modifier's
2621 * resolved_ids and resolved_sizes such that it can
2622 * save us a few type-following when we use it later (e.g. in
2625 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2626 if (env_type_is_resolved(env, next_type_id))
2627 next_type = btf_type_id_resolve(btf, &next_type_id);
2629 /* "typedef void new_void", "const void"...etc */
2630 if (!btf_type_is_void(next_type) &&
2631 !btf_type_is_fwd(next_type) &&
2632 !btf_type_is_func_proto(next_type)) {
2633 btf_verifier_log_type(env, v->t, "Invalid type_id");
2638 env_stack_pop_resolved(env, next_type_id, 0);
2643 static int btf_var_resolve(struct btf_verifier_env *env,
2644 const struct resolve_vertex *v)
2646 const struct btf_type *next_type;
2647 const struct btf_type *t = v->t;
2648 u32 next_type_id = t->type;
2649 struct btf *btf = env->btf;
2651 next_type = btf_type_by_id(btf, next_type_id);
2652 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2653 btf_verifier_log_type(env, v->t, "Invalid type_id");
2657 if (!env_type_is_resolve_sink(env, next_type) &&
2658 !env_type_is_resolved(env, next_type_id))
2659 return env_stack_push(env, next_type, next_type_id);
2661 if (btf_type_is_modifier(next_type)) {
2662 const struct btf_type *resolved_type;
2663 u32 resolved_type_id;
2665 resolved_type_id = next_type_id;
2666 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2668 if (btf_type_is_ptr(resolved_type) &&
2669 !env_type_is_resolve_sink(env, resolved_type) &&
2670 !env_type_is_resolved(env, resolved_type_id))
2671 return env_stack_push(env, resolved_type,
2675 /* We must resolve to something concrete at this point, no
2676 * forward types or similar that would resolve to size of
2679 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2680 btf_verifier_log_type(env, v->t, "Invalid type_id");
2684 env_stack_pop_resolved(env, next_type_id, 0);
2689 static int btf_ptr_resolve(struct btf_verifier_env *env,
2690 const struct resolve_vertex *v)
2692 const struct btf_type *next_type;
2693 const struct btf_type *t = v->t;
2694 u32 next_type_id = t->type;
2695 struct btf *btf = env->btf;
2697 next_type = btf_type_by_id(btf, next_type_id);
2698 if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2699 btf_verifier_log_type(env, v->t, "Invalid type_id");
2703 if (!env_type_is_resolve_sink(env, next_type) &&
2704 !env_type_is_resolved(env, next_type_id))
2705 return env_stack_push(env, next_type, next_type_id);
2707 /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2708 * the modifier may have stopped resolving when it was resolved
2709 * to a ptr (last-resolved-ptr).
2711 * We now need to continue from the last-resolved-ptr to
2712 * ensure the last-resolved-ptr will not referring back to
2713 * the current ptr (t).
2715 if (btf_type_is_modifier(next_type)) {
2716 const struct btf_type *resolved_type;
2717 u32 resolved_type_id;
2719 resolved_type_id = next_type_id;
2720 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2722 if (btf_type_is_ptr(resolved_type) &&
2723 !env_type_is_resolve_sink(env, resolved_type) &&
2724 !env_type_is_resolved(env, resolved_type_id))
2725 return env_stack_push(env, resolved_type,
2729 if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2730 if (env_type_is_resolved(env, next_type_id))
2731 next_type = btf_type_id_resolve(btf, &next_type_id);
2733 if (!btf_type_is_void(next_type) &&
2734 !btf_type_is_fwd(next_type) &&
2735 !btf_type_is_func_proto(next_type)) {
2736 btf_verifier_log_type(env, v->t, "Invalid type_id");
2741 env_stack_pop_resolved(env, next_type_id, 0);
2746 static void btf_modifier_show(const struct btf *btf,
2747 const struct btf_type *t,
2748 u32 type_id, void *data,
2749 u8 bits_offset, struct btf_show *show)
2751 if (btf->resolved_ids)
2752 t = btf_type_id_resolve(btf, &type_id);
2754 t = btf_type_skip_modifiers(btf, type_id, NULL);
2756 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2759 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2760 u32 type_id, void *data, u8 bits_offset,
2761 struct btf_show *show)
2763 t = btf_type_id_resolve(btf, &type_id);
2765 btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2768 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2769 u32 type_id, void *data, u8 bits_offset,
2770 struct btf_show *show)
2774 safe_data = btf_show_start_type(show, t, type_id, data);
2778 /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2779 if (show->flags & BTF_SHOW_PTR_RAW)
2780 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2782 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2783 btf_show_end_type(show);
2786 static void btf_ref_type_log(struct btf_verifier_env *env,
2787 const struct btf_type *t)
2789 btf_verifier_log(env, "type_id=%u", t->type);
2792 static struct btf_kind_operations modifier_ops = {
2793 .check_meta = btf_ref_type_check_meta,
2794 .resolve = btf_modifier_resolve,
2795 .check_member = btf_modifier_check_member,
2796 .check_kflag_member = btf_modifier_check_kflag_member,
2797 .log_details = btf_ref_type_log,
2798 .show = btf_modifier_show,
2801 static struct btf_kind_operations ptr_ops = {
2802 .check_meta = btf_ref_type_check_meta,
2803 .resolve = btf_ptr_resolve,
2804 .check_member = btf_ptr_check_member,
2805 .check_kflag_member = btf_generic_check_kflag_member,
2806 .log_details = btf_ref_type_log,
2807 .show = btf_ptr_show,
2810 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2811 const struct btf_type *t,
2814 if (btf_type_vlen(t)) {
2815 btf_verifier_log_type(env, t, "vlen != 0");
2820 btf_verifier_log_type(env, t, "type != 0");
2824 /* fwd type must have a valid name */
2826 !btf_name_valid_identifier(env->btf, t->name_off)) {
2827 btf_verifier_log_type(env, t, "Invalid name");
2831 btf_verifier_log_type(env, t, NULL);
2836 static void btf_fwd_type_log(struct btf_verifier_env *env,
2837 const struct btf_type *t)
2839 btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2842 static struct btf_kind_operations fwd_ops = {
2843 .check_meta = btf_fwd_check_meta,
2844 .resolve = btf_df_resolve,
2845 .check_member = btf_df_check_member,
2846 .check_kflag_member = btf_df_check_kflag_member,
2847 .log_details = btf_fwd_type_log,
2848 .show = btf_df_show,
2851 static int btf_array_check_member(struct btf_verifier_env *env,
2852 const struct btf_type *struct_type,
2853 const struct btf_member *member,
2854 const struct btf_type *member_type)
2856 u32 struct_bits_off = member->offset;
2857 u32 struct_size, bytes_offset;
2858 u32 array_type_id, array_size;
2859 struct btf *btf = env->btf;
2861 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2862 btf_verifier_log_member(env, struct_type, member,
2863 "Member is not byte aligned");
2867 array_type_id = member->type;
2868 btf_type_id_size(btf, &array_type_id, &array_size);
2869 struct_size = struct_type->size;
2870 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2871 if (struct_size - bytes_offset < array_size) {
2872 btf_verifier_log_member(env, struct_type, member,
2873 "Member exceeds struct_size");
2880 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2881 const struct btf_type *t,
2884 const struct btf_array *array = btf_type_array(t);
2885 u32 meta_needed = sizeof(*array);
2887 if (meta_left < meta_needed) {
2888 btf_verifier_log_basic(env, t,
2889 "meta_left:%u meta_needed:%u",
2890 meta_left, meta_needed);
2894 /* array type should not have a name */
2896 btf_verifier_log_type(env, t, "Invalid name");
2900 if (btf_type_vlen(t)) {
2901 btf_verifier_log_type(env, t, "vlen != 0");
2905 if (btf_type_kflag(t)) {
2906 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2911 btf_verifier_log_type(env, t, "size != 0");
2915 /* Array elem type and index type cannot be in type void,
2916 * so !array->type and !array->index_type are not allowed.
2918 if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2919 btf_verifier_log_type(env, t, "Invalid elem");
2923 if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2924 btf_verifier_log_type(env, t, "Invalid index");
2928 btf_verifier_log_type(env, t, NULL);
2933 static int btf_array_resolve(struct btf_verifier_env *env,
2934 const struct resolve_vertex *v)
2936 const struct btf_array *array = btf_type_array(v->t);
2937 const struct btf_type *elem_type, *index_type;
2938 u32 elem_type_id, index_type_id;
2939 struct btf *btf = env->btf;
2942 /* Check array->index_type */
2943 index_type_id = array->index_type;
2944 index_type = btf_type_by_id(btf, index_type_id);
2945 if (btf_type_nosize_or_null(index_type) ||
2946 btf_type_is_resolve_source_only(index_type)) {
2947 btf_verifier_log_type(env, v->t, "Invalid index");
2951 if (!env_type_is_resolve_sink(env, index_type) &&
2952 !env_type_is_resolved(env, index_type_id))
2953 return env_stack_push(env, index_type, index_type_id);
2955 index_type = btf_type_id_size(btf, &index_type_id, NULL);
2956 if (!index_type || !btf_type_is_int(index_type) ||
2957 !btf_type_int_is_regular(index_type)) {
2958 btf_verifier_log_type(env, v->t, "Invalid index");
2962 /* Check array->type */
2963 elem_type_id = array->type;
2964 elem_type = btf_type_by_id(btf, elem_type_id);
2965 if (btf_type_nosize_or_null(elem_type) ||
2966 btf_type_is_resolve_source_only(elem_type)) {
2967 btf_verifier_log_type(env, v->t,
2972 if (!env_type_is_resolve_sink(env, elem_type) &&
2973 !env_type_is_resolved(env, elem_type_id))
2974 return env_stack_push(env, elem_type, elem_type_id);
2976 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2978 btf_verifier_log_type(env, v->t, "Invalid elem");
2982 if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2983 btf_verifier_log_type(env, v->t, "Invalid array of int");
2987 if (array->nelems && elem_size > U32_MAX / array->nelems) {
2988 btf_verifier_log_type(env, v->t,
2989 "Array size overflows U32_MAX");
2993 env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2998 static void btf_array_log(struct btf_verifier_env *env,
2999 const struct btf_type *t)
3001 const struct btf_array *array = btf_type_array(t);
3003 btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3004 array->type, array->index_type, array->nelems);
3007 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
3008 u32 type_id, void *data, u8 bits_offset,
3009 struct btf_show *show)
3011 const struct btf_array *array = btf_type_array(t);
3012 const struct btf_kind_operations *elem_ops;
3013 const struct btf_type *elem_type;
3014 u32 i, elem_size = 0, elem_type_id;
3017 elem_type_id = array->type;
3018 elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
3019 if (elem_type && btf_type_has_size(elem_type))
3020 elem_size = elem_type->size;
3022 if (elem_type && btf_type_is_int(elem_type)) {
3023 u32 int_type = btf_type_int(elem_type);
3025 encoding = BTF_INT_ENCODING(int_type);
3028 * BTF_INT_CHAR encoding never seems to be set for
3029 * char arrays, so if size is 1 and element is
3030 * printable as a char, we'll do that.
3033 encoding = BTF_INT_CHAR;
3036 if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3041 elem_ops = btf_type_ops(elem_type);
3043 for (i = 0; i < array->nelems; i++) {
3045 btf_show_start_array_member(show);
3047 elem_ops->show(btf, elem_type, elem_type_id, data,
3051 btf_show_end_array_member(show);
3053 if (show->state.array_terminated)
3057 btf_show_end_array_type(show);
3060 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3061 u32 type_id, void *data, u8 bits_offset,
3062 struct btf_show *show)
3064 const struct btf_member *m = show->state.member;
3067 * First check if any members would be shown (are non-zero).
3068 * See comments above "struct btf_show" definition for more
3069 * details on how this works at a high-level.
3071 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3072 if (!show->state.depth_check) {
3073 show->state.depth_check = show->state.depth + 1;
3074 show->state.depth_to_show = 0;
3076 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3077 show->state.member = m;
3079 if (show->state.depth_check != show->state.depth + 1)
3081 show->state.depth_check = 0;
3083 if (show->state.depth_to_show <= show->state.depth)
3086 * Reaching here indicates we have recursed and found
3087 * non-zero array member(s).
3090 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3093 static struct btf_kind_operations array_ops = {
3094 .check_meta = btf_array_check_meta,
3095 .resolve = btf_array_resolve,
3096 .check_member = btf_array_check_member,
3097 .check_kflag_member = btf_generic_check_kflag_member,
3098 .log_details = btf_array_log,
3099 .show = btf_array_show,
3102 static int btf_struct_check_member(struct btf_verifier_env *env,
3103 const struct btf_type *struct_type,
3104 const struct btf_member *member,
3105 const struct btf_type *member_type)
3107 u32 struct_bits_off = member->offset;
3108 u32 struct_size, bytes_offset;
3110 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3111 btf_verifier_log_member(env, struct_type, member,
3112 "Member is not byte aligned");
3116 struct_size = struct_type->size;
3117 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3118 if (struct_size - bytes_offset < member_type->size) {
3119 btf_verifier_log_member(env, struct_type, member,
3120 "Member exceeds struct_size");
3127 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3128 const struct btf_type *t,
3131 bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3132 const struct btf_member *member;
3133 u32 meta_needed, last_offset;
3134 struct btf *btf = env->btf;
3135 u32 struct_size = t->size;
3139 meta_needed = btf_type_vlen(t) * sizeof(*member);
3140 if (meta_left < meta_needed) {
3141 btf_verifier_log_basic(env, t,
3142 "meta_left:%u meta_needed:%u",
3143 meta_left, meta_needed);
3147 /* struct type either no name or a valid one */
3149 !btf_name_valid_identifier(env->btf, t->name_off)) {
3150 btf_verifier_log_type(env, t, "Invalid name");
3154 btf_verifier_log_type(env, t, NULL);
3157 for_each_member(i, t, member) {
3158 if (!btf_name_offset_valid(btf, member->name_off)) {
3159 btf_verifier_log_member(env, t, member,
3160 "Invalid member name_offset:%u",
3165 /* struct member either no name or a valid one */
3166 if (member->name_off &&
3167 !btf_name_valid_identifier(btf, member->name_off)) {
3168 btf_verifier_log_member(env, t, member, "Invalid name");
3171 /* A member cannot be in type void */
3172 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3173 btf_verifier_log_member(env, t, member,
3178 offset = __btf_member_bit_offset(t, member);
3179 if (is_union && offset) {
3180 btf_verifier_log_member(env, t, member,
3181 "Invalid member bits_offset");
3186 * ">" instead of ">=" because the last member could be
3189 if (last_offset > offset) {
3190 btf_verifier_log_member(env, t, member,
3191 "Invalid member bits_offset");
3195 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3196 btf_verifier_log_member(env, t, member,
3197 "Member bits_offset exceeds its struct size");
3201 btf_verifier_log_member(env, t, member, NULL);
3202 last_offset = offset;
3208 static int btf_struct_resolve(struct btf_verifier_env *env,
3209 const struct resolve_vertex *v)
3211 const struct btf_member *member;
3215 /* Before continue resolving the next_member,
3216 * ensure the last member is indeed resolved to a
3217 * type with size info.
3219 if (v->next_member) {
3220 const struct btf_type *last_member_type;
3221 const struct btf_member *last_member;
3222 u32 last_member_type_id;
3224 last_member = btf_type_member(v->t) + v->next_member - 1;
3225 last_member_type_id = last_member->type;
3226 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3227 last_member_type_id)))
3230 last_member_type = btf_type_by_id(env->btf,
3231 last_member_type_id);
3232 if (btf_type_kflag(v->t))
3233 err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3237 err = btf_type_ops(last_member_type)->check_member(env, v->t,
3244 for_each_member_from(i, v->next_member, v->t, member) {
3245 u32 member_type_id = member->type;
3246 const struct btf_type *member_type = btf_type_by_id(env->btf,
3249 if (btf_type_nosize_or_null(member_type) ||
3250 btf_type_is_resolve_source_only(member_type)) {
3251 btf_verifier_log_member(env, v->t, member,
3256 if (!env_type_is_resolve_sink(env, member_type) &&
3257 !env_type_is_resolved(env, member_type_id)) {
3258 env_stack_set_next_member(env, i + 1);
3259 return env_stack_push(env, member_type, member_type_id);
3262 if (btf_type_kflag(v->t))
3263 err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3267 err = btf_type_ops(member_type)->check_member(env, v->t,
3274 env_stack_pop_resolved(env, 0, 0);
3279 static void btf_struct_log(struct btf_verifier_env *env,
3280 const struct btf_type *t)
3282 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3286 BTF_FIELD_IGNORE = 0,
3287 BTF_FIELD_FOUND = 1,
3290 struct btf_field_info {
3291 enum btf_field_type type;
3298 const char *node_name;
3304 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3305 u32 off, int sz, enum btf_field_type field_type,
3306 struct btf_field_info *info)
3308 if (!__btf_type_is_struct(t))
3309 return BTF_FIELD_IGNORE;
3311 return BTF_FIELD_IGNORE;
3312 info->type = field_type;
3314 return BTF_FIELD_FOUND;
3317 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3318 u32 off, int sz, struct btf_field_info *info)
3320 enum btf_field_type type;
3323 /* Permit modifiers on the pointer itself */
3324 if (btf_type_is_volatile(t))
3325 t = btf_type_by_id(btf, t->type);
3326 /* For PTR, sz is always == 8 */
3327 if (!btf_type_is_ptr(t))
3328 return BTF_FIELD_IGNORE;
3329 t = btf_type_by_id(btf, t->type);
3331 if (!btf_type_is_type_tag(t))
3332 return BTF_FIELD_IGNORE;
3333 /* Reject extra tags */
3334 if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3336 if (!strcmp("kptr_untrusted", __btf_name_by_offset(btf, t->name_off)))
3337 type = BPF_KPTR_UNREF;
3338 else if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3339 type = BPF_KPTR_REF;
3340 else if (!strcmp("percpu_kptr", __btf_name_by_offset(btf, t->name_off)))
3341 type = BPF_KPTR_PERCPU;
3345 /* Get the base type */
3346 t = btf_type_skip_modifiers(btf, t->type, &res_id);
3347 /* Only pointer to struct is allowed */
3348 if (!__btf_type_is_struct(t))
3353 info->kptr.type_id = res_id;
3354 return BTF_FIELD_FOUND;
3357 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3358 int comp_idx, const char *tag_key, int last_id)
3360 int len = strlen(tag_key);
3363 for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
3364 const struct btf_type *t = btf_type_by_id(btf, i);
3366 if (!btf_type_is_decl_tag(t))
3368 if (pt != btf_type_by_id(btf, t->type))
3370 if (btf_type_decl_tag(t)->component_idx != comp_idx)
3372 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3379 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3380 int comp_idx, const char *tag_key)
3382 const char *value = NULL;
3383 const struct btf_type *t;
3386 id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, 0);
3390 t = btf_type_by_id(btf, id);
3391 len = strlen(tag_key);
3392 value = __btf_name_by_offset(btf, t->name_off) + len;
3394 /* Prevent duplicate entries for same type */
3395 id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3397 return ERR_PTR(-EEXIST);
3403 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3404 const struct btf_type *t, int comp_idx, u32 off,
3405 int sz, struct btf_field_info *info,
3406 enum btf_field_type head_type)
3408 const char *node_field_name;
3409 const char *value_type;
3412 if (!__btf_type_is_struct(t))
3413 return BTF_FIELD_IGNORE;
3415 return BTF_FIELD_IGNORE;
3416 value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3417 if (IS_ERR(value_type))
3419 node_field_name = strstr(value_type, ":");
3420 if (!node_field_name)
3422 value_type = kstrndup(value_type, node_field_name - value_type, GFP_KERNEL | __GFP_NOWARN);
3425 id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3430 if (str_is_empty(node_field_name))
3432 info->type = head_type;
3434 info->graph_root.value_btf_id = id;
3435 info->graph_root.node_name = node_field_name;
3436 return BTF_FIELD_FOUND;
3439 #define field_mask_test_name(field_type, field_type_str) \
3440 if (field_mask & field_type && !strcmp(name, field_type_str)) { \
3441 type = field_type; \
3445 static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3446 int *align, int *sz)
3450 if (field_mask & BPF_SPIN_LOCK) {
3451 if (!strcmp(name, "bpf_spin_lock")) {
3452 if (*seen_mask & BPF_SPIN_LOCK)
3454 *seen_mask |= BPF_SPIN_LOCK;
3455 type = BPF_SPIN_LOCK;
3459 if (field_mask & BPF_TIMER) {
3460 if (!strcmp(name, "bpf_timer")) {
3461 if (*seen_mask & BPF_TIMER)
3463 *seen_mask |= BPF_TIMER;
3468 if (field_mask & BPF_WORKQUEUE) {
3469 if (!strcmp(name, "bpf_wq")) {
3470 if (*seen_mask & BPF_WORKQUEUE)
3472 *seen_mask |= BPF_WORKQUEUE;
3473 type = BPF_WORKQUEUE;
3477 field_mask_test_name(BPF_LIST_HEAD, "bpf_list_head");
3478 field_mask_test_name(BPF_LIST_NODE, "bpf_list_node");
3479 field_mask_test_name(BPF_RB_ROOT, "bpf_rb_root");
3480 field_mask_test_name(BPF_RB_NODE, "bpf_rb_node");
3481 field_mask_test_name(BPF_REFCOUNT, "bpf_refcount");
3483 /* Only return BPF_KPTR when all other types with matchable names fail */
3484 if (field_mask & BPF_KPTR) {
3485 type = BPF_KPTR_REF;
3490 *sz = btf_field_type_size(type);
3491 *align = btf_field_type_align(type);
3495 #undef field_mask_test_name
3497 static int btf_find_struct_field(const struct btf *btf,
3498 const struct btf_type *t, u32 field_mask,
3499 struct btf_field_info *info, int info_cnt)
3501 int ret, idx = 0, align, sz, field_type;
3502 const struct btf_member *member;
3503 struct btf_field_info tmp;
3504 u32 i, off, seen_mask = 0;
3506 for_each_member(i, t, member) {
3507 const struct btf_type *member_type = btf_type_by_id(btf,
3510 field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3511 field_mask, &seen_mask, &align, &sz);
3512 if (field_type == 0)
3517 off = __btf_member_bit_offset(t, member);
3519 /* valid C code cannot generate such BTF */
3525 switch (field_type) {
3532 ret = btf_find_struct(btf, member_type, off, sz, field_type,
3533 idx < info_cnt ? &info[idx] : &tmp);
3537 case BPF_KPTR_UNREF:
3539 case BPF_KPTR_PERCPU:
3540 ret = btf_find_kptr(btf, member_type, off, sz,
3541 idx < info_cnt ? &info[idx] : &tmp);
3547 ret = btf_find_graph_root(btf, t, member_type,
3549 idx < info_cnt ? &info[idx] : &tmp,
3558 if (ret == BTF_FIELD_IGNORE)
3560 if (idx >= info_cnt)
3567 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3568 u32 field_mask, struct btf_field_info *info,
3571 int ret, idx = 0, align, sz, field_type;
3572 const struct btf_var_secinfo *vsi;
3573 struct btf_field_info tmp;
3574 u32 i, off, seen_mask = 0;
3576 for_each_vsi(i, t, vsi) {
3577 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3578 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3580 field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3581 field_mask, &seen_mask, &align, &sz);
3582 if (field_type == 0)
3588 if (vsi->size != sz)
3593 switch (field_type) {
3600 ret = btf_find_struct(btf, var_type, off, sz, field_type,
3601 idx < info_cnt ? &info[idx] : &tmp);
3605 case BPF_KPTR_UNREF:
3607 case BPF_KPTR_PERCPU:
3608 ret = btf_find_kptr(btf, var_type, off, sz,
3609 idx < info_cnt ? &info[idx] : &tmp);
3615 ret = btf_find_graph_root(btf, var, var_type,
3617 idx < info_cnt ? &info[idx] : &tmp,
3626 if (ret == BTF_FIELD_IGNORE)
3628 if (idx >= info_cnt)
3635 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3636 u32 field_mask, struct btf_field_info *info,
3639 if (__btf_type_is_struct(t))
3640 return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
3641 else if (btf_type_is_datasec(t))
3642 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
3646 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3647 struct btf_field_info *info)
3649 struct module *mod = NULL;
3650 const struct btf_type *t;
3651 /* If a matching btf type is found in kernel or module BTFs, kptr_ref
3652 * is that BTF, otherwise it's program BTF
3654 struct btf *kptr_btf;
3658 /* Find type in map BTF, and use it to look up the matching type
3659 * in vmlinux or module BTFs, by name and kind.
3661 t = btf_type_by_id(btf, info->kptr.type_id);
3662 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3664 if (id == -ENOENT) {
3665 /* btf_parse_kptr should only be called w/ btf = program BTF */
3666 WARN_ON_ONCE(btf_is_kernel(btf));
3668 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3669 * kptr allocated via bpf_obj_new
3671 field->kptr.dtor = NULL;
3672 id = info->kptr.type_id;
3673 kptr_btf = (struct btf *)btf;
3680 /* Find and stash the function pointer for the destruction function that
3681 * needs to be eventually invoked from the map free path.
3683 if (info->type == BPF_KPTR_REF) {
3684 const struct btf_type *dtor_func;
3685 const char *dtor_func_name;
3689 /* This call also serves as a whitelist of allowed objects that
3690 * can be used as a referenced pointer and be stored in a map at
3693 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3694 if (dtor_btf_id < 0) {
3699 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3705 if (btf_is_module(kptr_btf)) {
3706 mod = btf_try_get_module(kptr_btf);
3713 /* We already verified dtor_func to be btf_type_is_func
3714 * in register_btf_id_dtor_kfuncs.
3716 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3717 addr = kallsyms_lookup_name(dtor_func_name);
3722 field->kptr.dtor = (void *)addr;
3726 field->kptr.btf_id = id;
3727 field->kptr.btf = kptr_btf;
3728 field->kptr.module = mod;
3737 static int btf_parse_graph_root(const struct btf *btf,
3738 struct btf_field *field,
3739 struct btf_field_info *info,
3740 const char *node_type_name,
3741 size_t node_type_align)
3743 const struct btf_type *t, *n = NULL;
3744 const struct btf_member *member;
3748 t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3749 /* We've already checked that value_btf_id is a struct type. We
3750 * just need to figure out the offset of the list_node, and
3753 for_each_member(i, t, member) {
3754 if (strcmp(info->graph_root.node_name,
3755 __btf_name_by_offset(btf, member->name_off)))
3757 /* Invalid BTF, two members with same name */
3760 n = btf_type_by_id(btf, member->type);
3761 if (!__btf_type_is_struct(n))
3763 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3765 offset = __btf_member_bit_offset(n, member);
3769 if (offset % node_type_align)
3772 field->graph_root.btf = (struct btf *)btf;
3773 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3774 field->graph_root.node_offset = offset;
3781 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3782 struct btf_field_info *info)
3784 return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3785 __alignof__(struct bpf_list_node));
3788 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3789 struct btf_field_info *info)
3791 return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3792 __alignof__(struct bpf_rb_node));
3795 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3797 const struct btf_field *a = (const struct btf_field *)_a;
3798 const struct btf_field *b = (const struct btf_field *)_b;
3800 if (a->offset < b->offset)
3802 else if (a->offset > b->offset)
3807 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3808 u32 field_mask, u32 value_size)
3810 struct btf_field_info info_arr[BTF_FIELDS_MAX];
3811 u32 next_off = 0, field_type_size;
3812 struct btf_record *rec;
3815 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3817 return ERR_PTR(ret);
3822 /* This needs to be kzalloc to zero out padding and unused fields, see
3823 * comment in btf_record_equal.
3825 rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3827 return ERR_PTR(-ENOMEM);
3829 rec->spin_lock_off = -EINVAL;
3830 rec->timer_off = -EINVAL;
3831 rec->wq_off = -EINVAL;
3832 rec->refcount_off = -EINVAL;
3833 for (i = 0; i < cnt; i++) {
3834 field_type_size = btf_field_type_size(info_arr[i].type);
3835 if (info_arr[i].off + field_type_size > value_size) {
3836 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3840 if (info_arr[i].off < next_off) {
3844 next_off = info_arr[i].off + field_type_size;
3846 rec->field_mask |= info_arr[i].type;
3847 rec->fields[i].offset = info_arr[i].off;
3848 rec->fields[i].type = info_arr[i].type;
3849 rec->fields[i].size = field_type_size;
3851 switch (info_arr[i].type) {
3853 WARN_ON_ONCE(rec->spin_lock_off >= 0);
3854 /* Cache offset for faster lookup at runtime */
3855 rec->spin_lock_off = rec->fields[i].offset;
3858 WARN_ON_ONCE(rec->timer_off >= 0);
3859 /* Cache offset for faster lookup at runtime */
3860 rec->timer_off = rec->fields[i].offset;
3863 WARN_ON_ONCE(rec->wq_off >= 0);
3864 /* Cache offset for faster lookup at runtime */
3865 rec->wq_off = rec->fields[i].offset;
3868 WARN_ON_ONCE(rec->refcount_off >= 0);
3869 /* Cache offset for faster lookup at runtime */
3870 rec->refcount_off = rec->fields[i].offset;
3872 case BPF_KPTR_UNREF:
3874 case BPF_KPTR_PERCPU:
3875 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3880 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3885 ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
3899 /* bpf_{list_head, rb_node} require bpf_spin_lock */
3900 if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
3901 btf_record_has_field(rec, BPF_RB_ROOT)) && rec->spin_lock_off < 0) {
3906 if (rec->refcount_off < 0 &&
3907 btf_record_has_field(rec, BPF_LIST_NODE) &&
3908 btf_record_has_field(rec, BPF_RB_NODE)) {
3913 sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
3918 btf_record_free(rec);
3919 return ERR_PTR(ret);
3922 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3926 /* There are three types that signify ownership of some other type:
3927 * kptr_ref, bpf_list_head, bpf_rb_root.
3928 * kptr_ref only supports storing kernel types, which can't store
3929 * references to program allocated local types.
3931 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
3932 * does not form cycles.
3934 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & BPF_GRAPH_ROOT))
3936 for (i = 0; i < rec->cnt; i++) {
3937 struct btf_struct_meta *meta;
3940 if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
3942 btf_id = rec->fields[i].graph_root.value_btf_id;
3943 meta = btf_find_struct_meta(btf, btf_id);
3946 rec->fields[i].graph_root.value_rec = meta->record;
3948 /* We need to set value_rec for all root types, but no need
3949 * to check ownership cycle for a type unless it's also a
3952 if (!(rec->field_mask & BPF_GRAPH_NODE))
3955 /* We need to ensure ownership acyclicity among all types. The
3956 * proper way to do it would be to topologically sort all BTF
3957 * IDs based on the ownership edges, since there can be multiple
3958 * bpf_{list_head,rb_node} in a type. Instead, we use the
3959 * following resaoning:
3961 * - A type can only be owned by another type in user BTF if it
3962 * has a bpf_{list,rb}_node. Let's call these node types.
3963 * - A type can only _own_ another type in user BTF if it has a
3964 * bpf_{list_head,rb_root}. Let's call these root types.
3966 * We ensure that if a type is both a root and node, its
3967 * element types cannot be root types.
3969 * To ensure acyclicity:
3971 * When A is an root type but not a node, its ownership
3975 * - A is an root, e.g. has bpf_rb_root.
3976 * - B is both a root and node, e.g. has bpf_rb_node and
3978 * - C is only an root, e.g. has bpf_list_node
3980 * When A is both a root and node, some other type already
3981 * owns it in the BTF domain, hence it can not own
3982 * another root type through any of the ownership edges.
3985 * - A is both an root and node.
3986 * - B is only an node.
3988 if (meta->record->field_mask & BPF_GRAPH_ROOT)
3994 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3995 u32 type_id, void *data, u8 bits_offset,
3996 struct btf_show *show)
3998 const struct btf_member *member;
4002 safe_data = btf_show_start_struct_type(show, t, type_id, data);
4006 for_each_member(i, t, member) {
4007 const struct btf_type *member_type = btf_type_by_id(btf,
4009 const struct btf_kind_operations *ops;
4010 u32 member_offset, bitfield_size;
4014 btf_show_start_member(show, member);
4016 member_offset = __btf_member_bit_offset(t, member);
4017 bitfield_size = __btf_member_bitfield_size(t, member);
4018 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4019 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4020 if (bitfield_size) {
4021 safe_data = btf_show_start_type(show, member_type,
4023 data + bytes_offset);
4025 btf_bitfield_show(safe_data,
4027 bitfield_size, show);
4028 btf_show_end_type(show);
4030 ops = btf_type_ops(member_type);
4031 ops->show(btf, member_type, member->type,
4032 data + bytes_offset, bits8_offset, show);
4035 btf_show_end_member(show);
4038 btf_show_end_struct_type(show);
4041 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4042 u32 type_id, void *data, u8 bits_offset,
4043 struct btf_show *show)
4045 const struct btf_member *m = show->state.member;
4048 * First check if any members would be shown (are non-zero).
4049 * See comments above "struct btf_show" definition for more
4050 * details on how this works at a high-level.
4052 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4053 if (!show->state.depth_check) {
4054 show->state.depth_check = show->state.depth + 1;
4055 show->state.depth_to_show = 0;
4057 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4058 /* Restore saved member data here */
4059 show->state.member = m;
4060 if (show->state.depth_check != show->state.depth + 1)
4062 show->state.depth_check = 0;
4064 if (show->state.depth_to_show <= show->state.depth)
4067 * Reaching here indicates we have recursed and found
4068 * non-zero child values.
4072 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4075 static struct btf_kind_operations struct_ops = {
4076 .check_meta = btf_struct_check_meta,
4077 .resolve = btf_struct_resolve,
4078 .check_member = btf_struct_check_member,
4079 .check_kflag_member = btf_generic_check_kflag_member,
4080 .log_details = btf_struct_log,
4081 .show = btf_struct_show,
4084 static int btf_enum_check_member(struct btf_verifier_env *env,
4085 const struct btf_type *struct_type,
4086 const struct btf_member *member,
4087 const struct btf_type *member_type)
4089 u32 struct_bits_off = member->offset;
4090 u32 struct_size, bytes_offset;
4092 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4093 btf_verifier_log_member(env, struct_type, member,
4094 "Member is not byte aligned");
4098 struct_size = struct_type->size;
4099 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4100 if (struct_size - bytes_offset < member_type->size) {
4101 btf_verifier_log_member(env, struct_type, member,
4102 "Member exceeds struct_size");
4109 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4110 const struct btf_type *struct_type,
4111 const struct btf_member *member,
4112 const struct btf_type *member_type)
4114 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4115 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4117 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4118 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4120 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4121 btf_verifier_log_member(env, struct_type, member,
4122 "Member is not byte aligned");
4126 nr_bits = int_bitsize;
4127 } else if (nr_bits > int_bitsize) {
4128 btf_verifier_log_member(env, struct_type, member,
4129 "Invalid member bitfield_size");
4133 struct_size = struct_type->size;
4134 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4135 if (struct_size < bytes_end) {
4136 btf_verifier_log_member(env, struct_type, member,
4137 "Member exceeds struct_size");
4144 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4145 const struct btf_type *t,
4148 const struct btf_enum *enums = btf_type_enum(t);
4149 struct btf *btf = env->btf;
4150 const char *fmt_str;
4154 nr_enums = btf_type_vlen(t);
4155 meta_needed = nr_enums * sizeof(*enums);
4157 if (meta_left < meta_needed) {
4158 btf_verifier_log_basic(env, t,
4159 "meta_left:%u meta_needed:%u",
4160 meta_left, meta_needed);
4164 if (t->size > 8 || !is_power_of_2(t->size)) {
4165 btf_verifier_log_type(env, t, "Unexpected size");
4169 /* enum type either no name or a valid one */
4171 !btf_name_valid_identifier(env->btf, t->name_off)) {
4172 btf_verifier_log_type(env, t, "Invalid name");
4176 btf_verifier_log_type(env, t, NULL);
4178 for (i = 0; i < nr_enums; i++) {
4179 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4180 btf_verifier_log(env, "\tInvalid name_offset:%u",
4185 /* enum member must have a valid name */
4186 if (!enums[i].name_off ||
4187 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4188 btf_verifier_log_type(env, t, "Invalid name");
4192 if (env->log.level == BPF_LOG_KERNEL)
4194 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4195 btf_verifier_log(env, fmt_str,
4196 __btf_name_by_offset(btf, enums[i].name_off),
4203 static void btf_enum_log(struct btf_verifier_env *env,
4204 const struct btf_type *t)
4206 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4209 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4210 u32 type_id, void *data, u8 bits_offset,
4211 struct btf_show *show)
4213 const struct btf_enum *enums = btf_type_enum(t);
4214 u32 i, nr_enums = btf_type_vlen(t);
4218 safe_data = btf_show_start_type(show, t, type_id, data);
4222 v = *(int *)safe_data;
4224 for (i = 0; i < nr_enums; i++) {
4225 if (v != enums[i].val)
4228 btf_show_type_value(show, "%s",
4229 __btf_name_by_offset(btf,
4230 enums[i].name_off));
4232 btf_show_end_type(show);
4236 if (btf_type_kflag(t))
4237 btf_show_type_value(show, "%d", v);
4239 btf_show_type_value(show, "%u", v);
4240 btf_show_end_type(show);
4243 static struct btf_kind_operations enum_ops = {
4244 .check_meta = btf_enum_check_meta,
4245 .resolve = btf_df_resolve,
4246 .check_member = btf_enum_check_member,
4247 .check_kflag_member = btf_enum_check_kflag_member,
4248 .log_details = btf_enum_log,
4249 .show = btf_enum_show,
4252 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4253 const struct btf_type *t,
4256 const struct btf_enum64 *enums = btf_type_enum64(t);
4257 struct btf *btf = env->btf;
4258 const char *fmt_str;
4262 nr_enums = btf_type_vlen(t);
4263 meta_needed = nr_enums * sizeof(*enums);
4265 if (meta_left < meta_needed) {
4266 btf_verifier_log_basic(env, t,
4267 "meta_left:%u meta_needed:%u",
4268 meta_left, meta_needed);
4272 if (t->size > 8 || !is_power_of_2(t->size)) {
4273 btf_verifier_log_type(env, t, "Unexpected size");
4277 /* enum type either no name or a valid one */
4279 !btf_name_valid_identifier(env->btf, t->name_off)) {
4280 btf_verifier_log_type(env, t, "Invalid name");
4284 btf_verifier_log_type(env, t, NULL);
4286 for (i = 0; i < nr_enums; i++) {
4287 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4288 btf_verifier_log(env, "\tInvalid name_offset:%u",
4293 /* enum member must have a valid name */
4294 if (!enums[i].name_off ||
4295 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4296 btf_verifier_log_type(env, t, "Invalid name");
4300 if (env->log.level == BPF_LOG_KERNEL)
4303 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4304 btf_verifier_log(env, fmt_str,
4305 __btf_name_by_offset(btf, enums[i].name_off),
4306 btf_enum64_value(enums + i));
4312 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4313 u32 type_id, void *data, u8 bits_offset,
4314 struct btf_show *show)
4316 const struct btf_enum64 *enums = btf_type_enum64(t);
4317 u32 i, nr_enums = btf_type_vlen(t);
4321 safe_data = btf_show_start_type(show, t, type_id, data);
4325 v = *(u64 *)safe_data;
4327 for (i = 0; i < nr_enums; i++) {
4328 if (v != btf_enum64_value(enums + i))
4331 btf_show_type_value(show, "%s",
4332 __btf_name_by_offset(btf,
4333 enums[i].name_off));
4335 btf_show_end_type(show);
4339 if (btf_type_kflag(t))
4340 btf_show_type_value(show, "%lld", v);
4342 btf_show_type_value(show, "%llu", v);
4343 btf_show_end_type(show);
4346 static struct btf_kind_operations enum64_ops = {
4347 .check_meta = btf_enum64_check_meta,
4348 .resolve = btf_df_resolve,
4349 .check_member = btf_enum_check_member,
4350 .check_kflag_member = btf_enum_check_kflag_member,
4351 .log_details = btf_enum_log,
4352 .show = btf_enum64_show,
4355 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4356 const struct btf_type *t,
4359 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4361 if (meta_left < meta_needed) {
4362 btf_verifier_log_basic(env, t,
4363 "meta_left:%u meta_needed:%u",
4364 meta_left, meta_needed);
4369 btf_verifier_log_type(env, t, "Invalid name");
4373 if (btf_type_kflag(t)) {
4374 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4378 btf_verifier_log_type(env, t, NULL);
4383 static void btf_func_proto_log(struct btf_verifier_env *env,
4384 const struct btf_type *t)
4386 const struct btf_param *args = (const struct btf_param *)(t + 1);
4387 u16 nr_args = btf_type_vlen(t), i;
4389 btf_verifier_log(env, "return=%u args=(", t->type);
4391 btf_verifier_log(env, "void");
4395 if (nr_args == 1 && !args[0].type) {
4396 /* Only one vararg */
4397 btf_verifier_log(env, "vararg");
4401 btf_verifier_log(env, "%u %s", args[0].type,
4402 __btf_name_by_offset(env->btf,
4404 for (i = 1; i < nr_args - 1; i++)
4405 btf_verifier_log(env, ", %u %s", args[i].type,
4406 __btf_name_by_offset(env->btf,
4410 const struct btf_param *last_arg = &args[nr_args - 1];
4413 btf_verifier_log(env, ", %u %s", last_arg->type,
4414 __btf_name_by_offset(env->btf,
4415 last_arg->name_off));
4417 btf_verifier_log(env, ", vararg");
4421 btf_verifier_log(env, ")");
4424 static struct btf_kind_operations func_proto_ops = {
4425 .check_meta = btf_func_proto_check_meta,
4426 .resolve = btf_df_resolve,
4428 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4429 * a struct's member.
4431 * It should be a function pointer instead.
4432 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4434 * Hence, there is no btf_func_check_member().
4436 .check_member = btf_df_check_member,
4437 .check_kflag_member = btf_df_check_kflag_member,
4438 .log_details = btf_func_proto_log,
4439 .show = btf_df_show,
4442 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4443 const struct btf_type *t,
4447 !btf_name_valid_identifier(env->btf, t->name_off)) {
4448 btf_verifier_log_type(env, t, "Invalid name");
4452 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4453 btf_verifier_log_type(env, t, "Invalid func linkage");
4457 if (btf_type_kflag(t)) {
4458 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4462 btf_verifier_log_type(env, t, NULL);
4467 static int btf_func_resolve(struct btf_verifier_env *env,
4468 const struct resolve_vertex *v)
4470 const struct btf_type *t = v->t;
4471 u32 next_type_id = t->type;
4474 err = btf_func_check(env, t);
4478 env_stack_pop_resolved(env, next_type_id, 0);
4482 static struct btf_kind_operations func_ops = {
4483 .check_meta = btf_func_check_meta,
4484 .resolve = btf_func_resolve,
4485 .check_member = btf_df_check_member,
4486 .check_kflag_member = btf_df_check_kflag_member,
4487 .log_details = btf_ref_type_log,
4488 .show = btf_df_show,
4491 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4492 const struct btf_type *t,
4495 const struct btf_var *var;
4496 u32 meta_needed = sizeof(*var);
4498 if (meta_left < meta_needed) {
4499 btf_verifier_log_basic(env, t,
4500 "meta_left:%u meta_needed:%u",
4501 meta_left, meta_needed);
4505 if (btf_type_vlen(t)) {
4506 btf_verifier_log_type(env, t, "vlen != 0");
4510 if (btf_type_kflag(t)) {
4511 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4516 !__btf_name_valid(env->btf, t->name_off)) {
4517 btf_verifier_log_type(env, t, "Invalid name");
4521 /* A var cannot be in type void */
4522 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4523 btf_verifier_log_type(env, t, "Invalid type_id");
4527 var = btf_type_var(t);
4528 if (var->linkage != BTF_VAR_STATIC &&
4529 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4530 btf_verifier_log_type(env, t, "Linkage not supported");
4534 btf_verifier_log_type(env, t, NULL);
4539 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4541 const struct btf_var *var = btf_type_var(t);
4543 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4546 static const struct btf_kind_operations var_ops = {
4547 .check_meta = btf_var_check_meta,
4548 .resolve = btf_var_resolve,
4549 .check_member = btf_df_check_member,
4550 .check_kflag_member = btf_df_check_kflag_member,
4551 .log_details = btf_var_log,
4552 .show = btf_var_show,
4555 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4556 const struct btf_type *t,
4559 const struct btf_var_secinfo *vsi;
4560 u64 last_vsi_end_off = 0, sum = 0;
4563 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4564 if (meta_left < meta_needed) {
4565 btf_verifier_log_basic(env, t,
4566 "meta_left:%u meta_needed:%u",
4567 meta_left, meta_needed);
4572 btf_verifier_log_type(env, t, "size == 0");
4576 if (btf_type_kflag(t)) {
4577 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4582 !btf_name_valid_section(env->btf, t->name_off)) {
4583 btf_verifier_log_type(env, t, "Invalid name");
4587 btf_verifier_log_type(env, t, NULL);
4589 for_each_vsi(i, t, vsi) {
4590 /* A var cannot be in type void */
4591 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4592 btf_verifier_log_vsi(env, t, vsi,
4597 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4598 btf_verifier_log_vsi(env, t, vsi,
4603 if (!vsi->size || vsi->size > t->size) {
4604 btf_verifier_log_vsi(env, t, vsi,
4609 last_vsi_end_off = vsi->offset + vsi->size;
4610 if (last_vsi_end_off > t->size) {
4611 btf_verifier_log_vsi(env, t, vsi,
4612 "Invalid offset+size");
4616 btf_verifier_log_vsi(env, t, vsi, NULL);
4620 if (t->size < sum) {
4621 btf_verifier_log_type(env, t, "Invalid btf_info size");
4628 static int btf_datasec_resolve(struct btf_verifier_env *env,
4629 const struct resolve_vertex *v)
4631 const struct btf_var_secinfo *vsi;
4632 struct btf *btf = env->btf;
4635 env->resolve_mode = RESOLVE_TBD;
4636 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4637 u32 var_type_id = vsi->type, type_id, type_size = 0;
4638 const struct btf_type *var_type = btf_type_by_id(env->btf,
4640 if (!var_type || !btf_type_is_var(var_type)) {
4641 btf_verifier_log_vsi(env, v->t, vsi,
4642 "Not a VAR kind member");
4646 if (!env_type_is_resolve_sink(env, var_type) &&
4647 !env_type_is_resolved(env, var_type_id)) {
4648 env_stack_set_next_member(env, i + 1);
4649 return env_stack_push(env, var_type, var_type_id);
4652 type_id = var_type->type;
4653 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4654 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4658 if (vsi->size < type_size) {
4659 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4664 env_stack_pop_resolved(env, 0, 0);
4668 static void btf_datasec_log(struct btf_verifier_env *env,
4669 const struct btf_type *t)
4671 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4674 static void btf_datasec_show(const struct btf *btf,
4675 const struct btf_type *t, u32 type_id,
4676 void *data, u8 bits_offset,
4677 struct btf_show *show)
4679 const struct btf_var_secinfo *vsi;
4680 const struct btf_type *var;
4683 if (!btf_show_start_type(show, t, type_id, data))
4686 btf_show_type_value(show, "section (\"%s\") = {",
4687 __btf_name_by_offset(btf, t->name_off));
4688 for_each_vsi(i, t, vsi) {
4689 var = btf_type_by_id(btf, vsi->type);
4691 btf_show(show, ",");
4692 btf_type_ops(var)->show(btf, var, vsi->type,
4693 data + vsi->offset, bits_offset, show);
4695 btf_show_end_type(show);
4698 static const struct btf_kind_operations datasec_ops = {
4699 .check_meta = btf_datasec_check_meta,
4700 .resolve = btf_datasec_resolve,
4701 .check_member = btf_df_check_member,
4702 .check_kflag_member = btf_df_check_kflag_member,
4703 .log_details = btf_datasec_log,
4704 .show = btf_datasec_show,
4707 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4708 const struct btf_type *t,
4711 if (btf_type_vlen(t)) {
4712 btf_verifier_log_type(env, t, "vlen != 0");
4716 if (btf_type_kflag(t)) {
4717 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4721 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4723 btf_verifier_log_type(env, t, "Invalid type_size");
4727 btf_verifier_log_type(env, t, NULL);
4732 static int btf_float_check_member(struct btf_verifier_env *env,
4733 const struct btf_type *struct_type,
4734 const struct btf_member *member,
4735 const struct btf_type *member_type)
4737 u64 start_offset_bytes;
4738 u64 end_offset_bytes;
4743 /* Different architectures have different alignment requirements, so
4744 * here we check only for the reasonable minimum. This way we ensure
4745 * that types after CO-RE can pass the kernel BTF verifier.
4747 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4748 align_bits = align_bytes * BITS_PER_BYTE;
4749 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4750 if (misalign_bits) {
4751 btf_verifier_log_member(env, struct_type, member,
4752 "Member is not properly aligned");
4756 start_offset_bytes = member->offset / BITS_PER_BYTE;
4757 end_offset_bytes = start_offset_bytes + member_type->size;
4758 if (end_offset_bytes > struct_type->size) {
4759 btf_verifier_log_member(env, struct_type, member,
4760 "Member exceeds struct_size");
4767 static void btf_float_log(struct btf_verifier_env *env,
4768 const struct btf_type *t)
4770 btf_verifier_log(env, "size=%u", t->size);
4773 static const struct btf_kind_operations float_ops = {
4774 .check_meta = btf_float_check_meta,
4775 .resolve = btf_df_resolve,
4776 .check_member = btf_float_check_member,
4777 .check_kflag_member = btf_generic_check_kflag_member,
4778 .log_details = btf_float_log,
4779 .show = btf_df_show,
4782 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4783 const struct btf_type *t,
4786 const struct btf_decl_tag *tag;
4787 u32 meta_needed = sizeof(*tag);
4791 if (meta_left < meta_needed) {
4792 btf_verifier_log_basic(env, t,
4793 "meta_left:%u meta_needed:%u",
4794 meta_left, meta_needed);
4798 value = btf_name_by_offset(env->btf, t->name_off);
4799 if (!value || !value[0]) {
4800 btf_verifier_log_type(env, t, "Invalid value");
4804 if (btf_type_vlen(t)) {
4805 btf_verifier_log_type(env, t, "vlen != 0");
4809 if (btf_type_kflag(t)) {
4810 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4814 component_idx = btf_type_decl_tag(t)->component_idx;
4815 if (component_idx < -1) {
4816 btf_verifier_log_type(env, t, "Invalid component_idx");
4820 btf_verifier_log_type(env, t, NULL);
4825 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4826 const struct resolve_vertex *v)
4828 const struct btf_type *next_type;
4829 const struct btf_type *t = v->t;
4830 u32 next_type_id = t->type;
4831 struct btf *btf = env->btf;
4835 next_type = btf_type_by_id(btf, next_type_id);
4836 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4837 btf_verifier_log_type(env, v->t, "Invalid type_id");
4841 if (!env_type_is_resolve_sink(env, next_type) &&
4842 !env_type_is_resolved(env, next_type_id))
4843 return env_stack_push(env, next_type, next_type_id);
4845 component_idx = btf_type_decl_tag(t)->component_idx;
4846 if (component_idx != -1) {
4847 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4848 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4852 if (btf_type_is_struct(next_type)) {
4853 vlen = btf_type_vlen(next_type);
4855 /* next_type should be a function */
4856 next_type = btf_type_by_id(btf, next_type->type);
4857 vlen = btf_type_vlen(next_type);
4860 if ((u32)component_idx >= vlen) {
4861 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4866 env_stack_pop_resolved(env, next_type_id, 0);
4871 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4873 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4874 btf_type_decl_tag(t)->component_idx);
4877 static const struct btf_kind_operations decl_tag_ops = {
4878 .check_meta = btf_decl_tag_check_meta,
4879 .resolve = btf_decl_tag_resolve,
4880 .check_member = btf_df_check_member,
4881 .check_kflag_member = btf_df_check_kflag_member,
4882 .log_details = btf_decl_tag_log,
4883 .show = btf_df_show,
4886 static int btf_func_proto_check(struct btf_verifier_env *env,
4887 const struct btf_type *t)
4889 const struct btf_type *ret_type;
4890 const struct btf_param *args;
4891 const struct btf *btf;
4896 args = (const struct btf_param *)(t + 1);
4897 nr_args = btf_type_vlen(t);
4899 /* Check func return type which could be "void" (t->type == 0) */
4901 u32 ret_type_id = t->type;
4903 ret_type = btf_type_by_id(btf, ret_type_id);
4905 btf_verifier_log_type(env, t, "Invalid return type");
4909 if (btf_type_is_resolve_source_only(ret_type)) {
4910 btf_verifier_log_type(env, t, "Invalid return type");
4914 if (btf_type_needs_resolve(ret_type) &&
4915 !env_type_is_resolved(env, ret_type_id)) {
4916 err = btf_resolve(env, ret_type, ret_type_id);
4921 /* Ensure the return type is a type that has a size */
4922 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4923 btf_verifier_log_type(env, t, "Invalid return type");
4931 /* Last func arg type_id could be 0 if it is a vararg */
4932 if (!args[nr_args - 1].type) {
4933 if (args[nr_args - 1].name_off) {
4934 btf_verifier_log_type(env, t, "Invalid arg#%u",
4941 for (i = 0; i < nr_args; i++) {
4942 const struct btf_type *arg_type;
4945 arg_type_id = args[i].type;
4946 arg_type = btf_type_by_id(btf, arg_type_id);
4948 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4952 if (btf_type_is_resolve_source_only(arg_type)) {
4953 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4957 if (args[i].name_off &&
4958 (!btf_name_offset_valid(btf, args[i].name_off) ||
4959 !btf_name_valid_identifier(btf, args[i].name_off))) {
4960 btf_verifier_log_type(env, t,
4961 "Invalid arg#%u", i + 1);
4965 if (btf_type_needs_resolve(arg_type) &&
4966 !env_type_is_resolved(env, arg_type_id)) {
4967 err = btf_resolve(env, arg_type, arg_type_id);
4972 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4973 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4981 static int btf_func_check(struct btf_verifier_env *env,
4982 const struct btf_type *t)
4984 const struct btf_type *proto_type;
4985 const struct btf_param *args;
4986 const struct btf *btf;
4990 proto_type = btf_type_by_id(btf, t->type);
4992 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4993 btf_verifier_log_type(env, t, "Invalid type_id");
4997 args = (const struct btf_param *)(proto_type + 1);
4998 nr_args = btf_type_vlen(proto_type);
4999 for (i = 0; i < nr_args; i++) {
5000 if (!args[i].name_off && args[i].type) {
5001 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5009 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5010 [BTF_KIND_INT] = &int_ops,
5011 [BTF_KIND_PTR] = &ptr_ops,
5012 [BTF_KIND_ARRAY] = &array_ops,
5013 [BTF_KIND_STRUCT] = &struct_ops,
5014 [BTF_KIND_UNION] = &struct_ops,
5015 [BTF_KIND_ENUM] = &enum_ops,
5016 [BTF_KIND_FWD] = &fwd_ops,
5017 [BTF_KIND_TYPEDEF] = &modifier_ops,
5018 [BTF_KIND_VOLATILE] = &modifier_ops,
5019 [BTF_KIND_CONST] = &modifier_ops,
5020 [BTF_KIND_RESTRICT] = &modifier_ops,
5021 [BTF_KIND_FUNC] = &func_ops,
5022 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5023 [BTF_KIND_VAR] = &var_ops,
5024 [BTF_KIND_DATASEC] = &datasec_ops,
5025 [BTF_KIND_FLOAT] = &float_ops,
5026 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
5027 [BTF_KIND_TYPE_TAG] = &modifier_ops,
5028 [BTF_KIND_ENUM64] = &enum64_ops,
5031 static s32 btf_check_meta(struct btf_verifier_env *env,
5032 const struct btf_type *t,
5035 u32 saved_meta_left = meta_left;
5038 if (meta_left < sizeof(*t)) {
5039 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5040 env->log_type_id, meta_left, sizeof(*t));
5043 meta_left -= sizeof(*t);
5045 if (t->info & ~BTF_INFO_MASK) {
5046 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
5047 env->log_type_id, t->info);
5051 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5052 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5053 btf_verifier_log(env, "[%u] Invalid kind:%u",
5054 env->log_type_id, BTF_INFO_KIND(t->info));
5058 if (!btf_name_offset_valid(env->btf, t->name_off)) {
5059 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5060 env->log_type_id, t->name_off);
5064 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5065 if (var_meta_size < 0)
5066 return var_meta_size;
5068 meta_left -= var_meta_size;
5070 return saved_meta_left - meta_left;
5073 static int btf_check_all_metas(struct btf_verifier_env *env)
5075 struct btf *btf = env->btf;
5076 struct btf_header *hdr;
5080 cur = btf->nohdr_data + hdr->type_off;
5081 end = cur + hdr->type_len;
5083 env->log_type_id = btf->base_btf ? btf->start_id : 1;
5085 struct btf_type *t = cur;
5088 meta_size = btf_check_meta(env, t, end - cur);
5092 btf_add_type(env, t);
5100 static bool btf_resolve_valid(struct btf_verifier_env *env,
5101 const struct btf_type *t,
5104 struct btf *btf = env->btf;
5106 if (!env_type_is_resolved(env, type_id))
5109 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5110 return !btf_resolved_type_id(btf, type_id) &&
5111 !btf_resolved_type_size(btf, type_id);
5113 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5114 return btf_resolved_type_id(btf, type_id) &&
5115 !btf_resolved_type_size(btf, type_id);
5117 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5118 btf_type_is_var(t)) {
5119 t = btf_type_id_resolve(btf, &type_id);
5121 !btf_type_is_modifier(t) &&
5122 !btf_type_is_var(t) &&
5123 !btf_type_is_datasec(t);
5126 if (btf_type_is_array(t)) {
5127 const struct btf_array *array = btf_type_array(t);
5128 const struct btf_type *elem_type;
5129 u32 elem_type_id = array->type;
5132 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5133 return elem_type && !btf_type_is_modifier(elem_type) &&
5134 (array->nelems * elem_size ==
5135 btf_resolved_type_size(btf, type_id));
5141 static int btf_resolve(struct btf_verifier_env *env,
5142 const struct btf_type *t, u32 type_id)
5144 u32 save_log_type_id = env->log_type_id;
5145 const struct resolve_vertex *v;
5148 env->resolve_mode = RESOLVE_TBD;
5149 env_stack_push(env, t, type_id);
5150 while (!err && (v = env_stack_peak(env))) {
5151 env->log_type_id = v->type_id;
5152 err = btf_type_ops(v->t)->resolve(env, v);
5155 env->log_type_id = type_id;
5156 if (err == -E2BIG) {
5157 btf_verifier_log_type(env, t,
5158 "Exceeded max resolving depth:%u",
5160 } else if (err == -EEXIST) {
5161 btf_verifier_log_type(env, t, "Loop detected");
5164 /* Final sanity check */
5165 if (!err && !btf_resolve_valid(env, t, type_id)) {
5166 btf_verifier_log_type(env, t, "Invalid resolve state");
5170 env->log_type_id = save_log_type_id;
5174 static int btf_check_all_types(struct btf_verifier_env *env)
5176 struct btf *btf = env->btf;
5177 const struct btf_type *t;
5181 err = env_resolve_init(env);
5186 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5187 type_id = btf->start_id + i;
5188 t = btf_type_by_id(btf, type_id);
5190 env->log_type_id = type_id;
5191 if (btf_type_needs_resolve(t) &&
5192 !env_type_is_resolved(env, type_id)) {
5193 err = btf_resolve(env, t, type_id);
5198 if (btf_type_is_func_proto(t)) {
5199 err = btf_func_proto_check(env, t);
5208 static int btf_parse_type_sec(struct btf_verifier_env *env)
5210 const struct btf_header *hdr = &env->btf->hdr;
5213 /* Type section must align to 4 bytes */
5214 if (hdr->type_off & (sizeof(u32) - 1)) {
5215 btf_verifier_log(env, "Unaligned type_off");
5219 if (!env->btf->base_btf && !hdr->type_len) {
5220 btf_verifier_log(env, "No type found");
5224 err = btf_check_all_metas(env);
5228 return btf_check_all_types(env);
5231 static int btf_parse_str_sec(struct btf_verifier_env *env)
5233 const struct btf_header *hdr;
5234 struct btf *btf = env->btf;
5235 const char *start, *end;
5238 start = btf->nohdr_data + hdr->str_off;
5239 end = start + hdr->str_len;
5241 if (end != btf->data + btf->data_size) {
5242 btf_verifier_log(env, "String section is not at the end");
5246 btf->strings = start;
5248 if (btf->base_btf && !hdr->str_len)
5250 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5251 btf_verifier_log(env, "Invalid string section");
5254 if (!btf->base_btf && start[0]) {
5255 btf_verifier_log(env, "Invalid string section");
5262 static const size_t btf_sec_info_offset[] = {
5263 offsetof(struct btf_header, type_off),
5264 offsetof(struct btf_header, str_off),
5267 static int btf_sec_info_cmp(const void *a, const void *b)
5269 const struct btf_sec_info *x = a;
5270 const struct btf_sec_info *y = b;
5272 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5275 static int btf_check_sec_info(struct btf_verifier_env *env,
5278 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5279 u32 total, expected_total, i;
5280 const struct btf_header *hdr;
5281 const struct btf *btf;
5286 /* Populate the secs from hdr */
5287 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5288 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5289 btf_sec_info_offset[i]);
5291 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5292 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5294 /* Check for gaps and overlap among sections */
5296 expected_total = btf_data_size - hdr->hdr_len;
5297 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5298 if (expected_total < secs[i].off) {
5299 btf_verifier_log(env, "Invalid section offset");
5302 if (total < secs[i].off) {
5304 btf_verifier_log(env, "Unsupported section found");
5307 if (total > secs[i].off) {
5308 btf_verifier_log(env, "Section overlap found");
5311 if (expected_total - total < secs[i].len) {
5312 btf_verifier_log(env,
5313 "Total section length too long");
5316 total += secs[i].len;
5319 /* There is data other than hdr and known sections */
5320 if (expected_total != total) {
5321 btf_verifier_log(env, "Unsupported section found");
5328 static int btf_parse_hdr(struct btf_verifier_env *env)
5330 u32 hdr_len, hdr_copy, btf_data_size;
5331 const struct btf_header *hdr;
5335 btf_data_size = btf->data_size;
5337 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5338 btf_verifier_log(env, "hdr_len not found");
5343 hdr_len = hdr->hdr_len;
5344 if (btf_data_size < hdr_len) {
5345 btf_verifier_log(env, "btf_header not found");
5349 /* Ensure the unsupported header fields are zero */
5350 if (hdr_len > sizeof(btf->hdr)) {
5351 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5352 u8 *end = btf->data + hdr_len;
5354 for (; expected_zero < end; expected_zero++) {
5355 if (*expected_zero) {
5356 btf_verifier_log(env, "Unsupported btf_header");
5362 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5363 memcpy(&btf->hdr, btf->data, hdr_copy);
5367 btf_verifier_log_hdr(env, btf_data_size);
5369 if (hdr->magic != BTF_MAGIC) {
5370 btf_verifier_log(env, "Invalid magic");
5374 if (hdr->version != BTF_VERSION) {
5375 btf_verifier_log(env, "Unsupported version");
5380 btf_verifier_log(env, "Unsupported flags");
5384 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5385 btf_verifier_log(env, "No data");
5389 return btf_check_sec_info(env, btf_data_size);
5392 static const char *alloc_obj_fields[] = {
5401 static struct btf_struct_metas *
5402 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5405 struct btf_id_set set;
5408 u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5411 struct btf_struct_metas *tab = NULL;
5414 BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5415 BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5417 memset(&aof, 0, sizeof(aof));
5418 for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5419 /* Try to find whether this special type exists in user BTF, and
5420 * if so remember its ID so we can easily find it among members
5421 * of structs that we iterate in the next loop.
5423 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5426 aof.set.ids[aof.set.cnt++] = id;
5431 sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5433 n = btf_nr_types(btf);
5434 for (i = 1; i < n; i++) {
5435 struct btf_struct_metas *new_tab;
5436 const struct btf_member *member;
5437 struct btf_struct_meta *type;
5438 struct btf_record *record;
5439 const struct btf_type *t;
5442 t = btf_type_by_id(btf, i);
5447 if (!__btf_type_is_struct(t))
5452 for_each_member(j, t, member) {
5453 if (btf_id_set_contains(&aof.set, member->type))
5458 tab_cnt = tab ? tab->cnt : 0;
5459 new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5460 GFP_KERNEL | __GFP_NOWARN);
5469 type = &tab->types[tab->cnt];
5471 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5472 BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT, t->size);
5473 /* The record cannot be unset, treat it as an error if so */
5474 if (IS_ERR_OR_NULL(record)) {
5475 ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5478 type->record = record;
5483 btf_struct_metas_free(tab);
5484 return ERR_PTR(ret);
5487 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5489 struct btf_struct_metas *tab;
5491 BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5492 tab = btf->struct_meta_tab;
5495 return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5498 static int btf_check_type_tags(struct btf_verifier_env *env,
5499 struct btf *btf, int start_id)
5501 int i, n, good_id = start_id - 1;
5504 n = btf_nr_types(btf);
5505 for (i = start_id; i < n; i++) {
5506 const struct btf_type *t;
5507 int chain_limit = 32;
5510 t = btf_type_by_id(btf, i);
5513 if (!btf_type_is_modifier(t))
5518 in_tags = btf_type_is_type_tag(t);
5519 while (btf_type_is_modifier(t)) {
5520 if (!chain_limit--) {
5521 btf_verifier_log(env, "Max chain length or cycle detected");
5524 if (btf_type_is_type_tag(t)) {
5526 btf_verifier_log(env, "Type tags don't precede modifiers");
5529 } else if (in_tags) {
5532 if (cur_id <= good_id)
5534 /* Move to next type */
5536 t = btf_type_by_id(btf, cur_id);
5545 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5550 err = bpf_vlog_finalize(log, &log_true_size);
5552 if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5553 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5554 &log_true_size, sizeof(log_true_size)))
5560 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5562 bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5563 char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5564 struct btf_struct_metas *struct_meta_tab;
5565 struct btf_verifier_env *env = NULL;
5566 struct btf *btf = NULL;
5570 if (attr->btf_size > BTF_MAX_SIZE)
5571 return ERR_PTR(-E2BIG);
5573 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5575 return ERR_PTR(-ENOMEM);
5577 /* user could have requested verbose verifier output
5578 * and supplied buffer to store the verification trace
5580 err = bpf_vlog_init(&env->log, attr->btf_log_level,
5581 log_ubuf, attr->btf_log_size);
5585 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5592 data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5599 btf->data_size = attr->btf_size;
5601 if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5606 err = btf_parse_hdr(env);
5610 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5612 err = btf_parse_str_sec(env);
5616 err = btf_parse_type_sec(env);
5620 err = btf_check_type_tags(env, btf, 1);
5624 struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5625 if (IS_ERR(struct_meta_tab)) {
5626 err = PTR_ERR(struct_meta_tab);
5629 btf->struct_meta_tab = struct_meta_tab;
5631 if (struct_meta_tab) {
5634 for (i = 0; i < struct_meta_tab->cnt; i++) {
5635 err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5641 err = finalize_log(&env->log, uattr, uattr_size);
5645 btf_verifier_env_free(env);
5646 refcount_set(&btf->refcnt, 1);
5650 btf_free_struct_meta_tab(btf);
5652 /* overwrite err with -ENOSPC or -EFAULT */
5653 ret = finalize_log(&env->log, uattr, uattr_size);
5657 btf_verifier_env_free(env);
5660 return ERR_PTR(err);
5663 extern char __start_BTF[];
5664 extern char __stop_BTF[];
5665 extern struct btf *btf_vmlinux;
5667 #define BPF_MAP_TYPE(_id, _ops)
5668 #define BPF_LINK_TYPE(_id, _name)
5670 struct bpf_ctx_convert {
5671 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5672 prog_ctx_type _id##_prog; \
5673 kern_ctx_type _id##_kern;
5674 #include <linux/bpf_types.h>
5675 #undef BPF_PROG_TYPE
5677 /* 't' is written once under lock. Read many times. */
5678 const struct btf_type *t;
5681 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5683 #include <linux/bpf_types.h>
5684 #undef BPF_PROG_TYPE
5685 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5687 static u8 bpf_ctx_convert_map[] = {
5688 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5689 [_id] = __ctx_convert##_id,
5690 #include <linux/bpf_types.h>
5691 #undef BPF_PROG_TYPE
5692 0, /* avoid empty array */
5695 #undef BPF_LINK_TYPE
5697 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
5699 const struct btf_type *conv_struct;
5700 const struct btf_member *ctx_type;
5702 conv_struct = bpf_ctx_convert.t;
5705 /* prog_type is valid bpf program type. No need for bounds check. */
5706 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5707 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5708 * Like 'struct __sk_buff'
5710 return btf_type_by_id(btf_vmlinux, ctx_type->type);
5713 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
5715 const struct btf_type *conv_struct;
5716 const struct btf_member *ctx_type;
5718 conv_struct = bpf_ctx_convert.t;
5721 /* prog_type is valid bpf program type. No need for bounds check. */
5722 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5723 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5724 * Like 'struct sk_buff'
5726 return ctx_type->type;
5729 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5730 const struct btf_type *t, enum bpf_prog_type prog_type,
5733 const struct btf_type *ctx_type;
5734 const char *tname, *ctx_tname;
5736 t = btf_type_by_id(btf, t->type);
5738 /* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
5739 * check before we skip all the typedef below.
5741 if (prog_type == BPF_PROG_TYPE_KPROBE) {
5742 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5743 t = btf_type_by_id(btf, t->type);
5745 if (btf_type_is_typedef(t)) {
5746 tname = btf_name_by_offset(btf, t->name_off);
5747 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5752 while (btf_type_is_modifier(t))
5753 t = btf_type_by_id(btf, t->type);
5754 if (!btf_type_is_struct(t)) {
5755 /* Only pointer to struct is supported for now.
5756 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5757 * is not supported yet.
5758 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5762 tname = btf_name_by_offset(btf, t->name_off);
5764 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5768 ctx_type = find_canonical_prog_ctx_type(prog_type);
5770 bpf_log(log, "btf_vmlinux is malformed\n");
5771 /* should not happen */
5775 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5777 /* should not happen */
5778 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5781 /* program types without named context types work only with arg:ctx tag */
5782 if (ctx_tname[0] == '\0')
5784 /* only compare that prog's ctx type name is the same as
5785 * kernel expects. No need to compare field by field.
5786 * It's ok for bpf prog to do:
5787 * struct __sk_buff {};
5788 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5789 * { // no fields of skb are ever used }
5791 if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5793 if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5795 if (strcmp(ctx_tname, tname)) {
5796 /* bpf_user_pt_regs_t is a typedef, so resolve it to
5797 * underlying struct and check name again
5799 if (!btf_type_is_modifier(ctx_type))
5801 while (btf_type_is_modifier(ctx_type))
5802 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
5808 /* forward declarations for arch-specific underlying types of
5809 * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
5810 * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
5811 * works correctly with __builtin_types_compatible_p() on respective
5814 struct user_regs_struct;
5815 struct user_pt_regs;
5817 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5818 const struct btf_type *t, int arg,
5819 enum bpf_prog_type prog_type,
5820 enum bpf_attach_type attach_type)
5822 const struct btf_type *ctx_type;
5823 const char *tname, *ctx_tname;
5825 if (!btf_is_ptr(t)) {
5826 bpf_log(log, "arg#%d type isn't a pointer\n", arg);
5829 t = btf_type_by_id(btf, t->type);
5831 /* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
5832 if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
5833 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5834 t = btf_type_by_id(btf, t->type);
5836 if (btf_type_is_typedef(t)) {
5837 tname = btf_name_by_offset(btf, t->name_off);
5838 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5843 /* all other program types don't use typedefs for context type */
5844 while (btf_type_is_modifier(t))
5845 t = btf_type_by_id(btf, t->type);
5847 /* `void *ctx __arg_ctx` is always valid */
5848 if (btf_type_is_void(t))
5851 tname = btf_name_by_offset(btf, t->name_off);
5852 if (str_is_empty(tname)) {
5853 bpf_log(log, "arg#%d type doesn't have a name\n", arg);
5858 switch (prog_type) {
5859 case BPF_PROG_TYPE_KPROBE:
5860 if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5863 case BPF_PROG_TYPE_PERF_EVENT:
5864 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
5865 __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5867 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
5868 __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
5870 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
5871 __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
5874 case BPF_PROG_TYPE_RAW_TRACEPOINT:
5875 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
5876 /* allow u64* as ctx */
5877 if (btf_is_int(t) && t->size == 8)
5880 case BPF_PROG_TYPE_TRACING:
5881 switch (attach_type) {
5882 case BPF_TRACE_RAW_TP:
5883 /* tp_btf program is TRACING, so need special case here */
5884 if (__btf_type_is_struct(t) &&
5885 strcmp(tname, "bpf_raw_tracepoint_args") == 0)
5887 /* allow u64* as ctx */
5888 if (btf_is_int(t) && t->size == 8)
5891 case BPF_TRACE_ITER:
5892 /* allow struct bpf_iter__xxx types only */
5893 if (__btf_type_is_struct(t) &&
5894 strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
5897 case BPF_TRACE_FENTRY:
5898 case BPF_TRACE_FEXIT:
5899 case BPF_MODIFY_RETURN:
5900 /* allow u64* as ctx */
5901 if (btf_is_int(t) && t->size == 8)
5908 case BPF_PROG_TYPE_LSM:
5909 case BPF_PROG_TYPE_STRUCT_OPS:
5910 /* allow u64* as ctx */
5911 if (btf_is_int(t) && t->size == 8)
5914 case BPF_PROG_TYPE_TRACEPOINT:
5915 case BPF_PROG_TYPE_SYSCALL:
5916 case BPF_PROG_TYPE_EXT:
5917 return 0; /* anything goes */
5922 ctx_type = find_canonical_prog_ctx_type(prog_type);
5924 /* should not happen */
5925 bpf_log(log, "btf_vmlinux is malformed\n");
5929 /* resolve typedefs and check that underlying structs are matching as well */
5930 while (btf_type_is_modifier(ctx_type))
5931 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
5933 /* if program type doesn't have distinctly named struct type for
5934 * context, then __arg_ctx argument can only be `void *`, which we
5935 * already checked above
5937 if (!__btf_type_is_struct(ctx_type)) {
5938 bpf_log(log, "arg#%d should be void pointer\n", arg);
5942 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5943 if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
5944 bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
5951 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5953 const struct btf_type *t,
5954 enum bpf_prog_type prog_type,
5957 if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
5959 return find_kern_ctx_type_id(prog_type);
5962 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5964 const struct btf_member *kctx_member;
5965 const struct btf_type *conv_struct;
5966 const struct btf_type *kctx_type;
5969 conv_struct = bpf_ctx_convert.t;
5970 /* get member for kernel ctx type */
5971 kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5972 kctx_type_id = kctx_member->type;
5973 kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5974 if (!btf_type_is_struct(kctx_type)) {
5975 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5979 return kctx_type_id;
5982 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5983 BTF_ID(struct, bpf_ctx_convert)
5985 struct btf *btf_parse_vmlinux(void)
5987 struct btf_verifier_env *env = NULL;
5988 struct bpf_verifier_log *log;
5989 struct btf *btf = NULL;
5992 if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
5993 return ERR_PTR(-ENOENT);
5995 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5997 return ERR_PTR(-ENOMEM);
6000 log->level = BPF_LOG_KERNEL;
6002 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6009 btf->data = __start_BTF;
6010 btf->data_size = __stop_BTF - __start_BTF;
6011 btf->kernel_btf = true;
6012 snprintf(btf->name, sizeof(btf->name), "vmlinux");
6014 err = btf_parse_hdr(env);
6018 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6020 err = btf_parse_str_sec(env);
6024 err = btf_check_all_metas(env);
6028 err = btf_check_type_tags(env, btf, 1);
6032 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
6033 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6035 refcount_set(&btf->refcnt, 1);
6037 err = btf_alloc_id(btf);
6041 btf_verifier_env_free(env);
6045 btf_verifier_env_free(env);
6050 return ERR_PTR(err);
6053 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6055 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
6057 struct btf_verifier_env *env = NULL;
6058 struct bpf_verifier_log *log;
6059 struct btf *btf = NULL, *base_btf;
6062 base_btf = bpf_get_btf_vmlinux();
6063 if (IS_ERR(base_btf))
6066 return ERR_PTR(-EINVAL);
6068 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6070 return ERR_PTR(-ENOMEM);
6073 log->level = BPF_LOG_KERNEL;
6075 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6082 btf->base_btf = base_btf;
6083 btf->start_id = base_btf->nr_types;
6084 btf->start_str_off = base_btf->hdr.str_len;
6085 btf->kernel_btf = true;
6086 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
6088 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
6093 memcpy(btf->data, data, data_size);
6094 btf->data_size = data_size;
6096 err = btf_parse_hdr(env);
6100 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6102 err = btf_parse_str_sec(env);
6106 err = btf_check_all_metas(env);
6110 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6114 btf_verifier_env_free(env);
6115 refcount_set(&btf->refcnt, 1);
6119 btf_verifier_env_free(env);
6125 return ERR_PTR(err);
6128 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6130 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6132 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6135 return tgt_prog->aux->btf;
6137 return prog->aux->attach_btf;
6140 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
6142 /* skip modifiers */
6143 t = btf_type_skip_modifiers(btf, t->type, NULL);
6145 return btf_type_is_int(t);
6148 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6151 const struct btf_param *args;
6152 const struct btf_type *t;
6153 u32 offset = 0, nr_args;
6159 nr_args = btf_type_vlen(func_proto);
6160 args = (const struct btf_param *)(func_proto + 1);
6161 for (i = 0; i < nr_args; i++) {
6162 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6163 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6168 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6169 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6176 static bool prog_args_trusted(const struct bpf_prog *prog)
6178 enum bpf_attach_type atype = prog->expected_attach_type;
6180 switch (prog->type) {
6181 case BPF_PROG_TYPE_TRACING:
6182 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
6183 case BPF_PROG_TYPE_LSM:
6184 return bpf_lsm_is_trusted(prog);
6185 case BPF_PROG_TYPE_STRUCT_OPS:
6192 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6195 const struct btf_param *args;
6196 const struct btf_type *t;
6200 args = btf_params(func_proto);
6201 for (i = 0; i < arg_no; i++) {
6202 t = btf_type_by_id(btf, args[i].type);
6203 t = btf_resolve_size(btf, t, &sz);
6206 off += roundup(sz, 8);
6212 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
6213 const struct bpf_prog *prog,
6214 struct bpf_insn_access_aux *info)
6216 const struct btf_type *t = prog->aux->attach_func_proto;
6217 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6218 struct btf *btf = bpf_prog_get_target_btf(prog);
6219 const char *tname = prog->aux->attach_func_name;
6220 struct bpf_verifier_log *log = info->log;
6221 const struct btf_param *args;
6222 const char *tag_value;
6227 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6231 arg = get_ctx_arg_idx(btf, t, off);
6232 args = (const struct btf_param *)(t + 1);
6233 /* if (t == NULL) Fall back to default BPF prog with
6234 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
6236 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
6237 if (prog->aux->attach_btf_trace) {
6238 /* skip first 'void *__data' argument in btf_trace_##name typedef */
6243 if (arg > nr_args) {
6244 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6249 if (arg == nr_args) {
6250 switch (prog->expected_attach_type) {
6251 case BPF_LSM_CGROUP:
6253 case BPF_TRACE_FEXIT:
6254 /* When LSM programs are attached to void LSM hooks
6255 * they use FEXIT trampolines and when attached to
6256 * int LSM hooks, they use MODIFY_RETURN trampolines.
6258 * While the LSM programs are BPF_MODIFY_RETURN-like
6261 * if (ret_type != 'int')
6264 * is _not_ done here. This is still safe as LSM hooks
6265 * have only void and int return types.
6269 t = btf_type_by_id(btf, t->type);
6271 case BPF_MODIFY_RETURN:
6272 /* For now the BPF_MODIFY_RETURN can only be attached to
6273 * functions that return an int.
6278 t = btf_type_skip_modifiers(btf, t->type, NULL);
6279 if (!btf_type_is_small_int(t)) {
6281 "ret type %s not allowed for fmod_ret\n",
6287 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6293 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6295 t = btf_type_by_id(btf, args[arg].type);
6298 /* skip modifiers */
6299 while (btf_type_is_modifier(t))
6300 t = btf_type_by_id(btf, t->type);
6301 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6302 /* accessing a scalar */
6304 if (!btf_type_is_ptr(t)) {
6306 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6308 __btf_name_by_offset(btf, t->name_off),
6313 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6314 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6315 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6318 type = base_type(ctx_arg_info->reg_type);
6319 flag = type_flag(ctx_arg_info->reg_type);
6320 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6321 (flag & PTR_MAYBE_NULL)) {
6322 info->reg_type = ctx_arg_info->reg_type;
6328 /* This is a pointer to void.
6329 * It is the same as scalar from the verifier safety pov.
6330 * No further pointer walking is allowed.
6334 if (is_int_ptr(btf, t))
6337 /* this is a pointer to another type */
6338 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6339 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6341 if (ctx_arg_info->offset == off) {
6342 if (!ctx_arg_info->btf_id) {
6343 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6347 info->reg_type = ctx_arg_info->reg_type;
6348 info->btf = ctx_arg_info->btf ? : btf_vmlinux;
6349 info->btf_id = ctx_arg_info->btf_id;
6354 info->reg_type = PTR_TO_BTF_ID;
6355 if (prog_args_trusted(prog))
6356 info->reg_type |= PTR_TRUSTED;
6359 enum bpf_prog_type tgt_type;
6361 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6362 tgt_type = tgt_prog->aux->saved_dst_prog_type;
6364 tgt_type = tgt_prog->type;
6366 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6368 info->btf = btf_vmlinux;
6377 info->btf_id = t->type;
6378 t = btf_type_by_id(btf, t->type);
6380 if (btf_type_is_type_tag(t)) {
6381 tag_value = __btf_name_by_offset(btf, t->name_off);
6382 if (strcmp(tag_value, "user") == 0)
6383 info->reg_type |= MEM_USER;
6384 if (strcmp(tag_value, "percpu") == 0)
6385 info->reg_type |= MEM_PERCPU;
6388 /* skip modifiers */
6389 while (btf_type_is_modifier(t)) {
6390 info->btf_id = t->type;
6391 t = btf_type_by_id(btf, t->type);
6393 if (!btf_type_is_struct(t)) {
6395 "func '%s' arg%d type %s is not a struct\n",
6396 tname, arg, btf_type_str(t));
6399 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6400 tname, arg, info->btf_id, btf_type_str(t),
6401 __btf_name_by_offset(btf, t->name_off));
6404 EXPORT_SYMBOL_GPL(btf_ctx_access);
6406 enum bpf_struct_walk_result {
6413 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6414 const struct btf_type *t, int off, int size,
6415 u32 *next_btf_id, enum bpf_type_flag *flag,
6416 const char **field_name)
6418 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6419 const struct btf_type *mtype, *elem_type = NULL;
6420 const struct btf_member *member;
6421 const char *tname, *mname, *tag_value;
6422 u32 vlen, elem_id, mid;
6425 if (btf_type_is_modifier(t))
6426 t = btf_type_skip_modifiers(btf, t->type, NULL);
6427 tname = __btf_name_by_offset(btf, t->name_off);
6428 if (!btf_type_is_struct(t)) {
6429 bpf_log(log, "Type '%s' is not a struct\n", tname);
6433 vlen = btf_type_vlen(t);
6434 if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
6436 * walking unions yields untrusted pointers
6437 * with exception of __bpf_md_ptr and other
6438 * unions with a single member
6440 *flag |= PTR_UNTRUSTED;
6442 if (off + size > t->size) {
6443 /* If the last element is a variable size array, we may
6444 * need to relax the rule.
6446 struct btf_array *array_elem;
6451 member = btf_type_member(t) + vlen - 1;
6452 mtype = btf_type_skip_modifiers(btf, member->type,
6454 if (!btf_type_is_array(mtype))
6457 array_elem = (struct btf_array *)(mtype + 1);
6458 if (array_elem->nelems != 0)
6461 moff = __btf_member_bit_offset(t, member) / 8;
6465 /* allow structure and integer */
6466 t = btf_type_skip_modifiers(btf, array_elem->type,
6469 if (btf_type_is_int(t))
6472 if (!btf_type_is_struct(t))
6475 off = (off - moff) % t->size;
6479 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6484 for_each_member(i, t, member) {
6485 /* offset of the field in bytes */
6486 moff = __btf_member_bit_offset(t, member) / 8;
6487 if (off + size <= moff)
6488 /* won't find anything, field is already too far */
6491 if (__btf_member_bitfield_size(t, member)) {
6492 u32 end_bit = __btf_member_bit_offset(t, member) +
6493 __btf_member_bitfield_size(t, member);
6495 /* off <= moff instead of off == moff because clang
6496 * does not generate a BTF member for anonymous
6497 * bitfield like the ":16" here:
6504 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6507 /* off may be accessing a following member
6511 * Doing partial access at either end of this
6512 * bitfield. Continue on this case also to
6513 * treat it as not accessing this bitfield
6514 * and eventually error out as field not
6515 * found to keep it simple.
6516 * It could be relaxed if there was a legit
6517 * partial access case later.
6522 /* In case of "off" is pointing to holes of a struct */
6526 /* type of the field */
6528 mtype = btf_type_by_id(btf, member->type);
6529 mname = __btf_name_by_offset(btf, member->name_off);
6531 mtype = __btf_resolve_size(btf, mtype, &msize,
6532 &elem_type, &elem_id, &total_nelems,
6534 if (IS_ERR(mtype)) {
6535 bpf_log(log, "field %s doesn't have size\n", mname);
6539 mtrue_end = moff + msize;
6540 if (off >= mtrue_end)
6541 /* no overlap with member, keep iterating */
6544 if (btf_type_is_array(mtype)) {
6547 /* __btf_resolve_size() above helps to
6548 * linearize a multi-dimensional array.
6550 * The logic here is treating an array
6551 * in a struct as the following way:
6554 * struct inner array[2][2];
6560 * struct inner array_elem0;
6561 * struct inner array_elem1;
6562 * struct inner array_elem2;
6563 * struct inner array_elem3;
6566 * When accessing outer->array[1][0], it moves
6567 * moff to "array_elem2", set mtype to
6568 * "struct inner", and msize also becomes
6569 * sizeof(struct inner). Then most of the
6570 * remaining logic will fall through without
6571 * caring the current member is an array or
6574 * Unlike mtype/msize/moff, mtrue_end does not
6575 * change. The naming difference ("_true") tells
6576 * that it is not always corresponding to
6577 * the current mtype/msize/moff.
6578 * It is the true end of the current
6579 * member (i.e. array in this case). That
6580 * will allow an int array to be accessed like
6582 * i.e. allow access beyond the size of
6583 * the array's element as long as it is
6584 * within the mtrue_end boundary.
6587 /* skip empty array */
6588 if (moff == mtrue_end)
6591 msize /= total_nelems;
6592 elem_idx = (off - moff) / msize;
6593 moff += elem_idx * msize;
6598 /* the 'off' we're looking for is either equal to start
6599 * of this field or inside of this struct
6601 if (btf_type_is_struct(mtype)) {
6602 /* our field must be inside that union or struct */
6605 /* return if the offset matches the member offset */
6611 /* adjust offset we're looking for */
6616 if (btf_type_is_ptr(mtype)) {
6617 const struct btf_type *stype, *t;
6618 enum bpf_type_flag tmp_flag = 0;
6621 if (msize != size || off != moff) {
6623 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6624 mname, moff, tname, off, size);
6628 /* check type tag */
6629 t = btf_type_by_id(btf, mtype->type);
6630 if (btf_type_is_type_tag(t)) {
6631 tag_value = __btf_name_by_offset(btf, t->name_off);
6632 /* check __user tag */
6633 if (strcmp(tag_value, "user") == 0)
6634 tmp_flag = MEM_USER;
6635 /* check __percpu tag */
6636 if (strcmp(tag_value, "percpu") == 0)
6637 tmp_flag = MEM_PERCPU;
6638 /* check __rcu tag */
6639 if (strcmp(tag_value, "rcu") == 0)
6643 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6644 if (btf_type_is_struct(stype)) {
6648 *field_name = mname;
6653 /* Allow more flexible access within an int as long as
6654 * it is within mtrue_end.
6655 * Since mtrue_end could be the end of an array,
6656 * that also allows using an array of int as a scratch
6657 * space. e.g. skb->cb[].
6659 if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
6661 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6662 mname, mtrue_end, tname, off, size);
6668 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6672 int btf_struct_access(struct bpf_verifier_log *log,
6673 const struct bpf_reg_state *reg,
6674 int off, int size, enum bpf_access_type atype __maybe_unused,
6675 u32 *next_btf_id, enum bpf_type_flag *flag,
6676 const char **field_name)
6678 const struct btf *btf = reg->btf;
6679 enum bpf_type_flag tmp_flag = 0;
6680 const struct btf_type *t;
6681 u32 id = reg->btf_id;
6684 while (type_is_alloc(reg->type)) {
6685 struct btf_struct_meta *meta;
6686 struct btf_record *rec;
6689 meta = btf_find_struct_meta(btf, id);
6693 for (i = 0; i < rec->cnt; i++) {
6694 struct btf_field *field = &rec->fields[i];
6695 u32 offset = field->offset;
6696 if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6698 "direct access to %s is disallowed\n",
6699 btf_field_type_name(field->type));
6706 t = btf_type_by_id(btf, id);
6708 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6712 /* For local types, the destination register cannot
6713 * become a pointer again.
6715 if (type_is_alloc(reg->type))
6716 return SCALAR_VALUE;
6717 /* If we found the pointer or scalar on t+off,
6722 return PTR_TO_BTF_ID;
6724 return SCALAR_VALUE;
6726 /* We found nested struct, so continue the search
6727 * by diving in it. At this point the offset is
6728 * aligned with the new type, so set it to 0.
6730 t = btf_type_by_id(btf, id);
6734 /* It's either error or unknown return value..
6737 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6746 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6747 * the same. Trivial ID check is not enough due to module BTFs, because we can
6748 * end up with two different module BTFs, but IDs point to the common type in
6751 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6752 const struct btf *btf2, u32 id2)
6758 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6761 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6762 const struct btf *btf, u32 id, int off,
6763 const struct btf *need_btf, u32 need_type_id,
6766 const struct btf_type *type;
6767 enum bpf_type_flag flag = 0;
6770 /* Are we already done? */
6771 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6773 /* In case of strict type match, we do not walk struct, the top level
6774 * type match must succeed. When strict is true, off should have already
6780 type = btf_type_by_id(btf, id);
6783 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6784 if (err != WALK_STRUCT)
6787 /* We found nested struct object. If it matches
6788 * the requested ID, we're done. Otherwise let's
6789 * continue the search with offset 0 in the new
6792 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6800 static int __get_type_size(struct btf *btf, u32 btf_id,
6801 const struct btf_type **ret_type)
6803 const struct btf_type *t;
6805 *ret_type = btf_type_by_id(btf, 0);
6809 t = btf_type_by_id(btf, btf_id);
6810 while (t && btf_type_is_modifier(t))
6811 t = btf_type_by_id(btf, t->type);
6815 if (btf_type_is_ptr(t))
6816 /* kernel size of pointer. Not BPF's size of pointer*/
6817 return sizeof(void *);
6818 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6823 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6827 if (__btf_type_is_struct(t))
6828 flags |= BTF_FMODEL_STRUCT_ARG;
6829 if (btf_type_is_signed_int(t))
6830 flags |= BTF_FMODEL_SIGNED_ARG;
6835 int btf_distill_func_proto(struct bpf_verifier_log *log,
6837 const struct btf_type *func,
6839 struct btf_func_model *m)
6841 const struct btf_param *args;
6842 const struct btf_type *t;
6847 /* BTF function prototype doesn't match the verifier types.
6848 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6850 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6852 m->arg_flags[i] = 0;
6856 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6859 args = (const struct btf_param *)(func + 1);
6860 nargs = btf_type_vlen(func);
6861 if (nargs > MAX_BPF_FUNC_ARGS) {
6863 "The function %s has %d arguments. Too many.\n",
6867 ret = __get_type_size(btf, func->type, &t);
6868 if (ret < 0 || __btf_type_is_struct(t)) {
6870 "The function %s return type %s is unsupported.\n",
6871 tname, btf_type_str(t));
6875 m->ret_flags = __get_type_fmodel_flags(t);
6877 for (i = 0; i < nargs; i++) {
6878 if (i == nargs - 1 && args[i].type == 0) {
6880 "The function %s with variable args is unsupported.\n",
6884 ret = __get_type_size(btf, args[i].type, &t);
6886 /* No support of struct argument size greater than 16 bytes */
6887 if (ret < 0 || ret > 16) {
6889 "The function %s arg%d type %s is unsupported.\n",
6890 tname, i, btf_type_str(t));
6895 "The function %s has malformed void argument.\n",
6899 m->arg_size[i] = ret;
6900 m->arg_flags[i] = __get_type_fmodel_flags(t);
6906 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6907 * t1 points to BTF_KIND_FUNC in btf1
6908 * t2 points to BTF_KIND_FUNC in btf2
6910 * EINVAL - function prototype mismatch
6911 * EFAULT - verifier bug
6912 * 0 - 99% match. The last 1% is validated by the verifier.
6914 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6915 struct btf *btf1, const struct btf_type *t1,
6916 struct btf *btf2, const struct btf_type *t2)
6918 const struct btf_param *args1, *args2;
6919 const char *fn1, *fn2, *s1, *s2;
6920 u32 nargs1, nargs2, i;
6922 fn1 = btf_name_by_offset(btf1, t1->name_off);
6923 fn2 = btf_name_by_offset(btf2, t2->name_off);
6925 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6926 bpf_log(log, "%s() is not a global function\n", fn1);
6929 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6930 bpf_log(log, "%s() is not a global function\n", fn2);
6934 t1 = btf_type_by_id(btf1, t1->type);
6935 if (!t1 || !btf_type_is_func_proto(t1))
6937 t2 = btf_type_by_id(btf2, t2->type);
6938 if (!t2 || !btf_type_is_func_proto(t2))
6941 args1 = (const struct btf_param *)(t1 + 1);
6942 nargs1 = btf_type_vlen(t1);
6943 args2 = (const struct btf_param *)(t2 + 1);
6944 nargs2 = btf_type_vlen(t2);
6946 if (nargs1 != nargs2) {
6947 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6948 fn1, nargs1, fn2, nargs2);
6952 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6953 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6954 if (t1->info != t2->info) {
6956 "Return type %s of %s() doesn't match type %s of %s()\n",
6957 btf_type_str(t1), fn1,
6958 btf_type_str(t2), fn2);
6962 for (i = 0; i < nargs1; i++) {
6963 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6964 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6966 if (t1->info != t2->info) {
6967 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6968 i, fn1, btf_type_str(t1),
6969 fn2, btf_type_str(t2));
6972 if (btf_type_has_size(t1) && t1->size != t2->size) {
6974 "arg%d in %s() has size %d while %s() has %d\n",
6980 /* global functions are validated with scalars and pointers
6981 * to context only. And only global functions can be replaced.
6982 * Hence type check only those types.
6984 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6986 if (!btf_type_is_ptr(t1)) {
6988 "arg%d in %s() has unrecognized type\n",
6992 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6993 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6994 if (!btf_type_is_struct(t1)) {
6996 "arg%d in %s() is not a pointer to context\n",
7000 if (!btf_type_is_struct(t2)) {
7002 "arg%d in %s() is not a pointer to context\n",
7006 /* This is an optional check to make program writing easier.
7007 * Compare names of structs and report an error to the user.
7008 * btf_prepare_func_args() already checked that t2 struct
7009 * is a context type. btf_prepare_func_args() will check
7010 * later that t1 struct is a context type as well.
7012 s1 = btf_name_by_offset(btf1, t1->name_off);
7013 s2 = btf_name_by_offset(btf2, t2->name_off);
7014 if (strcmp(s1, s2)) {
7016 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7017 i, fn1, s1, fn2, s2);
7024 /* Compare BTFs of given program with BTF of target program */
7025 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
7026 struct btf *btf2, const struct btf_type *t2)
7028 struct btf *btf1 = prog->aux->btf;
7029 const struct btf_type *t1;
7032 if (!prog->aux->func_info) {
7033 bpf_log(log, "Program extension requires BTF\n");
7037 btf_id = prog->aux->func_info[0].type_id;
7041 t1 = btf_type_by_id(btf1, btf_id);
7042 if (!t1 || !btf_type_is_func(t1))
7045 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7048 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7052 t = btf_type_by_id(btf, t->type); /* skip PTR */
7054 while (btf_type_is_modifier(t))
7055 t = btf_type_by_id(btf, t->type);
7057 /* allow either struct or struct forward declaration */
7058 if (btf_type_is_struct(t) ||
7059 (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
7060 name = btf_str_by_offset(btf, t->name_off);
7061 return name && strcmp(name, "bpf_dynptr") == 0;
7067 struct bpf_cand_cache {
7073 const struct btf *btf;
7078 static DEFINE_MUTEX(cand_cache_mutex);
7080 static struct bpf_cand_cache *
7081 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7083 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
7084 const struct btf *btf, const struct btf_type *t)
7086 struct bpf_cand_cache *cc;
7087 struct bpf_core_ctx ctx = {
7091 u32 kern_type_id, type_id;
7094 /* skip PTR and modifiers */
7096 t = btf_type_by_id(btf, t->type);
7097 while (btf_type_is_modifier(t)) {
7099 t = btf_type_by_id(btf, t->type);
7102 mutex_lock(&cand_cache_mutex);
7103 cc = bpf_core_find_cands(&ctx, type_id);
7106 bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
7107 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7109 goto cand_cache_unlock;
7112 bpf_log(log, "arg#%d reference type('%s %s') %s\n",
7113 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7114 cc->cnt == 0 ? "has no matches" : "is ambiguous");
7115 err = cc->cnt == 0 ? -ENOENT : -ESRCH;
7116 goto cand_cache_unlock;
7118 if (btf_is_module(cc->cands[0].btf)) {
7119 bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
7120 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
7122 goto cand_cache_unlock;
7124 kern_type_id = cc->cands[0].id;
7127 mutex_unlock(&cand_cache_mutex);
7131 return kern_type_id;
7135 ARG_TAG_CTX = BIT_ULL(0),
7136 ARG_TAG_NONNULL = BIT_ULL(1),
7137 ARG_TAG_TRUSTED = BIT_ULL(2),
7138 ARG_TAG_NULLABLE = BIT_ULL(3),
7139 ARG_TAG_ARENA = BIT_ULL(4),
7142 /* Process BTF of a function to produce high-level expectation of function
7143 * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
7144 * is cached in subprog info for reuse.
7146 * EFAULT - there is a verifier bug. Abort verification.
7147 * EINVAL - cannot convert BTF.
7148 * 0 - Successfully processed BTF and constructed argument expectations.
7150 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7152 bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
7153 struct bpf_subprog_info *sub = subprog_info(env, subprog);
7154 struct bpf_verifier_log *log = &env->log;
7155 struct bpf_prog *prog = env->prog;
7156 enum bpf_prog_type prog_type = prog->type;
7157 struct btf *btf = prog->aux->btf;
7158 const struct btf_param *args;
7159 const struct btf_type *t, *ref_t, *fn_t;
7160 u32 i, nargs, btf_id;
7163 if (sub->args_cached)
7166 if (!prog->aux->func_info) {
7167 bpf_log(log, "Verifier bug\n");
7171 btf_id = prog->aux->func_info[subprog].type_id;
7173 if (!is_global) /* not fatal for static funcs */
7175 bpf_log(log, "Global functions need valid BTF\n");
7179 fn_t = btf_type_by_id(btf, btf_id);
7180 if (!fn_t || !btf_type_is_func(fn_t)) {
7181 /* These checks were already done by the verifier while loading
7182 * struct bpf_func_info
7184 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7188 tname = btf_name_by_offset(btf, fn_t->name_off);
7190 if (prog->aux->func_info_aux[subprog].unreliable) {
7191 bpf_log(log, "Verifier bug in function %s()\n", tname);
7194 if (prog_type == BPF_PROG_TYPE_EXT)
7195 prog_type = prog->aux->dst_prog->type;
7197 t = btf_type_by_id(btf, fn_t->type);
7198 if (!t || !btf_type_is_func_proto(t)) {
7199 bpf_log(log, "Invalid type of function %s()\n", tname);
7202 args = (const struct btf_param *)(t + 1);
7203 nargs = btf_type_vlen(t);
7204 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7207 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7208 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7211 /* check that function returns int, exception cb also requires this */
7212 t = btf_type_by_id(btf, t->type);
7213 while (btf_type_is_modifier(t))
7214 t = btf_type_by_id(btf, t->type);
7215 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7219 "Global function %s() doesn't return scalar. Only those are supported.\n",
7223 /* Convert BTF function arguments into verifier types.
7224 * Only PTR_TO_CTX and SCALAR are supported atm.
7226 for (i = 0; i < nargs; i++) {
7230 /* 'arg:<tag>' decl_tag takes precedence over derivation of
7231 * register type from BTF type itself
7233 while ((id = btf_find_next_decl_tag(btf, fn_t, i, "arg:", id)) > 0) {
7234 const struct btf_type *tag_t = btf_type_by_id(btf, id);
7235 const char *tag = __btf_name_by_offset(btf, tag_t->name_off) + 4;
7237 /* disallow arg tags in static subprogs */
7239 bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7243 if (strcmp(tag, "ctx") == 0) {
7244 tags |= ARG_TAG_CTX;
7245 } else if (strcmp(tag, "trusted") == 0) {
7246 tags |= ARG_TAG_TRUSTED;
7247 } else if (strcmp(tag, "nonnull") == 0) {
7248 tags |= ARG_TAG_NONNULL;
7249 } else if (strcmp(tag, "nullable") == 0) {
7250 tags |= ARG_TAG_NULLABLE;
7251 } else if (strcmp(tag, "arena") == 0) {
7252 tags |= ARG_TAG_ARENA;
7254 bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7258 if (id != -ENOENT) {
7259 bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7263 t = btf_type_by_id(btf, args[i].type);
7264 while (btf_type_is_modifier(t))
7265 t = btf_type_by_id(btf, t->type);
7266 if (!btf_type_is_ptr(t))
7269 if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
7270 if (tags & ~ARG_TAG_CTX) {
7271 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7274 if ((tags & ARG_TAG_CTX) &&
7275 btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7276 prog->expected_attach_type))
7278 sub->args[i].arg_type = ARG_PTR_TO_CTX;
7281 if (btf_is_dynptr_ptr(btf, t)) {
7283 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7286 sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7289 if (tags & ARG_TAG_TRUSTED) {
7292 if (tags & ARG_TAG_NONNULL) {
7293 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7297 kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7298 if (kern_type_id < 0)
7299 return kern_type_id;
7301 sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
7302 if (tags & ARG_TAG_NULLABLE)
7303 sub->args[i].arg_type |= PTR_MAYBE_NULL;
7304 sub->args[i].btf_id = kern_type_id;
7307 if (tags & ARG_TAG_ARENA) {
7308 if (tags & ~ARG_TAG_ARENA) {
7309 bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
7312 sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7315 if (is_global) { /* generic user data pointer */
7318 if (tags & ARG_TAG_NULLABLE) {
7319 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7323 t = btf_type_skip_modifiers(btf, t->type, NULL);
7324 ref_t = btf_resolve_size(btf, t, &mem_size);
7325 if (IS_ERR(ref_t)) {
7326 bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7327 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7332 sub->args[i].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
7333 if (tags & ARG_TAG_NONNULL)
7334 sub->args[i].arg_type &= ~PTR_MAYBE_NULL;
7335 sub->args[i].mem_size = mem_size;
7341 bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
7344 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7345 sub->args[i].arg_type = ARG_ANYTHING;
7350 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7351 i, btf_type_str(t), tname);
7355 sub->arg_cnt = nargs;
7356 sub->args_cached = true;
7361 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7362 struct btf_show *show)
7364 const struct btf_type *t = btf_type_by_id(btf, type_id);
7367 memset(&show->state, 0, sizeof(show->state));
7368 memset(&show->obj, 0, sizeof(show->obj));
7370 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7373 static void btf_seq_show(struct btf_show *show, const char *fmt,
7376 seq_vprintf((struct seq_file *)show->target, fmt, args);
7379 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7380 void *obj, struct seq_file *m, u64 flags)
7382 struct btf_show sseq;
7385 sseq.showfn = btf_seq_show;
7388 btf_type_show(btf, type_id, obj, &sseq);
7390 return sseq.state.status;
7393 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7396 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7397 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7398 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7401 struct btf_show_snprintf {
7402 struct btf_show show;
7403 int len_left; /* space left in string */
7404 int len; /* length we would have written */
7407 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7410 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7413 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7416 ssnprintf->len_left = 0;
7417 ssnprintf->len = len;
7418 } else if (len >= ssnprintf->len_left) {
7419 /* no space, drive on to get length we would have written */
7420 ssnprintf->len_left = 0;
7421 ssnprintf->len += len;
7423 ssnprintf->len_left -= len;
7424 ssnprintf->len += len;
7425 show->target += len;
7429 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7430 char *buf, int len, u64 flags)
7432 struct btf_show_snprintf ssnprintf;
7434 ssnprintf.show.target = buf;
7435 ssnprintf.show.flags = flags;
7436 ssnprintf.show.showfn = btf_snprintf_show;
7437 ssnprintf.len_left = len;
7440 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7442 /* If we encountered an error, return it. */
7443 if (ssnprintf.show.state.status)
7444 return ssnprintf.show.state.status;
7446 /* Otherwise return length we would have written */
7447 return ssnprintf.len;
7450 #ifdef CONFIG_PROC_FS
7451 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7453 const struct btf *btf = filp->private_data;
7455 seq_printf(m, "btf_id:\t%u\n", btf->id);
7459 static int btf_release(struct inode *inode, struct file *filp)
7461 btf_put(filp->private_data);
7465 const struct file_operations btf_fops = {
7466 #ifdef CONFIG_PROC_FS
7467 .show_fdinfo = bpf_btf_show_fdinfo,
7469 .release = btf_release,
7472 static int __btf_new_fd(struct btf *btf)
7474 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7477 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7482 btf = btf_parse(attr, uattr, uattr_size);
7484 return PTR_ERR(btf);
7486 ret = btf_alloc_id(btf);
7493 * The BTF ID is published to the userspace.
7494 * All BTF free must go through call_rcu() from
7495 * now on (i.e. free by calling btf_put()).
7498 ret = __btf_new_fd(btf);
7505 struct btf *btf_get_by_fd(int fd)
7513 return ERR_PTR(-EBADF);
7515 if (f.file->f_op != &btf_fops) {
7517 return ERR_PTR(-EINVAL);
7520 btf = f.file->private_data;
7521 refcount_inc(&btf->refcnt);
7527 int btf_get_info_by_fd(const struct btf *btf,
7528 const union bpf_attr *attr,
7529 union bpf_attr __user *uattr)
7531 struct bpf_btf_info __user *uinfo;
7532 struct bpf_btf_info info;
7533 u32 info_copy, btf_copy;
7536 u32 uinfo_len, uname_len, name_len;
7539 uinfo = u64_to_user_ptr(attr->info.info);
7540 uinfo_len = attr->info.info_len;
7542 info_copy = min_t(u32, uinfo_len, sizeof(info));
7543 memset(&info, 0, sizeof(info));
7544 if (copy_from_user(&info, uinfo, info_copy))
7548 ubtf = u64_to_user_ptr(info.btf);
7549 btf_copy = min_t(u32, btf->data_size, info.btf_size);
7550 if (copy_to_user(ubtf, btf->data, btf_copy))
7552 info.btf_size = btf->data_size;
7554 info.kernel_btf = btf->kernel_btf;
7556 uname = u64_to_user_ptr(info.name);
7557 uname_len = info.name_len;
7558 if (!uname ^ !uname_len)
7561 name_len = strlen(btf->name);
7562 info.name_len = name_len;
7565 if (uname_len >= name_len + 1) {
7566 if (copy_to_user(uname, btf->name, name_len + 1))
7571 if (copy_to_user(uname, btf->name, uname_len - 1))
7573 if (put_user(zero, uname + uname_len - 1))
7575 /* let user-space know about too short buffer */
7580 if (copy_to_user(uinfo, &info, info_copy) ||
7581 put_user(info_copy, &uattr->info.info_len))
7587 int btf_get_fd_by_id(u32 id)
7593 btf = idr_find(&btf_idr, id);
7594 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7595 btf = ERR_PTR(-ENOENT);
7599 return PTR_ERR(btf);
7601 fd = __btf_new_fd(btf);
7608 u32 btf_obj_id(const struct btf *btf)
7613 bool btf_is_kernel(const struct btf *btf)
7615 return btf->kernel_btf;
7618 bool btf_is_module(const struct btf *btf)
7620 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7624 BTF_MODULE_F_LIVE = (1 << 0),
7627 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7629 struct list_head list;
7630 struct module *module;
7632 struct bin_attribute *sysfs_attr;
7636 static LIST_HEAD(btf_modules);
7637 static DEFINE_MUTEX(btf_module_mutex);
7640 btf_module_read(struct file *file, struct kobject *kobj,
7641 struct bin_attribute *bin_attr,
7642 char *buf, loff_t off, size_t len)
7644 const struct btf *btf = bin_attr->private;
7646 memcpy(buf, btf->data + off, len);
7650 static void purge_cand_cache(struct btf *btf);
7652 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7655 struct btf_module *btf_mod, *tmp;
7656 struct module *mod = module;
7660 if (mod->btf_data_size == 0 ||
7661 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7662 op != MODULE_STATE_GOING))
7666 case MODULE_STATE_COMING:
7667 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7672 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7675 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7676 pr_warn("failed to validate module [%s] BTF: %ld\n",
7677 mod->name, PTR_ERR(btf));
7680 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7684 err = btf_alloc_id(btf);
7691 purge_cand_cache(NULL);
7692 mutex_lock(&btf_module_mutex);
7693 btf_mod->module = module;
7695 list_add(&btf_mod->list, &btf_modules);
7696 mutex_unlock(&btf_module_mutex);
7698 if (IS_ENABLED(CONFIG_SYSFS)) {
7699 struct bin_attribute *attr;
7701 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7705 sysfs_bin_attr_init(attr);
7706 attr->attr.name = btf->name;
7707 attr->attr.mode = 0444;
7708 attr->size = btf->data_size;
7709 attr->private = btf;
7710 attr->read = btf_module_read;
7712 err = sysfs_create_bin_file(btf_kobj, attr);
7714 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7721 btf_mod->sysfs_attr = attr;
7725 case MODULE_STATE_LIVE:
7726 mutex_lock(&btf_module_mutex);
7727 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7728 if (btf_mod->module != module)
7731 btf_mod->flags |= BTF_MODULE_F_LIVE;
7734 mutex_unlock(&btf_module_mutex);
7736 case MODULE_STATE_GOING:
7737 mutex_lock(&btf_module_mutex);
7738 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7739 if (btf_mod->module != module)
7742 list_del(&btf_mod->list);
7743 if (btf_mod->sysfs_attr)
7744 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7745 purge_cand_cache(btf_mod->btf);
7746 btf_put(btf_mod->btf);
7747 kfree(btf_mod->sysfs_attr);
7751 mutex_unlock(&btf_module_mutex);
7755 return notifier_from_errno(err);
7758 static struct notifier_block btf_module_nb = {
7759 .notifier_call = btf_module_notify,
7762 static int __init btf_module_init(void)
7764 register_module_notifier(&btf_module_nb);
7768 fs_initcall(btf_module_init);
7769 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7771 struct module *btf_try_get_module(const struct btf *btf)
7773 struct module *res = NULL;
7774 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7775 struct btf_module *btf_mod, *tmp;
7777 mutex_lock(&btf_module_mutex);
7778 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7779 if (btf_mod->btf != btf)
7782 /* We must only consider module whose __init routine has
7783 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7784 * which is set from the notifier callback for
7785 * MODULE_STATE_LIVE.
7787 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7788 res = btf_mod->module;
7792 mutex_unlock(&btf_module_mutex);
7798 /* Returns struct btf corresponding to the struct module.
7799 * This function can return NULL or ERR_PTR.
7801 static struct btf *btf_get_module_btf(const struct module *module)
7803 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7804 struct btf_module *btf_mod, *tmp;
7806 struct btf *btf = NULL;
7809 btf = bpf_get_btf_vmlinux();
7810 if (!IS_ERR_OR_NULL(btf))
7815 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7816 mutex_lock(&btf_module_mutex);
7817 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7818 if (btf_mod->module != module)
7821 btf_get(btf_mod->btf);
7825 mutex_unlock(&btf_module_mutex);
7831 static int check_btf_kconfigs(const struct module *module, const char *feature)
7833 if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7834 pr_err("missing vmlinux BTF, cannot register %s\n", feature);
7837 if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
7838 pr_warn("missing module BTF, cannot register %s\n", feature);
7842 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7844 struct btf *btf = NULL;
7851 if (name_sz <= 1 || name[name_sz - 1])
7854 ret = bpf_find_btf_id(name, kind, &btf);
7855 if (ret > 0 && btf_is_module(btf)) {
7856 btf_obj_fd = __btf_new_fd(btf);
7857 if (btf_obj_fd < 0) {
7861 return ret | (((u64)btf_obj_fd) << 32);
7868 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7869 .func = bpf_btf_find_by_name_kind,
7871 .ret_type = RET_INTEGER,
7872 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
7873 .arg2_type = ARG_CONST_SIZE,
7874 .arg3_type = ARG_ANYTHING,
7875 .arg4_type = ARG_ANYTHING,
7878 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7879 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7880 BTF_TRACING_TYPE_xxx
7881 #undef BTF_TRACING_TYPE
7883 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
7884 const struct btf_type *func, u32 func_flags)
7886 u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7887 const char *name, *sfx, *iter_name;
7888 const struct btf_param *arg;
7889 const struct btf_type *t;
7893 /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
7894 if (!flags || (flags & (flags - 1)))
7897 /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
7898 nr_args = btf_type_vlen(func);
7902 arg = &btf_params(func)[0];
7903 t = btf_type_skip_modifiers(btf, arg->type, NULL);
7904 if (!t || !btf_type_is_ptr(t))
7906 t = btf_type_skip_modifiers(btf, t->type, NULL);
7907 if (!t || !__btf_type_is_struct(t))
7910 name = btf_name_by_offset(btf, t->name_off);
7911 if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
7914 /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
7915 * fit nicely in stack slots
7917 if (t->size == 0 || (t->size % 8))
7920 /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
7923 iter_name = name + sizeof(ITER_PREFIX) - 1;
7924 if (flags & KF_ITER_NEW)
7926 else if (flags & KF_ITER_NEXT)
7928 else /* (flags & KF_ITER_DESTROY) */
7931 snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
7932 if (strcmp(func_name, exp_name))
7935 /* only iter constructor should have extra arguments */
7936 if (!(flags & KF_ITER_NEW) && nr_args != 1)
7939 if (flags & KF_ITER_NEXT) {
7940 /* bpf_iter_<type>_next() should return pointer */
7941 t = btf_type_skip_modifiers(btf, func->type, NULL);
7942 if (!t || !btf_type_is_ptr(t))
7946 if (flags & KF_ITER_DESTROY) {
7947 /* bpf_iter_<type>_destroy() should return void */
7948 t = btf_type_by_id(btf, func->type);
7949 if (!t || !btf_type_is_void(t))
7956 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
7958 const struct btf_type *func;
7959 const char *func_name;
7962 /* any kfunc should be FUNC -> FUNC_PROTO */
7963 func = btf_type_by_id(btf, func_id);
7964 if (!func || !btf_type_is_func(func))
7967 /* sanity check kfunc name */
7968 func_name = btf_name_by_offset(btf, func->name_off);
7969 if (!func_name || !func_name[0])
7972 func = btf_type_by_id(btf, func->type);
7973 if (!func || !btf_type_is_func_proto(func))
7976 if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
7977 err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
7985 /* Kernel Function (kfunc) BTF ID set registration API */
7987 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7988 const struct btf_kfunc_id_set *kset)
7990 struct btf_kfunc_hook_filter *hook_filter;
7991 struct btf_id_set8 *add_set = kset->set;
7992 bool vmlinux_set = !btf_is_module(btf);
7993 bool add_filter = !!kset->filter;
7994 struct btf_kfunc_set_tab *tab;
7995 struct btf_id_set8 *set;
7999 if (hook >= BTF_KFUNC_HOOK_MAX) {
8007 tab = btf->kfunc_set_tab;
8009 if (tab && add_filter) {
8012 hook_filter = &tab->hook_filters[hook];
8013 for (i = 0; i < hook_filter->nr_filters; i++) {
8014 if (hook_filter->filters[i] == kset->filter) {
8020 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8027 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
8030 btf->kfunc_set_tab = tab;
8033 set = tab->sets[hook];
8034 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
8037 if (WARN_ON_ONCE(set && !vmlinux_set)) {
8042 /* We don't need to allocate, concatenate, and sort module sets, because
8043 * only one is allowed per hook. Hence, we can directly assign the
8044 * pointer and return.
8047 tab->sets[hook] = add_set;
8051 /* In case of vmlinux sets, there may be more than one set being
8052 * registered per hook. To create a unified set, we allocate a new set
8053 * and concatenate all individual sets being registered. While each set
8054 * is individually sorted, they may become unsorted when concatenated,
8055 * hence re-sorting the final set again is required to make binary
8056 * searching the set using btf_id_set8_contains function work.
8058 set_cnt = set ? set->cnt : 0;
8060 if (set_cnt > U32_MAX - add_set->cnt) {
8065 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8071 set = krealloc(tab->sets[hook],
8072 offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
8073 GFP_KERNEL | __GFP_NOWARN);
8079 /* For newly allocated set, initialize set->cnt to 0 */
8080 if (!tab->sets[hook])
8082 tab->sets[hook] = set;
8084 /* Concatenate the two sets */
8085 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
8086 set->cnt += add_set->cnt;
8088 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8092 hook_filter = &tab->hook_filters[hook];
8093 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8097 btf_free_kfunc_set_tab(btf);
8101 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
8102 enum btf_kfunc_hook hook,
8104 const struct bpf_prog *prog)
8106 struct btf_kfunc_hook_filter *hook_filter;
8107 struct btf_id_set8 *set;
8110 if (hook >= BTF_KFUNC_HOOK_MAX)
8112 if (!btf->kfunc_set_tab)
8114 hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
8115 for (i = 0; i < hook_filter->nr_filters; i++) {
8116 if (hook_filter->filters[i](prog, kfunc_btf_id))
8119 set = btf->kfunc_set_tab->sets[hook];
8122 id = btf_id_set8_contains(set, kfunc_btf_id);
8125 /* The flags for BTF ID are located next to it */
8129 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8131 switch (prog_type) {
8132 case BPF_PROG_TYPE_UNSPEC:
8133 return BTF_KFUNC_HOOK_COMMON;
8134 case BPF_PROG_TYPE_XDP:
8135 return BTF_KFUNC_HOOK_XDP;
8136 case BPF_PROG_TYPE_SCHED_CLS:
8137 return BTF_KFUNC_HOOK_TC;
8138 case BPF_PROG_TYPE_STRUCT_OPS:
8139 return BTF_KFUNC_HOOK_STRUCT_OPS;
8140 case BPF_PROG_TYPE_TRACING:
8141 case BPF_PROG_TYPE_LSM:
8142 return BTF_KFUNC_HOOK_TRACING;
8143 case BPF_PROG_TYPE_SYSCALL:
8144 return BTF_KFUNC_HOOK_SYSCALL;
8145 case BPF_PROG_TYPE_CGROUP_SKB:
8146 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8147 return BTF_KFUNC_HOOK_CGROUP_SKB;
8148 case BPF_PROG_TYPE_SCHED_ACT:
8149 return BTF_KFUNC_HOOK_SCHED_ACT;
8150 case BPF_PROG_TYPE_SK_SKB:
8151 return BTF_KFUNC_HOOK_SK_SKB;
8152 case BPF_PROG_TYPE_SOCKET_FILTER:
8153 return BTF_KFUNC_HOOK_SOCKET_FILTER;
8154 case BPF_PROG_TYPE_LWT_OUT:
8155 case BPF_PROG_TYPE_LWT_IN:
8156 case BPF_PROG_TYPE_LWT_XMIT:
8157 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
8158 return BTF_KFUNC_HOOK_LWT;
8159 case BPF_PROG_TYPE_NETFILTER:
8160 return BTF_KFUNC_HOOK_NETFILTER;
8161 case BPF_PROG_TYPE_KPROBE:
8162 return BTF_KFUNC_HOOK_KPROBE;
8164 return BTF_KFUNC_HOOK_MAX;
8169 * Reference to the module (obtained using btf_try_get_module) corresponding to
8170 * the struct btf *MUST* be held when calling this function from verifier
8171 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
8172 * keeping the reference for the duration of the call provides the necessary
8173 * protection for looking up a well-formed btf->kfunc_set_tab.
8175 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8177 const struct bpf_prog *prog)
8179 enum bpf_prog_type prog_type = resolve_prog_type(prog);
8180 enum btf_kfunc_hook hook;
8183 kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
8187 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8188 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
8191 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8192 const struct bpf_prog *prog)
8194 return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
8197 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8198 const struct btf_kfunc_id_set *kset)
8203 btf = btf_get_module_btf(kset->owner);
8205 return check_btf_kconfigs(kset->owner, "kfunc");
8207 return PTR_ERR(btf);
8209 for (i = 0; i < kset->set->cnt; i++) {
8210 ret = btf_check_kfunc_protos(btf, kset->set->pairs[i].id,
8211 kset->set->pairs[i].flags);
8216 ret = btf_populate_kfunc_set(btf, hook, kset);
8223 /* This function must be invoked only from initcalls/module init functions */
8224 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
8225 const struct btf_kfunc_id_set *kset)
8227 enum btf_kfunc_hook hook;
8229 /* All kfuncs need to be tagged as such in BTF.
8230 * WARN() for initcall registrations that do not check errors.
8232 if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8233 WARN_ON(!kset->owner);
8237 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8238 return __register_btf_kfunc_id_set(hook, kset);
8240 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8242 /* This function must be invoked only from initcalls/module init functions */
8243 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
8245 return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8247 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8249 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8251 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8252 struct btf_id_dtor_kfunc *dtor;
8256 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
8257 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
8259 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
8260 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
8263 return dtor->kfunc_btf_id;
8266 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8268 const struct btf_type *dtor_func, *dtor_func_proto, *t;
8269 const struct btf_param *args;
8273 for (i = 0; i < cnt; i++) {
8274 dtor_btf_id = dtors[i].kfunc_btf_id;
8276 dtor_func = btf_type_by_id(btf, dtor_btf_id);
8277 if (!dtor_func || !btf_type_is_func(dtor_func))
8280 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
8281 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
8284 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
8285 t = btf_type_by_id(btf, dtor_func_proto->type);
8286 if (!t || !btf_type_is_void(t))
8289 nr_args = btf_type_vlen(dtor_func_proto);
8292 args = btf_params(dtor_func_proto);
8293 t = btf_type_by_id(btf, args[0].type);
8294 /* Allow any pointer type, as width on targets Linux supports
8295 * will be same for all pointer types (i.e. sizeof(void *))
8297 if (!t || !btf_type_is_ptr(t))
8303 /* This function must be invoked only from initcalls/module init functions */
8304 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
8305 struct module *owner)
8307 struct btf_id_dtor_kfunc_tab *tab;
8312 btf = btf_get_module_btf(owner);
8314 return check_btf_kconfigs(owner, "dtor kfuncs");
8316 return PTR_ERR(btf);
8318 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8319 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8324 /* Ensure that the prototype of dtor kfuncs being registered is sane */
8325 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8329 tab = btf->dtor_kfunc_tab;
8330 /* Only one call allowed for modules */
8331 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8336 tab_cnt = tab ? tab->cnt : 0;
8337 if (tab_cnt > U32_MAX - add_cnt) {
8341 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8342 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8347 tab = krealloc(btf->dtor_kfunc_tab,
8348 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
8349 GFP_KERNEL | __GFP_NOWARN);
8355 if (!btf->dtor_kfunc_tab)
8357 btf->dtor_kfunc_tab = tab;
8359 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8360 tab->cnt += add_cnt;
8362 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8366 btf_free_dtor_kfunc_tab(btf);
8370 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8372 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8374 /* Check local and target types for compatibility. This check is used for
8375 * type-based CO-RE relocations and follow slightly different rules than
8376 * field-based relocations. This function assumes that root types were already
8377 * checked for name match. Beyond that initial root-level name check, names
8378 * are completely ignored. Compatibility rules are as follows:
8379 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8380 * kind should match for local and target types (i.e., STRUCT is not
8381 * compatible with UNION);
8382 * - for ENUMs/ENUM64s, the size is ignored;
8383 * - for INT, size and signedness are ignored;
8384 * - for ARRAY, dimensionality is ignored, element types are checked for
8385 * compatibility recursively;
8386 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
8387 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8388 * - FUNC_PROTOs are compatible if they have compatible signature: same
8389 * number of input args and compatible return and argument types.
8390 * These rules are not set in stone and probably will be adjusted as we get
8391 * more experience with using BPF CO-RE relocations.
8393 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8394 const struct btf *targ_btf, __u32 targ_id)
8396 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8397 MAX_TYPES_ARE_COMPAT_DEPTH);
8400 #define MAX_TYPES_MATCH_DEPTH 2
8402 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8403 const struct btf *targ_btf, u32 targ_id)
8405 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8406 MAX_TYPES_MATCH_DEPTH);
8409 static bool bpf_core_is_flavor_sep(const char *s)
8411 /* check X___Y name pattern, where X and Y are not underscores */
8412 return s[0] != '_' && /* X */
8413 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
8414 s[4] != '_'; /* Y */
8417 size_t bpf_core_essential_name_len(const char *name)
8419 size_t n = strlen(name);
8422 for (i = n - 5; i >= 0; i--) {
8423 if (bpf_core_is_flavor_sep(name + i))
8429 static void bpf_free_cands(struct bpf_cand_cache *cands)
8432 /* empty candidate array was allocated on stack */
8437 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8443 #define VMLINUX_CAND_CACHE_SIZE 31
8444 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8446 #define MODULE_CAND_CACHE_SIZE 31
8447 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8449 static void __print_cand_cache(struct bpf_verifier_log *log,
8450 struct bpf_cand_cache **cache,
8453 struct bpf_cand_cache *cc;
8456 for (i = 0; i < cache_size; i++) {
8460 bpf_log(log, "[%d]%s(", i, cc->name);
8461 for (j = 0; j < cc->cnt; j++) {
8462 bpf_log(log, "%d", cc->cands[j].id);
8463 if (j < cc->cnt - 1)
8466 bpf_log(log, "), ");
8470 static void print_cand_cache(struct bpf_verifier_log *log)
8472 mutex_lock(&cand_cache_mutex);
8473 bpf_log(log, "vmlinux_cand_cache:");
8474 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8475 bpf_log(log, "\nmodule_cand_cache:");
8476 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8478 mutex_unlock(&cand_cache_mutex);
8481 static u32 hash_cands(struct bpf_cand_cache *cands)
8483 return jhash(cands->name, cands->name_len, 0);
8486 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8487 struct bpf_cand_cache **cache,
8490 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8492 if (cc && cc->name_len == cands->name_len &&
8493 !strncmp(cc->name, cands->name, cands->name_len))
8498 static size_t sizeof_cands(int cnt)
8500 return offsetof(struct bpf_cand_cache, cands[cnt]);
8503 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8504 struct bpf_cand_cache **cache,
8507 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8510 bpf_free_cands_from_cache(*cc);
8513 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8515 bpf_free_cands(cands);
8516 return ERR_PTR(-ENOMEM);
8518 /* strdup the name, since it will stay in cache.
8519 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8521 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8522 bpf_free_cands(cands);
8523 if (!new_cands->name) {
8525 return ERR_PTR(-ENOMEM);
8531 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8532 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8535 struct bpf_cand_cache *cc;
8538 for (i = 0; i < cache_size; i++) {
8543 /* when new module is loaded purge all of module_cand_cache,
8544 * since new module might have candidates with the name
8545 * that matches cached cands.
8547 bpf_free_cands_from_cache(cc);
8551 /* when module is unloaded purge cache entries
8552 * that match module's btf
8554 for (j = 0; j < cc->cnt; j++)
8555 if (cc->cands[j].btf == btf) {
8556 bpf_free_cands_from_cache(cc);
8564 static void purge_cand_cache(struct btf *btf)
8566 mutex_lock(&cand_cache_mutex);
8567 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8568 mutex_unlock(&cand_cache_mutex);
8572 static struct bpf_cand_cache *
8573 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8576 struct bpf_cand_cache *new_cands;
8577 const struct btf_type *t;
8578 const char *targ_name;
8579 size_t targ_essent_len;
8582 n = btf_nr_types(targ_btf);
8583 for (i = targ_start_id; i < n; i++) {
8584 t = btf_type_by_id(targ_btf, i);
8585 if (btf_kind(t) != cands->kind)
8588 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8592 /* the resched point is before strncmp to make sure that search
8593 * for non-existing name will have a chance to schedule().
8597 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8600 targ_essent_len = bpf_core_essential_name_len(targ_name);
8601 if (targ_essent_len != cands->name_len)
8604 /* most of the time there is only one candidate for a given kind+name pair */
8605 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8607 bpf_free_cands(cands);
8608 return ERR_PTR(-ENOMEM);
8611 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8612 bpf_free_cands(cands);
8614 cands->cands[cands->cnt].btf = targ_btf;
8615 cands->cands[cands->cnt].id = i;
8621 static struct bpf_cand_cache *
8622 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8624 struct bpf_cand_cache *cands, *cc, local_cand = {};
8625 const struct btf *local_btf = ctx->btf;
8626 const struct btf_type *local_type;
8627 const struct btf *main_btf;
8628 size_t local_essent_len;
8629 struct btf *mod_btf;
8633 main_btf = bpf_get_btf_vmlinux();
8634 if (IS_ERR(main_btf))
8635 return ERR_CAST(main_btf);
8637 return ERR_PTR(-EINVAL);
8639 local_type = btf_type_by_id(local_btf, local_type_id);
8641 return ERR_PTR(-EINVAL);
8643 name = btf_name_by_offset(local_btf, local_type->name_off);
8644 if (str_is_empty(name))
8645 return ERR_PTR(-EINVAL);
8646 local_essent_len = bpf_core_essential_name_len(name);
8648 cands = &local_cand;
8650 cands->kind = btf_kind(local_type);
8651 cands->name_len = local_essent_len;
8653 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8654 /* cands is a pointer to stack here */
8661 /* Attempt to find target candidates in vmlinux BTF first */
8662 cands = bpf_core_add_cands(cands, main_btf, 1);
8664 return ERR_CAST(cands);
8666 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8668 /* populate cache even when cands->cnt == 0 */
8669 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8671 return ERR_CAST(cc);
8673 /* if vmlinux BTF has any candidate, don't go for module BTFs */
8678 /* cands is a pointer to stack here and cands->cnt == 0 */
8679 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8681 /* if cache has it return it even if cc->cnt == 0 */
8684 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8685 spin_lock_bh(&btf_idr_lock);
8686 idr_for_each_entry(&btf_idr, mod_btf, id) {
8687 if (!btf_is_module(mod_btf))
8689 /* linear search could be slow hence unlock/lock
8690 * the IDR to avoiding holding it for too long
8693 spin_unlock_bh(&btf_idr_lock);
8694 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8697 return ERR_CAST(cands);
8698 spin_lock_bh(&btf_idr_lock);
8700 spin_unlock_bh(&btf_idr_lock);
8701 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8702 * or pointer to stack if cands->cnd == 0.
8703 * Copy it into the cache even when cands->cnt == 0 and
8704 * return the result.
8706 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8709 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8710 int relo_idx, void *insn)
8712 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8713 struct bpf_core_cand_list cands = {};
8714 struct bpf_core_relo_res targ_res;
8715 struct bpf_core_spec *specs;
8718 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8719 * into arrays of btf_ids of struct fields and array indices.
8721 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8726 struct bpf_cand_cache *cc;
8729 mutex_lock(&cand_cache_mutex);
8730 cc = bpf_core_find_cands(ctx, relo->type_id);
8732 bpf_log(ctx->log, "target candidate search failed for %d\n",
8738 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8744 for (i = 0; i < cc->cnt; i++) {
8746 "CO-RE relocating %s %s: found target candidate [%d]\n",
8747 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8748 cands.cands[i].btf = cc->cands[i].btf;
8749 cands.cands[i].id = cc->cands[i].id;
8751 cands.len = cc->cnt;
8752 /* cand_cache_mutex needs to span the cache lookup and
8753 * copy of btf pointer into bpf_core_cand_list,
8754 * since module can be unloaded while bpf_core_calc_relo_insn
8755 * is working with module's btf.
8759 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8764 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8771 mutex_unlock(&cand_cache_mutex);
8772 if (ctx->log->level & BPF_LOG_LEVEL2)
8773 print_cand_cache(ctx->log);
8778 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8779 const struct bpf_reg_state *reg,
8780 const char *field_name, u32 btf_id, const char *suffix)
8782 struct btf *btf = reg->btf;
8783 const struct btf_type *walk_type, *safe_type;
8785 char safe_tname[64];
8787 const struct btf_member *member;
8790 walk_type = btf_type_by_id(btf, reg->btf_id);
8794 tname = btf_name_by_offset(btf, walk_type->name_off);
8796 ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8797 if (ret >= sizeof(safe_tname))
8800 safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8804 safe_type = btf_type_by_id(btf, safe_id);
8808 for_each_member(i, safe_type, member) {
8809 const char *m_name = __btf_name_by_offset(btf, member->name_off);
8810 const struct btf_type *mtype = btf_type_by_id(btf, member->type);
8813 if (!btf_type_is_ptr(mtype))
8816 btf_type_skip_modifiers(btf, mtype->type, &id);
8817 /* If we match on both type and name, the field is considered trusted. */
8818 if (btf_id == id && !strcmp(field_name, m_name))
8825 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8826 const struct btf *reg_btf, u32 reg_id,
8827 const struct btf *arg_btf, u32 arg_id)
8829 const char *reg_name, *arg_name, *search_needle;
8830 const struct btf_type *reg_type, *arg_type;
8831 int reg_len, arg_len, cmp_len;
8832 size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8834 reg_type = btf_type_by_id(reg_btf, reg_id);
8838 arg_type = btf_type_by_id(arg_btf, arg_id);
8842 reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8843 arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8845 reg_len = strlen(reg_name);
8846 arg_len = strlen(arg_name);
8848 /* Exactly one of the two type names may be suffixed with ___init, so
8849 * if the strings are the same size, they can't possibly be no-cast
8850 * aliases of one another. If you have two of the same type names, e.g.
8851 * they're both nf_conn___init, it would be improper to return true
8852 * because they are _not_ no-cast aliases, they are the same type.
8854 if (reg_len == arg_len)
8857 /* Either of the two names must be the other name, suffixed with ___init. */
8858 if ((reg_len != arg_len + pattern_len) &&
8859 (arg_len != reg_len + pattern_len))
8862 if (reg_len < arg_len) {
8863 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8866 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8873 /* ___init suffix must come at the end of the name */
8874 if (*(search_needle + pattern_len) != '\0')
8877 return !strncmp(reg_name, arg_name, cmp_len);
8880 #ifdef CONFIG_BPF_JIT
8882 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
8883 struct bpf_verifier_log *log)
8885 struct btf_struct_ops_tab *tab, *new_tab;
8888 tab = btf->struct_ops_tab;
8890 tab = kzalloc(offsetof(struct btf_struct_ops_tab, ops[4]),
8895 btf->struct_ops_tab = tab;
8898 for (i = 0; i < tab->cnt; i++)
8899 if (tab->ops[i].st_ops == st_ops)
8902 if (tab->cnt == tab->capacity) {
8903 new_tab = krealloc(tab,
8904 offsetof(struct btf_struct_ops_tab,
8905 ops[tab->capacity * 2]),
8911 btf->struct_ops_tab = tab;
8914 tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
8916 err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
8920 btf->struct_ops_tab->cnt++;
8925 const struct bpf_struct_ops_desc *
8926 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
8928 const struct bpf_struct_ops_desc *st_ops_list;
8934 if (!btf->struct_ops_tab)
8937 cnt = btf->struct_ops_tab->cnt;
8938 st_ops_list = btf->struct_ops_tab->ops;
8939 for (i = 0; i < cnt; i++) {
8940 if (st_ops_list[i].value_id == value_id)
8941 return &st_ops_list[i];
8947 const struct bpf_struct_ops_desc *
8948 bpf_struct_ops_find(struct btf *btf, u32 type_id)
8950 const struct bpf_struct_ops_desc *st_ops_list;
8956 if (!btf->struct_ops_tab)
8959 cnt = btf->struct_ops_tab->cnt;
8960 st_ops_list = btf->struct_ops_tab->ops;
8961 for (i = 0; i < cnt; i++) {
8962 if (st_ops_list[i].type_id == type_id)
8963 return &st_ops_list[i];
8969 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
8971 struct bpf_verifier_log *log;
8975 btf = btf_get_module_btf(st_ops->owner);
8977 return check_btf_kconfigs(st_ops->owner, "struct_ops");
8979 return PTR_ERR(btf);
8981 log = kzalloc(sizeof(*log), GFP_KERNEL | __GFP_NOWARN);
8987 log->level = BPF_LOG_KERNEL;
8989 err = btf_add_struct_ops(btf, st_ops, log);
8997 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
9000 bool btf_param_match_suffix(const struct btf *btf,
9001 const struct btf_param *arg,
9004 int suffix_len = strlen(suffix), len;
9005 const char *param_name;
9007 /* In the future, this can be ported to use BTF tagging */
9008 param_name = btf_name_by_offset(btf, arg->name_off);
9009 if (str_is_empty(param_name))
9011 len = strlen(param_name);
9012 if (len <= suffix_len)
9014 param_name += len - suffix_len;
9015 return !strncmp(param_name, suffix, suffix_len);