Merge tag 'mm-nonmm-stable-2024-05-19-11-56' of git://git.kernel.org/pub/scm/linux...
[sfrench/cifs-2.6.git] / kernel / bpf / btf.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018 Facebook */
3
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>
29
30 #include <net/netfilter/nf_bpf_link.h>
31
32 #include <net/sock.h>
33 #include <net/xdp.h>
34 #include "../tools/lib/bpf/relo_core.h"
35
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
39  * using.
40  *
41  * ELF Section:
42  * ~~~~~~~~~~~
43  * The BTF data is stored under the ".BTF" ELF section
44  *
45  * struct btf_type:
46  * ~~~~~~~~~~~~~~~
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
51  * 'struct btf_array'.
52  *
53  * 'struct btf_type' and any extra data following it are
54  * 4 bytes aligned.
55  *
56  * Type section:
57  * ~~~~~~~~~~~~~
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.
62  *
63  * type_id:
64  * ~~~~~~~
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
69  * a smaller type_id.
70  *
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").
73  *
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.
77  *
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:
82  *
83  * [1] CONST (anon) type_id=2
84  * [2] PTR (anon) type_id=0
85  *
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
93  *
94  * NOTE: "void" has type_id 0
95  *
96  * String section:
97  * ~~~~~~~~~~~~~~
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
100  * string section.
101  *
102  * Each string is '\0' terminated.
103  *
104  * The first character in the string section must be '\0'
105  * which is used to mean 'anonymous'. Some btf_type may not
106  * have a name.
107  */
108
109 /* BTF verification:
110  *
111  * To verify BTF data, two passes are needed.
112  *
113  * Pass #1
114  * ~~~~~~~
115  * The first pass is to collect all btf_type objects to
116  * an array: "btf->types".
117  *
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.
122  *
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.
127  *
128  * In the first pass, it still does some verifications (e.g.
129  * checking the name is a valid offset to the string section).
130  *
131  * Pass #2
132  * ~~~~~~~
133  * The main focus is to resolve a btf_type that is referring
134  * to another type.
135  *
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:
139  *      struct A {
140  *              struct B b;
141  *      };
142  *
143  *      struct B {
144  *              struct A a;
145  *      };
146  *
147  * btf_type_needs_resolve() decides if a btf_type needs
148  * to be resolved.
149  *
150  * The needs_resolve type implements the "resolve()" ops which
151  * essentially does a DFS and detects backedge.
152  *
153  * During resolve (or DFS), different C types have different
154  * "RESOLVED" conditions.
155  *
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:
161  *
162  *      struct A {
163  *              int m;
164  *              struct A *a;
165  *      };
166  *
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 +
171  *                        ^                                         |
172  *                        +-----------------------------------------+
173  *
174  */
175
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))
182
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)
187
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.
191  */
192 #define BTF_MAX_SIZE (16 * 1024 * 1024)
193
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);                            \
197              i++, member++)
198
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);                                    \
202              i++, member++)
203
204 DEFINE_IDR(btf_idr);
205 DEFINE_SPINLOCK(btf_idr_lock);
206
207 enum btf_kfunc_hook {
208         BTF_KFUNC_HOOK_COMMON,
209         BTF_KFUNC_HOOK_XDP,
210         BTF_KFUNC_HOOK_TC,
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,
219         BTF_KFUNC_HOOK_LWT,
220         BTF_KFUNC_HOOK_NETFILTER,
221         BTF_KFUNC_HOOK_KPROBE,
222         BTF_KFUNC_HOOK_MAX,
223 };
224
225 enum {
226         BTF_KFUNC_SET_MAX_CNT = 256,
227         BTF_DTOR_KFUNC_MAX_CNT = 256,
228         BTF_KFUNC_FILTER_MAX_CNT = 16,
229 };
230
231 struct btf_kfunc_hook_filter {
232         btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
233         u32 nr_filters;
234 };
235
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];
239 };
240
241 struct btf_id_dtor_kfunc_tab {
242         u32 cnt;
243         struct btf_id_dtor_kfunc dtors[];
244 };
245
246 struct btf_struct_ops_tab {
247         u32 cnt;
248         u32 capacity;
249         struct bpf_struct_ops_desc ops[];
250 };
251
252 struct btf {
253         void *data;
254         struct btf_type **types;
255         u32 *resolved_ids;
256         u32 *resolved_sizes;
257         const char *strings;
258         void *nohdr_data;
259         struct btf_header hdr;
260         u32 nr_types; /* includes VOID for base BTF */
261         u32 types_size;
262         u32 data_size;
263         refcount_t refcnt;
264         u32 id;
265         struct rcu_head rcu;
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;
270
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];
276         bool kernel_btf;
277 };
278
279 enum verifier_phase {
280         CHECK_META,
281         CHECK_TYPE,
282 };
283
284 struct resolve_vertex {
285         const struct btf_type *t;
286         u32 type_id;
287         u16 next_member;
288 };
289
290 enum visit_state {
291         NOT_VISITED,
292         VISITED,
293         RESOLVED,
294 };
295
296 enum resolve_mode {
297         RESOLVE_TBD,    /* To Be Determined */
298         RESOLVE_PTR,    /* Resolving for Pointer */
299         RESOLVE_STRUCT_OR_ARRAY,        /* Resolving for struct/union
300                                          * or array
301                                          */
302 };
303
304 #define MAX_RESOLVE_DEPTH 32
305
306 struct btf_sec_info {
307         u32 off;
308         u32 len;
309 };
310
311 struct btf_verifier_env {
312         struct btf *btf;
313         u8 *visit_states;
314         struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
315         struct bpf_verifier_log log;
316         u32 log_type_id;
317         u32 top_stack;
318         enum verifier_phase phase;
319         enum resolve_mode resolve_mode;
320 };
321
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",
343 };
344
345 const char *btf_type_str(const struct btf_type *t)
346 {
347         return btf_kind_str[BTF_INFO_KIND(t->info)];
348 }
349
350 /* Chunk size we use in safe copy of data to be shown. */
351 #define BTF_SHOW_OBJ_SAFE_SIZE          32
352
353 /*
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
358  * a new copy.
359  */
360 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE     16
361
362 /* Type name size */
363 #define BTF_SHOW_NAME_SIZE              80
364
365 /*
366  * The suffix of a type that indicates it cannot alias another type when
367  * comparing BTF IDs for kfunc invocations.
368  */
369 #define NOCAST_ALIAS_SUFFIX             "___init"
370
371 /*
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.
375  *
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.
387  *
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.
394  *
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
401  * used:
402  *
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.
408  *
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.
413  */
414 struct btf_show {
415         u64 flags;
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 */
420         struct {
421                 u8 depth;
422                 u8 depth_to_show;
423                 u8 depth_check;
424                 u8 array_member:1,
425                    array_terminated:1;
426                 u16 array_encoding;
427                 u32 type_id;
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 */
432         } state;
433         struct {
434                 u32 size;
435                 void *head;
436                 void *data;
437                 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
438         } obj;
439 };
440
441 struct btf_kind_operations {
442         s32 (*check_meta)(struct btf_verifier_env *env,
443                           const struct btf_type *t,
444                           u32 meta_left);
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);
460 };
461
462 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
463 static struct btf_type btf_void;
464
465 static int btf_resolve(struct btf_verifier_env *env,
466                        const struct btf_type *t, u32 type_id);
467
468 static int btf_func_check(struct btf_verifier_env *env,
469                           const struct btf_type *t);
470
471 static bool btf_type_is_modifier(const struct btf_type *t)
472 {
473         /* Some of them is not strictly a C modifier
474          * but they are grouped into the same bucket
475          * for BTF concern:
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.
479          *
480          * ptr does not fall into this bucket
481          * because its size is always sizeof(void *).
482          */
483         switch (BTF_INFO_KIND(t->info)) {
484         case BTF_KIND_TYPEDEF:
485         case BTF_KIND_VOLATILE:
486         case BTF_KIND_CONST:
487         case BTF_KIND_RESTRICT:
488         case BTF_KIND_TYPE_TAG:
489                 return true;
490         }
491
492         return false;
493 }
494
495 bool btf_type_is_void(const struct btf_type *t)
496 {
497         return t == &btf_void;
498 }
499
500 static bool btf_type_is_fwd(const struct btf_type *t)
501 {
502         return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
503 }
504
505 static bool btf_type_is_datasec(const struct btf_type *t)
506 {
507         return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
508 }
509
510 static bool btf_type_is_decl_tag(const struct btf_type *t)
511 {
512         return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
513 }
514
515 static bool btf_type_nosize(const struct btf_type *t)
516 {
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);
520 }
521
522 static bool btf_type_nosize_or_null(const struct btf_type *t)
523 {
524         return !t || btf_type_nosize(t);
525 }
526
527 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
528 {
529         return btf_type_is_func(t) || btf_type_is_struct(t) ||
530                btf_type_is_var(t) || btf_type_is_typedef(t);
531 }
532
533 u32 btf_nr_types(const struct btf *btf)
534 {
535         u32 total = 0;
536
537         while (btf) {
538                 total += btf->nr_types;
539                 btf = btf->base_btf;
540         }
541
542         return total;
543 }
544
545 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
546 {
547         const struct btf_type *t;
548         const char *tname;
549         u32 i, total;
550
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)
555                         continue;
556
557                 tname = btf_name_by_offset(btf, t->name_off);
558                 if (!strcmp(tname, name))
559                         return i;
560         }
561
562         return -ENOENT;
563 }
564
565 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
566 {
567         struct btf *btf;
568         s32 ret;
569         int id;
570
571         btf = bpf_get_btf_vmlinux();
572         if (IS_ERR(btf))
573                 return PTR_ERR(btf);
574         if (!btf)
575                 return -EINVAL;
576
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.
580          */
581         if (ret > 0) {
582                 btf_get(btf);
583                 *btf_p = btf;
584                 return ret;
585         }
586
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))
591                         continue;
592                 /* linear search could be slow hence unlock/lock
593                  * the IDR to avoiding holding it for too long
594                  */
595                 btf_get(btf);
596                 spin_unlock_bh(&btf_idr_lock);
597                 ret = btf_find_by_name_kind(btf, name, kind);
598                 if (ret > 0) {
599                         *btf_p = btf;
600                         return ret;
601                 }
602                 btf_put(btf);
603                 spin_lock_bh(&btf_idr_lock);
604         }
605         spin_unlock_bh(&btf_idr_lock);
606         return ret;
607 }
608
609 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
610                                                u32 id, u32 *res_id)
611 {
612         const struct btf_type *t = btf_type_by_id(btf, id);
613
614         while (btf_type_is_modifier(t)) {
615                 id = t->type;
616                 t = btf_type_by_id(btf, t->type);
617         }
618
619         if (res_id)
620                 *res_id = id;
621
622         return t;
623 }
624
625 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
626                                             u32 id, u32 *res_id)
627 {
628         const struct btf_type *t;
629
630         t = btf_type_skip_modifiers(btf, id, NULL);
631         if (!btf_type_is_ptr(t))
632                 return NULL;
633
634         return btf_type_skip_modifiers(btf, t->type, res_id);
635 }
636
637 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
638                                                  u32 id, u32 *res_id)
639 {
640         const struct btf_type *ptype;
641
642         ptype = btf_type_resolve_ptr(btf, id, res_id);
643         if (ptype && btf_type_is_func_proto(ptype))
644                 return ptype;
645
646         return NULL;
647 }
648
649 /* Types that act only as a source, not sink or intermediate
650  * type when resolving.
651  */
652 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
653 {
654         return btf_type_is_var(t) ||
655                btf_type_is_decl_tag(t) ||
656                btf_type_is_datasec(t);
657 }
658
659 /* What types need to be resolved?
660  *
661  * btf_type_is_modifier() is an obvious one.
662  *
663  * btf_type_is_struct() because its member refers to
664  * another type (through member->type).
665  *
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.
669  *
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.
674  */
675 static bool btf_type_needs_resolve(const struct btf_type *t)
676 {
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);
685 }
686
687 /* t->size can be used */
688 static bool btf_type_has_size(const struct btf_type *t)
689 {
690         switch (BTF_INFO_KIND(t->info)) {
691         case BTF_KIND_INT:
692         case BTF_KIND_STRUCT:
693         case BTF_KIND_UNION:
694         case BTF_KIND_ENUM:
695         case BTF_KIND_DATASEC:
696         case BTF_KIND_FLOAT:
697         case BTF_KIND_ENUM64:
698                 return true;
699         }
700
701         return false;
702 }
703
704 static const char *btf_int_encoding_str(u8 encoding)
705 {
706         if (encoding == 0)
707                 return "(none)";
708         else if (encoding == BTF_INT_SIGNED)
709                 return "SIGNED";
710         else if (encoding == BTF_INT_CHAR)
711                 return "CHAR";
712         else if (encoding == BTF_INT_BOOL)
713                 return "BOOL";
714         else
715                 return "UNKN";
716 }
717
718 static u32 btf_type_int(const struct btf_type *t)
719 {
720         return *(u32 *)(t + 1);
721 }
722
723 static const struct btf_array *btf_type_array(const struct btf_type *t)
724 {
725         return (const struct btf_array *)(t + 1);
726 }
727
728 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
729 {
730         return (const struct btf_enum *)(t + 1);
731 }
732
733 static const struct btf_var *btf_type_var(const struct btf_type *t)
734 {
735         return (const struct btf_var *)(t + 1);
736 }
737
738 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
739 {
740         return (const struct btf_decl_tag *)(t + 1);
741 }
742
743 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
744 {
745         return (const struct btf_enum64 *)(t + 1);
746 }
747
748 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
749 {
750         return kind_ops[BTF_INFO_KIND(t->info)];
751 }
752
753 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
754 {
755         if (!BTF_STR_OFFSET_VALID(offset))
756                 return false;
757
758         while (offset < btf->start_str_off)
759                 btf = btf->base_btf;
760
761         offset -= btf->start_str_off;
762         return offset < btf->hdr.str_len;
763 }
764
765 static bool __btf_name_char_ok(char c, bool first)
766 {
767         if ((first ? !isalpha(c) :
768                      !isalnum(c)) &&
769             c != '_' &&
770             c != '.')
771                 return false;
772         return true;
773 }
774
775 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
776 {
777         while (offset < btf->start_str_off)
778                 btf = btf->base_btf;
779
780         offset -= btf->start_str_off;
781         if (offset < btf->hdr.str_len)
782                 return &btf->strings[offset];
783
784         return NULL;
785 }
786
787 static bool __btf_name_valid(const struct btf *btf, u32 offset)
788 {
789         /* offset must be valid */
790         const char *src = btf_str_by_offset(btf, offset);
791         const char *src_limit;
792
793         if (!__btf_name_char_ok(*src, true))
794                 return false;
795
796         /* set a limit on identifier length */
797         src_limit = src + KSYM_NAME_LEN;
798         src++;
799         while (*src && src < src_limit) {
800                 if (!__btf_name_char_ok(*src, false))
801                         return false;
802                 src++;
803         }
804
805         return !*src;
806 }
807
808 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
809 {
810         return __btf_name_valid(btf, offset);
811 }
812
813 /* Allow any printable character in DATASEC names */
814 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
815 {
816         /* offset must be valid */
817         const char *src = btf_str_by_offset(btf, offset);
818         const char *src_limit;
819
820         /* set a limit on identifier length */
821         src_limit = src + KSYM_NAME_LEN;
822         src++;
823         while (*src && src < src_limit) {
824                 if (!isprint(*src))
825                         return false;
826                 src++;
827         }
828
829         return !*src;
830 }
831
832 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
833 {
834         const char *name;
835
836         if (!offset)
837                 return "(anon)";
838
839         name = btf_str_by_offset(btf, offset);
840         return name ?: "(invalid-name-offset)";
841 }
842
843 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
844 {
845         return btf_str_by_offset(btf, offset);
846 }
847
848 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
849 {
850         while (type_id < btf->start_id)
851                 btf = btf->base_btf;
852
853         type_id -= btf->start_id;
854         if (type_id >= btf->nr_types)
855                 return NULL;
856         return btf->types[type_id];
857 }
858 EXPORT_SYMBOL_GPL(btf_type_by_id);
859
860 /*
861  * Regular int is not a bit field and it must be either
862  * u8/u16/u32/u64 or __int128.
863  */
864 static bool btf_type_int_is_regular(const struct btf_type *t)
865 {
866         u8 nr_bits, nr_bytes;
867         u32 int_data;
868
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)))) {
877                 return false;
878         }
879
880         return true;
881 }
882
883 /*
884  * Check that given struct member is a regular int with expected
885  * offset and size.
886  */
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)
890 {
891         const struct btf_type *t;
892         u32 id, int_data;
893         u8 nr_bits;
894
895         id = m->type;
896         t = btf_type_id_size(btf, &id, NULL);
897         if (!t || !btf_type_is_int(t))
898                 return false;
899
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);
905
906                 /* if kflag set, int should be a regular int and
907                  * bit offset should be at byte boundary.
908                  */
909                 return !bitfield_size &&
910                        BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
911                        BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
912         }
913
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)
919                 return false;
920
921         return true;
922 }
923
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,
926                                                        u32 id)
927 {
928         const struct btf_type *t = btf_type_by_id(btf, id);
929
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);
933         }
934
935         return t;
936 }
937
938 #define BTF_SHOW_MAX_ITER       10
939
940 #define BTF_KIND_BIT(kind)      (1ULL << kind)
941
942 /*
943  * Populate show->state.name with type name information.
944  * Format of type name is
945  *
946  * [.member_name = ] (type_name)
947  */
948 static const char *btf_show_name(struct btf_show *show)
949 {
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;
963         u64 kinds = 0;
964         int i;
965
966         show->state.name[0] = '\0';
967
968         /*
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.
972          */
973         if (show->state.array_member)
974                 return "";
975
976         /* Retrieve member name, if any. */
977         if (m) {
978                 member = btf_name_by_offset(show->btf, m->name_off);
979                 show_member = strlen(member) > 0;
980                 id = m->type;
981         }
982
983         /*
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.
989          */
990         t = btf_type_by_id(show->btf, id);
991         if (!t)
992                 return "";
993
994         /*
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.
1001          *
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.
1005          *
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.
1011          *
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.
1015          */
1016         for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1017
1018                 switch (BTF_INFO_KIND(t->info)) {
1019                 case BTF_KIND_TYPEDEF:
1020                         if (!name)
1021                                 name = btf_name_by_offset(show->btf,
1022                                                                t->name_off);
1023                         kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1024                         id = t->type;
1025                         break;
1026                 case BTF_KIND_ARRAY:
1027                         kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1028                         parens = "[";
1029                         if (!t)
1030                                 return "";
1031                         array = btf_type_array(t);
1032                         if (array_suffix > array_suffixes)
1033                                 array_suffix -= 2;
1034                         id = array->type;
1035                         break;
1036                 case BTF_KIND_PTR:
1037                         kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1038                         if (ptr_suffix > ptr_suffixes)
1039                                 ptr_suffix -= 1;
1040                         id = t->type;
1041                         break;
1042                 default:
1043                         id = 0;
1044                         break;
1045                 }
1046                 if (!id)
1047                         break;
1048                 t = btf_type_skip_qualifiers(show->btf, id);
1049         }
1050         /* We may not be able to represent this type; bail to be safe */
1051         if (i == BTF_SHOW_MAX_ITER)
1052                 return "";
1053
1054         if (!name)
1055                 name = btf_name_by_offset(show->btf, t->name_off);
1056
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 ?
1061                          "struct" : "union";
1062                 /* if it's an array of struct/union, parens is already set */
1063                 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1064                         parens = "{";
1065                 break;
1066         case BTF_KIND_ENUM:
1067         case BTF_KIND_ENUM64:
1068                 prefix = "enum";
1069                 break;
1070         default:
1071                 break;
1072         }
1073
1074         /* pointer does not require parens */
1075         if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1076                 parens = "";
1077         /* typedef does not require struct/union/enum prefix */
1078         if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1079                 prefix = "";
1080
1081         if (!name)
1082                 name = "";
1083
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",
1087                          parens);
1088         else
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) */
1096                          prefix,
1097                          strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1098                          /* ...this is the type name itself */
1099                          name,
1100                          /* ...suffixed by the appropriate '*', '[]' suffixes */
1101                          strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1102                          array_suffix, parens);
1103
1104         return show->state.name;
1105 }
1106
1107 static const char *__btf_show_indent(struct btf_show *show)
1108 {
1109         const char *indents = "                                ";
1110         const char *indent = &indents[strlen(indents)];
1111
1112         if ((indent - show->state.depth) >= indents)
1113                 return indent - show->state.depth;
1114         return indents;
1115 }
1116
1117 static const char *btf_show_indent(struct btf_show *show)
1118 {
1119         return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1120 }
1121
1122 static const char *btf_show_newline(struct btf_show *show)
1123 {
1124         return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1125 }
1126
1127 static const char *btf_show_delim(struct btf_show *show)
1128 {
1129         if (show->state.depth == 0)
1130                 return "";
1131
1132         if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1133                 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1134                 return "|";
1135
1136         return ",";
1137 }
1138
1139 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1140 {
1141         va_list args;
1142
1143         if (!show->state.depth_check) {
1144                 va_start(args, fmt);
1145                 show->showfn(show, fmt, args);
1146                 va_end(args);
1147         }
1148 }
1149
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).
1154  */
1155 #define btf_show_type_value(show, fmt, value)                                  \
1156         do {                                                                   \
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; \
1167                 }                                                              \
1168         } while (0)
1169
1170 #define btf_show_type_values(show, fmt, ...)                                   \
1171         do {                                                                   \
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;         \
1178         } while (0)
1179
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)
1182 {
1183         return show->obj.head + show->obj.size - data;
1184 }
1185
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)
1188 {
1189         return data >= show->obj.data &&
1190                (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1191 }
1192
1193 /*
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
1197  * populated.
1198  */
1199 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1200 {
1201         if (btf_show_obj_is_safe(show, data, size))
1202                 return show->obj.safe + (data - show->obj.data);
1203         return NULL;
1204 }
1205
1206 /*
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().
1210  *
1211  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1212  * safe copy is needed.
1213  *
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.
1223  *
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.
1233  */
1234 static void *btf_show_obj_safe(struct btf_show *show,
1235                                const struct btf_type *t,
1236                                void *data)
1237 {
1238         const struct btf_type *rt;
1239         int size_left, size;
1240         void *safe = NULL;
1241
1242         if (show->flags & BTF_SHOW_UNSAFE)
1243                 return data;
1244
1245         rt = btf_resolve_size(show->btf, t, &size);
1246         if (IS_ERR(rt)) {
1247                 show->state.status = PTR_ERR(rt);
1248                 return NULL;
1249         }
1250
1251         /*
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.
1255          */
1256         if (show->state.depth == 0) {
1257                 show->obj.size = size;
1258                 show->obj.head = data;
1259         } else {
1260                 /*
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
1279                  *   the safe buffer.
1280                  */
1281                 safe = __btf_show_obj_safe(show, data,
1282                                            min(size,
1283                                                BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1284         }
1285
1286         /*
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.
1290          */
1291         if (!safe) {
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,
1296                                                               data, size_left);
1297                 if (!show->state.status) {
1298                         show->obj.data = data;
1299                         safe = show->obj.safe;
1300                 }
1301         }
1302
1303         return safe;
1304 }
1305
1306 /*
1307  * Set the type we are starting to show and return a safe data pointer
1308  * to be used for showing the associated data.
1309  */
1310 static void *btf_show_start_type(struct btf_show *show,
1311                                  const struct btf_type *t,
1312                                  u32 type_id, void *data)
1313 {
1314         show->state.type = t;
1315         show->state.type_id = type_id;
1316         show->state.name[0] = '\0';
1317
1318         return btf_show_obj_safe(show, t, data);
1319 }
1320
1321 static void btf_show_end_type(struct btf_show *show)
1322 {
1323         show->state.type = NULL;
1324         show->state.type_id = 0;
1325         show->state.name[0] = '\0';
1326 }
1327
1328 static void *btf_show_start_aggr_type(struct btf_show *show,
1329                                       const struct btf_type *t,
1330                                       u32 type_id, void *data)
1331 {
1332         void *safe_data = btf_show_start_type(show, t, type_id, data);
1333
1334         if (!safe_data)
1335                 return safe_data;
1336
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++;
1341         return safe_data;
1342 }
1343
1344 static void btf_show_end_aggr_type(struct btf_show *show,
1345                                    const char *suffix)
1346 {
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);
1351 }
1352
1353 static void btf_show_start_member(struct btf_show *show,
1354                                   const struct btf_member *m)
1355 {
1356         show->state.member = m;
1357 }
1358
1359 static void btf_show_start_array_member(struct btf_show *show)
1360 {
1361         show->state.array_member = 1;
1362         btf_show_start_member(show, NULL);
1363 }
1364
1365 static void btf_show_end_member(struct btf_show *show)
1366 {
1367         show->state.member = NULL;
1368 }
1369
1370 static void btf_show_end_array_member(struct btf_show *show)
1371 {
1372         show->state.array_member = 0;
1373         btf_show_end_member(show);
1374 }
1375
1376 static void *btf_show_start_array_type(struct btf_show *show,
1377                                        const struct btf_type *t,
1378                                        u32 type_id,
1379                                        u16 array_encoding,
1380                                        void *data)
1381 {
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);
1385 }
1386
1387 static void btf_show_end_array_type(struct btf_show *show)
1388 {
1389         show->state.array_encoding = 0;
1390         show->state.array_terminated = 0;
1391         btf_show_end_aggr_type(show, "]");
1392 }
1393
1394 static void *btf_show_start_struct_type(struct btf_show *show,
1395                                         const struct btf_type *t,
1396                                         u32 type_id,
1397                                         void *data)
1398 {
1399         return btf_show_start_aggr_type(show, t, type_id, data);
1400 }
1401
1402 static void btf_show_end_struct_type(struct btf_show *show)
1403 {
1404         btf_show_end_aggr_type(show, "}");
1405 }
1406
1407 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1408                                               const char *fmt, ...)
1409 {
1410         va_list args;
1411
1412         va_start(args, fmt);
1413         bpf_verifier_vlog(log, fmt, args);
1414         va_end(args);
1415 }
1416
1417 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1418                                             const char *fmt, ...)
1419 {
1420         struct bpf_verifier_log *log = &env->log;
1421         va_list args;
1422
1423         if (!bpf_verifier_log_needed(log))
1424                 return;
1425
1426         va_start(args, fmt);
1427         bpf_verifier_vlog(log, fmt, args);
1428         va_end(args);
1429 }
1430
1431 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1432                                                    const struct btf_type *t,
1433                                                    bool log_details,
1434                                                    const char *fmt, ...)
1435 {
1436         struct bpf_verifier_log *log = &env->log;
1437         struct btf *btf = env->btf;
1438         va_list args;
1439
1440         if (!bpf_verifier_log_needed(log))
1441                 return;
1442
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.
1447                  */
1448                 if (!fmt)
1449                         return;
1450
1451                 /* Skip logging when loading module BTF with mismatches permitted */
1452                 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1453                         return;
1454         }
1455
1456         __btf_verifier_log(log, "[%u] %s %s%s",
1457                            env->log_type_id,
1458                            btf_type_str(t),
1459                            __btf_name_by_offset(btf, t->name_off),
1460                            log_details ? " " : "");
1461
1462         if (log_details)
1463                 btf_type_ops(t)->log_details(env, t);
1464
1465         if (fmt && *fmt) {
1466                 __btf_verifier_log(log, " ");
1467                 va_start(args, fmt);
1468                 bpf_verifier_vlog(log, fmt, args);
1469                 va_end(args);
1470         }
1471
1472         __btf_verifier_log(log, "\n");
1473 }
1474
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__)
1479
1480 __printf(4, 5)
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, ...)
1485 {
1486         struct bpf_verifier_log *log = &env->log;
1487         struct btf *btf = env->btf;
1488         va_list args;
1489
1490         if (!bpf_verifier_log_needed(log))
1491                 return;
1492
1493         if (log->level == BPF_LOG_KERNEL) {
1494                 if (!fmt)
1495                         return;
1496
1497                 /* Skip logging when loading module BTF with mismatches permitted */
1498                 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1499                         return;
1500         }
1501
1502         /* The CHECK_META phase already did a btf dump.
1503          *
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.
1507          */
1508         if (env->phase != CHECK_META)
1509                 btf_verifier_log_type(env, struct_type, NULL);
1510
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),
1515                                    member->type,
1516                                    BTF_MEMBER_BITFIELD_SIZE(member->offset),
1517                                    BTF_MEMBER_BIT_OFFSET(member->offset));
1518         else
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);
1522
1523         if (fmt && *fmt) {
1524                 __btf_verifier_log(log, " ");
1525                 va_start(args, fmt);
1526                 bpf_verifier_vlog(log, fmt, args);
1527                 va_end(args);
1528         }
1529
1530         __btf_verifier_log(log, "\n");
1531 }
1532
1533 __printf(4, 5)
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, ...)
1538 {
1539         struct bpf_verifier_log *log = &env->log;
1540         va_list args;
1541
1542         if (!bpf_verifier_log_needed(log))
1543                 return;
1544         if (log->level == BPF_LOG_KERNEL && !fmt)
1545                 return;
1546         if (env->phase != CHECK_META)
1547                 btf_verifier_log_type(env, datasec_type, NULL);
1548
1549         __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1550                            vsi->type, vsi->offset, vsi->size);
1551         if (fmt && *fmt) {
1552                 __btf_verifier_log(log, " ");
1553                 va_start(args, fmt);
1554                 bpf_verifier_vlog(log, fmt, args);
1555                 va_end(args);
1556         }
1557
1558         __btf_verifier_log(log, "\n");
1559 }
1560
1561 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1562                                  u32 btf_data_size)
1563 {
1564         struct bpf_verifier_log *log = &env->log;
1565         const struct btf *btf = env->btf;
1566         const struct btf_header *hdr;
1567
1568         if (!bpf_verifier_log_needed(log))
1569                 return;
1570
1571         if (log->level == BPF_LOG_KERNEL)
1572                 return;
1573         hdr = &btf->hdr;
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);
1583 }
1584
1585 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1586 {
1587         struct btf *btf = env->btf;
1588
1589         if (btf->types_size == btf->nr_types) {
1590                 /* Expand 'types' array */
1591
1592                 struct btf_type **new_types;
1593                 u32 expand_by, new_size;
1594
1595                 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1596                         btf_verifier_log(env, "Exceeded max num of types");
1597                         return -E2BIG;
1598                 }
1599
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);
1603
1604                 new_types = kvcalloc(new_size, sizeof(*new_types),
1605                                      GFP_KERNEL | __GFP_NOWARN);
1606                 if (!new_types)
1607                         return -ENOMEM;
1608
1609                 if (btf->nr_types == 0) {
1610                         if (!btf->base_btf) {
1611                                 /* lazily init VOID type */
1612                                 new_types[0] = &btf_void;
1613                                 btf->nr_types++;
1614                         }
1615                 } else {
1616                         memcpy(new_types, btf->types,
1617                                sizeof(*btf->types) * btf->nr_types);
1618                 }
1619
1620                 kvfree(btf->types);
1621                 btf->types = new_types;
1622                 btf->types_size = new_size;
1623         }
1624
1625         btf->types[btf->nr_types++] = t;
1626
1627         return 0;
1628 }
1629
1630 static int btf_alloc_id(struct btf *btf)
1631 {
1632         int id;
1633
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);
1637         if (id > 0)
1638                 btf->id = id;
1639         spin_unlock_bh(&btf_idr_lock);
1640         idr_preload_end();
1641
1642         if (WARN_ON_ONCE(!id))
1643                 return -ENOSPC;
1644
1645         return id > 0 ? 0 : id;
1646 }
1647
1648 static void btf_free_id(struct btf *btf)
1649 {
1650         unsigned long flags;
1651
1652         /*
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.
1660          */
1661         spin_lock_irqsave(&btf_idr_lock, flags);
1662         idr_remove(&btf_idr, btf->id);
1663         spin_unlock_irqrestore(&btf_idr_lock, flags);
1664 }
1665
1666 static void btf_free_kfunc_set_tab(struct btf *btf)
1667 {
1668         struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1669         int hook;
1670
1671         if (!tab)
1672                 return;
1673         /* For module BTF, we directly assign the sets being registered, so
1674          * there is nothing to free except kfunc_set_tab.
1675          */
1676         if (btf_is_module(btf))
1677                 goto free_tab;
1678         for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1679                 kfree(tab->sets[hook]);
1680 free_tab:
1681         kfree(tab);
1682         btf->kfunc_set_tab = NULL;
1683 }
1684
1685 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1686 {
1687         struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1688
1689         if (!tab)
1690                 return;
1691         kfree(tab);
1692         btf->dtor_kfunc_tab = NULL;
1693 }
1694
1695 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1696 {
1697         int i;
1698
1699         if (!tab)
1700                 return;
1701         for (i = 0; i < tab->cnt; i++)
1702                 btf_record_free(tab->types[i].record);
1703         kfree(tab);
1704 }
1705
1706 static void btf_free_struct_meta_tab(struct btf *btf)
1707 {
1708         struct btf_struct_metas *tab = btf->struct_meta_tab;
1709
1710         btf_struct_metas_free(tab);
1711         btf->struct_meta_tab = NULL;
1712 }
1713
1714 static void btf_free_struct_ops_tab(struct btf *btf)
1715 {
1716         struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1717         u32 i;
1718
1719         if (!tab)
1720                 return;
1721
1722         for (i = 0; i < tab->cnt; i++)
1723                 bpf_struct_ops_desc_release(&tab->ops[i]);
1724
1725         kfree(tab);
1726         btf->struct_ops_tab = NULL;
1727 }
1728
1729 static void btf_free(struct btf *btf)
1730 {
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);
1735         kvfree(btf->types);
1736         kvfree(btf->resolved_sizes);
1737         kvfree(btf->resolved_ids);
1738         kvfree(btf->data);
1739         kfree(btf);
1740 }
1741
1742 static void btf_free_rcu(struct rcu_head *rcu)
1743 {
1744         struct btf *btf = container_of(rcu, struct btf, rcu);
1745
1746         btf_free(btf);
1747 }
1748
1749 const char *btf_get_name(const struct btf *btf)
1750 {
1751         return btf->name;
1752 }
1753
1754 void btf_get(struct btf *btf)
1755 {
1756         refcount_inc(&btf->refcnt);
1757 }
1758
1759 void btf_put(struct btf *btf)
1760 {
1761         if (btf && refcount_dec_and_test(&btf->refcnt)) {
1762                 btf_free_id(btf);
1763                 call_rcu(&btf->rcu, btf_free_rcu);
1764         }
1765 }
1766
1767 static int env_resolve_init(struct btf_verifier_env *env)
1768 {
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;
1774
1775         resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1776                                   GFP_KERNEL | __GFP_NOWARN);
1777         if (!resolved_sizes)
1778                 goto nomem;
1779
1780         resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1781                                 GFP_KERNEL | __GFP_NOWARN);
1782         if (!resolved_ids)
1783                 goto nomem;
1784
1785         visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1786                                 GFP_KERNEL | __GFP_NOWARN);
1787         if (!visit_states)
1788                 goto nomem;
1789
1790         btf->resolved_sizes = resolved_sizes;
1791         btf->resolved_ids = resolved_ids;
1792         env->visit_states = visit_states;
1793
1794         return 0;
1795
1796 nomem:
1797         kvfree(resolved_sizes);
1798         kvfree(resolved_ids);
1799         kvfree(visit_states);
1800         return -ENOMEM;
1801 }
1802
1803 static void btf_verifier_env_free(struct btf_verifier_env *env)
1804 {
1805         kvfree(env->visit_states);
1806         kfree(env);
1807 }
1808
1809 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1810                                      const struct btf_type *next_type)
1811 {
1812         switch (env->resolve_mode) {
1813         case RESOLVE_TBD:
1814                 /* int, enum or void is a sink */
1815                 return !btf_type_needs_resolve(next_type);
1816         case RESOLVE_PTR:
1817                 /* int, enum, void, struct, array, func or func_proto is a sink
1818                  * for ptr
1819                  */
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
1825                  */
1826                 return !btf_type_is_modifier(next_type) &&
1827                         !btf_type_is_array(next_type) &&
1828                         !btf_type_is_struct(next_type);
1829         default:
1830                 BUG();
1831         }
1832 }
1833
1834 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1835                                  u32 type_id)
1836 {
1837         /* base BTF types should be resolved by now */
1838         if (type_id < env->btf->start_id)
1839                 return true;
1840
1841         return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1842 }
1843
1844 static int env_stack_push(struct btf_verifier_env *env,
1845                           const struct btf_type *t, u32 type_id)
1846 {
1847         const struct btf *btf = env->btf;
1848         struct resolve_vertex *v;
1849
1850         if (env->top_stack == MAX_RESOLVE_DEPTH)
1851                 return -E2BIG;
1852
1853         if (type_id < btf->start_id
1854             || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1855                 return -EEXIST;
1856
1857         env->visit_states[type_id - btf->start_id] = VISITED;
1858
1859         v = &env->stack[env->top_stack++];
1860         v->t = t;
1861         v->type_id = type_id;
1862         v->next_member = 0;
1863
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;
1869         }
1870
1871         return 0;
1872 }
1873
1874 static void env_stack_set_next_member(struct btf_verifier_env *env,
1875                                       u16 next_member)
1876 {
1877         env->stack[env->top_stack - 1].next_member = next_member;
1878 }
1879
1880 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1881                                    u32 resolved_type_id,
1882                                    u32 resolved_size)
1883 {
1884         u32 type_id = env->stack[--(env->top_stack)].type_id;
1885         struct btf *btf = env->btf;
1886
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;
1891 }
1892
1893 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1894 {
1895         return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1896 }
1897
1898 /* Resolve the size of a passed-in "type"
1899  *
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.
1904  * *elem_type: u32
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
1909  *
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")
1914  * *elem_id: 0
1915  * *total_nelems: 1
1916  * *type_id: id of type if it's changed within the function, 0 if not
1917  */
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)
1922 {
1923         const struct btf_type *array_type = NULL;
1924         const struct btf_array *array = NULL;
1925         u32 i, size, nelems = 1, id = 0;
1926
1927         for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1928                 switch (BTF_INFO_KIND(type->info)) {
1929                 /* type->size can be used */
1930                 case BTF_KIND_INT:
1931                 case BTF_KIND_STRUCT:
1932                 case BTF_KIND_UNION:
1933                 case BTF_KIND_ENUM:
1934                 case BTF_KIND_FLOAT:
1935                 case BTF_KIND_ENUM64:
1936                         size = type->size;
1937                         goto resolved;
1938
1939                 case BTF_KIND_PTR:
1940                         size = sizeof(void *);
1941                         goto resolved;
1942
1943                 /* Modifiers */
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:
1949                         id = type->type;
1950                         type = btf_type_by_id(btf, type->type);
1951                         break;
1952
1953                 case BTF_KIND_ARRAY:
1954                         if (!array_type)
1955                                 array_type = type;
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);
1961                         break;
1962
1963                 /* type without size */
1964                 default:
1965                         return ERR_PTR(-EINVAL);
1966                 }
1967         }
1968
1969         return ERR_PTR(-EINVAL);
1970
1971 resolved:
1972         if (nelems && size > U32_MAX / nelems)
1973                 return ERR_PTR(-EINVAL);
1974
1975         *type_size = nelems * size;
1976         if (total_nelems)
1977                 *total_nelems = nelems;
1978         if (elem_type)
1979                 *elem_type = type;
1980         if (elem_id)
1981                 *elem_id = array ? array->type : 0;
1982         if (type_id && id)
1983                 *type_id = id;
1984
1985         return array_type ? : type;
1986 }
1987
1988 const struct btf_type *
1989 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1990                  u32 *type_size)
1991 {
1992         return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1993 }
1994
1995 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1996 {
1997         while (type_id < btf->start_id)
1998                 btf = btf->base_btf;
1999
2000         return btf->resolved_ids[type_id - btf->start_id];
2001 }
2002
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,
2005                                                   u32 *type_id)
2006 {
2007         *type_id = btf_resolved_type_id(btf, *type_id);
2008         return btf_type_by_id(btf, *type_id);
2009 }
2010
2011 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2012 {
2013         while (type_id < btf->start_id)
2014                 btf = btf->base_btf;
2015
2016         return btf->resolved_sizes[type_id - btf->start_id];
2017 }
2018
2019 const struct btf_type *btf_type_id_size(const struct btf *btf,
2020                                         u32 *type_id, u32 *ret_size)
2021 {
2022         const struct btf_type *size_type;
2023         u32 size_type_id = *type_id;
2024         u32 size = 0;
2025
2026         size_type = btf_type_by_id(btf, size_type_id);
2027         if (btf_type_nosize_or_null(size_type))
2028                 return NULL;
2029
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 *);
2036         } else {
2037                 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2038                                  !btf_type_is_var(size_type)))
2039                         return NULL;
2040
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))
2044                         return NULL;
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 *);
2051                 else
2052                         return NULL;
2053         }
2054
2055         *type_id = size_type_id;
2056         if (ret_size)
2057                 *ret_size = size;
2058
2059         return size_type;
2060 }
2061
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)
2066 {
2067         btf_verifier_log_basic(env, struct_type,
2068                                "Unsupported check_member");
2069         return -EINVAL;
2070 }
2071
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)
2076 {
2077         btf_verifier_log_basic(env, struct_type,
2078                                "Unsupported check_kflag_member");
2079         return -EINVAL;
2080 }
2081
2082 /* Used for ptr, array struct/union and float type members.
2083  * int, enum and modifier types have their specific callback functions.
2084  */
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)
2089 {
2090         if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2091                 btf_verifier_log_member(env, struct_type, member,
2092                                         "Invalid member bitfield_size");
2093                 return -EINVAL;
2094         }
2095
2096         /* bitfield size is 0, so member->offset represents bit offset only.
2097          * It is safe to call non kflag check_member variants.
2098          */
2099         return btf_type_ops(member_type)->check_member(env, struct_type,
2100                                                        member,
2101                                                        member_type);
2102 }
2103
2104 static int btf_df_resolve(struct btf_verifier_env *env,
2105                           const struct resolve_vertex *v)
2106 {
2107         btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2108         return -EINVAL;
2109 }
2110
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)
2114 {
2115         btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2116 }
2117
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)
2122 {
2123         u32 int_data = btf_type_int(member_type);
2124         u32 struct_bits_off = member->offset;
2125         u32 struct_size = struct_type->size;
2126         u32 nr_copy_bits;
2127         u32 bytes_offset;
2128
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");
2132                 return -EINVAL;
2133         }
2134
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);
2139
2140         if (nr_copy_bits > BITS_PER_U128) {
2141                 btf_verifier_log_member(env, struct_type, member,
2142                                         "nr_copy_bits exceeds 128");
2143                 return -EINVAL;
2144         }
2145
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");
2150                 return -EINVAL;
2151         }
2152
2153         return 0;
2154 }
2155
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)
2160 {
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;
2164         u32 nr_copy_bits;
2165
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");
2170                 return -EINVAL;
2171         }
2172
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);
2177         if (!nr_bits) {
2178                 /* Not a bitfield member, member offset must be at byte
2179                  * boundary.
2180                  */
2181                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2182                         btf_verifier_log_member(env, struct_type, member,
2183                                                 "Invalid member offset");
2184                         return -EINVAL;
2185                 }
2186
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");
2191                 return -EINVAL;
2192         }
2193
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");
2199                 return -EINVAL;
2200         }
2201
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");
2206                 return -EINVAL;
2207         }
2208
2209         return 0;
2210 }
2211
2212 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2213                               const struct btf_type *t,
2214                               u32 meta_left)
2215 {
2216         u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2217         u16 encoding;
2218
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);
2223                 return -EINVAL;
2224         }
2225
2226         if (btf_type_vlen(t)) {
2227                 btf_verifier_log_type(env, t, "vlen != 0");
2228                 return -EINVAL;
2229         }
2230
2231         if (btf_type_kflag(t)) {
2232                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2233                 return -EINVAL;
2234         }
2235
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",
2239                                        int_data);
2240                 return -EINVAL;
2241         }
2242
2243         nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2244
2245         if (nr_bits > BITS_PER_U128) {
2246                 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2247                                       BITS_PER_U128);
2248                 return -EINVAL;
2249         }
2250
2251         if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2252                 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2253                 return -EINVAL;
2254         }
2255
2256         /*
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.
2261          */
2262         encoding = BTF_INT_ENCODING(int_data);
2263         if (encoding &&
2264             encoding != BTF_INT_SIGNED &&
2265             encoding != BTF_INT_CHAR &&
2266             encoding != BTF_INT_BOOL) {
2267                 btf_verifier_log_type(env, t, "Unsupported encoding");
2268                 return -ENOTSUPP;
2269         }
2270
2271         btf_verifier_log_type(env, t, NULL);
2272
2273         return meta_needed;
2274 }
2275
2276 static void btf_int_log(struct btf_verifier_env *env,
2277                         const struct btf_type *t)
2278 {
2279         int int_data = btf_type_int(t);
2280
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)));
2286 }
2287
2288 static void btf_int128_print(struct btf_show *show, void *data)
2289 {
2290         /* data points to a __int128 number.
2291          * Suppose
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;
2296          */
2297         u64 upper_num, lower_num;
2298
2299 #ifdef __BIG_ENDIAN_BITFIELD
2300         upper_num = *(u64 *)data;
2301         lower_num = *(u64 *)(data + 8);
2302 #else
2303         upper_num = *(u64 *)(data + 8);
2304         lower_num = *(u64 *)data;
2305 #endif
2306         if (upper_num == 0)
2307                 btf_show_type_value(show, "0x%llx", lower_num);
2308         else
2309                 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2310                                      lower_num);
2311 }
2312
2313 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2314                              u16 right_shift_bits)
2315 {
2316         u64 upper_num, lower_num;
2317
2318 #ifdef __BIG_ENDIAN_BITFIELD
2319         upper_num = print_num[0];
2320         lower_num = print_num[1];
2321 #else
2322         upper_num = print_num[1];
2323         lower_num = print_num[0];
2324 #endif
2325
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);
2329                 lower_num = 0;
2330         } else {
2331                 upper_num = (upper_num << left_shift_bits) |
2332                             (lower_num >> (64 - left_shift_bits));
2333                 lower_num = lower_num << left_shift_bits;
2334         }
2335
2336         if (right_shift_bits >= 64) {
2337                 lower_num = upper_num >> (right_shift_bits - 64);
2338                 upper_num = 0;
2339         } else {
2340                 lower_num = (lower_num >> right_shift_bits) |
2341                             (upper_num << (64 - right_shift_bits));
2342                 upper_num = upper_num >> right_shift_bits;
2343         }
2344
2345 #ifdef __BIG_ENDIAN_BITFIELD
2346         print_num[0] = upper_num;
2347         print_num[1] = lower_num;
2348 #else
2349         print_num[0] = lower_num;
2350         print_num[1] = upper_num;
2351 #endif
2352 }
2353
2354 static void btf_bitfield_show(void *data, u8 bits_offset,
2355                               u8 nr_bits, struct btf_show *show)
2356 {
2357         u16 left_shift_bits, right_shift_bits;
2358         u8 nr_copy_bytes;
2359         u8 nr_copy_bits;
2360         u64 print_num[2] = {};
2361
2362         nr_copy_bits = nr_bits + bits_offset;
2363         nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2364
2365         memcpy(print_num, data, nr_copy_bytes);
2366
2367 #ifdef __BIG_ENDIAN_BITFIELD
2368         left_shift_bits = bits_offset;
2369 #else
2370         left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2371 #endif
2372         right_shift_bits = BITS_PER_U128 - nr_bits;
2373
2374         btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2375         btf_int128_print(show, print_num);
2376 }
2377
2378
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)
2383 {
2384         u32 int_data = btf_type_int(t);
2385         u8 nr_bits = BTF_INT_BITS(int_data);
2386         u8 total_bits_offset;
2387
2388         /*
2389          * bits_offset is at most 7.
2390          * BTF_INT_OFFSET() cannot exceed 128 bits.
2391          */
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);
2396 }
2397
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)
2401 {
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);
2406         void *safe_data;
2407
2408         safe_data = btf_show_start_type(show, t, type_id, data);
2409         if (!safe_data)
2410                 return;
2411
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);
2415                 goto out;
2416         }
2417
2418         switch (nr_bits) {
2419         case 128:
2420                 btf_int128_print(show, safe_data);
2421                 break;
2422         case 64:
2423                 if (sign)
2424                         btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2425                 else
2426                         btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2427                 break;
2428         case 32:
2429                 if (sign)
2430                         btf_show_type_value(show, "%d", *(s32 *)safe_data);
2431                 else
2432                         btf_show_type_value(show, "%u", *(u32 *)safe_data);
2433                 break;
2434         case 16:
2435                 if (sign)
2436                         btf_show_type_value(show, "%d", *(s16 *)safe_data);
2437                 else
2438                         btf_show_type_value(show, "%u", *(u16 *)safe_data);
2439                 break;
2440         case 8:
2441                 if (show->state.array_encoding == BTF_INT_CHAR) {
2442                         /* check for null terminator */
2443                         if (show->state.array_terminated)
2444                                 break;
2445                         if (*(char *)data == '\0') {
2446                                 show->state.array_terminated = 1;
2447                                 break;
2448                         }
2449                         if (isprint(*(char *)data)) {
2450                                 btf_show_type_value(show, "'%c'",
2451                                                     *(char *)safe_data);
2452                                 break;
2453                         }
2454                 }
2455                 if (sign)
2456                         btf_show_type_value(show, "%d", *(s8 *)safe_data);
2457                 else
2458                         btf_show_type_value(show, "%u", *(u8 *)safe_data);
2459                 break;
2460         default:
2461                 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2462                 break;
2463         }
2464 out:
2465         btf_show_end_type(show);
2466 }
2467
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,
2475 };
2476
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)
2481 {
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;
2486
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,
2490                                         "Invalid member");
2491                 return -EINVAL;
2492         }
2493
2494         resolved_member = *member;
2495         resolved_member.type = resolved_type_id;
2496
2497         return btf_type_ops(resolved_type)->check_member(env, struct_type,
2498                                                          &resolved_member,
2499                                                          resolved_type);
2500 }
2501
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)
2506 {
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;
2511
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,
2515                                         "Invalid member");
2516                 return -EINVAL;
2517         }
2518
2519         resolved_member = *member;
2520         resolved_member.type = resolved_type_id;
2521
2522         return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2523                                                                &resolved_member,
2524                                                                resolved_type);
2525 }
2526
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)
2531 {
2532         u32 struct_size, struct_bits_off, bytes_offset;
2533
2534         struct_size = struct_type->size;
2535         struct_bits_off = member->offset;
2536         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2537
2538         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2539                 btf_verifier_log_member(env, struct_type, member,
2540                                         "Member is not byte aligned");
2541                 return -EINVAL;
2542         }
2543
2544         if (struct_size - bytes_offset < sizeof(void *)) {
2545                 btf_verifier_log_member(env, struct_type, member,
2546                                         "Member exceeds struct_size");
2547                 return -EINVAL;
2548         }
2549
2550         return 0;
2551 }
2552
2553 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2554                                    const struct btf_type *t,
2555                                    u32 meta_left)
2556 {
2557         const char *value;
2558
2559         if (btf_type_vlen(t)) {
2560                 btf_verifier_log_type(env, t, "vlen != 0");
2561                 return -EINVAL;
2562         }
2563
2564         if (btf_type_kflag(t)) {
2565                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2566                 return -EINVAL;
2567         }
2568
2569         if (!BTF_TYPE_ID_VALID(t->type)) {
2570                 btf_verifier_log_type(env, t, "Invalid type_id");
2571                 return -EINVAL;
2572         }
2573
2574         /* typedef/type_tag type must have a valid name, and other ref types,
2575          * volatile, const, restrict, should have a null name.
2576          */
2577         if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2578                 if (!t->name_off ||
2579                     !btf_name_valid_identifier(env->btf, t->name_off)) {
2580                         btf_verifier_log_type(env, t, "Invalid name");
2581                         return -EINVAL;
2582                 }
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");
2587                         return -EINVAL;
2588                 }
2589         } else {
2590                 if (t->name_off) {
2591                         btf_verifier_log_type(env, t, "Invalid name");
2592                         return -EINVAL;
2593                 }
2594         }
2595
2596         btf_verifier_log_type(env, t, NULL);
2597
2598         return 0;
2599 }
2600
2601 static int btf_modifier_resolve(struct btf_verifier_env *env,
2602                                 const struct resolve_vertex *v)
2603 {
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;
2608
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");
2612                 return -EINVAL;
2613         }
2614
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);
2618
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
2623          * pretty print).
2624          */
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);
2628
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");
2634                         return -EINVAL;
2635                 }
2636         }
2637
2638         env_stack_pop_resolved(env, next_type_id, 0);
2639
2640         return 0;
2641 }
2642
2643 static int btf_var_resolve(struct btf_verifier_env *env,
2644                            const struct resolve_vertex *v)
2645 {
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;
2650
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");
2654                 return -EINVAL;
2655         }
2656
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);
2660
2661         if (btf_type_is_modifier(next_type)) {
2662                 const struct btf_type *resolved_type;
2663                 u32 resolved_type_id;
2664
2665                 resolved_type_id = next_type_id;
2666                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2667
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,
2672                                               resolved_type_id);
2673         }
2674
2675         /* We must resolve to something concrete at this point, no
2676          * forward types or similar that would resolve to size of
2677          * zero is allowed.
2678          */
2679         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2680                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2681                 return -EINVAL;
2682         }
2683
2684         env_stack_pop_resolved(env, next_type_id, 0);
2685
2686         return 0;
2687 }
2688
2689 static int btf_ptr_resolve(struct btf_verifier_env *env,
2690                            const struct resolve_vertex *v)
2691 {
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;
2696
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");
2700                 return -EINVAL;
2701         }
2702
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);
2706
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).
2710          *
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).
2714          */
2715         if (btf_type_is_modifier(next_type)) {
2716                 const struct btf_type *resolved_type;
2717                 u32 resolved_type_id;
2718
2719                 resolved_type_id = next_type_id;
2720                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2721
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,
2726                                               resolved_type_id);
2727         }
2728
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);
2732
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");
2737                         return -EINVAL;
2738                 }
2739         }
2740
2741         env_stack_pop_resolved(env, next_type_id, 0);
2742
2743         return 0;
2744 }
2745
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)
2750 {
2751         if (btf->resolved_ids)
2752                 t = btf_type_id_resolve(btf, &type_id);
2753         else
2754                 t = btf_type_skip_modifiers(btf, type_id, NULL);
2755
2756         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2757 }
2758
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)
2762 {
2763         t = btf_type_id_resolve(btf, &type_id);
2764
2765         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2766 }
2767
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)
2771 {
2772         void *safe_data;
2773
2774         safe_data = btf_show_start_type(show, t, type_id, data);
2775         if (!safe_data)
2776                 return;
2777
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);
2781         else
2782                 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2783         btf_show_end_type(show);
2784 }
2785
2786 static void btf_ref_type_log(struct btf_verifier_env *env,
2787                              const struct btf_type *t)
2788 {
2789         btf_verifier_log(env, "type_id=%u", t->type);
2790 }
2791
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,
2799 };
2800
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,
2808 };
2809
2810 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2811                               const struct btf_type *t,
2812                               u32 meta_left)
2813 {
2814         if (btf_type_vlen(t)) {
2815                 btf_verifier_log_type(env, t, "vlen != 0");
2816                 return -EINVAL;
2817         }
2818
2819         if (t->type) {
2820                 btf_verifier_log_type(env, t, "type != 0");
2821                 return -EINVAL;
2822         }
2823
2824         /* fwd type must have a valid name */
2825         if (!t->name_off ||
2826             !btf_name_valid_identifier(env->btf, t->name_off)) {
2827                 btf_verifier_log_type(env, t, "Invalid name");
2828                 return -EINVAL;
2829         }
2830
2831         btf_verifier_log_type(env, t, NULL);
2832
2833         return 0;
2834 }
2835
2836 static void btf_fwd_type_log(struct btf_verifier_env *env,
2837                              const struct btf_type *t)
2838 {
2839         btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2840 }
2841
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,
2849 };
2850
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)
2855 {
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;
2860
2861         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2862                 btf_verifier_log_member(env, struct_type, member,
2863                                         "Member is not byte aligned");
2864                 return -EINVAL;
2865         }
2866
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");
2874                 return -EINVAL;
2875         }
2876
2877         return 0;
2878 }
2879
2880 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2881                                 const struct btf_type *t,
2882                                 u32 meta_left)
2883 {
2884         const struct btf_array *array = btf_type_array(t);
2885         u32 meta_needed = sizeof(*array);
2886
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);
2891                 return -EINVAL;
2892         }
2893
2894         /* array type should not have a name */
2895         if (t->name_off) {
2896                 btf_verifier_log_type(env, t, "Invalid name");
2897                 return -EINVAL;
2898         }
2899
2900         if (btf_type_vlen(t)) {
2901                 btf_verifier_log_type(env, t, "vlen != 0");
2902                 return -EINVAL;
2903         }
2904
2905         if (btf_type_kflag(t)) {
2906                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2907                 return -EINVAL;
2908         }
2909
2910         if (t->size) {
2911                 btf_verifier_log_type(env, t, "size != 0");
2912                 return -EINVAL;
2913         }
2914
2915         /* Array elem type and index type cannot be in type void,
2916          * so !array->type and !array->index_type are not allowed.
2917          */
2918         if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2919                 btf_verifier_log_type(env, t, "Invalid elem");
2920                 return -EINVAL;
2921         }
2922
2923         if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2924                 btf_verifier_log_type(env, t, "Invalid index");
2925                 return -EINVAL;
2926         }
2927
2928         btf_verifier_log_type(env, t, NULL);
2929
2930         return meta_needed;
2931 }
2932
2933 static int btf_array_resolve(struct btf_verifier_env *env,
2934                              const struct resolve_vertex *v)
2935 {
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;
2940         u32 elem_size;
2941
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");
2948                 return -EINVAL;
2949         }
2950
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);
2954
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");
2959                 return -EINVAL;
2960         }
2961
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,
2968                                       "Invalid elem");
2969                 return -EINVAL;
2970         }
2971
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);
2975
2976         elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2977         if (!elem_type) {
2978                 btf_verifier_log_type(env, v->t, "Invalid elem");
2979                 return -EINVAL;
2980         }
2981
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");
2984                 return -EINVAL;
2985         }
2986
2987         if (array->nelems && elem_size > U32_MAX / array->nelems) {
2988                 btf_verifier_log_type(env, v->t,
2989                                       "Array size overflows U32_MAX");
2990                 return -EINVAL;
2991         }
2992
2993         env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2994
2995         return 0;
2996 }
2997
2998 static void btf_array_log(struct btf_verifier_env *env,
2999                           const struct btf_type *t)
3000 {
3001         const struct btf_array *array = btf_type_array(t);
3002
3003         btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3004                          array->type, array->index_type, array->nelems);
3005 }
3006
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)
3010 {
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;
3015         u16 encoding = 0;
3016
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;
3021
3022         if (elem_type && btf_type_is_int(elem_type)) {
3023                 u32 int_type = btf_type_int(elem_type);
3024
3025                 encoding = BTF_INT_ENCODING(int_type);
3026
3027                 /*
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.
3031                  */
3032                 if (elem_size == 1)
3033                         encoding = BTF_INT_CHAR;
3034         }
3035
3036         if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3037                 return;
3038
3039         if (!elem_type)
3040                 goto out;
3041         elem_ops = btf_type_ops(elem_type);
3042
3043         for (i = 0; i < array->nelems; i++) {
3044
3045                 btf_show_start_array_member(show);
3046
3047                 elem_ops->show(btf, elem_type, elem_type_id, data,
3048                                bits_offset, show);
3049                 data += elem_size;
3050
3051                 btf_show_end_array_member(show);
3052
3053                 if (show->state.array_terminated)
3054                         break;
3055         }
3056 out:
3057         btf_show_end_array_type(show);
3058 }
3059
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)
3063 {
3064         const struct btf_member *m = show->state.member;
3065
3066         /*
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.
3070          */
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;
3075                 }
3076                 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3077                 show->state.member = m;
3078
3079                 if (show->state.depth_check != show->state.depth + 1)
3080                         return;
3081                 show->state.depth_check = 0;
3082
3083                 if (show->state.depth_to_show <= show->state.depth)
3084                         return;
3085                 /*
3086                  * Reaching here indicates we have recursed and found
3087                  * non-zero array member(s).
3088                  */
3089         }
3090         __btf_array_show(btf, t, type_id, data, bits_offset, show);
3091 }
3092
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,
3100 };
3101
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)
3106 {
3107         u32 struct_bits_off = member->offset;
3108         u32 struct_size, bytes_offset;
3109
3110         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3111                 btf_verifier_log_member(env, struct_type, member,
3112                                         "Member is not byte aligned");
3113                 return -EINVAL;
3114         }
3115
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");
3121                 return -EINVAL;
3122         }
3123
3124         return 0;
3125 }
3126
3127 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3128                                  const struct btf_type *t,
3129                                  u32 meta_left)
3130 {
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;
3136         u32 offset;
3137         u16 i;
3138
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);
3144                 return -EINVAL;
3145         }
3146
3147         /* struct type either no name or a valid one */
3148         if (t->name_off &&
3149             !btf_name_valid_identifier(env->btf, t->name_off)) {
3150                 btf_verifier_log_type(env, t, "Invalid name");
3151                 return -EINVAL;
3152         }
3153
3154         btf_verifier_log_type(env, t, NULL);
3155
3156         last_offset = 0;
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",
3161                                                 member->name_off);
3162                         return -EINVAL;
3163                 }
3164
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");
3169                         return -EINVAL;
3170                 }
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,
3174                                                 "Invalid type_id");
3175                         return -EINVAL;
3176                 }
3177
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");
3182                         return -EINVAL;
3183                 }
3184
3185                 /*
3186                  * ">" instead of ">=" because the last member could be
3187                  * "char a[0];"
3188                  */
3189                 if (last_offset > offset) {
3190                         btf_verifier_log_member(env, t, member,
3191                                                 "Invalid member bits_offset");
3192                         return -EINVAL;
3193                 }
3194
3195                 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3196                         btf_verifier_log_member(env, t, member,
3197                                                 "Member bits_offset exceeds its struct size");
3198                         return -EINVAL;
3199                 }
3200
3201                 btf_verifier_log_member(env, t, member, NULL);
3202                 last_offset = offset;
3203         }
3204
3205         return meta_needed;
3206 }
3207
3208 static int btf_struct_resolve(struct btf_verifier_env *env,
3209                               const struct resolve_vertex *v)
3210 {
3211         const struct btf_member *member;
3212         int err;
3213         u16 i;
3214
3215         /* Before continue resolving the next_member,
3216          * ensure the last member is indeed resolved to a
3217          * type with size info.
3218          */
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;
3223
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)))
3228                         return -EINVAL;
3229
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,
3234                                                                 last_member,
3235                                                                 last_member_type);
3236                 else
3237                         err = btf_type_ops(last_member_type)->check_member(env, v->t,
3238                                                                 last_member,
3239                                                                 last_member_type);
3240                 if (err)
3241                         return err;
3242         }
3243
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,
3247                                                                 member_type_id);
3248
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,
3252                                                 "Invalid member");
3253                         return -EINVAL;
3254                 }
3255
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);
3260                 }
3261
3262                 if (btf_type_kflag(v->t))
3263                         err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3264                                                                             member,
3265                                                                             member_type);
3266                 else
3267                         err = btf_type_ops(member_type)->check_member(env, v->t,
3268                                                                       member,
3269                                                                       member_type);
3270                 if (err)
3271                         return err;
3272         }
3273
3274         env_stack_pop_resolved(env, 0, 0);
3275
3276         return 0;
3277 }
3278
3279 static void btf_struct_log(struct btf_verifier_env *env,
3280                            const struct btf_type *t)
3281 {
3282         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3283 }
3284
3285 enum {
3286         BTF_FIELD_IGNORE = 0,
3287         BTF_FIELD_FOUND  = 1,
3288 };
3289
3290 struct btf_field_info {
3291         enum btf_field_type type;
3292         u32 off;
3293         union {
3294                 struct {
3295                         u32 type_id;
3296                 } kptr;
3297                 struct {
3298                         const char *node_name;
3299                         u32 value_btf_id;
3300                 } graph_root;
3301         };
3302 };
3303
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)
3307 {
3308         if (!__btf_type_is_struct(t))
3309                 return BTF_FIELD_IGNORE;
3310         if (t->size != sz)
3311                 return BTF_FIELD_IGNORE;
3312         info->type = field_type;
3313         info->off = off;
3314         return BTF_FIELD_FOUND;
3315 }
3316
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)
3319 {
3320         enum btf_field_type type;
3321         u32 res_id;
3322
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);
3330
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)))
3335                 return -EINVAL;
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;
3342         else
3343                 return -EINVAL;
3344
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))
3349                 return -EINVAL;
3350
3351         info->type = type;
3352         info->off = off;
3353         info->kptr.type_id = res_id;
3354         return BTF_FIELD_FOUND;
3355 }
3356
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)
3359 {
3360         int len = strlen(tag_key);
3361         int i, n;
3362
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);
3365
3366                 if (!btf_type_is_decl_tag(t))
3367                         continue;
3368                 if (pt != btf_type_by_id(btf, t->type))
3369                         continue;
3370                 if (btf_type_decl_tag(t)->component_idx != comp_idx)
3371                         continue;
3372                 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3373                         continue;
3374                 return i;
3375         }
3376         return -ENOENT;
3377 }
3378
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)
3381 {
3382         const char *value = NULL;
3383         const struct btf_type *t;
3384         int len, id;
3385
3386         id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, 0);
3387         if (id < 0)
3388                 return ERR_PTR(id);
3389
3390         t = btf_type_by_id(btf, id);
3391         len = strlen(tag_key);
3392         value = __btf_name_by_offset(btf, t->name_off) + len;
3393
3394         /* Prevent duplicate entries for same type */
3395         id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3396         if (id >= 0)
3397                 return ERR_PTR(-EEXIST);
3398
3399         return value;
3400 }
3401
3402 static int
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)
3407 {
3408         const char *node_field_name;
3409         const char *value_type;
3410         s32 id;
3411
3412         if (!__btf_type_is_struct(t))
3413                 return BTF_FIELD_IGNORE;
3414         if (t->size != sz)
3415                 return BTF_FIELD_IGNORE;
3416         value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3417         if (IS_ERR(value_type))
3418                 return -EINVAL;
3419         node_field_name = strstr(value_type, ":");
3420         if (!node_field_name)
3421                 return -EINVAL;
3422         value_type = kstrndup(value_type, node_field_name - value_type, GFP_KERNEL | __GFP_NOWARN);
3423         if (!value_type)
3424                 return -ENOMEM;
3425         id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3426         kfree(value_type);
3427         if (id < 0)
3428                 return id;
3429         node_field_name++;
3430         if (str_is_empty(node_field_name))
3431                 return -EINVAL;
3432         info->type = head_type;
3433         info->off = off;
3434         info->graph_root.value_btf_id = id;
3435         info->graph_root.node_name = node_field_name;
3436         return BTF_FIELD_FOUND;
3437 }
3438
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;                                      \
3442                 goto end;                                               \
3443         }
3444
3445 static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3446                               int *align, int *sz)
3447 {
3448         int type = 0;
3449
3450         if (field_mask & BPF_SPIN_LOCK) {
3451                 if (!strcmp(name, "bpf_spin_lock")) {
3452                         if (*seen_mask & BPF_SPIN_LOCK)
3453                                 return -E2BIG;
3454                         *seen_mask |= BPF_SPIN_LOCK;
3455                         type = BPF_SPIN_LOCK;
3456                         goto end;
3457                 }
3458         }
3459         if (field_mask & BPF_TIMER) {
3460                 if (!strcmp(name, "bpf_timer")) {
3461                         if (*seen_mask & BPF_TIMER)
3462                                 return -E2BIG;
3463                         *seen_mask |= BPF_TIMER;
3464                         type = BPF_TIMER;
3465                         goto end;
3466                 }
3467         }
3468         if (field_mask & BPF_WORKQUEUE) {
3469                 if (!strcmp(name, "bpf_wq")) {
3470                         if (*seen_mask & BPF_WORKQUEUE)
3471                                 return -E2BIG;
3472                         *seen_mask |= BPF_WORKQUEUE;
3473                         type = BPF_WORKQUEUE;
3474                         goto end;
3475                 }
3476         }
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");
3482
3483         /* Only return BPF_KPTR when all other types with matchable names fail */
3484         if (field_mask & BPF_KPTR) {
3485                 type = BPF_KPTR_REF;
3486                 goto end;
3487         }
3488         return 0;
3489 end:
3490         *sz = btf_field_type_size(type);
3491         *align = btf_field_type_align(type);
3492         return type;
3493 }
3494
3495 #undef field_mask_test_name
3496
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)
3500 {
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;
3505
3506         for_each_member(i, t, member) {
3507                 const struct btf_type *member_type = btf_type_by_id(btf,
3508                                                                     member->type);
3509
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)
3513                         continue;
3514                 if (field_type < 0)
3515                         return field_type;
3516
3517                 off = __btf_member_bit_offset(t, member);
3518                 if (off % 8)
3519                         /* valid C code cannot generate such BTF */
3520                         return -EINVAL;
3521                 off /= 8;
3522                 if (off % align)
3523                         continue;
3524
3525                 switch (field_type) {
3526                 case BPF_SPIN_LOCK:
3527                 case BPF_TIMER:
3528                 case BPF_WORKQUEUE:
3529                 case BPF_LIST_NODE:
3530                 case BPF_RB_NODE:
3531                 case BPF_REFCOUNT:
3532                         ret = btf_find_struct(btf, member_type, off, sz, field_type,
3533                                               idx < info_cnt ? &info[idx] : &tmp);
3534                         if (ret < 0)
3535                                 return ret;
3536                         break;
3537                 case BPF_KPTR_UNREF:
3538                 case BPF_KPTR_REF:
3539                 case BPF_KPTR_PERCPU:
3540                         ret = btf_find_kptr(btf, member_type, off, sz,
3541                                             idx < info_cnt ? &info[idx] : &tmp);
3542                         if (ret < 0)
3543                                 return ret;
3544                         break;
3545                 case BPF_LIST_HEAD:
3546                 case BPF_RB_ROOT:
3547                         ret = btf_find_graph_root(btf, t, member_type,
3548                                                   i, off, sz,
3549                                                   idx < info_cnt ? &info[idx] : &tmp,
3550                                                   field_type);
3551                         if (ret < 0)
3552                                 return ret;
3553                         break;
3554                 default:
3555                         return -EFAULT;
3556                 }
3557
3558                 if (ret == BTF_FIELD_IGNORE)
3559                         continue;
3560                 if (idx >= info_cnt)
3561                         return -E2BIG;
3562                 ++idx;
3563         }
3564         return idx;
3565 }
3566
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,
3569                                 int info_cnt)
3570 {
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;
3575
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);
3579
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)
3583                         continue;
3584                 if (field_type < 0)
3585                         return field_type;
3586
3587                 off = vsi->offset;
3588                 if (vsi->size != sz)
3589                         continue;
3590                 if (off % align)
3591                         continue;
3592
3593                 switch (field_type) {
3594                 case BPF_SPIN_LOCK:
3595                 case BPF_TIMER:
3596                 case BPF_WORKQUEUE:
3597                 case BPF_LIST_NODE:
3598                 case BPF_RB_NODE:
3599                 case BPF_REFCOUNT:
3600                         ret = btf_find_struct(btf, var_type, off, sz, field_type,
3601                                               idx < info_cnt ? &info[idx] : &tmp);
3602                         if (ret < 0)
3603                                 return ret;
3604                         break;
3605                 case BPF_KPTR_UNREF:
3606                 case BPF_KPTR_REF:
3607                 case BPF_KPTR_PERCPU:
3608                         ret = btf_find_kptr(btf, var_type, off, sz,
3609                                             idx < info_cnt ? &info[idx] : &tmp);
3610                         if (ret < 0)
3611                                 return ret;
3612                         break;
3613                 case BPF_LIST_HEAD:
3614                 case BPF_RB_ROOT:
3615                         ret = btf_find_graph_root(btf, var, var_type,
3616                                                   -1, off, sz,
3617                                                   idx < info_cnt ? &info[idx] : &tmp,
3618                                                   field_type);
3619                         if (ret < 0)
3620                                 return ret;
3621                         break;
3622                 default:
3623                         return -EFAULT;
3624                 }
3625
3626                 if (ret == BTF_FIELD_IGNORE)
3627                         continue;
3628                 if (idx >= info_cnt)
3629                         return -E2BIG;
3630                 ++idx;
3631         }
3632         return idx;
3633 }
3634
3635 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3636                           u32 field_mask, struct btf_field_info *info,
3637                           int info_cnt)
3638 {
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);
3643         return -EINVAL;
3644 }
3645
3646 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3647                           struct btf_field_info *info)
3648 {
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
3653          */
3654         struct btf *kptr_btf;
3655         int ret;
3656         s32 id;
3657
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.
3660          */
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),
3663                              &kptr_btf);
3664         if (id == -ENOENT) {
3665                 /* btf_parse_kptr should only be called w/ btf = program BTF */
3666                 WARN_ON_ONCE(btf_is_kernel(btf));
3667
3668                 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3669                  * kptr allocated via bpf_obj_new
3670                  */
3671                 field->kptr.dtor = NULL;
3672                 id = info->kptr.type_id;
3673                 kptr_btf = (struct btf *)btf;
3674                 btf_get(kptr_btf);
3675                 goto found_dtor;
3676         }
3677         if (id < 0)
3678                 return id;
3679
3680         /* Find and stash the function pointer for the destruction function that
3681          * needs to be eventually invoked from the map free path.
3682          */
3683         if (info->type == BPF_KPTR_REF) {
3684                 const struct btf_type *dtor_func;
3685                 const char *dtor_func_name;
3686                 unsigned long addr;
3687                 s32 dtor_btf_id;
3688
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
3691                  * the same time.
3692                  */
3693                 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3694                 if (dtor_btf_id < 0) {
3695                         ret = dtor_btf_id;
3696                         goto end_btf;
3697                 }
3698
3699                 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3700                 if (!dtor_func) {
3701                         ret = -ENOENT;
3702                         goto end_btf;
3703                 }
3704
3705                 if (btf_is_module(kptr_btf)) {
3706                         mod = btf_try_get_module(kptr_btf);
3707                         if (!mod) {
3708                                 ret = -ENXIO;
3709                                 goto end_btf;
3710                         }
3711                 }
3712
3713                 /* We already verified dtor_func to be btf_type_is_func
3714                  * in register_btf_id_dtor_kfuncs.
3715                  */
3716                 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3717                 addr = kallsyms_lookup_name(dtor_func_name);
3718                 if (!addr) {
3719                         ret = -EINVAL;
3720                         goto end_mod;
3721                 }
3722                 field->kptr.dtor = (void *)addr;
3723         }
3724
3725 found_dtor:
3726         field->kptr.btf_id = id;
3727         field->kptr.btf = kptr_btf;
3728         field->kptr.module = mod;
3729         return 0;
3730 end_mod:
3731         module_put(mod);
3732 end_btf:
3733         btf_put(kptr_btf);
3734         return ret;
3735 }
3736
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)
3742 {
3743         const struct btf_type *t, *n = NULL;
3744         const struct btf_member *member;
3745         u32 offset;
3746         int i;
3747
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
3751          * verify its type.
3752          */
3753         for_each_member(i, t, member) {
3754                 if (strcmp(info->graph_root.node_name,
3755                            __btf_name_by_offset(btf, member->name_off)))
3756                         continue;
3757                 /* Invalid BTF, two members with same name */
3758                 if (n)
3759                         return -EINVAL;
3760                 n = btf_type_by_id(btf, member->type);
3761                 if (!__btf_type_is_struct(n))
3762                         return -EINVAL;
3763                 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3764                         return -EINVAL;
3765                 offset = __btf_member_bit_offset(n, member);
3766                 if (offset % 8)
3767                         return -EINVAL;
3768                 offset /= 8;
3769                 if (offset % node_type_align)
3770                         return -EINVAL;
3771
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;
3775         }
3776         if (!n)
3777                 return -ENOENT;
3778         return 0;
3779 }
3780
3781 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3782                                struct btf_field_info *info)
3783 {
3784         return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3785                                             __alignof__(struct bpf_list_node));
3786 }
3787
3788 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3789                              struct btf_field_info *info)
3790 {
3791         return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3792                                             __alignof__(struct bpf_rb_node));
3793 }
3794
3795 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3796 {
3797         const struct btf_field *a = (const struct btf_field *)_a;
3798         const struct btf_field *b = (const struct btf_field *)_b;
3799
3800         if (a->offset < b->offset)
3801                 return -1;
3802         else if (a->offset > b->offset)
3803                 return 1;
3804         return 0;
3805 }
3806
3807 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3808                                     u32 field_mask, u32 value_size)
3809 {
3810         struct btf_field_info info_arr[BTF_FIELDS_MAX];
3811         u32 next_off = 0, field_type_size;
3812         struct btf_record *rec;
3813         int ret, i, cnt;
3814
3815         ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3816         if (ret < 0)
3817                 return ERR_PTR(ret);
3818         if (!ret)
3819                 return NULL;
3820
3821         cnt = ret;
3822         /* This needs to be kzalloc to zero out padding and unused fields, see
3823          * comment in btf_record_equal.
3824          */
3825         rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3826         if (!rec)
3827                 return ERR_PTR(-ENOMEM);
3828
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);
3837                         ret = -EFAULT;
3838                         goto end;
3839                 }
3840                 if (info_arr[i].off < next_off) {
3841                         ret = -EEXIST;
3842                         goto end;
3843                 }
3844                 next_off = info_arr[i].off + field_type_size;
3845
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;
3850
3851                 switch (info_arr[i].type) {
3852                 case BPF_SPIN_LOCK:
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;
3856                         break;
3857                 case BPF_TIMER:
3858                         WARN_ON_ONCE(rec->timer_off >= 0);
3859                         /* Cache offset for faster lookup at runtime */
3860                         rec->timer_off = rec->fields[i].offset;
3861                         break;
3862                 case BPF_WORKQUEUE:
3863                         WARN_ON_ONCE(rec->wq_off >= 0);
3864                         /* Cache offset for faster lookup at runtime */
3865                         rec->wq_off = rec->fields[i].offset;
3866                         break;
3867                 case BPF_REFCOUNT:
3868                         WARN_ON_ONCE(rec->refcount_off >= 0);
3869                         /* Cache offset for faster lookup at runtime */
3870                         rec->refcount_off = rec->fields[i].offset;
3871                         break;
3872                 case BPF_KPTR_UNREF:
3873                 case BPF_KPTR_REF:
3874                 case BPF_KPTR_PERCPU:
3875                         ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3876                         if (ret < 0)
3877                                 goto end;
3878                         break;
3879                 case BPF_LIST_HEAD:
3880                         ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3881                         if (ret < 0)
3882                                 goto end;
3883                         break;
3884                 case BPF_RB_ROOT:
3885                         ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
3886                         if (ret < 0)
3887                                 goto end;
3888                         break;
3889                 case BPF_LIST_NODE:
3890                 case BPF_RB_NODE:
3891                         break;
3892                 default:
3893                         ret = -EFAULT;
3894                         goto end;
3895                 }
3896                 rec->cnt++;
3897         }
3898
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) {
3902                 ret = -EINVAL;
3903                 goto end;
3904         }
3905
3906         if (rec->refcount_off < 0 &&
3907             btf_record_has_field(rec, BPF_LIST_NODE) &&
3908             btf_record_has_field(rec, BPF_RB_NODE)) {
3909                 ret = -EINVAL;
3910                 goto end;
3911         }
3912
3913         sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
3914                NULL, rec);
3915
3916         return rec;
3917 end:
3918         btf_record_free(rec);
3919         return ERR_PTR(ret);
3920 }
3921
3922 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3923 {
3924         int i;
3925
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.
3930          *
3931          * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
3932          * does not form cycles.
3933          */
3934         if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & BPF_GRAPH_ROOT))
3935                 return 0;
3936         for (i = 0; i < rec->cnt; i++) {
3937                 struct btf_struct_meta *meta;
3938                 u32 btf_id;
3939
3940                 if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
3941                         continue;
3942                 btf_id = rec->fields[i].graph_root.value_btf_id;
3943                 meta = btf_find_struct_meta(btf, btf_id);
3944                 if (!meta)
3945                         return -EFAULT;
3946                 rec->fields[i].graph_root.value_rec = meta->record;
3947
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
3950                  * node type.
3951                  */
3952                 if (!(rec->field_mask & BPF_GRAPH_NODE))
3953                         continue;
3954
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:
3960                  *
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.
3965                  *
3966                  * We ensure that if a type is both a root and node, its
3967                  * element types cannot be root types.
3968                  *
3969                  * To ensure acyclicity:
3970                  *
3971                  * When A is an root type but not a node, its ownership
3972                  * chain can be:
3973                  *      A -> B -> C
3974                  * Where:
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
3977                  *   bpf_list_head.
3978                  * - C is only an root, e.g. has bpf_list_node
3979                  *
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.
3983                  *      A -> B
3984                  * Where:
3985                  * - A is both an root and node.
3986                  * - B is only an node.
3987                  */
3988                 if (meta->record->field_mask & BPF_GRAPH_ROOT)
3989                         return -ELOOP;
3990         }
3991         return 0;
3992 }
3993
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)
3997 {
3998         const struct btf_member *member;
3999         void *safe_data;
4000         u32 i;
4001
4002         safe_data = btf_show_start_struct_type(show, t, type_id, data);
4003         if (!safe_data)
4004                 return;
4005
4006         for_each_member(i, t, member) {
4007                 const struct btf_type *member_type = btf_type_by_id(btf,
4008                                                                 member->type);
4009                 const struct btf_kind_operations *ops;
4010                 u32 member_offset, bitfield_size;
4011                 u32 bytes_offset;
4012                 u8 bits8_offset;
4013
4014                 btf_show_start_member(show, member);
4015
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,
4022                                                         member->type,
4023                                                         data + bytes_offset);
4024                         if (safe_data)
4025                                 btf_bitfield_show(safe_data,
4026                                                   bits8_offset,
4027                                                   bitfield_size, show);
4028                         btf_show_end_type(show);
4029                 } else {
4030                         ops = btf_type_ops(member_type);
4031                         ops->show(btf, member_type, member->type,
4032                                   data + bytes_offset, bits8_offset, show);
4033                 }
4034
4035                 btf_show_end_member(show);
4036         }
4037
4038         btf_show_end_struct_type(show);
4039 }
4040
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)
4044 {
4045         const struct btf_member *m = show->state.member;
4046
4047         /*
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.
4051          */
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;
4056                 }
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)
4061                         return;
4062                 show->state.depth_check = 0;
4063
4064                 if (show->state.depth_to_show <= show->state.depth)
4065                         return;
4066                 /*
4067                  * Reaching here indicates we have recursed and found
4068                  * non-zero child values.
4069                  */
4070         }
4071
4072         __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4073 }
4074
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,
4082 };
4083
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)
4088 {
4089         u32 struct_bits_off = member->offset;
4090         u32 struct_size, bytes_offset;
4091
4092         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4093                 btf_verifier_log_member(env, struct_type, member,
4094                                         "Member is not byte aligned");
4095                 return -EINVAL;
4096         }
4097
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");
4103                 return -EINVAL;
4104         }
4105
4106         return 0;
4107 }
4108
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)
4113 {
4114         u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4115         u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4116
4117         struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4118         nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4119         if (!nr_bits) {
4120                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4121                         btf_verifier_log_member(env, struct_type, member,
4122                                                 "Member is not byte aligned");
4123                         return -EINVAL;
4124                 }
4125
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");
4130                 return -EINVAL;
4131         }
4132
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");
4138                 return -EINVAL;
4139         }
4140
4141         return 0;
4142 }
4143
4144 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4145                                const struct btf_type *t,
4146                                u32 meta_left)
4147 {
4148         const struct btf_enum *enums = btf_type_enum(t);
4149         struct btf *btf = env->btf;
4150         const char *fmt_str;
4151         u16 i, nr_enums;
4152         u32 meta_needed;
4153
4154         nr_enums = btf_type_vlen(t);
4155         meta_needed = nr_enums * sizeof(*enums);
4156
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);
4161                 return -EINVAL;
4162         }
4163
4164         if (t->size > 8 || !is_power_of_2(t->size)) {
4165                 btf_verifier_log_type(env, t, "Unexpected size");
4166                 return -EINVAL;
4167         }
4168
4169         /* enum type either no name or a valid one */
4170         if (t->name_off &&
4171             !btf_name_valid_identifier(env->btf, t->name_off)) {
4172                 btf_verifier_log_type(env, t, "Invalid name");
4173                 return -EINVAL;
4174         }
4175
4176         btf_verifier_log_type(env, t, NULL);
4177
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",
4181                                          enums[i].name_off);
4182                         return -EINVAL;
4183                 }
4184
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");
4189                         return -EINVAL;
4190                 }
4191
4192                 if (env->log.level == BPF_LOG_KERNEL)
4193                         continue;
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),
4197                                  enums[i].val);
4198         }
4199
4200         return meta_needed;
4201 }
4202
4203 static void btf_enum_log(struct btf_verifier_env *env,
4204                          const struct btf_type *t)
4205 {
4206         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4207 }
4208
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)
4212 {
4213         const struct btf_enum *enums = btf_type_enum(t);
4214         u32 i, nr_enums = btf_type_vlen(t);
4215         void *safe_data;
4216         int v;
4217
4218         safe_data = btf_show_start_type(show, t, type_id, data);
4219         if (!safe_data)
4220                 return;
4221
4222         v = *(int *)safe_data;
4223
4224         for (i = 0; i < nr_enums; i++) {
4225                 if (v != enums[i].val)
4226                         continue;
4227
4228                 btf_show_type_value(show, "%s",
4229                                     __btf_name_by_offset(btf,
4230                                                          enums[i].name_off));
4231
4232                 btf_show_end_type(show);
4233                 return;
4234         }
4235
4236         if (btf_type_kflag(t))
4237                 btf_show_type_value(show, "%d", v);
4238         else
4239                 btf_show_type_value(show, "%u", v);
4240         btf_show_end_type(show);
4241 }
4242
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,
4250 };
4251
4252 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4253                                  const struct btf_type *t,
4254                                  u32 meta_left)
4255 {
4256         const struct btf_enum64 *enums = btf_type_enum64(t);
4257         struct btf *btf = env->btf;
4258         const char *fmt_str;
4259         u16 i, nr_enums;
4260         u32 meta_needed;
4261
4262         nr_enums = btf_type_vlen(t);
4263         meta_needed = nr_enums * sizeof(*enums);
4264
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);
4269                 return -EINVAL;
4270         }
4271
4272         if (t->size > 8 || !is_power_of_2(t->size)) {
4273                 btf_verifier_log_type(env, t, "Unexpected size");
4274                 return -EINVAL;
4275         }
4276
4277         /* enum type either no name or a valid one */
4278         if (t->name_off &&
4279             !btf_name_valid_identifier(env->btf, t->name_off)) {
4280                 btf_verifier_log_type(env, t, "Invalid name");
4281                 return -EINVAL;
4282         }
4283
4284         btf_verifier_log_type(env, t, NULL);
4285
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",
4289                                          enums[i].name_off);
4290                         return -EINVAL;
4291                 }
4292
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");
4297                         return -EINVAL;
4298                 }
4299
4300                 if (env->log.level == BPF_LOG_KERNEL)
4301                         continue;
4302
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));
4307         }
4308
4309         return meta_needed;
4310 }
4311
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)
4315 {
4316         const struct btf_enum64 *enums = btf_type_enum64(t);
4317         u32 i, nr_enums = btf_type_vlen(t);
4318         void *safe_data;
4319         s64 v;
4320
4321         safe_data = btf_show_start_type(show, t, type_id, data);
4322         if (!safe_data)
4323                 return;
4324
4325         v = *(u64 *)safe_data;
4326
4327         for (i = 0; i < nr_enums; i++) {
4328                 if (v != btf_enum64_value(enums + i))
4329                         continue;
4330
4331                 btf_show_type_value(show, "%s",
4332                                     __btf_name_by_offset(btf,
4333                                                          enums[i].name_off));
4334
4335                 btf_show_end_type(show);
4336                 return;
4337         }
4338
4339         if (btf_type_kflag(t))
4340                 btf_show_type_value(show, "%lld", v);
4341         else
4342                 btf_show_type_value(show, "%llu", v);
4343         btf_show_end_type(show);
4344 }
4345
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,
4353 };
4354
4355 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4356                                      const struct btf_type *t,
4357                                      u32 meta_left)
4358 {
4359         u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4360
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);
4365                 return -EINVAL;
4366         }
4367
4368         if (t->name_off) {
4369                 btf_verifier_log_type(env, t, "Invalid name");
4370                 return -EINVAL;
4371         }
4372
4373         if (btf_type_kflag(t)) {
4374                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4375                 return -EINVAL;
4376         }
4377
4378         btf_verifier_log_type(env, t, NULL);
4379
4380         return meta_needed;
4381 }
4382
4383 static void btf_func_proto_log(struct btf_verifier_env *env,
4384                                const struct btf_type *t)
4385 {
4386         const struct btf_param *args = (const struct btf_param *)(t + 1);
4387         u16 nr_args = btf_type_vlen(t), i;
4388
4389         btf_verifier_log(env, "return=%u args=(", t->type);
4390         if (!nr_args) {
4391                 btf_verifier_log(env, "void");
4392                 goto done;
4393         }
4394
4395         if (nr_args == 1 && !args[0].type) {
4396                 /* Only one vararg */
4397                 btf_verifier_log(env, "vararg");
4398                 goto done;
4399         }
4400
4401         btf_verifier_log(env, "%u %s", args[0].type,
4402                          __btf_name_by_offset(env->btf,
4403                                               args[0].name_off));
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,
4407                                                       args[i].name_off));
4408
4409         if (nr_args > 1) {
4410                 const struct btf_param *last_arg = &args[nr_args - 1];
4411
4412                 if (last_arg->type)
4413                         btf_verifier_log(env, ", %u %s", last_arg->type,
4414                                          __btf_name_by_offset(env->btf,
4415                                                               last_arg->name_off));
4416                 else
4417                         btf_verifier_log(env, ", vararg");
4418         }
4419
4420 done:
4421         btf_verifier_log(env, ")");
4422 }
4423
4424 static struct btf_kind_operations func_proto_ops = {
4425         .check_meta = btf_func_proto_check_meta,
4426         .resolve = btf_df_resolve,
4427         /*
4428          * BTF_KIND_FUNC_PROTO cannot be directly referred by
4429          * a struct's member.
4430          *
4431          * It should be a function pointer instead.
4432          * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4433          *
4434          * Hence, there is no btf_func_check_member().
4435          */
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,
4440 };
4441
4442 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4443                                const struct btf_type *t,
4444                                u32 meta_left)
4445 {
4446         if (!t->name_off ||
4447             !btf_name_valid_identifier(env->btf, t->name_off)) {
4448                 btf_verifier_log_type(env, t, "Invalid name");
4449                 return -EINVAL;
4450         }
4451
4452         if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4453                 btf_verifier_log_type(env, t, "Invalid func linkage");
4454                 return -EINVAL;
4455         }
4456
4457         if (btf_type_kflag(t)) {
4458                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4459                 return -EINVAL;
4460         }
4461
4462         btf_verifier_log_type(env, t, NULL);
4463
4464         return 0;
4465 }
4466
4467 static int btf_func_resolve(struct btf_verifier_env *env,
4468                             const struct resolve_vertex *v)
4469 {
4470         const struct btf_type *t = v->t;
4471         u32 next_type_id = t->type;
4472         int err;
4473
4474         err = btf_func_check(env, t);
4475         if (err)
4476                 return err;
4477
4478         env_stack_pop_resolved(env, next_type_id, 0);
4479         return 0;
4480 }
4481
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,
4489 };
4490
4491 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4492                               const struct btf_type *t,
4493                               u32 meta_left)
4494 {
4495         const struct btf_var *var;
4496         u32 meta_needed = sizeof(*var);
4497
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);
4502                 return -EINVAL;
4503         }
4504
4505         if (btf_type_vlen(t)) {
4506                 btf_verifier_log_type(env, t, "vlen != 0");
4507                 return -EINVAL;
4508         }
4509
4510         if (btf_type_kflag(t)) {
4511                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4512                 return -EINVAL;
4513         }
4514
4515         if (!t->name_off ||
4516             !__btf_name_valid(env->btf, t->name_off)) {
4517                 btf_verifier_log_type(env, t, "Invalid name");
4518                 return -EINVAL;
4519         }
4520
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");
4524                 return -EINVAL;
4525         }
4526
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");
4531                 return -EINVAL;
4532         }
4533
4534         btf_verifier_log_type(env, t, NULL);
4535
4536         return meta_needed;
4537 }
4538
4539 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4540 {
4541         const struct btf_var *var = btf_type_var(t);
4542
4543         btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4544 }
4545
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,
4553 };
4554
4555 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4556                                   const struct btf_type *t,
4557                                   u32 meta_left)
4558 {
4559         const struct btf_var_secinfo *vsi;
4560         u64 last_vsi_end_off = 0, sum = 0;
4561         u32 i, meta_needed;
4562
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);
4568                 return -EINVAL;
4569         }
4570
4571         if (!t->size) {
4572                 btf_verifier_log_type(env, t, "size == 0");
4573                 return -EINVAL;
4574         }
4575
4576         if (btf_type_kflag(t)) {
4577                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4578                 return -EINVAL;
4579         }
4580
4581         if (!t->name_off ||
4582             !btf_name_valid_section(env->btf, t->name_off)) {
4583                 btf_verifier_log_type(env, t, "Invalid name");
4584                 return -EINVAL;
4585         }
4586
4587         btf_verifier_log_type(env, t, NULL);
4588
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,
4593                                              "Invalid type_id");
4594                         return -EINVAL;
4595                 }
4596
4597                 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4598                         btf_verifier_log_vsi(env, t, vsi,
4599                                              "Invalid offset");
4600                         return -EINVAL;
4601                 }
4602
4603                 if (!vsi->size || vsi->size > t->size) {
4604                         btf_verifier_log_vsi(env, t, vsi,
4605                                              "Invalid size");
4606                         return -EINVAL;
4607                 }
4608
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");
4613                         return -EINVAL;
4614                 }
4615
4616                 btf_verifier_log_vsi(env, t, vsi, NULL);
4617                 sum += vsi->size;
4618         }
4619
4620         if (t->size < sum) {
4621                 btf_verifier_log_type(env, t, "Invalid btf_info size");
4622                 return -EINVAL;
4623         }
4624
4625         return meta_needed;
4626 }
4627
4628 static int btf_datasec_resolve(struct btf_verifier_env *env,
4629                                const struct resolve_vertex *v)
4630 {
4631         const struct btf_var_secinfo *vsi;
4632         struct btf *btf = env->btf;
4633         u16 i;
4634
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,
4639                                                                  var_type_id);
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");
4643                         return -EINVAL;
4644                 }
4645
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);
4650                 }
4651
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");
4655                         return -EINVAL;
4656                 }
4657
4658                 if (vsi->size < type_size) {
4659                         btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4660                         return -EINVAL;
4661                 }
4662         }
4663
4664         env_stack_pop_resolved(env, 0, 0);
4665         return 0;
4666 }
4667
4668 static void btf_datasec_log(struct btf_verifier_env *env,
4669                             const struct btf_type *t)
4670 {
4671         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4672 }
4673
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)
4678 {
4679         const struct btf_var_secinfo *vsi;
4680         const struct btf_type *var;
4681         u32 i;
4682
4683         if (!btf_show_start_type(show, t, type_id, data))
4684                 return;
4685
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);
4690                 if (i)
4691                         btf_show(show, ",");
4692                 btf_type_ops(var)->show(btf, var, vsi->type,
4693                                         data + vsi->offset, bits_offset, show);
4694         }
4695         btf_show_end_type(show);
4696 }
4697
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,
4705 };
4706
4707 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4708                                 const struct btf_type *t,
4709                                 u32 meta_left)
4710 {
4711         if (btf_type_vlen(t)) {
4712                 btf_verifier_log_type(env, t, "vlen != 0");
4713                 return -EINVAL;
4714         }
4715
4716         if (btf_type_kflag(t)) {
4717                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4718                 return -EINVAL;
4719         }
4720
4721         if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4722             t->size != 16) {
4723                 btf_verifier_log_type(env, t, "Invalid type_size");
4724                 return -EINVAL;
4725         }
4726
4727         btf_verifier_log_type(env, t, NULL);
4728
4729         return 0;
4730 }
4731
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)
4736 {
4737         u64 start_offset_bytes;
4738         u64 end_offset_bytes;
4739         u64 misalign_bits;
4740         u64 align_bytes;
4741         u64 align_bits;
4742
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.
4746          */
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");
4753                 return -EINVAL;
4754         }
4755
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");
4761                 return -EINVAL;
4762         }
4763
4764         return 0;
4765 }
4766
4767 static void btf_float_log(struct btf_verifier_env *env,
4768                           const struct btf_type *t)
4769 {
4770         btf_verifier_log(env, "size=%u", t->size);
4771 }
4772
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,
4780 };
4781
4782 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4783                               const struct btf_type *t,
4784                               u32 meta_left)
4785 {
4786         const struct btf_decl_tag *tag;
4787         u32 meta_needed = sizeof(*tag);
4788         s32 component_idx;
4789         const char *value;
4790
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);
4795                 return -EINVAL;
4796         }
4797
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");
4801                 return -EINVAL;
4802         }
4803
4804         if (btf_type_vlen(t)) {
4805                 btf_verifier_log_type(env, t, "vlen != 0");
4806                 return -EINVAL;
4807         }
4808
4809         if (btf_type_kflag(t)) {
4810                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4811                 return -EINVAL;
4812         }
4813
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");
4817                 return -EINVAL;
4818         }
4819
4820         btf_verifier_log_type(env, t, NULL);
4821
4822         return meta_needed;
4823 }
4824
4825 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4826                            const struct resolve_vertex *v)
4827 {
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;
4832         s32 component_idx;
4833         u32 vlen;
4834
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");
4838                 return -EINVAL;
4839         }
4840
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);
4844
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");
4849                         return -EINVAL;
4850                 }
4851
4852                 if (btf_type_is_struct(next_type)) {
4853                         vlen = btf_type_vlen(next_type);
4854                 } else {
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);
4858                 }
4859
4860                 if ((u32)component_idx >= vlen) {
4861                         btf_verifier_log_type(env, v->t, "Invalid component_idx");
4862                         return -EINVAL;
4863                 }
4864         }
4865
4866         env_stack_pop_resolved(env, next_type_id, 0);
4867
4868         return 0;
4869 }
4870
4871 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4872 {
4873         btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4874                          btf_type_decl_tag(t)->component_idx);
4875 }
4876
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,
4884 };
4885
4886 static int btf_func_proto_check(struct btf_verifier_env *env,
4887                                 const struct btf_type *t)
4888 {
4889         const struct btf_type *ret_type;
4890         const struct btf_param *args;
4891         const struct btf *btf;
4892         u16 nr_args, i;
4893         int err;
4894
4895         btf = env->btf;
4896         args = (const struct btf_param *)(t + 1);
4897         nr_args = btf_type_vlen(t);
4898
4899         /* Check func return type which could be "void" (t->type == 0) */
4900         if (t->type) {
4901                 u32 ret_type_id = t->type;
4902
4903                 ret_type = btf_type_by_id(btf, ret_type_id);
4904                 if (!ret_type) {
4905                         btf_verifier_log_type(env, t, "Invalid return type");
4906                         return -EINVAL;
4907                 }
4908
4909                 if (btf_type_is_resolve_source_only(ret_type)) {
4910                         btf_verifier_log_type(env, t, "Invalid return type");
4911                         return -EINVAL;
4912                 }
4913
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);
4917                         if (err)
4918                                 return err;
4919                 }
4920
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");
4924                         return -EINVAL;
4925                 }
4926         }
4927
4928         if (!nr_args)
4929                 return 0;
4930
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",
4935                                               nr_args);
4936                         return -EINVAL;
4937                 }
4938                 nr_args--;
4939         }
4940
4941         for (i = 0; i < nr_args; i++) {
4942                 const struct btf_type *arg_type;
4943                 u32 arg_type_id;
4944
4945                 arg_type_id = args[i].type;
4946                 arg_type = btf_type_by_id(btf, arg_type_id);
4947                 if (!arg_type) {
4948                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4949                         return -EINVAL;
4950                 }
4951
4952                 if (btf_type_is_resolve_source_only(arg_type)) {
4953                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4954                         return -EINVAL;
4955                 }
4956
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);
4962                         return -EINVAL;
4963                 }
4964
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);
4968                         if (err)
4969                                 return err;
4970                 }
4971
4972                 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4973                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4974                         return -EINVAL;
4975                 }
4976         }
4977
4978         return 0;
4979 }
4980
4981 static int btf_func_check(struct btf_verifier_env *env,
4982                           const struct btf_type *t)
4983 {
4984         const struct btf_type *proto_type;
4985         const struct btf_param *args;
4986         const struct btf *btf;
4987         u16 nr_args, i;
4988
4989         btf = env->btf;
4990         proto_type = btf_type_by_id(btf, t->type);
4991
4992         if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4993                 btf_verifier_log_type(env, t, "Invalid type_id");
4994                 return -EINVAL;
4995         }
4996
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);
5002                         return -EINVAL;
5003                 }
5004         }
5005
5006         return 0;
5007 }
5008
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,
5029 };
5030
5031 static s32 btf_check_meta(struct btf_verifier_env *env,
5032                           const struct btf_type *t,
5033                           u32 meta_left)
5034 {
5035         u32 saved_meta_left = meta_left;
5036         s32 var_meta_size;
5037
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));
5041                 return -EINVAL;
5042         }
5043         meta_left -= sizeof(*t);
5044
5045         if (t->info & ~BTF_INFO_MASK) {
5046                 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
5047                                  env->log_type_id, t->info);
5048                 return -EINVAL;
5049         }
5050
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));
5055                 return -EINVAL;
5056         }
5057
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);
5061                 return -EINVAL;
5062         }
5063
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;
5067
5068         meta_left -= var_meta_size;
5069
5070         return saved_meta_left - meta_left;
5071 }
5072
5073 static int btf_check_all_metas(struct btf_verifier_env *env)
5074 {
5075         struct btf *btf = env->btf;
5076         struct btf_header *hdr;
5077         void *cur, *end;
5078
5079         hdr = &btf->hdr;
5080         cur = btf->nohdr_data + hdr->type_off;
5081         end = cur + hdr->type_len;
5082
5083         env->log_type_id = btf->base_btf ? btf->start_id : 1;
5084         while (cur < end) {
5085                 struct btf_type *t = cur;
5086                 s32 meta_size;
5087
5088                 meta_size = btf_check_meta(env, t, end - cur);
5089                 if (meta_size < 0)
5090                         return meta_size;
5091
5092                 btf_add_type(env, t);
5093                 cur += meta_size;
5094                 env->log_type_id++;
5095         }
5096
5097         return 0;
5098 }
5099
5100 static bool btf_resolve_valid(struct btf_verifier_env *env,
5101                               const struct btf_type *t,
5102                               u32 type_id)
5103 {
5104         struct btf *btf = env->btf;
5105
5106         if (!env_type_is_resolved(env, type_id))
5107                 return false;
5108
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);
5112
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);
5116
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);
5120                 return t &&
5121                        !btf_type_is_modifier(t) &&
5122                        !btf_type_is_var(t) &&
5123                        !btf_type_is_datasec(t);
5124         }
5125
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;
5130                 u32 elem_size;
5131
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));
5136         }
5137
5138         return false;
5139 }
5140
5141 static int btf_resolve(struct btf_verifier_env *env,
5142                        const struct btf_type *t, u32 type_id)
5143 {
5144         u32 save_log_type_id = env->log_type_id;
5145         const struct resolve_vertex *v;
5146         int err = 0;
5147
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);
5153         }
5154
5155         env->log_type_id = type_id;
5156         if (err == -E2BIG) {
5157                 btf_verifier_log_type(env, t,
5158                                       "Exceeded max resolving depth:%u",
5159                                       MAX_RESOLVE_DEPTH);
5160         } else if (err == -EEXIST) {
5161                 btf_verifier_log_type(env, t, "Loop detected");
5162         }
5163
5164         /* Final sanity check */
5165         if (!err && !btf_resolve_valid(env, t, type_id)) {
5166                 btf_verifier_log_type(env, t, "Invalid resolve state");
5167                 err = -EINVAL;
5168         }
5169
5170         env->log_type_id = save_log_type_id;
5171         return err;
5172 }
5173
5174 static int btf_check_all_types(struct btf_verifier_env *env)
5175 {
5176         struct btf *btf = env->btf;
5177         const struct btf_type *t;
5178         u32 type_id, i;
5179         int err;
5180
5181         err = env_resolve_init(env);
5182         if (err)
5183                 return err;
5184
5185         env->phase++;
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);
5189
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);
5194                         if (err)
5195                                 return err;
5196                 }
5197
5198                 if (btf_type_is_func_proto(t)) {
5199                         err = btf_func_proto_check(env, t);
5200                         if (err)
5201                                 return err;
5202                 }
5203         }
5204
5205         return 0;
5206 }
5207
5208 static int btf_parse_type_sec(struct btf_verifier_env *env)
5209 {
5210         const struct btf_header *hdr = &env->btf->hdr;
5211         int err;
5212
5213         /* Type section must align to 4 bytes */
5214         if (hdr->type_off & (sizeof(u32) - 1)) {
5215                 btf_verifier_log(env, "Unaligned type_off");
5216                 return -EINVAL;
5217         }
5218
5219         if (!env->btf->base_btf && !hdr->type_len) {
5220                 btf_verifier_log(env, "No type found");
5221                 return -EINVAL;
5222         }
5223
5224         err = btf_check_all_metas(env);
5225         if (err)
5226                 return err;
5227
5228         return btf_check_all_types(env);
5229 }
5230
5231 static int btf_parse_str_sec(struct btf_verifier_env *env)
5232 {
5233         const struct btf_header *hdr;
5234         struct btf *btf = env->btf;
5235         const char *start, *end;
5236
5237         hdr = &btf->hdr;
5238         start = btf->nohdr_data + hdr->str_off;
5239         end = start + hdr->str_len;
5240
5241         if (end != btf->data + btf->data_size) {
5242                 btf_verifier_log(env, "String section is not at the end");
5243                 return -EINVAL;
5244         }
5245
5246         btf->strings = start;
5247
5248         if (btf->base_btf && !hdr->str_len)
5249                 return 0;
5250         if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5251                 btf_verifier_log(env, "Invalid string section");
5252                 return -EINVAL;
5253         }
5254         if (!btf->base_btf && start[0]) {
5255                 btf_verifier_log(env, "Invalid string section");
5256                 return -EINVAL;
5257         }
5258
5259         return 0;
5260 }
5261
5262 static const size_t btf_sec_info_offset[] = {
5263         offsetof(struct btf_header, type_off),
5264         offsetof(struct btf_header, str_off),
5265 };
5266
5267 static int btf_sec_info_cmp(const void *a, const void *b)
5268 {
5269         const struct btf_sec_info *x = a;
5270         const struct btf_sec_info *y = b;
5271
5272         return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5273 }
5274
5275 static int btf_check_sec_info(struct btf_verifier_env *env,
5276                               u32 btf_data_size)
5277 {
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;
5282
5283         btf = env->btf;
5284         hdr = &btf->hdr;
5285
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]);
5290
5291         sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5292              sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5293
5294         /* Check for gaps and overlap among sections */
5295         total = 0;
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");
5300                         return -EINVAL;
5301                 }
5302                 if (total < secs[i].off) {
5303                         /* gap */
5304                         btf_verifier_log(env, "Unsupported section found");
5305                         return -EINVAL;
5306                 }
5307                 if (total > secs[i].off) {
5308                         btf_verifier_log(env, "Section overlap found");
5309                         return -EINVAL;
5310                 }
5311                 if (expected_total - total < secs[i].len) {
5312                         btf_verifier_log(env,
5313                                          "Total section length too long");
5314                         return -EINVAL;
5315                 }
5316                 total += secs[i].len;
5317         }
5318
5319         /* There is data other than hdr and known sections */
5320         if (expected_total != total) {
5321                 btf_verifier_log(env, "Unsupported section found");
5322                 return -EINVAL;
5323         }
5324
5325         return 0;
5326 }
5327
5328 static int btf_parse_hdr(struct btf_verifier_env *env)
5329 {
5330         u32 hdr_len, hdr_copy, btf_data_size;
5331         const struct btf_header *hdr;
5332         struct btf *btf;
5333
5334         btf = env->btf;
5335         btf_data_size = btf->data_size;
5336
5337         if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5338                 btf_verifier_log(env, "hdr_len not found");
5339                 return -EINVAL;
5340         }
5341
5342         hdr = btf->data;
5343         hdr_len = hdr->hdr_len;
5344         if (btf_data_size < hdr_len) {
5345                 btf_verifier_log(env, "btf_header not found");
5346                 return -EINVAL;
5347         }
5348
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;
5353
5354                 for (; expected_zero < end; expected_zero++) {
5355                         if (*expected_zero) {
5356                                 btf_verifier_log(env, "Unsupported btf_header");
5357                                 return -E2BIG;
5358                         }
5359                 }
5360         }
5361
5362         hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5363         memcpy(&btf->hdr, btf->data, hdr_copy);
5364
5365         hdr = &btf->hdr;
5366
5367         btf_verifier_log_hdr(env, btf_data_size);
5368
5369         if (hdr->magic != BTF_MAGIC) {
5370                 btf_verifier_log(env, "Invalid magic");
5371                 return -EINVAL;
5372         }
5373
5374         if (hdr->version != BTF_VERSION) {
5375                 btf_verifier_log(env, "Unsupported version");
5376                 return -ENOTSUPP;
5377         }
5378
5379         if (hdr->flags) {
5380                 btf_verifier_log(env, "Unsupported flags");
5381                 return -ENOTSUPP;
5382         }
5383
5384         if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5385                 btf_verifier_log(env, "No data");
5386                 return -EINVAL;
5387         }
5388
5389         return btf_check_sec_info(env, btf_data_size);
5390 }
5391
5392 static const char *alloc_obj_fields[] = {
5393         "bpf_spin_lock",
5394         "bpf_list_head",
5395         "bpf_list_node",
5396         "bpf_rb_root",
5397         "bpf_rb_node",
5398         "bpf_refcount",
5399 };
5400
5401 static struct btf_struct_metas *
5402 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5403 {
5404         union {
5405                 struct btf_id_set set;
5406                 struct {
5407                         u32 _cnt;
5408                         u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5409                 } _arr;
5410         } aof;
5411         struct btf_struct_metas *tab = NULL;
5412         int i, n, id, ret;
5413
5414         BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5415         BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5416
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.
5422                  */
5423                 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5424                 if (id < 0)
5425                         continue;
5426                 aof.set.ids[aof.set.cnt++] = id;
5427         }
5428
5429         if (!aof.set.cnt)
5430                 return NULL;
5431         sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5432
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;
5440                 int j, tab_cnt;
5441
5442                 t = btf_type_by_id(btf, i);
5443                 if (!t) {
5444                         ret = -EINVAL;
5445                         goto free;
5446                 }
5447                 if (!__btf_type_is_struct(t))
5448                         continue;
5449
5450                 cond_resched();
5451
5452                 for_each_member(j, t, member) {
5453                         if (btf_id_set_contains(&aof.set, member->type))
5454                                 goto parse;
5455                 }
5456                 continue;
5457         parse:
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);
5461                 if (!new_tab) {
5462                         ret = -ENOMEM;
5463                         goto free;
5464                 }
5465                 if (!tab)
5466                         new_tab->cnt = 0;
5467                 tab = new_tab;
5468
5469                 type = &tab->types[tab->cnt];
5470                 type->btf_id = i;
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;
5476                         goto free;
5477                 }
5478                 type->record = record;
5479                 tab->cnt++;
5480         }
5481         return tab;
5482 free:
5483         btf_struct_metas_free(tab);
5484         return ERR_PTR(ret);
5485 }
5486
5487 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5488 {
5489         struct btf_struct_metas *tab;
5490
5491         BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5492         tab = btf->struct_meta_tab;
5493         if (!tab)
5494                 return NULL;
5495         return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5496 }
5497
5498 static int btf_check_type_tags(struct btf_verifier_env *env,
5499                                struct btf *btf, int start_id)
5500 {
5501         int i, n, good_id = start_id - 1;
5502         bool in_tags;
5503
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;
5508                 u32 cur_id = i;
5509
5510                 t = btf_type_by_id(btf, i);
5511                 if (!t)
5512                         return -EINVAL;
5513                 if (!btf_type_is_modifier(t))
5514                         continue;
5515
5516                 cond_resched();
5517
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");
5522                                 return -ELOOP;
5523                         }
5524                         if (btf_type_is_type_tag(t)) {
5525                                 if (!in_tags) {
5526                                         btf_verifier_log(env, "Type tags don't precede modifiers");
5527                                         return -EINVAL;
5528                                 }
5529                         } else if (in_tags) {
5530                                 in_tags = false;
5531                         }
5532                         if (cur_id <= good_id)
5533                                 break;
5534                         /* Move to next type */
5535                         cur_id = t->type;
5536                         t = btf_type_by_id(btf, cur_id);
5537                         if (!t)
5538                                 return -EINVAL;
5539                 }
5540                 good_id = i;
5541         }
5542         return 0;
5543 }
5544
5545 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5546 {
5547         u32 log_true_size;
5548         int err;
5549
5550         err = bpf_vlog_finalize(log, &log_true_size);
5551
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)))
5555                 err = -EFAULT;
5556
5557         return err;
5558 }
5559
5560 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5561 {
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;
5567         u8 *data;
5568         int err, ret;
5569
5570         if (attr->btf_size > BTF_MAX_SIZE)
5571                 return ERR_PTR(-E2BIG);
5572
5573         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5574         if (!env)
5575                 return ERR_PTR(-ENOMEM);
5576
5577         /* user could have requested verbose verifier output
5578          * and supplied buffer to store the verification trace
5579          */
5580         err = bpf_vlog_init(&env->log, attr->btf_log_level,
5581                             log_ubuf, attr->btf_log_size);
5582         if (err)
5583                 goto errout_free;
5584
5585         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5586         if (!btf) {
5587                 err = -ENOMEM;
5588                 goto errout;
5589         }
5590         env->btf = btf;
5591
5592         data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5593         if (!data) {
5594                 err = -ENOMEM;
5595                 goto errout;
5596         }
5597
5598         btf->data = data;
5599         btf->data_size = attr->btf_size;
5600
5601         if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5602                 err = -EFAULT;
5603                 goto errout;
5604         }
5605
5606         err = btf_parse_hdr(env);
5607         if (err)
5608                 goto errout;
5609
5610         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5611
5612         err = btf_parse_str_sec(env);
5613         if (err)
5614                 goto errout;
5615
5616         err = btf_parse_type_sec(env);
5617         if (err)
5618                 goto errout;
5619
5620         err = btf_check_type_tags(env, btf, 1);
5621         if (err)
5622                 goto errout;
5623
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);
5627                 goto errout;
5628         }
5629         btf->struct_meta_tab = struct_meta_tab;
5630
5631         if (struct_meta_tab) {
5632                 int i;
5633
5634                 for (i = 0; i < struct_meta_tab->cnt; i++) {
5635                         err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5636                         if (err < 0)
5637                                 goto errout_meta;
5638                 }
5639         }
5640
5641         err = finalize_log(&env->log, uattr, uattr_size);
5642         if (err)
5643                 goto errout_free;
5644
5645         btf_verifier_env_free(env);
5646         refcount_set(&btf->refcnt, 1);
5647         return btf;
5648
5649 errout_meta:
5650         btf_free_struct_meta_tab(btf);
5651 errout:
5652         /* overwrite err with -ENOSPC or -EFAULT */
5653         ret = finalize_log(&env->log, uattr, uattr_size);
5654         if (ret)
5655                 err = ret;
5656 errout_free:
5657         btf_verifier_env_free(env);
5658         if (btf)
5659                 btf_free(btf);
5660         return ERR_PTR(err);
5661 }
5662
5663 extern char __start_BTF[];
5664 extern char __stop_BTF[];
5665 extern struct btf *btf_vmlinux;
5666
5667 #define BPF_MAP_TYPE(_id, _ops)
5668 #define BPF_LINK_TYPE(_id, _name)
5669 static union {
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
5676         } *__t;
5677         /* 't' is written once under lock. Read many times. */
5678         const struct btf_type *t;
5679 } bpf_ctx_convert;
5680 enum {
5681 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5682         __ctx_convert##_id,
5683 #include <linux/bpf_types.h>
5684 #undef BPF_PROG_TYPE
5685         __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5686 };
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 */
5693 };
5694 #undef BPF_MAP_TYPE
5695 #undef BPF_LINK_TYPE
5696
5697 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
5698 {
5699         const struct btf_type *conv_struct;
5700         const struct btf_member *ctx_type;
5701
5702         conv_struct = bpf_ctx_convert.t;
5703         if (!conv_struct)
5704                 return NULL;
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'
5709          */
5710         return btf_type_by_id(btf_vmlinux, ctx_type->type);
5711 }
5712
5713 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
5714 {
5715         const struct btf_type *conv_struct;
5716         const struct btf_member *ctx_type;
5717
5718         conv_struct = bpf_ctx_convert.t;
5719         if (!conv_struct)
5720                 return -EFAULT;
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'
5725          */
5726         return ctx_type->type;
5727 }
5728
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,
5731                           int arg)
5732 {
5733         const struct btf_type *ctx_type;
5734         const char *tname, *ctx_tname;
5735
5736         t = btf_type_by_id(btf, t->type);
5737
5738         /* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
5739          * check before we skip all the typedef below.
5740          */
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);
5744
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)
5748                                 return true;
5749                 }
5750         }
5751
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.
5759                  */
5760                 return false;
5761         }
5762         tname = btf_name_by_offset(btf, t->name_off);
5763         if (!tname) {
5764                 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5765                 return false;
5766         }
5767
5768         ctx_type = find_canonical_prog_ctx_type(prog_type);
5769         if (!ctx_type) {
5770                 bpf_log(log, "btf_vmlinux is malformed\n");
5771                 /* should not happen */
5772                 return false;
5773         }
5774 again:
5775         ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5776         if (!ctx_tname) {
5777                 /* should not happen */
5778                 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5779                 return false;
5780         }
5781         /* program types without named context types work only with arg:ctx tag */
5782         if (ctx_tname[0] == '\0')
5783                 return false;
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 }
5790          */
5791         if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5792                 return true;
5793         if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5794                 return true;
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
5798                  */
5799                 if (!btf_type_is_modifier(ctx_type))
5800                         return false;
5801                 while (btf_type_is_modifier(ctx_type))
5802                         ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
5803                 goto again;
5804         }
5805         return true;
5806 }
5807
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
5812  * architectures
5813  */
5814 struct user_regs_struct;
5815 struct user_pt_regs;
5816
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)
5821 {
5822         const struct btf_type *ctx_type;
5823         const char *tname, *ctx_tname;
5824
5825         if (!btf_is_ptr(t)) {
5826                 bpf_log(log, "arg#%d type isn't a pointer\n", arg);
5827                 return -EINVAL;
5828         }
5829         t = btf_type_by_id(btf, t->type);
5830
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);
5835
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)
5839                                 return 0;
5840                 }
5841         }
5842
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);
5846
5847         /* `void *ctx __arg_ctx` is always valid */
5848         if (btf_type_is_void(t))
5849                 return 0;
5850
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);
5854                 return -EINVAL;
5855         }
5856
5857         /* special cases */
5858         switch (prog_type) {
5859         case BPF_PROG_TYPE_KPROBE:
5860                 if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5861                         return 0;
5862                 break;
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)
5866                         return 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)
5869                         return 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)
5872                         return 0;
5873                 break;
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)
5878                         return 0;
5879                 break;
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)
5886                                 return 0;
5887                         /* allow u64* as ctx */
5888                         if (btf_is_int(t) && t->size == 8)
5889                                 return 0;
5890                         break;
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)
5895                                 return 0;
5896                         break;
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)
5902                                 return 0;
5903                         break;
5904                 default:
5905                         break;
5906                 }
5907                 break;
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)
5912                         return 0;
5913                 break;
5914         case BPF_PROG_TYPE_TRACEPOINT:
5915         case BPF_PROG_TYPE_SYSCALL:
5916         case BPF_PROG_TYPE_EXT:
5917                 return 0; /* anything goes */
5918         default:
5919                 break;
5920         }
5921
5922         ctx_type = find_canonical_prog_ctx_type(prog_type);
5923         if (!ctx_type) {
5924                 /* should not happen */
5925                 bpf_log(log, "btf_vmlinux is malformed\n");
5926                 return -EINVAL;
5927         }
5928
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);
5932
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
5936          */
5937         if (!__btf_type_is_struct(ctx_type)) {
5938                 bpf_log(log, "arg#%d should be void pointer\n", arg);
5939                 return -EINVAL;
5940         }
5941
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);
5945                 return -EINVAL;
5946         }
5947
5948         return 0;
5949 }
5950
5951 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5952                                      struct btf *btf,
5953                                      const struct btf_type *t,
5954                                      enum bpf_prog_type prog_type,
5955                                      int arg)
5956 {
5957         if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
5958                 return -ENOENT;
5959         return find_kern_ctx_type_id(prog_type);
5960 }
5961
5962 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5963 {
5964         const struct btf_member *kctx_member;
5965         const struct btf_type *conv_struct;
5966         const struct btf_type *kctx_type;
5967         u32 kctx_type_id;
5968
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);
5976                 return -EINVAL;
5977         }
5978
5979         return kctx_type_id;
5980 }
5981
5982 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5983 BTF_ID(struct, bpf_ctx_convert)
5984
5985 struct btf *btf_parse_vmlinux(void)
5986 {
5987         struct btf_verifier_env *env = NULL;
5988         struct bpf_verifier_log *log;
5989         struct btf *btf = NULL;
5990         int err;
5991
5992         if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
5993                 return ERR_PTR(-ENOENT);
5994
5995         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5996         if (!env)
5997                 return ERR_PTR(-ENOMEM);
5998
5999         log = &env->log;
6000         log->level = BPF_LOG_KERNEL;
6001
6002         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6003         if (!btf) {
6004                 err = -ENOMEM;
6005                 goto errout;
6006         }
6007         env->btf = btf;
6008
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");
6013
6014         err = btf_parse_hdr(env);
6015         if (err)
6016                 goto errout;
6017
6018         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6019
6020         err = btf_parse_str_sec(env);
6021         if (err)
6022                 goto errout;
6023
6024         err = btf_check_all_metas(env);
6025         if (err)
6026                 goto errout;
6027
6028         err = btf_check_type_tags(env, btf, 1);
6029         if (err)
6030                 goto errout;
6031
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]);
6034
6035         refcount_set(&btf->refcnt, 1);
6036
6037         err = btf_alloc_id(btf);
6038         if (err)
6039                 goto errout;
6040
6041         btf_verifier_env_free(env);
6042         return btf;
6043
6044 errout:
6045         btf_verifier_env_free(env);
6046         if (btf) {
6047                 kvfree(btf->types);
6048                 kfree(btf);
6049         }
6050         return ERR_PTR(err);
6051 }
6052
6053 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6054
6055 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
6056 {
6057         struct btf_verifier_env *env = NULL;
6058         struct bpf_verifier_log *log;
6059         struct btf *btf = NULL, *base_btf;
6060         int err;
6061
6062         base_btf = bpf_get_btf_vmlinux();
6063         if (IS_ERR(base_btf))
6064                 return base_btf;
6065         if (!base_btf)
6066                 return ERR_PTR(-EINVAL);
6067
6068         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6069         if (!env)
6070                 return ERR_PTR(-ENOMEM);
6071
6072         log = &env->log;
6073         log->level = BPF_LOG_KERNEL;
6074
6075         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6076         if (!btf) {
6077                 err = -ENOMEM;
6078                 goto errout;
6079         }
6080         env->btf = btf;
6081
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);
6087
6088         btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
6089         if (!btf->data) {
6090                 err = -ENOMEM;
6091                 goto errout;
6092         }
6093         memcpy(btf->data, data, data_size);
6094         btf->data_size = data_size;
6095
6096         err = btf_parse_hdr(env);
6097         if (err)
6098                 goto errout;
6099
6100         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6101
6102         err = btf_parse_str_sec(env);
6103         if (err)
6104                 goto errout;
6105
6106         err = btf_check_all_metas(env);
6107         if (err)
6108                 goto errout;
6109
6110         err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6111         if (err)
6112                 goto errout;
6113
6114         btf_verifier_env_free(env);
6115         refcount_set(&btf->refcnt, 1);
6116         return btf;
6117
6118 errout:
6119         btf_verifier_env_free(env);
6120         if (btf) {
6121                 kvfree(btf->data);
6122                 kvfree(btf->types);
6123                 kfree(btf);
6124         }
6125         return ERR_PTR(err);
6126 }
6127
6128 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6129
6130 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6131 {
6132         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6133
6134         if (tgt_prog)
6135                 return tgt_prog->aux->btf;
6136         else
6137                 return prog->aux->attach_btf;
6138 }
6139
6140 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
6141 {
6142         /* skip modifiers */
6143         t = btf_type_skip_modifiers(btf, t->type, NULL);
6144
6145         return btf_type_is_int(t);
6146 }
6147
6148 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6149                            int off)
6150 {
6151         const struct btf_param *args;
6152         const struct btf_type *t;
6153         u32 offset = 0, nr_args;
6154         int i;
6155
6156         if (!func_proto)
6157                 return off / 8;
6158
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);
6164                 if (off < offset)
6165                         return i;
6166         }
6167
6168         t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6169         offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6170         if (off < offset)
6171                 return nr_args;
6172
6173         return nr_args + 1;
6174 }
6175
6176 static bool prog_args_trusted(const struct bpf_prog *prog)
6177 {
6178         enum bpf_attach_type atype = prog->expected_attach_type;
6179
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:
6186                 return true;
6187         default:
6188                 return false;
6189         }
6190 }
6191
6192 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6193                        u32 arg_no)
6194 {
6195         const struct btf_param *args;
6196         const struct btf_type *t;
6197         int off = 0, i;
6198         u32 sz;
6199
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);
6204                 if (IS_ERR(t))
6205                         return PTR_ERR(t);
6206                 off += roundup(sz, 8);
6207         }
6208
6209         return off;
6210 }
6211
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)
6215 {
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;
6223         u32 nr_args, arg;
6224         int i, ret;
6225
6226         if (off % 8) {
6227                 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6228                         tname, off);
6229                 return false;
6230         }
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.
6235          */
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 */
6239                 args++;
6240                 nr_args--;
6241         }
6242
6243         if (arg > nr_args) {
6244                 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6245                         tname, arg + 1);
6246                 return false;
6247         }
6248
6249         if (arg == nr_args) {
6250                 switch (prog->expected_attach_type) {
6251                 case BPF_LSM_CGROUP:
6252                 case BPF_LSM_MAC:
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.
6257                          *
6258                          * While the LSM programs are BPF_MODIFY_RETURN-like
6259                          * the check:
6260                          *
6261                          *      if (ret_type != 'int')
6262                          *              return -EINVAL;
6263                          *
6264                          * is _not_ done here. This is still safe as LSM hooks
6265                          * have only void and int return types.
6266                          */
6267                         if (!t)
6268                                 return true;
6269                         t = btf_type_by_id(btf, t->type);
6270                         break;
6271                 case BPF_MODIFY_RETURN:
6272                         /* For now the BPF_MODIFY_RETURN can only be attached to
6273                          * functions that return an int.
6274                          */
6275                         if (!t)
6276                                 return false;
6277
6278                         t = btf_type_skip_modifiers(btf, t->type, NULL);
6279                         if (!btf_type_is_small_int(t)) {
6280                                 bpf_log(log,
6281                                         "ret type %s not allowed for fmod_ret\n",
6282                                         btf_type_str(t));
6283                                 return false;
6284                         }
6285                         break;
6286                 default:
6287                         bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6288                                 tname, arg + 1);
6289                         return false;
6290                 }
6291         } else {
6292                 if (!t)
6293                         /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6294                         return true;
6295                 t = btf_type_by_id(btf, args[arg].type);
6296         }
6297
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 */
6303                 return true;
6304         if (!btf_type_is_ptr(t)) {
6305                 bpf_log(log,
6306                         "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6307                         tname, arg,
6308                         __btf_name_by_offset(btf, t->name_off),
6309                         btf_type_str(t));
6310                 return false;
6311         }
6312
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];
6316                 u32 type, flag;
6317
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;
6323                         return true;
6324                 }
6325         }
6326
6327         if (t->type == 0)
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.
6331                  */
6332                 return true;
6333
6334         if (is_int_ptr(btf, t))
6335                 return true;
6336
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];
6340
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);
6344                                 return false;
6345                         }
6346
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;
6350                         return true;
6351                 }
6352         }
6353
6354         info->reg_type = PTR_TO_BTF_ID;
6355         if (prog_args_trusted(prog))
6356                 info->reg_type |= PTR_TRUSTED;
6357
6358         if (tgt_prog) {
6359                 enum bpf_prog_type tgt_type;
6360
6361                 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6362                         tgt_type = tgt_prog->aux->saved_dst_prog_type;
6363                 else
6364                         tgt_type = tgt_prog->type;
6365
6366                 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6367                 if (ret > 0) {
6368                         info->btf = btf_vmlinux;
6369                         info->btf_id = ret;
6370                         return true;
6371                 } else {
6372                         return false;
6373                 }
6374         }
6375
6376         info->btf = btf;
6377         info->btf_id = t->type;
6378         t = btf_type_by_id(btf, t->type);
6379
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;
6386         }
6387
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);
6392         }
6393         if (!btf_type_is_struct(t)) {
6394                 bpf_log(log,
6395                         "func '%s' arg%d type %s is not a struct\n",
6396                         tname, arg, btf_type_str(t));
6397                 return false;
6398         }
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));
6402         return true;
6403 }
6404 EXPORT_SYMBOL_GPL(btf_ctx_access);
6405
6406 enum bpf_struct_walk_result {
6407         /* < 0 error */
6408         WALK_SCALAR = 0,
6409         WALK_PTR,
6410         WALK_STRUCT,
6411 };
6412
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)
6417 {
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;
6423
6424 again:
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);
6430                 return -EINVAL;
6431         }
6432
6433         vlen = btf_type_vlen(t);
6434         if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
6435                 /*
6436                  * walking unions yields untrusted pointers
6437                  * with exception of __bpf_md_ptr and other
6438                  * unions with a single member
6439                  */
6440                 *flag |= PTR_UNTRUSTED;
6441
6442         if (off + size > t->size) {
6443                 /* If the last element is a variable size array, we may
6444                  * need to relax the rule.
6445                  */
6446                 struct btf_array *array_elem;
6447
6448                 if (vlen == 0)
6449                         goto error;
6450
6451                 member = btf_type_member(t) + vlen - 1;
6452                 mtype = btf_type_skip_modifiers(btf, member->type,
6453                                                 NULL);
6454                 if (!btf_type_is_array(mtype))
6455                         goto error;
6456
6457                 array_elem = (struct btf_array *)(mtype + 1);
6458                 if (array_elem->nelems != 0)
6459                         goto error;
6460
6461                 moff = __btf_member_bit_offset(t, member) / 8;
6462                 if (off < moff)
6463                         goto error;
6464
6465                 /* allow structure and integer */
6466                 t = btf_type_skip_modifiers(btf, array_elem->type,
6467                                             NULL);
6468
6469                 if (btf_type_is_int(t))
6470                         return WALK_SCALAR;
6471
6472                 if (!btf_type_is_struct(t))
6473                         goto error;
6474
6475                 off = (off - moff) % t->size;
6476                 goto again;
6477
6478 error:
6479                 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6480                         tname, off, size);
6481                 return -EACCES;
6482         }
6483
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 */
6489                         break;
6490
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);
6494
6495                         /* off <= moff instead of off == moff because clang
6496                          * does not generate a BTF member for anonymous
6497                          * bitfield like the ":16" here:
6498                          * struct {
6499                          *      int :16;
6500                          *      int x:8;
6501                          * };
6502                          */
6503                         if (off <= moff &&
6504                             BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6505                                 return WALK_SCALAR;
6506
6507                         /* off may be accessing a following member
6508                          *
6509                          * or
6510                          *
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.
6518                          */
6519                         continue;
6520                 }
6521
6522                 /* In case of "off" is pointing to holes of a struct */
6523                 if (off < moff)
6524                         break;
6525
6526                 /* type of the field */
6527                 mid = member->type;
6528                 mtype = btf_type_by_id(btf, member->type);
6529                 mname = __btf_name_by_offset(btf, member->name_off);
6530
6531                 mtype = __btf_resolve_size(btf, mtype, &msize,
6532                                            &elem_type, &elem_id, &total_nelems,
6533                                            &mid);
6534                 if (IS_ERR(mtype)) {
6535                         bpf_log(log, "field %s doesn't have size\n", mname);
6536                         return -EFAULT;
6537                 }
6538
6539                 mtrue_end = moff + msize;
6540                 if (off >= mtrue_end)
6541                         /* no overlap with member, keep iterating */
6542                         continue;
6543
6544                 if (btf_type_is_array(mtype)) {
6545                         u32 elem_idx;
6546
6547                         /* __btf_resolve_size() above helps to
6548                          * linearize a multi-dimensional array.
6549                          *
6550                          * The logic here is treating an array
6551                          * in a struct as the following way:
6552                          *
6553                          * struct outer {
6554                          *      struct inner array[2][2];
6555                          * };
6556                          *
6557                          * looks like:
6558                          *
6559                          * struct outer {
6560                          *      struct inner array_elem0;
6561                          *      struct inner array_elem1;
6562                          *      struct inner array_elem2;
6563                          *      struct inner array_elem3;
6564                          * };
6565                          *
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
6572                          * not.
6573                          *
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
6581                          * a scratch space,
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.
6585                          */
6586
6587                         /* skip empty array */
6588                         if (moff == mtrue_end)
6589                                 continue;
6590
6591                         msize /= total_nelems;
6592                         elem_idx = (off - moff) / msize;
6593                         moff += elem_idx * msize;
6594                         mtype = elem_type;
6595                         mid = elem_id;
6596                 }
6597
6598                 /* the 'off' we're looking for is either equal to start
6599                  * of this field or inside of this struct
6600                  */
6601                 if (btf_type_is_struct(mtype)) {
6602                         /* our field must be inside that union or struct */
6603                         t = mtype;
6604
6605                         /* return if the offset matches the member offset */
6606                         if (off == moff) {
6607                                 *next_btf_id = mid;
6608                                 return WALK_STRUCT;
6609                         }
6610
6611                         /* adjust offset we're looking for */
6612                         off -= moff;
6613                         goto again;
6614                 }
6615
6616                 if (btf_type_is_ptr(mtype)) {
6617                         const struct btf_type *stype, *t;
6618                         enum bpf_type_flag tmp_flag = 0;
6619                         u32 id;
6620
6621                         if (msize != size || off != moff) {
6622                                 bpf_log(log,
6623                                         "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6624                                         mname, moff, tname, off, size);
6625                                 return -EACCES;
6626                         }
6627
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)
6640                                         tmp_flag = MEM_RCU;
6641                         }
6642
6643                         stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6644                         if (btf_type_is_struct(stype)) {
6645                                 *next_btf_id = id;
6646                                 *flag |= tmp_flag;
6647                                 if (field_name)
6648                                         *field_name = mname;
6649                                 return WALK_PTR;
6650                         }
6651                 }
6652
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[].
6658                  */
6659                 if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
6660                         bpf_log(log,
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);
6663                         return -EACCES;
6664                 }
6665
6666                 return WALK_SCALAR;
6667         }
6668         bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6669         return -EINVAL;
6670 }
6671
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)
6677 {
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;
6682         int err;
6683
6684         while (type_is_alloc(reg->type)) {
6685                 struct btf_struct_meta *meta;
6686                 struct btf_record *rec;
6687                 int i;
6688
6689                 meta = btf_find_struct_meta(btf, id);
6690                 if (!meta)
6691                         break;
6692                 rec = meta->record;
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) {
6697                                 bpf_log(log,
6698                                         "direct access to %s is disallowed\n",
6699                                         btf_field_type_name(field->type));
6700                                 return -EACCES;
6701                         }
6702                 }
6703                 break;
6704         }
6705
6706         t = btf_type_by_id(btf, id);
6707         do {
6708                 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6709
6710                 switch (err) {
6711                 case WALK_PTR:
6712                         /* For local types, the destination register cannot
6713                          * become a pointer again.
6714                          */
6715                         if (type_is_alloc(reg->type))
6716                                 return SCALAR_VALUE;
6717                         /* If we found the pointer or scalar on t+off,
6718                          * we're done.
6719                          */
6720                         *next_btf_id = id;
6721                         *flag = tmp_flag;
6722                         return PTR_TO_BTF_ID;
6723                 case WALK_SCALAR:
6724                         return SCALAR_VALUE;
6725                 case WALK_STRUCT:
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.
6729                          */
6730                         t = btf_type_by_id(btf, id);
6731                         off = 0;
6732                         break;
6733                 default:
6734                         /* It's either error or unknown return value..
6735                          * scream and leave.
6736                          */
6737                         if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6738                                 return -EINVAL;
6739                         return err;
6740                 }
6741         } while (t);
6742
6743         return -EINVAL;
6744 }
6745
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
6749  * vmlinux BTF.
6750  */
6751 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6752                         const struct btf *btf2, u32 id2)
6753 {
6754         if (id1 != id2)
6755                 return false;
6756         if (btf1 == btf2)
6757                 return true;
6758         return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6759 }
6760
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,
6764                           bool strict)
6765 {
6766         const struct btf_type *type;
6767         enum bpf_type_flag flag = 0;
6768         int err;
6769
6770         /* Are we already done? */
6771         if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6772                 return true;
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
6775          * been 0.
6776          */
6777         if (strict)
6778                 return false;
6779 again:
6780         type = btf_type_by_id(btf, id);
6781         if (!type)
6782                 return false;
6783         err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6784         if (err != WALK_STRUCT)
6785                 return false;
6786
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
6790          * type.
6791          */
6792         if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6793                 off = 0;
6794                 goto again;
6795         }
6796
6797         return true;
6798 }
6799
6800 static int __get_type_size(struct btf *btf, u32 btf_id,
6801                            const struct btf_type **ret_type)
6802 {
6803         const struct btf_type *t;
6804
6805         *ret_type = btf_type_by_id(btf, 0);
6806         if (!btf_id)
6807                 /* void */
6808                 return 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);
6812         if (!t)
6813                 return -EINVAL;
6814         *ret_type = t;
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))
6819                 return t->size;
6820         return -EINVAL;
6821 }
6822
6823 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6824 {
6825         u8 flags = 0;
6826
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;
6831
6832         return flags;
6833 }
6834
6835 int btf_distill_func_proto(struct bpf_verifier_log *log,
6836                            struct btf *btf,
6837                            const struct btf_type *func,
6838                            const char *tname,
6839                            struct btf_func_model *m)
6840 {
6841         const struct btf_param *args;
6842         const struct btf_type *t;
6843         u32 i, nargs;
6844         int ret;
6845
6846         if (!func) {
6847                 /* BTF function prototype doesn't match the verifier types.
6848                  * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6849                  */
6850                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6851                         m->arg_size[i] = 8;
6852                         m->arg_flags[i] = 0;
6853                 }
6854                 m->ret_size = 8;
6855                 m->ret_flags = 0;
6856                 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6857                 return 0;
6858         }
6859         args = (const struct btf_param *)(func + 1);
6860         nargs = btf_type_vlen(func);
6861         if (nargs > MAX_BPF_FUNC_ARGS) {
6862                 bpf_log(log,
6863                         "The function %s has %d arguments. Too many.\n",
6864                         tname, nargs);
6865                 return -EINVAL;
6866         }
6867         ret = __get_type_size(btf, func->type, &t);
6868         if (ret < 0 || __btf_type_is_struct(t)) {
6869                 bpf_log(log,
6870                         "The function %s return type %s is unsupported.\n",
6871                         tname, btf_type_str(t));
6872                 return -EINVAL;
6873         }
6874         m->ret_size = ret;
6875         m->ret_flags = __get_type_fmodel_flags(t);
6876
6877         for (i = 0; i < nargs; i++) {
6878                 if (i == nargs - 1 && args[i].type == 0) {
6879                         bpf_log(log,
6880                                 "The function %s with variable args is unsupported.\n",
6881                                 tname);
6882                         return -EINVAL;
6883                 }
6884                 ret = __get_type_size(btf, args[i].type, &t);
6885
6886                 /* No support of struct argument size greater than 16 bytes */
6887                 if (ret < 0 || ret > 16) {
6888                         bpf_log(log,
6889                                 "The function %s arg%d type %s is unsupported.\n",
6890                                 tname, i, btf_type_str(t));
6891                         return -EINVAL;
6892                 }
6893                 if (ret == 0) {
6894                         bpf_log(log,
6895                                 "The function %s has malformed void argument.\n",
6896                                 tname);
6897                         return -EINVAL;
6898                 }
6899                 m->arg_size[i] = ret;
6900                 m->arg_flags[i] = __get_type_fmodel_flags(t);
6901         }
6902         m->nr_args = nargs;
6903         return 0;
6904 }
6905
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
6909  * Returns:
6910  * EINVAL - function prototype mismatch
6911  * EFAULT - verifier bug
6912  * 0 - 99% match. The last 1% is validated by the verifier.
6913  */
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)
6917 {
6918         const struct btf_param *args1, *args2;
6919         const char *fn1, *fn2, *s1, *s2;
6920         u32 nargs1, nargs2, i;
6921
6922         fn1 = btf_name_by_offset(btf1, t1->name_off);
6923         fn2 = btf_name_by_offset(btf2, t2->name_off);
6924
6925         if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6926                 bpf_log(log, "%s() is not a global function\n", fn1);
6927                 return -EINVAL;
6928         }
6929         if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6930                 bpf_log(log, "%s() is not a global function\n", fn2);
6931                 return -EINVAL;
6932         }
6933
6934         t1 = btf_type_by_id(btf1, t1->type);
6935         if (!t1 || !btf_type_is_func_proto(t1))
6936                 return -EFAULT;
6937         t2 = btf_type_by_id(btf2, t2->type);
6938         if (!t2 || !btf_type_is_func_proto(t2))
6939                 return -EFAULT;
6940
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);
6945
6946         if (nargs1 != nargs2) {
6947                 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6948                         fn1, nargs1, fn2, nargs2);
6949                 return -EINVAL;
6950         }
6951
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) {
6955                 bpf_log(log,
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);
6959                 return -EINVAL;
6960         }
6961
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);
6965
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));
6970                         return -EINVAL;
6971                 }
6972                 if (btf_type_has_size(t1) && t1->size != t2->size) {
6973                         bpf_log(log,
6974                                 "arg%d in %s() has size %d while %s() has %d\n",
6975                                 i, fn1, t1->size,
6976                                 fn2, t2->size);
6977                         return -EINVAL;
6978                 }
6979
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.
6983                  */
6984                 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6985                         continue;
6986                 if (!btf_type_is_ptr(t1)) {
6987                         bpf_log(log,
6988                                 "arg%d in %s() has unrecognized type\n",
6989                                 i, fn1);
6990                         return -EINVAL;
6991                 }
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)) {
6995                         bpf_log(log,
6996                                 "arg%d in %s() is not a pointer to context\n",
6997                                 i, fn1);
6998                         return -EINVAL;
6999                 }
7000                 if (!btf_type_is_struct(t2)) {
7001                         bpf_log(log,
7002                                 "arg%d in %s() is not a pointer to context\n",
7003                                 i, fn2);
7004                         return -EINVAL;
7005                 }
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.
7011                  */
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)) {
7015                         bpf_log(log,
7016                                 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7017                                 i, fn1, s1, fn2, s2);
7018                         return -EINVAL;
7019                 }
7020         }
7021         return 0;
7022 }
7023
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)
7027 {
7028         struct btf *btf1 = prog->aux->btf;
7029         const struct btf_type *t1;
7030         u32 btf_id = 0;
7031
7032         if (!prog->aux->func_info) {
7033                 bpf_log(log, "Program extension requires BTF\n");
7034                 return -EINVAL;
7035         }
7036
7037         btf_id = prog->aux->func_info[0].type_id;
7038         if (!btf_id)
7039                 return -EFAULT;
7040
7041         t1 = btf_type_by_id(btf1, btf_id);
7042         if (!t1 || !btf_type_is_func(t1))
7043                 return -EFAULT;
7044
7045         return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7046 }
7047
7048 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7049 {
7050         const char *name;
7051
7052         t = btf_type_by_id(btf, t->type); /* skip PTR */
7053
7054         while (btf_type_is_modifier(t))
7055                 t = btf_type_by_id(btf, t->type);
7056
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;
7062         }
7063
7064         return false;
7065 }
7066
7067 struct bpf_cand_cache {
7068         const char *name;
7069         u32 name_len;
7070         u16 kind;
7071         u16 cnt;
7072         struct {
7073                 const struct btf *btf;
7074                 u32 id;
7075         } cands[];
7076 };
7077
7078 static DEFINE_MUTEX(cand_cache_mutex);
7079
7080 static struct bpf_cand_cache *
7081 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7082
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)
7085 {
7086         struct bpf_cand_cache *cc;
7087         struct bpf_core_ctx ctx = {
7088                 .btf = btf,
7089                 .log = log,
7090         };
7091         u32 kern_type_id, type_id;
7092         int err = 0;
7093
7094         /* skip PTR and modifiers */
7095         type_id = t->type;
7096         t = btf_type_by_id(btf, t->type);
7097         while (btf_type_is_modifier(t)) {
7098                 type_id = t->type;
7099                 t = btf_type_by_id(btf, t->type);
7100         }
7101
7102         mutex_lock(&cand_cache_mutex);
7103         cc = bpf_core_find_cands(&ctx, type_id);
7104         if (IS_ERR(cc)) {
7105                 err = PTR_ERR(cc);
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),
7108                         err);
7109                 goto cand_cache_unlock;
7110         }
7111         if (cc->cnt != 1) {
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;
7117         }
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));
7121                 err = -EOPNOTSUPP;
7122                 goto cand_cache_unlock;
7123         }
7124         kern_type_id = cc->cands[0].id;
7125
7126 cand_cache_unlock:
7127         mutex_unlock(&cand_cache_mutex);
7128         if (err)
7129                 return err;
7130
7131         return kern_type_id;
7132 }
7133
7134 enum btf_arg_tag {
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),
7140 };
7141
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.
7145  * Returns:
7146  * EFAULT - there is a verifier bug. Abort verification.
7147  * EINVAL - cannot convert BTF.
7148  * 0 - Successfully processed BTF and constructed argument expectations.
7149  */
7150 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7151 {
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;
7161         const char *tname;
7162
7163         if (sub->args_cached)
7164                 return 0;
7165
7166         if (!prog->aux->func_info) {
7167                 bpf_log(log, "Verifier bug\n");
7168                 return -EFAULT;
7169         }
7170
7171         btf_id = prog->aux->func_info[subprog].type_id;
7172         if (!btf_id) {
7173                 if (!is_global) /* not fatal for static funcs */
7174                         return -EINVAL;
7175                 bpf_log(log, "Global functions need valid BTF\n");
7176                 return -EFAULT;
7177         }
7178
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
7183                  */
7184                 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7185                         subprog);
7186                 return -EFAULT;
7187         }
7188         tname = btf_name_by_offset(btf, fn_t->name_off);
7189
7190         if (prog->aux->func_info_aux[subprog].unreliable) {
7191                 bpf_log(log, "Verifier bug in function %s()\n", tname);
7192                 return -EFAULT;
7193         }
7194         if (prog_type == BPF_PROG_TYPE_EXT)
7195                 prog_type = prog->aux->dst_prog->type;
7196
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);
7200                 return -EFAULT;
7201         }
7202         args = (const struct btf_param *)(t + 1);
7203         nargs = btf_type_vlen(t);
7204         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7205                 if (!is_global)
7206                         return -EINVAL;
7207                 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7208                         tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7209                 return -EINVAL;
7210         }
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)) {
7216                 if (!is_global)
7217                         return -EINVAL;
7218                 bpf_log(log,
7219                         "Global function %s() doesn't return scalar. Only those are supported.\n",
7220                         tname);
7221                 return -EINVAL;
7222         }
7223         /* Convert BTF function arguments into verifier types.
7224          * Only PTR_TO_CTX and SCALAR are supported atm.
7225          */
7226         for (i = 0; i < nargs; i++) {
7227                 u32 tags = 0;
7228                 int id = 0;
7229
7230                 /* 'arg:<tag>' decl_tag takes precedence over derivation of
7231                  * register type from BTF type itself
7232                  */
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;
7236
7237                         /* disallow arg tags in static subprogs */
7238                         if (!is_global) {
7239                                 bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7240                                 return -EOPNOTSUPP;
7241                         }
7242
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;
7253                         } else {
7254                                 bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7255                                 return -EOPNOTSUPP;
7256                         }
7257                 }
7258                 if (id != -ENOENT) {
7259                         bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7260                         return id;
7261                 }
7262
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))
7267                         goto skip_pointer;
7268
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);
7272                                 return -EINVAL;
7273                         }
7274                         if ((tags & ARG_TAG_CTX) &&
7275                             btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7276                                                        prog->expected_attach_type))
7277                                 return -EINVAL;
7278                         sub->args[i].arg_type = ARG_PTR_TO_CTX;
7279                         continue;
7280                 }
7281                 if (btf_is_dynptr_ptr(btf, t)) {
7282                         if (tags) {
7283                                 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7284                                 return -EINVAL;
7285                         }
7286                         sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7287                         continue;
7288                 }
7289                 if (tags & ARG_TAG_TRUSTED) {
7290                         int kern_type_id;
7291
7292                         if (tags & ARG_TAG_NONNULL) {
7293                                 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7294                                 return -EINVAL;
7295                         }
7296
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;
7300
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;
7305                         continue;
7306                 }
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);
7310                                 return -EINVAL;
7311                         }
7312                         sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7313                         continue;
7314                 }
7315                 if (is_global) { /* generic user data pointer */
7316                         u32 mem_size;
7317
7318                         if (tags & ARG_TAG_NULLABLE) {
7319                                 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7320                                 return -EINVAL;
7321                         }
7322
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),
7328                                         PTR_ERR(ref_t));
7329                                 return -EINVAL;
7330                         }
7331
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;
7336                         continue;
7337                 }
7338
7339 skip_pointer:
7340                 if (tags) {
7341                         bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
7342                         return -EINVAL;
7343                 }
7344                 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7345                         sub->args[i].arg_type = ARG_ANYTHING;
7346                         continue;
7347                 }
7348                 if (!is_global)
7349                         return -EINVAL;
7350                 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7351                         i, btf_type_str(t), tname);
7352                 return -EINVAL;
7353         }
7354
7355         sub->arg_cnt = nargs;
7356         sub->args_cached = true;
7357
7358         return 0;
7359 }
7360
7361 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7362                           struct btf_show *show)
7363 {
7364         const struct btf_type *t = btf_type_by_id(btf, type_id);
7365
7366         show->btf = btf;
7367         memset(&show->state, 0, sizeof(show->state));
7368         memset(&show->obj, 0, sizeof(show->obj));
7369
7370         btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7371 }
7372
7373 static void btf_seq_show(struct btf_show *show, const char *fmt,
7374                          va_list args)
7375 {
7376         seq_vprintf((struct seq_file *)show->target, fmt, args);
7377 }
7378
7379 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7380                             void *obj, struct seq_file *m, u64 flags)
7381 {
7382         struct btf_show sseq;
7383
7384         sseq.target = m;
7385         sseq.showfn = btf_seq_show;
7386         sseq.flags = flags;
7387
7388         btf_type_show(btf, type_id, obj, &sseq);
7389
7390         return sseq.state.status;
7391 }
7392
7393 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7394                        struct seq_file *m)
7395 {
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);
7399 }
7400
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 */
7405 };
7406
7407 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7408                               va_list args)
7409 {
7410         struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7411         int len;
7412
7413         len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7414
7415         if (len < 0) {
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;
7422         } else {
7423                 ssnprintf->len_left -= len;
7424                 ssnprintf->len += len;
7425                 show->target += len;
7426         }
7427 }
7428
7429 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7430                            char *buf, int len, u64 flags)
7431 {
7432         struct btf_show_snprintf ssnprintf;
7433
7434         ssnprintf.show.target = buf;
7435         ssnprintf.show.flags = flags;
7436         ssnprintf.show.showfn = btf_snprintf_show;
7437         ssnprintf.len_left = len;
7438         ssnprintf.len = 0;
7439
7440         btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7441
7442         /* If we encountered an error, return it. */
7443         if (ssnprintf.show.state.status)
7444                 return ssnprintf.show.state.status;
7445
7446         /* Otherwise return length we would have written */
7447         return ssnprintf.len;
7448 }
7449
7450 #ifdef CONFIG_PROC_FS
7451 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7452 {
7453         const struct btf *btf = filp->private_data;
7454
7455         seq_printf(m, "btf_id:\t%u\n", btf->id);
7456 }
7457 #endif
7458
7459 static int btf_release(struct inode *inode, struct file *filp)
7460 {
7461         btf_put(filp->private_data);
7462         return 0;
7463 }
7464
7465 const struct file_operations btf_fops = {
7466 #ifdef CONFIG_PROC_FS
7467         .show_fdinfo    = bpf_btf_show_fdinfo,
7468 #endif
7469         .release        = btf_release,
7470 };
7471
7472 static int __btf_new_fd(struct btf *btf)
7473 {
7474         return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7475 }
7476
7477 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7478 {
7479         struct btf *btf;
7480         int ret;
7481
7482         btf = btf_parse(attr, uattr, uattr_size);
7483         if (IS_ERR(btf))
7484                 return PTR_ERR(btf);
7485
7486         ret = btf_alloc_id(btf);
7487         if (ret) {
7488                 btf_free(btf);
7489                 return ret;
7490         }
7491
7492         /*
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()).
7496          */
7497
7498         ret = __btf_new_fd(btf);
7499         if (ret < 0)
7500                 btf_put(btf);
7501
7502         return ret;
7503 }
7504
7505 struct btf *btf_get_by_fd(int fd)
7506 {
7507         struct btf *btf;
7508         struct fd f;
7509
7510         f = fdget(fd);
7511
7512         if (!f.file)
7513                 return ERR_PTR(-EBADF);
7514
7515         if (f.file->f_op != &btf_fops) {
7516                 fdput(f);
7517                 return ERR_PTR(-EINVAL);
7518         }
7519
7520         btf = f.file->private_data;
7521         refcount_inc(&btf->refcnt);
7522         fdput(f);
7523
7524         return btf;
7525 }
7526
7527 int btf_get_info_by_fd(const struct btf *btf,
7528                        const union bpf_attr *attr,
7529                        union bpf_attr __user *uattr)
7530 {
7531         struct bpf_btf_info __user *uinfo;
7532         struct bpf_btf_info info;
7533         u32 info_copy, btf_copy;
7534         void __user *ubtf;
7535         char __user *uname;
7536         u32 uinfo_len, uname_len, name_len;
7537         int ret = 0;
7538
7539         uinfo = u64_to_user_ptr(attr->info.info);
7540         uinfo_len = attr->info.info_len;
7541
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))
7545                 return -EFAULT;
7546
7547         info.id = btf->id;
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))
7551                 return -EFAULT;
7552         info.btf_size = btf->data_size;
7553
7554         info.kernel_btf = btf->kernel_btf;
7555
7556         uname = u64_to_user_ptr(info.name);
7557         uname_len = info.name_len;
7558         if (!uname ^ !uname_len)
7559                 return -EINVAL;
7560
7561         name_len = strlen(btf->name);
7562         info.name_len = name_len;
7563
7564         if (uname) {
7565                 if (uname_len >= name_len + 1) {
7566                         if (copy_to_user(uname, btf->name, name_len + 1))
7567                                 return -EFAULT;
7568                 } else {
7569                         char zero = '\0';
7570
7571                         if (copy_to_user(uname, btf->name, uname_len - 1))
7572                                 return -EFAULT;
7573                         if (put_user(zero, uname + uname_len - 1))
7574                                 return -EFAULT;
7575                         /* let user-space know about too short buffer */
7576                         ret = -ENOSPC;
7577                 }
7578         }
7579
7580         if (copy_to_user(uinfo, &info, info_copy) ||
7581             put_user(info_copy, &uattr->info.info_len))
7582                 return -EFAULT;
7583
7584         return ret;
7585 }
7586
7587 int btf_get_fd_by_id(u32 id)
7588 {
7589         struct btf *btf;
7590         int fd;
7591
7592         rcu_read_lock();
7593         btf = idr_find(&btf_idr, id);
7594         if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7595                 btf = ERR_PTR(-ENOENT);
7596         rcu_read_unlock();
7597
7598         if (IS_ERR(btf))
7599                 return PTR_ERR(btf);
7600
7601         fd = __btf_new_fd(btf);
7602         if (fd < 0)
7603                 btf_put(btf);
7604
7605         return fd;
7606 }
7607
7608 u32 btf_obj_id(const struct btf *btf)
7609 {
7610         return btf->id;
7611 }
7612
7613 bool btf_is_kernel(const struct btf *btf)
7614 {
7615         return btf->kernel_btf;
7616 }
7617
7618 bool btf_is_module(const struct btf *btf)
7619 {
7620         return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7621 }
7622
7623 enum {
7624         BTF_MODULE_F_LIVE = (1 << 0),
7625 };
7626
7627 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7628 struct btf_module {
7629         struct list_head list;
7630         struct module *module;
7631         struct btf *btf;
7632         struct bin_attribute *sysfs_attr;
7633         int flags;
7634 };
7635
7636 static LIST_HEAD(btf_modules);
7637 static DEFINE_MUTEX(btf_module_mutex);
7638
7639 static ssize_t
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)
7643 {
7644         const struct btf *btf = bin_attr->private;
7645
7646         memcpy(buf, btf->data + off, len);
7647         return len;
7648 }
7649
7650 static void purge_cand_cache(struct btf *btf);
7651
7652 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7653                              void *module)
7654 {
7655         struct btf_module *btf_mod, *tmp;
7656         struct module *mod = module;
7657         struct btf *btf;
7658         int err = 0;
7659
7660         if (mod->btf_data_size == 0 ||
7661             (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7662              op != MODULE_STATE_GOING))
7663                 goto out;
7664
7665         switch (op) {
7666         case MODULE_STATE_COMING:
7667                 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7668                 if (!btf_mod) {
7669                         err = -ENOMEM;
7670                         goto out;
7671                 }
7672                 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7673                 if (IS_ERR(btf)) {
7674                         kfree(btf_mod);
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));
7678                                 err = PTR_ERR(btf);
7679                         } else {
7680                                 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7681                         }
7682                         goto out;
7683                 }
7684                 err = btf_alloc_id(btf);
7685                 if (err) {
7686                         btf_free(btf);
7687                         kfree(btf_mod);
7688                         goto out;
7689                 }
7690
7691                 purge_cand_cache(NULL);
7692                 mutex_lock(&btf_module_mutex);
7693                 btf_mod->module = module;
7694                 btf_mod->btf = btf;
7695                 list_add(&btf_mod->list, &btf_modules);
7696                 mutex_unlock(&btf_module_mutex);
7697
7698                 if (IS_ENABLED(CONFIG_SYSFS)) {
7699                         struct bin_attribute *attr;
7700
7701                         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7702                         if (!attr)
7703                                 goto out;
7704
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;
7711
7712                         err = sysfs_create_bin_file(btf_kobj, attr);
7713                         if (err) {
7714                                 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7715                                         mod->name, err);
7716                                 kfree(attr);
7717                                 err = 0;
7718                                 goto out;
7719                         }
7720
7721                         btf_mod->sysfs_attr = attr;
7722                 }
7723
7724                 break;
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)
7729                                 continue;
7730
7731                         btf_mod->flags |= BTF_MODULE_F_LIVE;
7732                         break;
7733                 }
7734                 mutex_unlock(&btf_module_mutex);
7735                 break;
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)
7740                                 continue;
7741
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);
7748                         kfree(btf_mod);
7749                         break;
7750                 }
7751                 mutex_unlock(&btf_module_mutex);
7752                 break;
7753         }
7754 out:
7755         return notifier_from_errno(err);
7756 }
7757
7758 static struct notifier_block btf_module_nb = {
7759         .notifier_call = btf_module_notify,
7760 };
7761
7762 static int __init btf_module_init(void)
7763 {
7764         register_module_notifier(&btf_module_nb);
7765         return 0;
7766 }
7767
7768 fs_initcall(btf_module_init);
7769 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7770
7771 struct module *btf_try_get_module(const struct btf *btf)
7772 {
7773         struct module *res = NULL;
7774 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7775         struct btf_module *btf_mod, *tmp;
7776
7777         mutex_lock(&btf_module_mutex);
7778         list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7779                 if (btf_mod->btf != btf)
7780                         continue;
7781
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.
7786                  */
7787                 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7788                         res = btf_mod->module;
7789
7790                 break;
7791         }
7792         mutex_unlock(&btf_module_mutex);
7793 #endif
7794
7795         return res;
7796 }
7797
7798 /* Returns struct btf corresponding to the struct module.
7799  * This function can return NULL or ERR_PTR.
7800  */
7801 static struct btf *btf_get_module_btf(const struct module *module)
7802 {
7803 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7804         struct btf_module *btf_mod, *tmp;
7805 #endif
7806         struct btf *btf = NULL;
7807
7808         if (!module) {
7809                 btf = bpf_get_btf_vmlinux();
7810                 if (!IS_ERR_OR_NULL(btf))
7811                         btf_get(btf);
7812                 return btf;
7813         }
7814
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)
7819                         continue;
7820
7821                 btf_get(btf_mod->btf);
7822                 btf = btf_mod->btf;
7823                 break;
7824         }
7825         mutex_unlock(&btf_module_mutex);
7826 #endif
7827
7828         return btf;
7829 }
7830
7831 static int check_btf_kconfigs(const struct module *module, const char *feature)
7832 {
7833         if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7834                 pr_err("missing vmlinux BTF, cannot register %s\n", feature);
7835                 return -ENOENT;
7836         }
7837         if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
7838                 pr_warn("missing module BTF, cannot register %s\n", feature);
7839         return 0;
7840 }
7841
7842 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7843 {
7844         struct btf *btf = NULL;
7845         int btf_obj_fd = 0;
7846         long ret;
7847
7848         if (flags)
7849                 return -EINVAL;
7850
7851         if (name_sz <= 1 || name[name_sz - 1])
7852                 return -EINVAL;
7853
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) {
7858                         btf_put(btf);
7859                         return btf_obj_fd;
7860                 }
7861                 return ret | (((u64)btf_obj_fd) << 32);
7862         }
7863         if (ret > 0)
7864                 btf_put(btf);
7865         return ret;
7866 }
7867
7868 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7869         .func           = bpf_btf_find_by_name_kind,
7870         .gpl_only       = false,
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,
7876 };
7877
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
7882
7883 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
7884                                  const struct btf_type *func, u32 func_flags)
7885 {
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;
7890         char exp_name[128];
7891         u32 nr_args;
7892
7893         /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
7894         if (!flags || (flags & (flags - 1)))
7895                 return -EINVAL;
7896
7897         /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
7898         nr_args = btf_type_vlen(func);
7899         if (nr_args < 1)
7900                 return -EINVAL;
7901
7902         arg = &btf_params(func)[0];
7903         t = btf_type_skip_modifiers(btf, arg->type, NULL);
7904         if (!t || !btf_type_is_ptr(t))
7905                 return -EINVAL;
7906         t = btf_type_skip_modifiers(btf, t->type, NULL);
7907         if (!t || !__btf_type_is_struct(t))
7908                 return -EINVAL;
7909
7910         name = btf_name_by_offset(btf, t->name_off);
7911         if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
7912                 return -EINVAL;
7913
7914         /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
7915          * fit nicely in stack slots
7916          */
7917         if (t->size == 0 || (t->size % 8))
7918                 return -EINVAL;
7919
7920         /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
7921          * naming pattern
7922          */
7923         iter_name = name + sizeof(ITER_PREFIX) - 1;
7924         if (flags & KF_ITER_NEW)
7925                 sfx = "new";
7926         else if (flags & KF_ITER_NEXT)
7927                 sfx = "next";
7928         else /* (flags & KF_ITER_DESTROY) */
7929                 sfx = "destroy";
7930
7931         snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
7932         if (strcmp(func_name, exp_name))
7933                 return -EINVAL;
7934
7935         /* only iter constructor should have extra arguments */
7936         if (!(flags & KF_ITER_NEW) && nr_args != 1)
7937                 return -EINVAL;
7938
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))
7943                         return -EINVAL;
7944         }
7945
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))
7950                         return -EINVAL;
7951         }
7952
7953         return 0;
7954 }
7955
7956 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
7957 {
7958         const struct btf_type *func;
7959         const char *func_name;
7960         int err;
7961
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))
7965                 return -EINVAL;
7966
7967         /* sanity check kfunc name */
7968         func_name = btf_name_by_offset(btf, func->name_off);
7969         if (!func_name || !func_name[0])
7970                 return -EINVAL;
7971
7972         func = btf_type_by_id(btf, func->type);
7973         if (!func || !btf_type_is_func_proto(func))
7974                 return -EINVAL;
7975
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);
7978                 if (err)
7979                         return err;
7980         }
7981
7982         return 0;
7983 }
7984
7985 /* Kernel Function (kfunc) BTF ID set registration API */
7986
7987 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7988                                   const struct btf_kfunc_id_set *kset)
7989 {
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;
7996         u32 set_cnt;
7997         int ret;
7998
7999         if (hook >= BTF_KFUNC_HOOK_MAX) {
8000                 ret = -EINVAL;
8001                 goto end;
8002         }
8003
8004         if (!add_set->cnt)
8005                 return 0;
8006
8007         tab = btf->kfunc_set_tab;
8008
8009         if (tab && add_filter) {
8010                 u32 i;
8011
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) {
8015                                 add_filter = false;
8016                                 break;
8017                         }
8018                 }
8019
8020                 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8021                         ret = -E2BIG;
8022                         goto end;
8023                 }
8024         }
8025
8026         if (!tab) {
8027                 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
8028                 if (!tab)
8029                         return -ENOMEM;
8030                 btf->kfunc_set_tab = tab;
8031         }
8032
8033         set = tab->sets[hook];
8034         /* Warn when register_btf_kfunc_id_set is called twice for the same hook
8035          * for module sets.
8036          */
8037         if (WARN_ON_ONCE(set && !vmlinux_set)) {
8038                 ret = -EINVAL;
8039                 goto end;
8040         }
8041
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.
8045          */
8046         if (!vmlinux_set) {
8047                 tab->sets[hook] = add_set;
8048                 goto do_add_filter;
8049         }
8050
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.
8057          */
8058         set_cnt = set ? set->cnt : 0;
8059
8060         if (set_cnt > U32_MAX - add_set->cnt) {
8061                 ret = -EOVERFLOW;
8062                 goto end;
8063         }
8064
8065         if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8066                 ret = -E2BIG;
8067                 goto end;
8068         }
8069
8070         /* Grow set */
8071         set = krealloc(tab->sets[hook],
8072                        offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
8073                        GFP_KERNEL | __GFP_NOWARN);
8074         if (!set) {
8075                 ret = -ENOMEM;
8076                 goto end;
8077         }
8078
8079         /* For newly allocated set, initialize set->cnt to 0 */
8080         if (!tab->sets[hook])
8081                 set->cnt = 0;
8082         tab->sets[hook] = set;
8083
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;
8087
8088         sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8089
8090 do_add_filter:
8091         if (add_filter) {
8092                 hook_filter = &tab->hook_filters[hook];
8093                 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8094         }
8095         return 0;
8096 end:
8097         btf_free_kfunc_set_tab(btf);
8098         return ret;
8099 }
8100
8101 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
8102                                         enum btf_kfunc_hook hook,
8103                                         u32 kfunc_btf_id,
8104                                         const struct bpf_prog *prog)
8105 {
8106         struct btf_kfunc_hook_filter *hook_filter;
8107         struct btf_id_set8 *set;
8108         u32 *id, i;
8109
8110         if (hook >= BTF_KFUNC_HOOK_MAX)
8111                 return NULL;
8112         if (!btf->kfunc_set_tab)
8113                 return NULL;
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))
8117                         return NULL;
8118         }
8119         set = btf->kfunc_set_tab->sets[hook];
8120         if (!set)
8121                 return NULL;
8122         id = btf_id_set8_contains(set, kfunc_btf_id);
8123         if (!id)
8124                 return NULL;
8125         /* The flags for BTF ID are located next to it */
8126         return id + 1;
8127 }
8128
8129 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8130 {
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;
8163         default:
8164                 return BTF_KFUNC_HOOK_MAX;
8165         }
8166 }
8167
8168 /* Caution:
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.
8174  */
8175 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8176                                u32 kfunc_btf_id,
8177                                const struct bpf_prog *prog)
8178 {
8179         enum bpf_prog_type prog_type = resolve_prog_type(prog);
8180         enum btf_kfunc_hook hook;
8181         u32 *kfunc_flags;
8182
8183         kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
8184         if (kfunc_flags)
8185                 return kfunc_flags;
8186
8187         hook = bpf_prog_type_to_kfunc_hook(prog_type);
8188         return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
8189 }
8190
8191 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8192                                 const struct bpf_prog *prog)
8193 {
8194         return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
8195 }
8196
8197 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8198                                        const struct btf_kfunc_id_set *kset)
8199 {
8200         struct btf *btf;
8201         int ret, i;
8202
8203         btf = btf_get_module_btf(kset->owner);
8204         if (!btf)
8205                 return check_btf_kconfigs(kset->owner, "kfunc");
8206         if (IS_ERR(btf))
8207                 return PTR_ERR(btf);
8208
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);
8212                 if (ret)
8213                         goto err_out;
8214         }
8215
8216         ret = btf_populate_kfunc_set(btf, hook, kset);
8217
8218 err_out:
8219         btf_put(btf);
8220         return ret;
8221 }
8222
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)
8226 {
8227         enum btf_kfunc_hook hook;
8228
8229         /* All kfuncs need to be tagged as such in BTF.
8230          * WARN() for initcall registrations that do not check errors.
8231          */
8232         if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8233                 WARN_ON(!kset->owner);
8234                 return -EINVAL;
8235         }
8236
8237         hook = bpf_prog_type_to_kfunc_hook(prog_type);
8238         return __register_btf_kfunc_id_set(hook, kset);
8239 }
8240 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8241
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)
8244 {
8245         return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8246 }
8247 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8248
8249 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8250 {
8251         struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8252         struct btf_id_dtor_kfunc *dtor;
8253
8254         if (!tab)
8255                 return -ENOENT;
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.
8258          */
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);
8261         if (!dtor)
8262                 return -ENOENT;
8263         return dtor->kfunc_btf_id;
8264 }
8265
8266 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8267 {
8268         const struct btf_type *dtor_func, *dtor_func_proto, *t;
8269         const struct btf_param *args;
8270         s32 dtor_btf_id;
8271         u32 nr_args, i;
8272
8273         for (i = 0; i < cnt; i++) {
8274                 dtor_btf_id = dtors[i].kfunc_btf_id;
8275
8276                 dtor_func = btf_type_by_id(btf, dtor_btf_id);
8277                 if (!dtor_func || !btf_type_is_func(dtor_func))
8278                         return -EINVAL;
8279
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))
8282                         return -EINVAL;
8283
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))
8287                         return -EINVAL;
8288
8289                 nr_args = btf_type_vlen(dtor_func_proto);
8290                 if (nr_args != 1)
8291                         return -EINVAL;
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 *))
8296                  */
8297                 if (!t || !btf_type_is_ptr(t))
8298                         return -EINVAL;
8299         }
8300         return 0;
8301 }
8302
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)
8306 {
8307         struct btf_id_dtor_kfunc_tab *tab;
8308         struct btf *btf;
8309         u32 tab_cnt;
8310         int ret;
8311
8312         btf = btf_get_module_btf(owner);
8313         if (!btf)
8314                 return check_btf_kconfigs(owner, "dtor kfuncs");
8315         if (IS_ERR(btf))
8316                 return PTR_ERR(btf);
8317
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);
8320                 ret = -E2BIG;
8321                 goto end;
8322         }
8323
8324         /* Ensure that the prototype of dtor kfuncs being registered is sane */
8325         ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8326         if (ret < 0)
8327                 goto end;
8328
8329         tab = btf->dtor_kfunc_tab;
8330         /* Only one call allowed for modules */
8331         if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8332                 ret = -EINVAL;
8333                 goto end;
8334         }
8335
8336         tab_cnt = tab ? tab->cnt : 0;
8337         if (tab_cnt > U32_MAX - add_cnt) {
8338                 ret = -EOVERFLOW;
8339                 goto end;
8340         }
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);
8343                 ret = -E2BIG;
8344                 goto end;
8345         }
8346
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);
8350         if (!tab) {
8351                 ret = -ENOMEM;
8352                 goto end;
8353         }
8354
8355         if (!btf->dtor_kfunc_tab)
8356                 tab->cnt = 0;
8357         btf->dtor_kfunc_tab = tab;
8358
8359         memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8360         tab->cnt += add_cnt;
8361
8362         sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8363
8364 end:
8365         if (ret)
8366                 btf_free_dtor_kfunc_tab(btf);
8367         btf_put(btf);
8368         return ret;
8369 }
8370 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8371
8372 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8373
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.
8392  */
8393 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8394                               const struct btf *targ_btf, __u32 targ_id)
8395 {
8396         return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8397                                            MAX_TYPES_ARE_COMPAT_DEPTH);
8398 }
8399
8400 #define MAX_TYPES_MATCH_DEPTH 2
8401
8402 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8403                          const struct btf *targ_btf, u32 targ_id)
8404 {
8405         return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8406                                       MAX_TYPES_MATCH_DEPTH);
8407 }
8408
8409 static bool bpf_core_is_flavor_sep(const char *s)
8410 {
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 */
8415 }
8416
8417 size_t bpf_core_essential_name_len(const char *name)
8418 {
8419         size_t n = strlen(name);
8420         int i;
8421
8422         for (i = n - 5; i >= 0; i--) {
8423                 if (bpf_core_is_flavor_sep(name + i))
8424                         return i + 1;
8425         }
8426         return n;
8427 }
8428
8429 static void bpf_free_cands(struct bpf_cand_cache *cands)
8430 {
8431         if (!cands->cnt)
8432                 /* empty candidate array was allocated on stack */
8433                 return;
8434         kfree(cands);
8435 }
8436
8437 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8438 {
8439         kfree(cands->name);
8440         kfree(cands);
8441 }
8442
8443 #define VMLINUX_CAND_CACHE_SIZE 31
8444 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8445
8446 #define MODULE_CAND_CACHE_SIZE 31
8447 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8448
8449 static void __print_cand_cache(struct bpf_verifier_log *log,
8450                                struct bpf_cand_cache **cache,
8451                                int cache_size)
8452 {
8453         struct bpf_cand_cache *cc;
8454         int i, j;
8455
8456         for (i = 0; i < cache_size; i++) {
8457                 cc = cache[i];
8458                 if (!cc)
8459                         continue;
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)
8464                                 bpf_log(log, " ");
8465                 }
8466                 bpf_log(log, "), ");
8467         }
8468 }
8469
8470 static void print_cand_cache(struct bpf_verifier_log *log)
8471 {
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);
8477         bpf_log(log, "\n");
8478         mutex_unlock(&cand_cache_mutex);
8479 }
8480
8481 static u32 hash_cands(struct bpf_cand_cache *cands)
8482 {
8483         return jhash(cands->name, cands->name_len, 0);
8484 }
8485
8486 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8487                                                struct bpf_cand_cache **cache,
8488                                                int cache_size)
8489 {
8490         struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8491
8492         if (cc && cc->name_len == cands->name_len &&
8493             !strncmp(cc->name, cands->name, cands->name_len))
8494                 return cc;
8495         return NULL;
8496 }
8497
8498 static size_t sizeof_cands(int cnt)
8499 {
8500         return offsetof(struct bpf_cand_cache, cands[cnt]);
8501 }
8502
8503 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8504                                                   struct bpf_cand_cache **cache,
8505                                                   int cache_size)
8506 {
8507         struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8508
8509         if (*cc) {
8510                 bpf_free_cands_from_cache(*cc);
8511                 *cc = NULL;
8512         }
8513         new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8514         if (!new_cands) {
8515                 bpf_free_cands(cands);
8516                 return ERR_PTR(-ENOMEM);
8517         }
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.
8520          */
8521         new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8522         bpf_free_cands(cands);
8523         if (!new_cands->name) {
8524                 kfree(new_cands);
8525                 return ERR_PTR(-ENOMEM);
8526         }
8527         *cc = new_cands;
8528         return new_cands;
8529 }
8530
8531 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8532 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8533                                int cache_size)
8534 {
8535         struct bpf_cand_cache *cc;
8536         int i, j;
8537
8538         for (i = 0; i < cache_size; i++) {
8539                 cc = cache[i];
8540                 if (!cc)
8541                         continue;
8542                 if (!btf) {
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.
8546                          */
8547                         bpf_free_cands_from_cache(cc);
8548                         cache[i] = NULL;
8549                         continue;
8550                 }
8551                 /* when module is unloaded purge cache entries
8552                  * that match module's btf
8553                  */
8554                 for (j = 0; j < cc->cnt; j++)
8555                         if (cc->cands[j].btf == btf) {
8556                                 bpf_free_cands_from_cache(cc);
8557                                 cache[i] = NULL;
8558                                 break;
8559                         }
8560         }
8561
8562 }
8563
8564 static void purge_cand_cache(struct btf *btf)
8565 {
8566         mutex_lock(&cand_cache_mutex);
8567         __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8568         mutex_unlock(&cand_cache_mutex);
8569 }
8570 #endif
8571
8572 static struct bpf_cand_cache *
8573 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8574                    int targ_start_id)
8575 {
8576         struct bpf_cand_cache *new_cands;
8577         const struct btf_type *t;
8578         const char *targ_name;
8579         size_t targ_essent_len;
8580         int n, i;
8581
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)
8586                         continue;
8587
8588                 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8589                 if (!targ_name)
8590                         continue;
8591
8592                 /* the resched point is before strncmp to make sure that search
8593                  * for non-existing name will have a chance to schedule().
8594                  */
8595                 cond_resched();
8596
8597                 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8598                         continue;
8599
8600                 targ_essent_len = bpf_core_essential_name_len(targ_name);
8601                 if (targ_essent_len != cands->name_len)
8602                         continue;
8603
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);
8606                 if (!new_cands) {
8607                         bpf_free_cands(cands);
8608                         return ERR_PTR(-ENOMEM);
8609                 }
8610
8611                 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8612                 bpf_free_cands(cands);
8613                 cands = new_cands;
8614                 cands->cands[cands->cnt].btf = targ_btf;
8615                 cands->cands[cands->cnt].id = i;
8616                 cands->cnt++;
8617         }
8618         return cands;
8619 }
8620
8621 static struct bpf_cand_cache *
8622 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8623 {
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;
8630         const char *name;
8631         int id;
8632
8633         main_btf = bpf_get_btf_vmlinux();
8634         if (IS_ERR(main_btf))
8635                 return ERR_CAST(main_btf);
8636         if (!main_btf)
8637                 return ERR_PTR(-EINVAL);
8638
8639         local_type = btf_type_by_id(local_btf, local_type_id);
8640         if (!local_type)
8641                 return ERR_PTR(-EINVAL);
8642
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);
8647
8648         cands = &local_cand;
8649         cands->name = name;
8650         cands->kind = btf_kind(local_type);
8651         cands->name_len = local_essent_len;
8652
8653         cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8654         /* cands is a pointer to stack here */
8655         if (cc) {
8656                 if (cc->cnt)
8657                         return cc;
8658                 goto check_modules;
8659         }
8660
8661         /* Attempt to find target candidates in vmlinux BTF first */
8662         cands = bpf_core_add_cands(cands, main_btf, 1);
8663         if (IS_ERR(cands))
8664                 return ERR_CAST(cands);
8665
8666         /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8667
8668         /* populate cache even when cands->cnt == 0 */
8669         cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8670         if (IS_ERR(cc))
8671                 return ERR_CAST(cc);
8672
8673         /* if vmlinux BTF has any candidate, don't go for module BTFs */
8674         if (cc->cnt)
8675                 return cc;
8676
8677 check_modules:
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);
8680         if (cc)
8681                 /* if cache has it return it even if cc->cnt == 0 */
8682                 return cc;
8683
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))
8688                         continue;
8689                 /* linear search could be slow hence unlock/lock
8690                  * the IDR to avoiding holding it for too long
8691                  */
8692                 btf_get(mod_btf);
8693                 spin_unlock_bh(&btf_idr_lock);
8694                 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8695                 btf_put(mod_btf);
8696                 if (IS_ERR(cands))
8697                         return ERR_CAST(cands);
8698                 spin_lock_bh(&btf_idr_lock);
8699         }
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.
8705          */
8706         return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8707 }
8708
8709 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8710                    int relo_idx, void *insn)
8711 {
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;
8716         int err;
8717
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.
8720          */
8721         specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8722         if (!specs)
8723                 return -ENOMEM;
8724
8725         if (need_cands) {
8726                 struct bpf_cand_cache *cc;
8727                 int i;
8728
8729                 mutex_lock(&cand_cache_mutex);
8730                 cc = bpf_core_find_cands(ctx, relo->type_id);
8731                 if (IS_ERR(cc)) {
8732                         bpf_log(ctx->log, "target candidate search failed for %d\n",
8733                                 relo->type_id);
8734                         err = PTR_ERR(cc);
8735                         goto out;
8736                 }
8737                 if (cc->cnt) {
8738                         cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8739                         if (!cands.cands) {
8740                                 err = -ENOMEM;
8741                                 goto out;
8742                         }
8743                 }
8744                 for (i = 0; i < cc->cnt; i++) {
8745                         bpf_log(ctx->log,
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;
8750                 }
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.
8756                  */
8757         }
8758
8759         err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8760                                       &targ_res);
8761         if (err)
8762                 goto out;
8763
8764         err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8765                                   &targ_res);
8766
8767 out:
8768         kfree(specs);
8769         if (need_cands) {
8770                 kfree(cands.cands);
8771                 mutex_unlock(&cand_cache_mutex);
8772                 if (ctx->log->level & BPF_LOG_LEVEL2)
8773                         print_cand_cache(ctx->log);
8774         }
8775         return err;
8776 }
8777
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)
8781 {
8782         struct btf *btf = reg->btf;
8783         const struct btf_type *walk_type, *safe_type;
8784         const char *tname;
8785         char safe_tname[64];
8786         long ret, safe_id;
8787         const struct btf_member *member;
8788         u32 i;
8789
8790         walk_type = btf_type_by_id(btf, reg->btf_id);
8791         if (!walk_type)
8792                 return false;
8793
8794         tname = btf_name_by_offset(btf, walk_type->name_off);
8795
8796         ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8797         if (ret >= sizeof(safe_tname))
8798                 return false;
8799
8800         safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8801         if (safe_id < 0)
8802                 return false;
8803
8804         safe_type = btf_type_by_id(btf, safe_id);
8805         if (!safe_type)
8806                 return false;
8807
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);
8811                 u32 id;
8812
8813                 if (!btf_type_is_ptr(mtype))
8814                         continue;
8815
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))
8819                         return true;
8820         }
8821
8822         return false;
8823 }
8824
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)
8828 {
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);
8833
8834         reg_type = btf_type_by_id(reg_btf, reg_id);
8835         if (!reg_type)
8836                 return false;
8837
8838         arg_type = btf_type_by_id(arg_btf, arg_id);
8839         if (!arg_type)
8840                 return false;
8841
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);
8844
8845         reg_len = strlen(reg_name);
8846         arg_len = strlen(arg_name);
8847
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.
8853          */
8854         if (reg_len == arg_len)
8855                 return false;
8856
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))
8860                 return false;
8861
8862         if (reg_len < arg_len) {
8863                 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8864                 cmp_len = reg_len;
8865         } else {
8866                 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8867                 cmp_len = arg_len;
8868         }
8869
8870         if (!search_needle)
8871                 return false;
8872
8873         /* ___init suffix must come at the end of the name */
8874         if (*(search_needle + pattern_len) != '\0')
8875                 return false;
8876
8877         return !strncmp(reg_name, arg_name, cmp_len);
8878 }
8879
8880 #ifdef CONFIG_BPF_JIT
8881 static int
8882 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
8883                    struct bpf_verifier_log *log)
8884 {
8885         struct btf_struct_ops_tab *tab, *new_tab;
8886         int i, err;
8887
8888         tab = btf->struct_ops_tab;
8889         if (!tab) {
8890                 tab = kzalloc(offsetof(struct btf_struct_ops_tab, ops[4]),
8891                               GFP_KERNEL);
8892                 if (!tab)
8893                         return -ENOMEM;
8894                 tab->capacity = 4;
8895                 btf->struct_ops_tab = tab;
8896         }
8897
8898         for (i = 0; i < tab->cnt; i++)
8899                 if (tab->ops[i].st_ops == st_ops)
8900                         return -EEXIST;
8901
8902         if (tab->cnt == tab->capacity) {
8903                 new_tab = krealloc(tab,
8904                                    offsetof(struct btf_struct_ops_tab,
8905                                             ops[tab->capacity * 2]),
8906                                    GFP_KERNEL);
8907                 if (!new_tab)
8908                         return -ENOMEM;
8909                 tab = new_tab;
8910                 tab->capacity *= 2;
8911                 btf->struct_ops_tab = tab;
8912         }
8913
8914         tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
8915
8916         err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
8917         if (err)
8918                 return err;
8919
8920         btf->struct_ops_tab->cnt++;
8921
8922         return 0;
8923 }
8924
8925 const struct bpf_struct_ops_desc *
8926 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
8927 {
8928         const struct bpf_struct_ops_desc *st_ops_list;
8929         unsigned int i;
8930         u32 cnt;
8931
8932         if (!value_id)
8933                 return NULL;
8934         if (!btf->struct_ops_tab)
8935                 return NULL;
8936
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];
8942         }
8943
8944         return NULL;
8945 }
8946
8947 const struct bpf_struct_ops_desc *
8948 bpf_struct_ops_find(struct btf *btf, u32 type_id)
8949 {
8950         const struct bpf_struct_ops_desc *st_ops_list;
8951         unsigned int i;
8952         u32 cnt;
8953
8954         if (!type_id)
8955                 return NULL;
8956         if (!btf->struct_ops_tab)
8957                 return NULL;
8958
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];
8964         }
8965
8966         return NULL;
8967 }
8968
8969 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
8970 {
8971         struct bpf_verifier_log *log;
8972         struct btf *btf;
8973         int err = 0;
8974
8975         btf = btf_get_module_btf(st_ops->owner);
8976         if (!btf)
8977                 return check_btf_kconfigs(st_ops->owner, "struct_ops");
8978         if (IS_ERR(btf))
8979                 return PTR_ERR(btf);
8980
8981         log = kzalloc(sizeof(*log), GFP_KERNEL | __GFP_NOWARN);
8982         if (!log) {
8983                 err = -ENOMEM;
8984                 goto errout;
8985         }
8986
8987         log->level = BPF_LOG_KERNEL;
8988
8989         err = btf_add_struct_ops(btf, st_ops, log);
8990
8991 errout:
8992         kfree(log);
8993         btf_put(btf);
8994
8995         return err;
8996 }
8997 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
8998 #endif
8999
9000 bool btf_param_match_suffix(const struct btf *btf,
9001                             const struct btf_param *arg,
9002                             const char *suffix)
9003 {
9004         int suffix_len = strlen(suffix), len;
9005         const char *param_name;
9006
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))
9010                 return false;
9011         len = strlen(param_name);
9012         if (len <= suffix_len)
9013                 return false;
9014         param_name += len - suffix_len;
9015         return !strncmp(param_name, suffix, suffix_len);
9016 }