Merge tag 'f2fs-for-6.5-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk...
[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_lsm.h>
23 #include <linux/skmsg.h>
24 #include <linux/perf_event.h>
25 #include <linux/bsearch.h>
26 #include <linux/kobject.h>
27 #include <linux/sysfs.h>
28
29 #include <net/netfilter/nf_bpf_link.h>
30
31 #include <net/sock.h>
32 #include "../tools/lib/bpf/relo_core.h"
33
34 /* BTF (BPF Type Format) is the meta data format which describes
35  * the data types of BPF program/map.  Hence, it basically focus
36  * on the C programming language which the modern BPF is primary
37  * using.
38  *
39  * ELF Section:
40  * ~~~~~~~~~~~
41  * The BTF data is stored under the ".BTF" ELF section
42  *
43  * struct btf_type:
44  * ~~~~~~~~~~~~~~~
45  * Each 'struct btf_type' object describes a C data type.
46  * Depending on the type it is describing, a 'struct btf_type'
47  * object may be followed by more data.  F.e.
48  * To describe an array, 'struct btf_type' is followed by
49  * 'struct btf_array'.
50  *
51  * 'struct btf_type' and any extra data following it are
52  * 4 bytes aligned.
53  *
54  * Type section:
55  * ~~~~~~~~~~~~~
56  * The BTF type section contains a list of 'struct btf_type' objects.
57  * Each one describes a C type.  Recall from the above section
58  * that a 'struct btf_type' object could be immediately followed by extra
59  * data in order to describe some particular C types.
60  *
61  * type_id:
62  * ~~~~~~~
63  * Each btf_type object is identified by a type_id.  The type_id
64  * is implicitly implied by the location of the btf_type object in
65  * the BTF type section.  The first one has type_id 1.  The second
66  * one has type_id 2...etc.  Hence, an earlier btf_type has
67  * a smaller type_id.
68  *
69  * A btf_type object may refer to another btf_type object by using
70  * type_id (i.e. the "type" in the "struct btf_type").
71  *
72  * NOTE that we cannot assume any reference-order.
73  * A btf_type object can refer to an earlier btf_type object
74  * but it can also refer to a later btf_type object.
75  *
76  * For example, to describe "const void *".  A btf_type
77  * object describing "const" may refer to another btf_type
78  * object describing "void *".  This type-reference is done
79  * by specifying type_id:
80  *
81  * [1] CONST (anon) type_id=2
82  * [2] PTR (anon) type_id=0
83  *
84  * The above is the btf_verifier debug log:
85  *   - Each line started with "[?]" is a btf_type object
86  *   - [?] is the type_id of the btf_type object.
87  *   - CONST/PTR is the BTF_KIND_XXX
88  *   - "(anon)" is the name of the type.  It just
89  *     happens that CONST and PTR has no name.
90  *   - type_id=XXX is the 'u32 type' in btf_type
91  *
92  * NOTE: "void" has type_id 0
93  *
94  * String section:
95  * ~~~~~~~~~~~~~~
96  * The BTF string section contains the names used by the type section.
97  * Each string is referred by an "offset" from the beginning of the
98  * string section.
99  *
100  * Each string is '\0' terminated.
101  *
102  * The first character in the string section must be '\0'
103  * which is used to mean 'anonymous'. Some btf_type may not
104  * have a name.
105  */
106
107 /* BTF verification:
108  *
109  * To verify BTF data, two passes are needed.
110  *
111  * Pass #1
112  * ~~~~~~~
113  * The first pass is to collect all btf_type objects to
114  * an array: "btf->types".
115  *
116  * Depending on the C type that a btf_type is describing,
117  * a btf_type may be followed by extra data.  We don't know
118  * how many btf_type is there, and more importantly we don't
119  * know where each btf_type is located in the type section.
120  *
121  * Without knowing the location of each type_id, most verifications
122  * cannot be done.  e.g. an earlier btf_type may refer to a later
123  * btf_type (recall the "const void *" above), so we cannot
124  * check this type-reference in the first pass.
125  *
126  * In the first pass, it still does some verifications (e.g.
127  * checking the name is a valid offset to the string section).
128  *
129  * Pass #2
130  * ~~~~~~~
131  * The main focus is to resolve a btf_type that is referring
132  * to another type.
133  *
134  * We have to ensure the referring type:
135  * 1) does exist in the BTF (i.e. in btf->types[])
136  * 2) does not cause a loop:
137  *      struct A {
138  *              struct B b;
139  *      };
140  *
141  *      struct B {
142  *              struct A a;
143  *      };
144  *
145  * btf_type_needs_resolve() decides if a btf_type needs
146  * to be resolved.
147  *
148  * The needs_resolve type implements the "resolve()" ops which
149  * essentially does a DFS and detects backedge.
150  *
151  * During resolve (or DFS), different C types have different
152  * "RESOLVED" conditions.
153  *
154  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
155  * members because a member is always referring to another
156  * type.  A struct's member can be treated as "RESOLVED" if
157  * it is referring to a BTF_KIND_PTR.  Otherwise, the
158  * following valid C struct would be rejected:
159  *
160  *      struct A {
161  *              int m;
162  *              struct A *a;
163  *      };
164  *
165  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
166  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
167  * detect a pointer loop, e.g.:
168  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
169  *                        ^                                         |
170  *                        +-----------------------------------------+
171  *
172  */
173
174 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
175 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
176 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
177 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
178 #define BITS_ROUNDUP_BYTES(bits) \
179         (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
180
181 #define BTF_INFO_MASK 0x9f00ffff
182 #define BTF_INT_MASK 0x0fffffff
183 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
184 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
185
186 /* 16MB for 64k structs and each has 16 members and
187  * a few MB spaces for the string section.
188  * The hard limit is S32_MAX.
189  */
190 #define BTF_MAX_SIZE (16 * 1024 * 1024)
191
192 #define for_each_member_from(i, from, struct_type, member)              \
193         for (i = from, member = btf_type_member(struct_type) + from;    \
194              i < btf_type_vlen(struct_type);                            \
195              i++, member++)
196
197 #define for_each_vsi_from(i, from, struct_type, member)                         \
198         for (i = from, member = btf_type_var_secinfo(struct_type) + from;       \
199              i < btf_type_vlen(struct_type);                                    \
200              i++, member++)
201
202 DEFINE_IDR(btf_idr);
203 DEFINE_SPINLOCK(btf_idr_lock);
204
205 enum btf_kfunc_hook {
206         BTF_KFUNC_HOOK_COMMON,
207         BTF_KFUNC_HOOK_XDP,
208         BTF_KFUNC_HOOK_TC,
209         BTF_KFUNC_HOOK_STRUCT_OPS,
210         BTF_KFUNC_HOOK_TRACING,
211         BTF_KFUNC_HOOK_SYSCALL,
212         BTF_KFUNC_HOOK_FMODRET,
213         BTF_KFUNC_HOOK_CGROUP_SKB,
214         BTF_KFUNC_HOOK_SCHED_ACT,
215         BTF_KFUNC_HOOK_SK_SKB,
216         BTF_KFUNC_HOOK_SOCKET_FILTER,
217         BTF_KFUNC_HOOK_LWT,
218         BTF_KFUNC_HOOK_NETFILTER,
219         BTF_KFUNC_HOOK_MAX,
220 };
221
222 enum {
223         BTF_KFUNC_SET_MAX_CNT = 256,
224         BTF_DTOR_KFUNC_MAX_CNT = 256,
225         BTF_KFUNC_FILTER_MAX_CNT = 16,
226 };
227
228 struct btf_kfunc_hook_filter {
229         btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
230         u32 nr_filters;
231 };
232
233 struct btf_kfunc_set_tab {
234         struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
235         struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
236 };
237
238 struct btf_id_dtor_kfunc_tab {
239         u32 cnt;
240         struct btf_id_dtor_kfunc dtors[];
241 };
242
243 struct btf {
244         void *data;
245         struct btf_type **types;
246         u32 *resolved_ids;
247         u32 *resolved_sizes;
248         const char *strings;
249         void *nohdr_data;
250         struct btf_header hdr;
251         u32 nr_types; /* includes VOID for base BTF */
252         u32 types_size;
253         u32 data_size;
254         refcount_t refcnt;
255         u32 id;
256         struct rcu_head rcu;
257         struct btf_kfunc_set_tab *kfunc_set_tab;
258         struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
259         struct btf_struct_metas *struct_meta_tab;
260
261         /* split BTF support */
262         struct btf *base_btf;
263         u32 start_id; /* first type ID in this BTF (0 for base BTF) */
264         u32 start_str_off; /* first string offset (0 for base BTF) */
265         char name[MODULE_NAME_LEN];
266         bool kernel_btf;
267 };
268
269 enum verifier_phase {
270         CHECK_META,
271         CHECK_TYPE,
272 };
273
274 struct resolve_vertex {
275         const struct btf_type *t;
276         u32 type_id;
277         u16 next_member;
278 };
279
280 enum visit_state {
281         NOT_VISITED,
282         VISITED,
283         RESOLVED,
284 };
285
286 enum resolve_mode {
287         RESOLVE_TBD,    /* To Be Determined */
288         RESOLVE_PTR,    /* Resolving for Pointer */
289         RESOLVE_STRUCT_OR_ARRAY,        /* Resolving for struct/union
290                                          * or array
291                                          */
292 };
293
294 #define MAX_RESOLVE_DEPTH 32
295
296 struct btf_sec_info {
297         u32 off;
298         u32 len;
299 };
300
301 struct btf_verifier_env {
302         struct btf *btf;
303         u8 *visit_states;
304         struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
305         struct bpf_verifier_log log;
306         u32 log_type_id;
307         u32 top_stack;
308         enum verifier_phase phase;
309         enum resolve_mode resolve_mode;
310 };
311
312 static const char * const btf_kind_str[NR_BTF_KINDS] = {
313         [BTF_KIND_UNKN]         = "UNKNOWN",
314         [BTF_KIND_INT]          = "INT",
315         [BTF_KIND_PTR]          = "PTR",
316         [BTF_KIND_ARRAY]        = "ARRAY",
317         [BTF_KIND_STRUCT]       = "STRUCT",
318         [BTF_KIND_UNION]        = "UNION",
319         [BTF_KIND_ENUM]         = "ENUM",
320         [BTF_KIND_FWD]          = "FWD",
321         [BTF_KIND_TYPEDEF]      = "TYPEDEF",
322         [BTF_KIND_VOLATILE]     = "VOLATILE",
323         [BTF_KIND_CONST]        = "CONST",
324         [BTF_KIND_RESTRICT]     = "RESTRICT",
325         [BTF_KIND_FUNC]         = "FUNC",
326         [BTF_KIND_FUNC_PROTO]   = "FUNC_PROTO",
327         [BTF_KIND_VAR]          = "VAR",
328         [BTF_KIND_DATASEC]      = "DATASEC",
329         [BTF_KIND_FLOAT]        = "FLOAT",
330         [BTF_KIND_DECL_TAG]     = "DECL_TAG",
331         [BTF_KIND_TYPE_TAG]     = "TYPE_TAG",
332         [BTF_KIND_ENUM64]       = "ENUM64",
333 };
334
335 const char *btf_type_str(const struct btf_type *t)
336 {
337         return btf_kind_str[BTF_INFO_KIND(t->info)];
338 }
339
340 /* Chunk size we use in safe copy of data to be shown. */
341 #define BTF_SHOW_OBJ_SAFE_SIZE          32
342
343 /*
344  * This is the maximum size of a base type value (equivalent to a
345  * 128-bit int); if we are at the end of our safe buffer and have
346  * less than 16 bytes space we can't be assured of being able
347  * to copy the next type safely, so in such cases we will initiate
348  * a new copy.
349  */
350 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE     16
351
352 /* Type name size */
353 #define BTF_SHOW_NAME_SIZE              80
354
355 /*
356  * The suffix of a type that indicates it cannot alias another type when
357  * comparing BTF IDs for kfunc invocations.
358  */
359 #define NOCAST_ALIAS_SUFFIX             "___init"
360
361 /*
362  * Common data to all BTF show operations. Private show functions can add
363  * their own data to a structure containing a struct btf_show and consult it
364  * in the show callback.  See btf_type_show() below.
365  *
366  * One challenge with showing nested data is we want to skip 0-valued
367  * data, but in order to figure out whether a nested object is all zeros
368  * we need to walk through it.  As a result, we need to make two passes
369  * when handling structs, unions and arrays; the first path simply looks
370  * for nonzero data, while the second actually does the display.  The first
371  * pass is signalled by show->state.depth_check being set, and if we
372  * encounter a non-zero value we set show->state.depth_to_show to
373  * the depth at which we encountered it.  When we have completed the
374  * first pass, we will know if anything needs to be displayed if
375  * depth_to_show > depth.  See btf_[struct,array]_show() for the
376  * implementation of this.
377  *
378  * Another problem is we want to ensure the data for display is safe to
379  * access.  To support this, the anonymous "struct {} obj" tracks the data
380  * object and our safe copy of it.  We copy portions of the data needed
381  * to the object "copy" buffer, but because its size is limited to
382  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
383  * traverse larger objects for display.
384  *
385  * The various data type show functions all start with a call to
386  * btf_show_start_type() which returns a pointer to the safe copy
387  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
388  * raw data itself).  btf_show_obj_safe() is responsible for
389  * using copy_from_kernel_nofault() to update the safe data if necessary
390  * as we traverse the object's data.  skbuff-like semantics are
391  * used:
392  *
393  * - obj.head points to the start of the toplevel object for display
394  * - obj.size is the size of the toplevel object
395  * - obj.data points to the current point in the original data at
396  *   which our safe data starts.  obj.data will advance as we copy
397  *   portions of the data.
398  *
399  * In most cases a single copy will suffice, but larger data structures
400  * such as "struct task_struct" will require many copies.  The logic in
401  * btf_show_obj_safe() handles the logic that determines if a new
402  * copy_from_kernel_nofault() is needed.
403  */
404 struct btf_show {
405         u64 flags;
406         void *target;   /* target of show operation (seq file, buffer) */
407         void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
408         const struct btf *btf;
409         /* below are used during iteration */
410         struct {
411                 u8 depth;
412                 u8 depth_to_show;
413                 u8 depth_check;
414                 u8 array_member:1,
415                    array_terminated:1;
416                 u16 array_encoding;
417                 u32 type_id;
418                 int status;                     /* non-zero for error */
419                 const struct btf_type *type;
420                 const struct btf_member *member;
421                 char name[BTF_SHOW_NAME_SIZE];  /* space for member name/type */
422         } state;
423         struct {
424                 u32 size;
425                 void *head;
426                 void *data;
427                 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
428         } obj;
429 };
430
431 struct btf_kind_operations {
432         s32 (*check_meta)(struct btf_verifier_env *env,
433                           const struct btf_type *t,
434                           u32 meta_left);
435         int (*resolve)(struct btf_verifier_env *env,
436                        const struct resolve_vertex *v);
437         int (*check_member)(struct btf_verifier_env *env,
438                             const struct btf_type *struct_type,
439                             const struct btf_member *member,
440                             const struct btf_type *member_type);
441         int (*check_kflag_member)(struct btf_verifier_env *env,
442                                   const struct btf_type *struct_type,
443                                   const struct btf_member *member,
444                                   const struct btf_type *member_type);
445         void (*log_details)(struct btf_verifier_env *env,
446                             const struct btf_type *t);
447         void (*show)(const struct btf *btf, const struct btf_type *t,
448                          u32 type_id, void *data, u8 bits_offsets,
449                          struct btf_show *show);
450 };
451
452 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
453 static struct btf_type btf_void;
454
455 static int btf_resolve(struct btf_verifier_env *env,
456                        const struct btf_type *t, u32 type_id);
457
458 static int btf_func_check(struct btf_verifier_env *env,
459                           const struct btf_type *t);
460
461 static bool btf_type_is_modifier(const struct btf_type *t)
462 {
463         /* Some of them is not strictly a C modifier
464          * but they are grouped into the same bucket
465          * for BTF concern:
466          *   A type (t) that refers to another
467          *   type through t->type AND its size cannot
468          *   be determined without following the t->type.
469          *
470          * ptr does not fall into this bucket
471          * because its size is always sizeof(void *).
472          */
473         switch (BTF_INFO_KIND(t->info)) {
474         case BTF_KIND_TYPEDEF:
475         case BTF_KIND_VOLATILE:
476         case BTF_KIND_CONST:
477         case BTF_KIND_RESTRICT:
478         case BTF_KIND_TYPE_TAG:
479                 return true;
480         }
481
482         return false;
483 }
484
485 bool btf_type_is_void(const struct btf_type *t)
486 {
487         return t == &btf_void;
488 }
489
490 static bool btf_type_is_fwd(const struct btf_type *t)
491 {
492         return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
493 }
494
495 static bool btf_type_is_datasec(const struct btf_type *t)
496 {
497         return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
498 }
499
500 static bool btf_type_is_decl_tag(const struct btf_type *t)
501 {
502         return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
503 }
504
505 static bool btf_type_nosize(const struct btf_type *t)
506 {
507         return btf_type_is_void(t) || btf_type_is_fwd(t) ||
508                btf_type_is_func(t) || btf_type_is_func_proto(t) ||
509                btf_type_is_decl_tag(t);
510 }
511
512 static bool btf_type_nosize_or_null(const struct btf_type *t)
513 {
514         return !t || btf_type_nosize(t);
515 }
516
517 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
518 {
519         return btf_type_is_func(t) || btf_type_is_struct(t) ||
520                btf_type_is_var(t) || btf_type_is_typedef(t);
521 }
522
523 u32 btf_nr_types(const struct btf *btf)
524 {
525         u32 total = 0;
526
527         while (btf) {
528                 total += btf->nr_types;
529                 btf = btf->base_btf;
530         }
531
532         return total;
533 }
534
535 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
536 {
537         const struct btf_type *t;
538         const char *tname;
539         u32 i, total;
540
541         total = btf_nr_types(btf);
542         for (i = 1; i < total; i++) {
543                 t = btf_type_by_id(btf, i);
544                 if (BTF_INFO_KIND(t->info) != kind)
545                         continue;
546
547                 tname = btf_name_by_offset(btf, t->name_off);
548                 if (!strcmp(tname, name))
549                         return i;
550         }
551
552         return -ENOENT;
553 }
554
555 static s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
556 {
557         struct btf *btf;
558         s32 ret;
559         int id;
560
561         btf = bpf_get_btf_vmlinux();
562         if (IS_ERR(btf))
563                 return PTR_ERR(btf);
564         if (!btf)
565                 return -EINVAL;
566
567         ret = btf_find_by_name_kind(btf, name, kind);
568         /* ret is never zero, since btf_find_by_name_kind returns
569          * positive btf_id or negative error.
570          */
571         if (ret > 0) {
572                 btf_get(btf);
573                 *btf_p = btf;
574                 return ret;
575         }
576
577         /* If name is not found in vmlinux's BTF then search in module's BTFs */
578         spin_lock_bh(&btf_idr_lock);
579         idr_for_each_entry(&btf_idr, btf, id) {
580                 if (!btf_is_module(btf))
581                         continue;
582                 /* linear search could be slow hence unlock/lock
583                  * the IDR to avoiding holding it for too long
584                  */
585                 btf_get(btf);
586                 spin_unlock_bh(&btf_idr_lock);
587                 ret = btf_find_by_name_kind(btf, name, kind);
588                 if (ret > 0) {
589                         *btf_p = btf;
590                         return ret;
591                 }
592                 btf_put(btf);
593                 spin_lock_bh(&btf_idr_lock);
594         }
595         spin_unlock_bh(&btf_idr_lock);
596         return ret;
597 }
598
599 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
600                                                u32 id, u32 *res_id)
601 {
602         const struct btf_type *t = btf_type_by_id(btf, id);
603
604         while (btf_type_is_modifier(t)) {
605                 id = t->type;
606                 t = btf_type_by_id(btf, t->type);
607         }
608
609         if (res_id)
610                 *res_id = id;
611
612         return t;
613 }
614
615 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
616                                             u32 id, u32 *res_id)
617 {
618         const struct btf_type *t;
619
620         t = btf_type_skip_modifiers(btf, id, NULL);
621         if (!btf_type_is_ptr(t))
622                 return NULL;
623
624         return btf_type_skip_modifiers(btf, t->type, res_id);
625 }
626
627 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
628                                                  u32 id, u32 *res_id)
629 {
630         const struct btf_type *ptype;
631
632         ptype = btf_type_resolve_ptr(btf, id, res_id);
633         if (ptype && btf_type_is_func_proto(ptype))
634                 return ptype;
635
636         return NULL;
637 }
638
639 /* Types that act only as a source, not sink or intermediate
640  * type when resolving.
641  */
642 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
643 {
644         return btf_type_is_var(t) ||
645                btf_type_is_decl_tag(t) ||
646                btf_type_is_datasec(t);
647 }
648
649 /* What types need to be resolved?
650  *
651  * btf_type_is_modifier() is an obvious one.
652  *
653  * btf_type_is_struct() because its member refers to
654  * another type (through member->type).
655  *
656  * btf_type_is_var() because the variable refers to
657  * another type. btf_type_is_datasec() holds multiple
658  * btf_type_is_var() types that need resolving.
659  *
660  * btf_type_is_array() because its element (array->type)
661  * refers to another type.  Array can be thought of a
662  * special case of struct while array just has the same
663  * member-type repeated by array->nelems of times.
664  */
665 static bool btf_type_needs_resolve(const struct btf_type *t)
666 {
667         return btf_type_is_modifier(t) ||
668                btf_type_is_ptr(t) ||
669                btf_type_is_struct(t) ||
670                btf_type_is_array(t) ||
671                btf_type_is_var(t) ||
672                btf_type_is_func(t) ||
673                btf_type_is_decl_tag(t) ||
674                btf_type_is_datasec(t);
675 }
676
677 /* t->size can be used */
678 static bool btf_type_has_size(const struct btf_type *t)
679 {
680         switch (BTF_INFO_KIND(t->info)) {
681         case BTF_KIND_INT:
682         case BTF_KIND_STRUCT:
683         case BTF_KIND_UNION:
684         case BTF_KIND_ENUM:
685         case BTF_KIND_DATASEC:
686         case BTF_KIND_FLOAT:
687         case BTF_KIND_ENUM64:
688                 return true;
689         }
690
691         return false;
692 }
693
694 static const char *btf_int_encoding_str(u8 encoding)
695 {
696         if (encoding == 0)
697                 return "(none)";
698         else if (encoding == BTF_INT_SIGNED)
699                 return "SIGNED";
700         else if (encoding == BTF_INT_CHAR)
701                 return "CHAR";
702         else if (encoding == BTF_INT_BOOL)
703                 return "BOOL";
704         else
705                 return "UNKN";
706 }
707
708 static u32 btf_type_int(const struct btf_type *t)
709 {
710         return *(u32 *)(t + 1);
711 }
712
713 static const struct btf_array *btf_type_array(const struct btf_type *t)
714 {
715         return (const struct btf_array *)(t + 1);
716 }
717
718 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
719 {
720         return (const struct btf_enum *)(t + 1);
721 }
722
723 static const struct btf_var *btf_type_var(const struct btf_type *t)
724 {
725         return (const struct btf_var *)(t + 1);
726 }
727
728 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
729 {
730         return (const struct btf_decl_tag *)(t + 1);
731 }
732
733 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
734 {
735         return (const struct btf_enum64 *)(t + 1);
736 }
737
738 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
739 {
740         return kind_ops[BTF_INFO_KIND(t->info)];
741 }
742
743 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
744 {
745         if (!BTF_STR_OFFSET_VALID(offset))
746                 return false;
747
748         while (offset < btf->start_str_off)
749                 btf = btf->base_btf;
750
751         offset -= btf->start_str_off;
752         return offset < btf->hdr.str_len;
753 }
754
755 static bool __btf_name_char_ok(char c, bool first)
756 {
757         if ((first ? !isalpha(c) :
758                      !isalnum(c)) &&
759             c != '_' &&
760             c != '.')
761                 return false;
762         return true;
763 }
764
765 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
766 {
767         while (offset < btf->start_str_off)
768                 btf = btf->base_btf;
769
770         offset -= btf->start_str_off;
771         if (offset < btf->hdr.str_len)
772                 return &btf->strings[offset];
773
774         return NULL;
775 }
776
777 static bool __btf_name_valid(const struct btf *btf, u32 offset)
778 {
779         /* offset must be valid */
780         const char *src = btf_str_by_offset(btf, offset);
781         const char *src_limit;
782
783         if (!__btf_name_char_ok(*src, true))
784                 return false;
785
786         /* set a limit on identifier length */
787         src_limit = src + KSYM_NAME_LEN;
788         src++;
789         while (*src && src < src_limit) {
790                 if (!__btf_name_char_ok(*src, false))
791                         return false;
792                 src++;
793         }
794
795         return !*src;
796 }
797
798 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
799 {
800         return __btf_name_valid(btf, offset);
801 }
802
803 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
804 {
805         return __btf_name_valid(btf, offset);
806 }
807
808 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
809 {
810         const char *name;
811
812         if (!offset)
813                 return "(anon)";
814
815         name = btf_str_by_offset(btf, offset);
816         return name ?: "(invalid-name-offset)";
817 }
818
819 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
820 {
821         return btf_str_by_offset(btf, offset);
822 }
823
824 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
825 {
826         while (type_id < btf->start_id)
827                 btf = btf->base_btf;
828
829         type_id -= btf->start_id;
830         if (type_id >= btf->nr_types)
831                 return NULL;
832         return btf->types[type_id];
833 }
834 EXPORT_SYMBOL_GPL(btf_type_by_id);
835
836 /*
837  * Regular int is not a bit field and it must be either
838  * u8/u16/u32/u64 or __int128.
839  */
840 static bool btf_type_int_is_regular(const struct btf_type *t)
841 {
842         u8 nr_bits, nr_bytes;
843         u32 int_data;
844
845         int_data = btf_type_int(t);
846         nr_bits = BTF_INT_BITS(int_data);
847         nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
848         if (BITS_PER_BYTE_MASKED(nr_bits) ||
849             BTF_INT_OFFSET(int_data) ||
850             (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
851              nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
852              nr_bytes != (2 * sizeof(u64)))) {
853                 return false;
854         }
855
856         return true;
857 }
858
859 /*
860  * Check that given struct member is a regular int with expected
861  * offset and size.
862  */
863 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
864                            const struct btf_member *m,
865                            u32 expected_offset, u32 expected_size)
866 {
867         const struct btf_type *t;
868         u32 id, int_data;
869         u8 nr_bits;
870
871         id = m->type;
872         t = btf_type_id_size(btf, &id, NULL);
873         if (!t || !btf_type_is_int(t))
874                 return false;
875
876         int_data = btf_type_int(t);
877         nr_bits = BTF_INT_BITS(int_data);
878         if (btf_type_kflag(s)) {
879                 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
880                 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
881
882                 /* if kflag set, int should be a regular int and
883                  * bit offset should be at byte boundary.
884                  */
885                 return !bitfield_size &&
886                        BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
887                        BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
888         }
889
890         if (BTF_INT_OFFSET(int_data) ||
891             BITS_PER_BYTE_MASKED(m->offset) ||
892             BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
893             BITS_PER_BYTE_MASKED(nr_bits) ||
894             BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
895                 return false;
896
897         return true;
898 }
899
900 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
901 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
902                                                        u32 id)
903 {
904         const struct btf_type *t = btf_type_by_id(btf, id);
905
906         while (btf_type_is_modifier(t) &&
907                BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
908                 t = btf_type_by_id(btf, t->type);
909         }
910
911         return t;
912 }
913
914 #define BTF_SHOW_MAX_ITER       10
915
916 #define BTF_KIND_BIT(kind)      (1ULL << kind)
917
918 /*
919  * Populate show->state.name with type name information.
920  * Format of type name is
921  *
922  * [.member_name = ] (type_name)
923  */
924 static const char *btf_show_name(struct btf_show *show)
925 {
926         /* BTF_MAX_ITER array suffixes "[]" */
927         const char *array_suffixes = "[][][][][][][][][][]";
928         const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
929         /* BTF_MAX_ITER pointer suffixes "*" */
930         const char *ptr_suffixes = "**********";
931         const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
932         const char *name = NULL, *prefix = "", *parens = "";
933         const struct btf_member *m = show->state.member;
934         const struct btf_type *t;
935         const struct btf_array *array;
936         u32 id = show->state.type_id;
937         const char *member = NULL;
938         bool show_member = false;
939         u64 kinds = 0;
940         int i;
941
942         show->state.name[0] = '\0';
943
944         /*
945          * Don't show type name if we're showing an array member;
946          * in that case we show the array type so don't need to repeat
947          * ourselves for each member.
948          */
949         if (show->state.array_member)
950                 return "";
951
952         /* Retrieve member name, if any. */
953         if (m) {
954                 member = btf_name_by_offset(show->btf, m->name_off);
955                 show_member = strlen(member) > 0;
956                 id = m->type;
957         }
958
959         /*
960          * Start with type_id, as we have resolved the struct btf_type *
961          * via btf_modifier_show() past the parent typedef to the child
962          * struct, int etc it is defined as.  In such cases, the type_id
963          * still represents the starting type while the struct btf_type *
964          * in our show->state points at the resolved type of the typedef.
965          */
966         t = btf_type_by_id(show->btf, id);
967         if (!t)
968                 return "";
969
970         /*
971          * The goal here is to build up the right number of pointer and
972          * array suffixes while ensuring the type name for a typedef
973          * is represented.  Along the way we accumulate a list of
974          * BTF kinds we have encountered, since these will inform later
975          * display; for example, pointer types will not require an
976          * opening "{" for struct, we will just display the pointer value.
977          *
978          * We also want to accumulate the right number of pointer or array
979          * indices in the format string while iterating until we get to
980          * the typedef/pointee/array member target type.
981          *
982          * We start by pointing at the end of pointer and array suffix
983          * strings; as we accumulate pointers and arrays we move the pointer
984          * or array string backwards so it will show the expected number of
985          * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
986          * and/or arrays and typedefs are supported as a precaution.
987          *
988          * We also want to get typedef name while proceeding to resolve
989          * type it points to so that we can add parentheses if it is a
990          * "typedef struct" etc.
991          */
992         for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
993
994                 switch (BTF_INFO_KIND(t->info)) {
995                 case BTF_KIND_TYPEDEF:
996                         if (!name)
997                                 name = btf_name_by_offset(show->btf,
998                                                                t->name_off);
999                         kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1000                         id = t->type;
1001                         break;
1002                 case BTF_KIND_ARRAY:
1003                         kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1004                         parens = "[";
1005                         if (!t)
1006                                 return "";
1007                         array = btf_type_array(t);
1008                         if (array_suffix > array_suffixes)
1009                                 array_suffix -= 2;
1010                         id = array->type;
1011                         break;
1012                 case BTF_KIND_PTR:
1013                         kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1014                         if (ptr_suffix > ptr_suffixes)
1015                                 ptr_suffix -= 1;
1016                         id = t->type;
1017                         break;
1018                 default:
1019                         id = 0;
1020                         break;
1021                 }
1022                 if (!id)
1023                         break;
1024                 t = btf_type_skip_qualifiers(show->btf, id);
1025         }
1026         /* We may not be able to represent this type; bail to be safe */
1027         if (i == BTF_SHOW_MAX_ITER)
1028                 return "";
1029
1030         if (!name)
1031                 name = btf_name_by_offset(show->btf, t->name_off);
1032
1033         switch (BTF_INFO_KIND(t->info)) {
1034         case BTF_KIND_STRUCT:
1035         case BTF_KIND_UNION:
1036                 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1037                          "struct" : "union";
1038                 /* if it's an array of struct/union, parens is already set */
1039                 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1040                         parens = "{";
1041                 break;
1042         case BTF_KIND_ENUM:
1043         case BTF_KIND_ENUM64:
1044                 prefix = "enum";
1045                 break;
1046         default:
1047                 break;
1048         }
1049
1050         /* pointer does not require parens */
1051         if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1052                 parens = "";
1053         /* typedef does not require struct/union/enum prefix */
1054         if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1055                 prefix = "";
1056
1057         if (!name)
1058                 name = "";
1059
1060         /* Even if we don't want type name info, we want parentheses etc */
1061         if (show->flags & BTF_SHOW_NONAME)
1062                 snprintf(show->state.name, sizeof(show->state.name), "%s",
1063                          parens);
1064         else
1065                 snprintf(show->state.name, sizeof(show->state.name),
1066                          "%s%s%s(%s%s%s%s%s%s)%s",
1067                          /* first 3 strings comprise ".member = " */
1068                          show_member ? "." : "",
1069                          show_member ? member : "",
1070                          show_member ? " = " : "",
1071                          /* ...next is our prefix (struct, enum, etc) */
1072                          prefix,
1073                          strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1074                          /* ...this is the type name itself */
1075                          name,
1076                          /* ...suffixed by the appropriate '*', '[]' suffixes */
1077                          strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1078                          array_suffix, parens);
1079
1080         return show->state.name;
1081 }
1082
1083 static const char *__btf_show_indent(struct btf_show *show)
1084 {
1085         const char *indents = "                                ";
1086         const char *indent = &indents[strlen(indents)];
1087
1088         if ((indent - show->state.depth) >= indents)
1089                 return indent - show->state.depth;
1090         return indents;
1091 }
1092
1093 static const char *btf_show_indent(struct btf_show *show)
1094 {
1095         return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1096 }
1097
1098 static const char *btf_show_newline(struct btf_show *show)
1099 {
1100         return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1101 }
1102
1103 static const char *btf_show_delim(struct btf_show *show)
1104 {
1105         if (show->state.depth == 0)
1106                 return "";
1107
1108         if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1109                 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1110                 return "|";
1111
1112         return ",";
1113 }
1114
1115 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1116 {
1117         va_list args;
1118
1119         if (!show->state.depth_check) {
1120                 va_start(args, fmt);
1121                 show->showfn(show, fmt, args);
1122                 va_end(args);
1123         }
1124 }
1125
1126 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1127  * format specifiers to the format specifier passed in; these do the work of
1128  * adding indentation, delimiters etc while the caller simply has to specify
1129  * the type value(s) in the format specifier + value(s).
1130  */
1131 #define btf_show_type_value(show, fmt, value)                                  \
1132         do {                                                                   \
1133                 if ((value) != (__typeof__(value))0 ||                         \
1134                     (show->flags & BTF_SHOW_ZERO) ||                           \
1135                     show->state.depth == 0) {                                  \
1136                         btf_show(show, "%s%s" fmt "%s%s",                      \
1137                                  btf_show_indent(show),                        \
1138                                  btf_show_name(show),                          \
1139                                  value, btf_show_delim(show),                  \
1140                                  btf_show_newline(show));                      \
1141                         if (show->state.depth > show->state.depth_to_show)     \
1142                                 show->state.depth_to_show = show->state.depth; \
1143                 }                                                              \
1144         } while (0)
1145
1146 #define btf_show_type_values(show, fmt, ...)                                   \
1147         do {                                                                   \
1148                 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1149                          btf_show_name(show),                                  \
1150                          __VA_ARGS__, btf_show_delim(show),                    \
1151                          btf_show_newline(show));                              \
1152                 if (show->state.depth > show->state.depth_to_show)             \
1153                         show->state.depth_to_show = show->state.depth;         \
1154         } while (0)
1155
1156 /* How much is left to copy to safe buffer after @data? */
1157 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1158 {
1159         return show->obj.head + show->obj.size - data;
1160 }
1161
1162 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1163 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1164 {
1165         return data >= show->obj.data &&
1166                (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1167 }
1168
1169 /*
1170  * If object pointed to by @data of @size falls within our safe buffer, return
1171  * the equivalent pointer to the same safe data.  Assumes
1172  * copy_from_kernel_nofault() has already happened and our safe buffer is
1173  * populated.
1174  */
1175 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1176 {
1177         if (btf_show_obj_is_safe(show, data, size))
1178                 return show->obj.safe + (data - show->obj.data);
1179         return NULL;
1180 }
1181
1182 /*
1183  * Return a safe-to-access version of data pointed to by @data.
1184  * We do this by copying the relevant amount of information
1185  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1186  *
1187  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1188  * safe copy is needed.
1189  *
1190  * Otherwise we need to determine if we have the required amount
1191  * of data (determined by the @data pointer and the size of the
1192  * largest base type we can encounter (represented by
1193  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1194  * that we will be able to print some of the current object,
1195  * and if more is needed a copy will be triggered.
1196  * Some objects such as structs will not fit into the buffer;
1197  * in such cases additional copies when we iterate over their
1198  * members may be needed.
1199  *
1200  * btf_show_obj_safe() is used to return a safe buffer for
1201  * btf_show_start_type(); this ensures that as we recurse into
1202  * nested types we always have safe data for the given type.
1203  * This approach is somewhat wasteful; it's possible for example
1204  * that when iterating over a large union we'll end up copying the
1205  * same data repeatedly, but the goal is safety not performance.
1206  * We use stack data as opposed to per-CPU buffers because the
1207  * iteration over a type can take some time, and preemption handling
1208  * would greatly complicate use of the safe buffer.
1209  */
1210 static void *btf_show_obj_safe(struct btf_show *show,
1211                                const struct btf_type *t,
1212                                void *data)
1213 {
1214         const struct btf_type *rt;
1215         int size_left, size;
1216         void *safe = NULL;
1217
1218         if (show->flags & BTF_SHOW_UNSAFE)
1219                 return data;
1220
1221         rt = btf_resolve_size(show->btf, t, &size);
1222         if (IS_ERR(rt)) {
1223                 show->state.status = PTR_ERR(rt);
1224                 return NULL;
1225         }
1226
1227         /*
1228          * Is this toplevel object? If so, set total object size and
1229          * initialize pointers.  Otherwise check if we still fall within
1230          * our safe object data.
1231          */
1232         if (show->state.depth == 0) {
1233                 show->obj.size = size;
1234                 show->obj.head = data;
1235         } else {
1236                 /*
1237                  * If the size of the current object is > our remaining
1238                  * safe buffer we _may_ need to do a new copy.  However
1239                  * consider the case of a nested struct; it's size pushes
1240                  * us over the safe buffer limit, but showing any individual
1241                  * struct members does not.  In such cases, we don't need
1242                  * to initiate a fresh copy yet; however we definitely need
1243                  * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1244                  * in our buffer, regardless of the current object size.
1245                  * The logic here is that as we resolve types we will
1246                  * hit a base type at some point, and we need to be sure
1247                  * the next chunk of data is safely available to display
1248                  * that type info safely.  We cannot rely on the size of
1249                  * the current object here because it may be much larger
1250                  * than our current buffer (e.g. task_struct is 8k).
1251                  * All we want to do here is ensure that we can print the
1252                  * next basic type, which we can if either
1253                  * - the current type size is within the safe buffer; or
1254                  * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1255                  *   the safe buffer.
1256                  */
1257                 safe = __btf_show_obj_safe(show, data,
1258                                            min(size,
1259                                                BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1260         }
1261
1262         /*
1263          * We need a new copy to our safe object, either because we haven't
1264          * yet copied and are initializing safe data, or because the data
1265          * we want falls outside the boundaries of the safe object.
1266          */
1267         if (!safe) {
1268                 size_left = btf_show_obj_size_left(show, data);
1269                 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1270                         size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1271                 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1272                                                               data, size_left);
1273                 if (!show->state.status) {
1274                         show->obj.data = data;
1275                         safe = show->obj.safe;
1276                 }
1277         }
1278
1279         return safe;
1280 }
1281
1282 /*
1283  * Set the type we are starting to show and return a safe data pointer
1284  * to be used for showing the associated data.
1285  */
1286 static void *btf_show_start_type(struct btf_show *show,
1287                                  const struct btf_type *t,
1288                                  u32 type_id, void *data)
1289 {
1290         show->state.type = t;
1291         show->state.type_id = type_id;
1292         show->state.name[0] = '\0';
1293
1294         return btf_show_obj_safe(show, t, data);
1295 }
1296
1297 static void btf_show_end_type(struct btf_show *show)
1298 {
1299         show->state.type = NULL;
1300         show->state.type_id = 0;
1301         show->state.name[0] = '\0';
1302 }
1303
1304 static void *btf_show_start_aggr_type(struct btf_show *show,
1305                                       const struct btf_type *t,
1306                                       u32 type_id, void *data)
1307 {
1308         void *safe_data = btf_show_start_type(show, t, type_id, data);
1309
1310         if (!safe_data)
1311                 return safe_data;
1312
1313         btf_show(show, "%s%s%s", btf_show_indent(show),
1314                  btf_show_name(show),
1315                  btf_show_newline(show));
1316         show->state.depth++;
1317         return safe_data;
1318 }
1319
1320 static void btf_show_end_aggr_type(struct btf_show *show,
1321                                    const char *suffix)
1322 {
1323         show->state.depth--;
1324         btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1325                  btf_show_delim(show), btf_show_newline(show));
1326         btf_show_end_type(show);
1327 }
1328
1329 static void btf_show_start_member(struct btf_show *show,
1330                                   const struct btf_member *m)
1331 {
1332         show->state.member = m;
1333 }
1334
1335 static void btf_show_start_array_member(struct btf_show *show)
1336 {
1337         show->state.array_member = 1;
1338         btf_show_start_member(show, NULL);
1339 }
1340
1341 static void btf_show_end_member(struct btf_show *show)
1342 {
1343         show->state.member = NULL;
1344 }
1345
1346 static void btf_show_end_array_member(struct btf_show *show)
1347 {
1348         show->state.array_member = 0;
1349         btf_show_end_member(show);
1350 }
1351
1352 static void *btf_show_start_array_type(struct btf_show *show,
1353                                        const struct btf_type *t,
1354                                        u32 type_id,
1355                                        u16 array_encoding,
1356                                        void *data)
1357 {
1358         show->state.array_encoding = array_encoding;
1359         show->state.array_terminated = 0;
1360         return btf_show_start_aggr_type(show, t, type_id, data);
1361 }
1362
1363 static void btf_show_end_array_type(struct btf_show *show)
1364 {
1365         show->state.array_encoding = 0;
1366         show->state.array_terminated = 0;
1367         btf_show_end_aggr_type(show, "]");
1368 }
1369
1370 static void *btf_show_start_struct_type(struct btf_show *show,
1371                                         const struct btf_type *t,
1372                                         u32 type_id,
1373                                         void *data)
1374 {
1375         return btf_show_start_aggr_type(show, t, type_id, data);
1376 }
1377
1378 static void btf_show_end_struct_type(struct btf_show *show)
1379 {
1380         btf_show_end_aggr_type(show, "}");
1381 }
1382
1383 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1384                                               const char *fmt, ...)
1385 {
1386         va_list args;
1387
1388         va_start(args, fmt);
1389         bpf_verifier_vlog(log, fmt, args);
1390         va_end(args);
1391 }
1392
1393 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1394                                             const char *fmt, ...)
1395 {
1396         struct bpf_verifier_log *log = &env->log;
1397         va_list args;
1398
1399         if (!bpf_verifier_log_needed(log))
1400                 return;
1401
1402         va_start(args, fmt);
1403         bpf_verifier_vlog(log, fmt, args);
1404         va_end(args);
1405 }
1406
1407 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1408                                                    const struct btf_type *t,
1409                                                    bool log_details,
1410                                                    const char *fmt, ...)
1411 {
1412         struct bpf_verifier_log *log = &env->log;
1413         struct btf *btf = env->btf;
1414         va_list args;
1415
1416         if (!bpf_verifier_log_needed(log))
1417                 return;
1418
1419         if (log->level == BPF_LOG_KERNEL) {
1420                 /* btf verifier prints all types it is processing via
1421                  * btf_verifier_log_type(..., fmt = NULL).
1422                  * Skip those prints for in-kernel BTF verification.
1423                  */
1424                 if (!fmt)
1425                         return;
1426
1427                 /* Skip logging when loading module BTF with mismatches permitted */
1428                 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1429                         return;
1430         }
1431
1432         __btf_verifier_log(log, "[%u] %s %s%s",
1433                            env->log_type_id,
1434                            btf_type_str(t),
1435                            __btf_name_by_offset(btf, t->name_off),
1436                            log_details ? " " : "");
1437
1438         if (log_details)
1439                 btf_type_ops(t)->log_details(env, t);
1440
1441         if (fmt && *fmt) {
1442                 __btf_verifier_log(log, " ");
1443                 va_start(args, fmt);
1444                 bpf_verifier_vlog(log, fmt, args);
1445                 va_end(args);
1446         }
1447
1448         __btf_verifier_log(log, "\n");
1449 }
1450
1451 #define btf_verifier_log_type(env, t, ...) \
1452         __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1453 #define btf_verifier_log_basic(env, t, ...) \
1454         __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1455
1456 __printf(4, 5)
1457 static void btf_verifier_log_member(struct btf_verifier_env *env,
1458                                     const struct btf_type *struct_type,
1459                                     const struct btf_member *member,
1460                                     const char *fmt, ...)
1461 {
1462         struct bpf_verifier_log *log = &env->log;
1463         struct btf *btf = env->btf;
1464         va_list args;
1465
1466         if (!bpf_verifier_log_needed(log))
1467                 return;
1468
1469         if (log->level == BPF_LOG_KERNEL) {
1470                 if (!fmt)
1471                         return;
1472
1473                 /* Skip logging when loading module BTF with mismatches permitted */
1474                 if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1475                         return;
1476         }
1477
1478         /* The CHECK_META phase already did a btf dump.
1479          *
1480          * If member is logged again, it must hit an error in
1481          * parsing this member.  It is useful to print out which
1482          * struct this member belongs to.
1483          */
1484         if (env->phase != CHECK_META)
1485                 btf_verifier_log_type(env, struct_type, NULL);
1486
1487         if (btf_type_kflag(struct_type))
1488                 __btf_verifier_log(log,
1489                                    "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1490                                    __btf_name_by_offset(btf, member->name_off),
1491                                    member->type,
1492                                    BTF_MEMBER_BITFIELD_SIZE(member->offset),
1493                                    BTF_MEMBER_BIT_OFFSET(member->offset));
1494         else
1495                 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1496                                    __btf_name_by_offset(btf, member->name_off),
1497                                    member->type, member->offset);
1498
1499         if (fmt && *fmt) {
1500                 __btf_verifier_log(log, " ");
1501                 va_start(args, fmt);
1502                 bpf_verifier_vlog(log, fmt, args);
1503                 va_end(args);
1504         }
1505
1506         __btf_verifier_log(log, "\n");
1507 }
1508
1509 __printf(4, 5)
1510 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1511                                  const struct btf_type *datasec_type,
1512                                  const struct btf_var_secinfo *vsi,
1513                                  const char *fmt, ...)
1514 {
1515         struct bpf_verifier_log *log = &env->log;
1516         va_list args;
1517
1518         if (!bpf_verifier_log_needed(log))
1519                 return;
1520         if (log->level == BPF_LOG_KERNEL && !fmt)
1521                 return;
1522         if (env->phase != CHECK_META)
1523                 btf_verifier_log_type(env, datasec_type, NULL);
1524
1525         __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1526                            vsi->type, vsi->offset, vsi->size);
1527         if (fmt && *fmt) {
1528                 __btf_verifier_log(log, " ");
1529                 va_start(args, fmt);
1530                 bpf_verifier_vlog(log, fmt, args);
1531                 va_end(args);
1532         }
1533
1534         __btf_verifier_log(log, "\n");
1535 }
1536
1537 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1538                                  u32 btf_data_size)
1539 {
1540         struct bpf_verifier_log *log = &env->log;
1541         const struct btf *btf = env->btf;
1542         const struct btf_header *hdr;
1543
1544         if (!bpf_verifier_log_needed(log))
1545                 return;
1546
1547         if (log->level == BPF_LOG_KERNEL)
1548                 return;
1549         hdr = &btf->hdr;
1550         __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1551         __btf_verifier_log(log, "version: %u\n", hdr->version);
1552         __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1553         __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1554         __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1555         __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1556         __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1557         __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1558         __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1559 }
1560
1561 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1562 {
1563         struct btf *btf = env->btf;
1564
1565         if (btf->types_size == btf->nr_types) {
1566                 /* Expand 'types' array */
1567
1568                 struct btf_type **new_types;
1569                 u32 expand_by, new_size;
1570
1571                 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1572                         btf_verifier_log(env, "Exceeded max num of types");
1573                         return -E2BIG;
1574                 }
1575
1576                 expand_by = max_t(u32, btf->types_size >> 2, 16);
1577                 new_size = min_t(u32, BTF_MAX_TYPE,
1578                                  btf->types_size + expand_by);
1579
1580                 new_types = kvcalloc(new_size, sizeof(*new_types),
1581                                      GFP_KERNEL | __GFP_NOWARN);
1582                 if (!new_types)
1583                         return -ENOMEM;
1584
1585                 if (btf->nr_types == 0) {
1586                         if (!btf->base_btf) {
1587                                 /* lazily init VOID type */
1588                                 new_types[0] = &btf_void;
1589                                 btf->nr_types++;
1590                         }
1591                 } else {
1592                         memcpy(new_types, btf->types,
1593                                sizeof(*btf->types) * btf->nr_types);
1594                 }
1595
1596                 kvfree(btf->types);
1597                 btf->types = new_types;
1598                 btf->types_size = new_size;
1599         }
1600
1601         btf->types[btf->nr_types++] = t;
1602
1603         return 0;
1604 }
1605
1606 static int btf_alloc_id(struct btf *btf)
1607 {
1608         int id;
1609
1610         idr_preload(GFP_KERNEL);
1611         spin_lock_bh(&btf_idr_lock);
1612         id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1613         if (id > 0)
1614                 btf->id = id;
1615         spin_unlock_bh(&btf_idr_lock);
1616         idr_preload_end();
1617
1618         if (WARN_ON_ONCE(!id))
1619                 return -ENOSPC;
1620
1621         return id > 0 ? 0 : id;
1622 }
1623
1624 static void btf_free_id(struct btf *btf)
1625 {
1626         unsigned long flags;
1627
1628         /*
1629          * In map-in-map, calling map_delete_elem() on outer
1630          * map will call bpf_map_put on the inner map.
1631          * It will then eventually call btf_free_id()
1632          * on the inner map.  Some of the map_delete_elem()
1633          * implementation may have irq disabled, so
1634          * we need to use the _irqsave() version instead
1635          * of the _bh() version.
1636          */
1637         spin_lock_irqsave(&btf_idr_lock, flags);
1638         idr_remove(&btf_idr, btf->id);
1639         spin_unlock_irqrestore(&btf_idr_lock, flags);
1640 }
1641
1642 static void btf_free_kfunc_set_tab(struct btf *btf)
1643 {
1644         struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1645         int hook;
1646
1647         if (!tab)
1648                 return;
1649         /* For module BTF, we directly assign the sets being registered, so
1650          * there is nothing to free except kfunc_set_tab.
1651          */
1652         if (btf_is_module(btf))
1653                 goto free_tab;
1654         for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1655                 kfree(tab->sets[hook]);
1656 free_tab:
1657         kfree(tab);
1658         btf->kfunc_set_tab = NULL;
1659 }
1660
1661 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1662 {
1663         struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1664
1665         if (!tab)
1666                 return;
1667         kfree(tab);
1668         btf->dtor_kfunc_tab = NULL;
1669 }
1670
1671 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1672 {
1673         int i;
1674
1675         if (!tab)
1676                 return;
1677         for (i = 0; i < tab->cnt; i++)
1678                 btf_record_free(tab->types[i].record);
1679         kfree(tab);
1680 }
1681
1682 static void btf_free_struct_meta_tab(struct btf *btf)
1683 {
1684         struct btf_struct_metas *tab = btf->struct_meta_tab;
1685
1686         btf_struct_metas_free(tab);
1687         btf->struct_meta_tab = NULL;
1688 }
1689
1690 static void btf_free(struct btf *btf)
1691 {
1692         btf_free_struct_meta_tab(btf);
1693         btf_free_dtor_kfunc_tab(btf);
1694         btf_free_kfunc_set_tab(btf);
1695         kvfree(btf->types);
1696         kvfree(btf->resolved_sizes);
1697         kvfree(btf->resolved_ids);
1698         kvfree(btf->data);
1699         kfree(btf);
1700 }
1701
1702 static void btf_free_rcu(struct rcu_head *rcu)
1703 {
1704         struct btf *btf = container_of(rcu, struct btf, rcu);
1705
1706         btf_free(btf);
1707 }
1708
1709 void btf_get(struct btf *btf)
1710 {
1711         refcount_inc(&btf->refcnt);
1712 }
1713
1714 void btf_put(struct btf *btf)
1715 {
1716         if (btf && refcount_dec_and_test(&btf->refcnt)) {
1717                 btf_free_id(btf);
1718                 call_rcu(&btf->rcu, btf_free_rcu);
1719         }
1720 }
1721
1722 static int env_resolve_init(struct btf_verifier_env *env)
1723 {
1724         struct btf *btf = env->btf;
1725         u32 nr_types = btf->nr_types;
1726         u32 *resolved_sizes = NULL;
1727         u32 *resolved_ids = NULL;
1728         u8 *visit_states = NULL;
1729
1730         resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1731                                   GFP_KERNEL | __GFP_NOWARN);
1732         if (!resolved_sizes)
1733                 goto nomem;
1734
1735         resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1736                                 GFP_KERNEL | __GFP_NOWARN);
1737         if (!resolved_ids)
1738                 goto nomem;
1739
1740         visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1741                                 GFP_KERNEL | __GFP_NOWARN);
1742         if (!visit_states)
1743                 goto nomem;
1744
1745         btf->resolved_sizes = resolved_sizes;
1746         btf->resolved_ids = resolved_ids;
1747         env->visit_states = visit_states;
1748
1749         return 0;
1750
1751 nomem:
1752         kvfree(resolved_sizes);
1753         kvfree(resolved_ids);
1754         kvfree(visit_states);
1755         return -ENOMEM;
1756 }
1757
1758 static void btf_verifier_env_free(struct btf_verifier_env *env)
1759 {
1760         kvfree(env->visit_states);
1761         kfree(env);
1762 }
1763
1764 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1765                                      const struct btf_type *next_type)
1766 {
1767         switch (env->resolve_mode) {
1768         case RESOLVE_TBD:
1769                 /* int, enum or void is a sink */
1770                 return !btf_type_needs_resolve(next_type);
1771         case RESOLVE_PTR:
1772                 /* int, enum, void, struct, array, func or func_proto is a sink
1773                  * for ptr
1774                  */
1775                 return !btf_type_is_modifier(next_type) &&
1776                         !btf_type_is_ptr(next_type);
1777         case RESOLVE_STRUCT_OR_ARRAY:
1778                 /* int, enum, void, ptr, func or func_proto is a sink
1779                  * for struct and array
1780                  */
1781                 return !btf_type_is_modifier(next_type) &&
1782                         !btf_type_is_array(next_type) &&
1783                         !btf_type_is_struct(next_type);
1784         default:
1785                 BUG();
1786         }
1787 }
1788
1789 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1790                                  u32 type_id)
1791 {
1792         /* base BTF types should be resolved by now */
1793         if (type_id < env->btf->start_id)
1794                 return true;
1795
1796         return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1797 }
1798
1799 static int env_stack_push(struct btf_verifier_env *env,
1800                           const struct btf_type *t, u32 type_id)
1801 {
1802         const struct btf *btf = env->btf;
1803         struct resolve_vertex *v;
1804
1805         if (env->top_stack == MAX_RESOLVE_DEPTH)
1806                 return -E2BIG;
1807
1808         if (type_id < btf->start_id
1809             || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1810                 return -EEXIST;
1811
1812         env->visit_states[type_id - btf->start_id] = VISITED;
1813
1814         v = &env->stack[env->top_stack++];
1815         v->t = t;
1816         v->type_id = type_id;
1817         v->next_member = 0;
1818
1819         if (env->resolve_mode == RESOLVE_TBD) {
1820                 if (btf_type_is_ptr(t))
1821                         env->resolve_mode = RESOLVE_PTR;
1822                 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1823                         env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1824         }
1825
1826         return 0;
1827 }
1828
1829 static void env_stack_set_next_member(struct btf_verifier_env *env,
1830                                       u16 next_member)
1831 {
1832         env->stack[env->top_stack - 1].next_member = next_member;
1833 }
1834
1835 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1836                                    u32 resolved_type_id,
1837                                    u32 resolved_size)
1838 {
1839         u32 type_id = env->stack[--(env->top_stack)].type_id;
1840         struct btf *btf = env->btf;
1841
1842         type_id -= btf->start_id; /* adjust to local type id */
1843         btf->resolved_sizes[type_id] = resolved_size;
1844         btf->resolved_ids[type_id] = resolved_type_id;
1845         env->visit_states[type_id] = RESOLVED;
1846 }
1847
1848 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1849 {
1850         return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1851 }
1852
1853 /* Resolve the size of a passed-in "type"
1854  *
1855  * type: is an array (e.g. u32 array[x][y])
1856  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1857  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1858  *             corresponds to the return type.
1859  * *elem_type: u32
1860  * *elem_id: id of u32
1861  * *total_nelems: (x * y).  Hence, individual elem size is
1862  *                (*type_size / *total_nelems)
1863  * *type_id: id of type if it's changed within the function, 0 if not
1864  *
1865  * type: is not an array (e.g. const struct X)
1866  * return type: type "struct X"
1867  * *type_size: sizeof(struct X)
1868  * *elem_type: same as return type ("struct X")
1869  * *elem_id: 0
1870  * *total_nelems: 1
1871  * *type_id: id of type if it's changed within the function, 0 if not
1872  */
1873 static const struct btf_type *
1874 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1875                    u32 *type_size, const struct btf_type **elem_type,
1876                    u32 *elem_id, u32 *total_nelems, u32 *type_id)
1877 {
1878         const struct btf_type *array_type = NULL;
1879         const struct btf_array *array = NULL;
1880         u32 i, size, nelems = 1, id = 0;
1881
1882         for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1883                 switch (BTF_INFO_KIND(type->info)) {
1884                 /* type->size can be used */
1885                 case BTF_KIND_INT:
1886                 case BTF_KIND_STRUCT:
1887                 case BTF_KIND_UNION:
1888                 case BTF_KIND_ENUM:
1889                 case BTF_KIND_FLOAT:
1890                 case BTF_KIND_ENUM64:
1891                         size = type->size;
1892                         goto resolved;
1893
1894                 case BTF_KIND_PTR:
1895                         size = sizeof(void *);
1896                         goto resolved;
1897
1898                 /* Modifiers */
1899                 case BTF_KIND_TYPEDEF:
1900                 case BTF_KIND_VOLATILE:
1901                 case BTF_KIND_CONST:
1902                 case BTF_KIND_RESTRICT:
1903                 case BTF_KIND_TYPE_TAG:
1904                         id = type->type;
1905                         type = btf_type_by_id(btf, type->type);
1906                         break;
1907
1908                 case BTF_KIND_ARRAY:
1909                         if (!array_type)
1910                                 array_type = type;
1911                         array = btf_type_array(type);
1912                         if (nelems && array->nelems > U32_MAX / nelems)
1913                                 return ERR_PTR(-EINVAL);
1914                         nelems *= array->nelems;
1915                         type = btf_type_by_id(btf, array->type);
1916                         break;
1917
1918                 /* type without size */
1919                 default:
1920                         return ERR_PTR(-EINVAL);
1921                 }
1922         }
1923
1924         return ERR_PTR(-EINVAL);
1925
1926 resolved:
1927         if (nelems && size > U32_MAX / nelems)
1928                 return ERR_PTR(-EINVAL);
1929
1930         *type_size = nelems * size;
1931         if (total_nelems)
1932                 *total_nelems = nelems;
1933         if (elem_type)
1934                 *elem_type = type;
1935         if (elem_id)
1936                 *elem_id = array ? array->type : 0;
1937         if (type_id && id)
1938                 *type_id = id;
1939
1940         return array_type ? : type;
1941 }
1942
1943 const struct btf_type *
1944 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1945                  u32 *type_size)
1946 {
1947         return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1948 }
1949
1950 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1951 {
1952         while (type_id < btf->start_id)
1953                 btf = btf->base_btf;
1954
1955         return btf->resolved_ids[type_id - btf->start_id];
1956 }
1957
1958 /* The input param "type_id" must point to a needs_resolve type */
1959 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1960                                                   u32 *type_id)
1961 {
1962         *type_id = btf_resolved_type_id(btf, *type_id);
1963         return btf_type_by_id(btf, *type_id);
1964 }
1965
1966 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1967 {
1968         while (type_id < btf->start_id)
1969                 btf = btf->base_btf;
1970
1971         return btf->resolved_sizes[type_id - btf->start_id];
1972 }
1973
1974 const struct btf_type *btf_type_id_size(const struct btf *btf,
1975                                         u32 *type_id, u32 *ret_size)
1976 {
1977         const struct btf_type *size_type;
1978         u32 size_type_id = *type_id;
1979         u32 size = 0;
1980
1981         size_type = btf_type_by_id(btf, size_type_id);
1982         if (btf_type_nosize_or_null(size_type))
1983                 return NULL;
1984
1985         if (btf_type_has_size(size_type)) {
1986                 size = size_type->size;
1987         } else if (btf_type_is_array(size_type)) {
1988                 size = btf_resolved_type_size(btf, size_type_id);
1989         } else if (btf_type_is_ptr(size_type)) {
1990                 size = sizeof(void *);
1991         } else {
1992                 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1993                                  !btf_type_is_var(size_type)))
1994                         return NULL;
1995
1996                 size_type_id = btf_resolved_type_id(btf, size_type_id);
1997                 size_type = btf_type_by_id(btf, size_type_id);
1998                 if (btf_type_nosize_or_null(size_type))
1999                         return NULL;
2000                 else if (btf_type_has_size(size_type))
2001                         size = size_type->size;
2002                 else if (btf_type_is_array(size_type))
2003                         size = btf_resolved_type_size(btf, size_type_id);
2004                 else if (btf_type_is_ptr(size_type))
2005                         size = sizeof(void *);
2006                 else
2007                         return NULL;
2008         }
2009
2010         *type_id = size_type_id;
2011         if (ret_size)
2012                 *ret_size = size;
2013
2014         return size_type;
2015 }
2016
2017 static int btf_df_check_member(struct btf_verifier_env *env,
2018                                const struct btf_type *struct_type,
2019                                const struct btf_member *member,
2020                                const struct btf_type *member_type)
2021 {
2022         btf_verifier_log_basic(env, struct_type,
2023                                "Unsupported check_member");
2024         return -EINVAL;
2025 }
2026
2027 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2028                                      const struct btf_type *struct_type,
2029                                      const struct btf_member *member,
2030                                      const struct btf_type *member_type)
2031 {
2032         btf_verifier_log_basic(env, struct_type,
2033                                "Unsupported check_kflag_member");
2034         return -EINVAL;
2035 }
2036
2037 /* Used for ptr, array struct/union and float type members.
2038  * int, enum and modifier types have their specific callback functions.
2039  */
2040 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2041                                           const struct btf_type *struct_type,
2042                                           const struct btf_member *member,
2043                                           const struct btf_type *member_type)
2044 {
2045         if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2046                 btf_verifier_log_member(env, struct_type, member,
2047                                         "Invalid member bitfield_size");
2048                 return -EINVAL;
2049         }
2050
2051         /* bitfield size is 0, so member->offset represents bit offset only.
2052          * It is safe to call non kflag check_member variants.
2053          */
2054         return btf_type_ops(member_type)->check_member(env, struct_type,
2055                                                        member,
2056                                                        member_type);
2057 }
2058
2059 static int btf_df_resolve(struct btf_verifier_env *env,
2060                           const struct resolve_vertex *v)
2061 {
2062         btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2063         return -EINVAL;
2064 }
2065
2066 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2067                         u32 type_id, void *data, u8 bits_offsets,
2068                         struct btf_show *show)
2069 {
2070         btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2071 }
2072
2073 static int btf_int_check_member(struct btf_verifier_env *env,
2074                                 const struct btf_type *struct_type,
2075                                 const struct btf_member *member,
2076                                 const struct btf_type *member_type)
2077 {
2078         u32 int_data = btf_type_int(member_type);
2079         u32 struct_bits_off = member->offset;
2080         u32 struct_size = struct_type->size;
2081         u32 nr_copy_bits;
2082         u32 bytes_offset;
2083
2084         if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2085                 btf_verifier_log_member(env, struct_type, member,
2086                                         "bits_offset exceeds U32_MAX");
2087                 return -EINVAL;
2088         }
2089
2090         struct_bits_off += BTF_INT_OFFSET(int_data);
2091         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2092         nr_copy_bits = BTF_INT_BITS(int_data) +
2093                 BITS_PER_BYTE_MASKED(struct_bits_off);
2094
2095         if (nr_copy_bits > BITS_PER_U128) {
2096                 btf_verifier_log_member(env, struct_type, member,
2097                                         "nr_copy_bits exceeds 128");
2098                 return -EINVAL;
2099         }
2100
2101         if (struct_size < bytes_offset ||
2102             struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2103                 btf_verifier_log_member(env, struct_type, member,
2104                                         "Member exceeds struct_size");
2105                 return -EINVAL;
2106         }
2107
2108         return 0;
2109 }
2110
2111 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2112                                       const struct btf_type *struct_type,
2113                                       const struct btf_member *member,
2114                                       const struct btf_type *member_type)
2115 {
2116         u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2117         u32 int_data = btf_type_int(member_type);
2118         u32 struct_size = struct_type->size;
2119         u32 nr_copy_bits;
2120
2121         /* a regular int type is required for the kflag int member */
2122         if (!btf_type_int_is_regular(member_type)) {
2123                 btf_verifier_log_member(env, struct_type, member,
2124                                         "Invalid member base type");
2125                 return -EINVAL;
2126         }
2127
2128         /* check sanity of bitfield size */
2129         nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2130         struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2131         nr_int_data_bits = BTF_INT_BITS(int_data);
2132         if (!nr_bits) {
2133                 /* Not a bitfield member, member offset must be at byte
2134                  * boundary.
2135                  */
2136                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2137                         btf_verifier_log_member(env, struct_type, member,
2138                                                 "Invalid member offset");
2139                         return -EINVAL;
2140                 }
2141
2142                 nr_bits = nr_int_data_bits;
2143         } else if (nr_bits > nr_int_data_bits) {
2144                 btf_verifier_log_member(env, struct_type, member,
2145                                         "Invalid member bitfield_size");
2146                 return -EINVAL;
2147         }
2148
2149         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2150         nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2151         if (nr_copy_bits > BITS_PER_U128) {
2152                 btf_verifier_log_member(env, struct_type, member,
2153                                         "nr_copy_bits exceeds 128");
2154                 return -EINVAL;
2155         }
2156
2157         if (struct_size < bytes_offset ||
2158             struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2159                 btf_verifier_log_member(env, struct_type, member,
2160                                         "Member exceeds struct_size");
2161                 return -EINVAL;
2162         }
2163
2164         return 0;
2165 }
2166
2167 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2168                               const struct btf_type *t,
2169                               u32 meta_left)
2170 {
2171         u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2172         u16 encoding;
2173
2174         if (meta_left < meta_needed) {
2175                 btf_verifier_log_basic(env, t,
2176                                        "meta_left:%u meta_needed:%u",
2177                                        meta_left, meta_needed);
2178                 return -EINVAL;
2179         }
2180
2181         if (btf_type_vlen(t)) {
2182                 btf_verifier_log_type(env, t, "vlen != 0");
2183                 return -EINVAL;
2184         }
2185
2186         if (btf_type_kflag(t)) {
2187                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2188                 return -EINVAL;
2189         }
2190
2191         int_data = btf_type_int(t);
2192         if (int_data & ~BTF_INT_MASK) {
2193                 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2194                                        int_data);
2195                 return -EINVAL;
2196         }
2197
2198         nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2199
2200         if (nr_bits > BITS_PER_U128) {
2201                 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2202                                       BITS_PER_U128);
2203                 return -EINVAL;
2204         }
2205
2206         if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2207                 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2208                 return -EINVAL;
2209         }
2210
2211         /*
2212          * Only one of the encoding bits is allowed and it
2213          * should be sufficient for the pretty print purpose (i.e. decoding).
2214          * Multiple bits can be allowed later if it is found
2215          * to be insufficient.
2216          */
2217         encoding = BTF_INT_ENCODING(int_data);
2218         if (encoding &&
2219             encoding != BTF_INT_SIGNED &&
2220             encoding != BTF_INT_CHAR &&
2221             encoding != BTF_INT_BOOL) {
2222                 btf_verifier_log_type(env, t, "Unsupported encoding");
2223                 return -ENOTSUPP;
2224         }
2225
2226         btf_verifier_log_type(env, t, NULL);
2227
2228         return meta_needed;
2229 }
2230
2231 static void btf_int_log(struct btf_verifier_env *env,
2232                         const struct btf_type *t)
2233 {
2234         int int_data = btf_type_int(t);
2235
2236         btf_verifier_log(env,
2237                          "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2238                          t->size, BTF_INT_OFFSET(int_data),
2239                          BTF_INT_BITS(int_data),
2240                          btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2241 }
2242
2243 static void btf_int128_print(struct btf_show *show, void *data)
2244 {
2245         /* data points to a __int128 number.
2246          * Suppose
2247          *     int128_num = *(__int128 *)data;
2248          * The below formulas shows what upper_num and lower_num represents:
2249          *     upper_num = int128_num >> 64;
2250          *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2251          */
2252         u64 upper_num, lower_num;
2253
2254 #ifdef __BIG_ENDIAN_BITFIELD
2255         upper_num = *(u64 *)data;
2256         lower_num = *(u64 *)(data + 8);
2257 #else
2258         upper_num = *(u64 *)(data + 8);
2259         lower_num = *(u64 *)data;
2260 #endif
2261         if (upper_num == 0)
2262                 btf_show_type_value(show, "0x%llx", lower_num);
2263         else
2264                 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2265                                      lower_num);
2266 }
2267
2268 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2269                              u16 right_shift_bits)
2270 {
2271         u64 upper_num, lower_num;
2272
2273 #ifdef __BIG_ENDIAN_BITFIELD
2274         upper_num = print_num[0];
2275         lower_num = print_num[1];
2276 #else
2277         upper_num = print_num[1];
2278         lower_num = print_num[0];
2279 #endif
2280
2281         /* shake out un-needed bits by shift/or operations */
2282         if (left_shift_bits >= 64) {
2283                 upper_num = lower_num << (left_shift_bits - 64);
2284                 lower_num = 0;
2285         } else {
2286                 upper_num = (upper_num << left_shift_bits) |
2287                             (lower_num >> (64 - left_shift_bits));
2288                 lower_num = lower_num << left_shift_bits;
2289         }
2290
2291         if (right_shift_bits >= 64) {
2292                 lower_num = upper_num >> (right_shift_bits - 64);
2293                 upper_num = 0;
2294         } else {
2295                 lower_num = (lower_num >> right_shift_bits) |
2296                             (upper_num << (64 - right_shift_bits));
2297                 upper_num = upper_num >> right_shift_bits;
2298         }
2299
2300 #ifdef __BIG_ENDIAN_BITFIELD
2301         print_num[0] = upper_num;
2302         print_num[1] = lower_num;
2303 #else
2304         print_num[0] = lower_num;
2305         print_num[1] = upper_num;
2306 #endif
2307 }
2308
2309 static void btf_bitfield_show(void *data, u8 bits_offset,
2310                               u8 nr_bits, struct btf_show *show)
2311 {
2312         u16 left_shift_bits, right_shift_bits;
2313         u8 nr_copy_bytes;
2314         u8 nr_copy_bits;
2315         u64 print_num[2] = {};
2316
2317         nr_copy_bits = nr_bits + bits_offset;
2318         nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2319
2320         memcpy(print_num, data, nr_copy_bytes);
2321
2322 #ifdef __BIG_ENDIAN_BITFIELD
2323         left_shift_bits = bits_offset;
2324 #else
2325         left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2326 #endif
2327         right_shift_bits = BITS_PER_U128 - nr_bits;
2328
2329         btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2330         btf_int128_print(show, print_num);
2331 }
2332
2333
2334 static void btf_int_bits_show(const struct btf *btf,
2335                               const struct btf_type *t,
2336                               void *data, u8 bits_offset,
2337                               struct btf_show *show)
2338 {
2339         u32 int_data = btf_type_int(t);
2340         u8 nr_bits = BTF_INT_BITS(int_data);
2341         u8 total_bits_offset;
2342
2343         /*
2344          * bits_offset is at most 7.
2345          * BTF_INT_OFFSET() cannot exceed 128 bits.
2346          */
2347         total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2348         data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2349         bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2350         btf_bitfield_show(data, bits_offset, nr_bits, show);
2351 }
2352
2353 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2354                          u32 type_id, void *data, u8 bits_offset,
2355                          struct btf_show *show)
2356 {
2357         u32 int_data = btf_type_int(t);
2358         u8 encoding = BTF_INT_ENCODING(int_data);
2359         bool sign = encoding & BTF_INT_SIGNED;
2360         u8 nr_bits = BTF_INT_BITS(int_data);
2361         void *safe_data;
2362
2363         safe_data = btf_show_start_type(show, t, type_id, data);
2364         if (!safe_data)
2365                 return;
2366
2367         if (bits_offset || BTF_INT_OFFSET(int_data) ||
2368             BITS_PER_BYTE_MASKED(nr_bits)) {
2369                 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2370                 goto out;
2371         }
2372
2373         switch (nr_bits) {
2374         case 128:
2375                 btf_int128_print(show, safe_data);
2376                 break;
2377         case 64:
2378                 if (sign)
2379                         btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2380                 else
2381                         btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2382                 break;
2383         case 32:
2384                 if (sign)
2385                         btf_show_type_value(show, "%d", *(s32 *)safe_data);
2386                 else
2387                         btf_show_type_value(show, "%u", *(u32 *)safe_data);
2388                 break;
2389         case 16:
2390                 if (sign)
2391                         btf_show_type_value(show, "%d", *(s16 *)safe_data);
2392                 else
2393                         btf_show_type_value(show, "%u", *(u16 *)safe_data);
2394                 break;
2395         case 8:
2396                 if (show->state.array_encoding == BTF_INT_CHAR) {
2397                         /* check for null terminator */
2398                         if (show->state.array_terminated)
2399                                 break;
2400                         if (*(char *)data == '\0') {
2401                                 show->state.array_terminated = 1;
2402                                 break;
2403                         }
2404                         if (isprint(*(char *)data)) {
2405                                 btf_show_type_value(show, "'%c'",
2406                                                     *(char *)safe_data);
2407                                 break;
2408                         }
2409                 }
2410                 if (sign)
2411                         btf_show_type_value(show, "%d", *(s8 *)safe_data);
2412                 else
2413                         btf_show_type_value(show, "%u", *(u8 *)safe_data);
2414                 break;
2415         default:
2416                 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2417                 break;
2418         }
2419 out:
2420         btf_show_end_type(show);
2421 }
2422
2423 static const struct btf_kind_operations int_ops = {
2424         .check_meta = btf_int_check_meta,
2425         .resolve = btf_df_resolve,
2426         .check_member = btf_int_check_member,
2427         .check_kflag_member = btf_int_check_kflag_member,
2428         .log_details = btf_int_log,
2429         .show = btf_int_show,
2430 };
2431
2432 static int btf_modifier_check_member(struct btf_verifier_env *env,
2433                                      const struct btf_type *struct_type,
2434                                      const struct btf_member *member,
2435                                      const struct btf_type *member_type)
2436 {
2437         const struct btf_type *resolved_type;
2438         u32 resolved_type_id = member->type;
2439         struct btf_member resolved_member;
2440         struct btf *btf = env->btf;
2441
2442         resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2443         if (!resolved_type) {
2444                 btf_verifier_log_member(env, struct_type, member,
2445                                         "Invalid member");
2446                 return -EINVAL;
2447         }
2448
2449         resolved_member = *member;
2450         resolved_member.type = resolved_type_id;
2451
2452         return btf_type_ops(resolved_type)->check_member(env, struct_type,
2453                                                          &resolved_member,
2454                                                          resolved_type);
2455 }
2456
2457 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2458                                            const struct btf_type *struct_type,
2459                                            const struct btf_member *member,
2460                                            const struct btf_type *member_type)
2461 {
2462         const struct btf_type *resolved_type;
2463         u32 resolved_type_id = member->type;
2464         struct btf_member resolved_member;
2465         struct btf *btf = env->btf;
2466
2467         resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2468         if (!resolved_type) {
2469                 btf_verifier_log_member(env, struct_type, member,
2470                                         "Invalid member");
2471                 return -EINVAL;
2472         }
2473
2474         resolved_member = *member;
2475         resolved_member.type = resolved_type_id;
2476
2477         return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2478                                                                &resolved_member,
2479                                                                resolved_type);
2480 }
2481
2482 static int btf_ptr_check_member(struct btf_verifier_env *env,
2483                                 const struct btf_type *struct_type,
2484                                 const struct btf_member *member,
2485                                 const struct btf_type *member_type)
2486 {
2487         u32 struct_size, struct_bits_off, bytes_offset;
2488
2489         struct_size = struct_type->size;
2490         struct_bits_off = member->offset;
2491         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2492
2493         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2494                 btf_verifier_log_member(env, struct_type, member,
2495                                         "Member is not byte aligned");
2496                 return -EINVAL;
2497         }
2498
2499         if (struct_size - bytes_offset < sizeof(void *)) {
2500                 btf_verifier_log_member(env, struct_type, member,
2501                                         "Member exceeds struct_size");
2502                 return -EINVAL;
2503         }
2504
2505         return 0;
2506 }
2507
2508 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2509                                    const struct btf_type *t,
2510                                    u32 meta_left)
2511 {
2512         const char *value;
2513
2514         if (btf_type_vlen(t)) {
2515                 btf_verifier_log_type(env, t, "vlen != 0");
2516                 return -EINVAL;
2517         }
2518
2519         if (btf_type_kflag(t)) {
2520                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2521                 return -EINVAL;
2522         }
2523
2524         if (!BTF_TYPE_ID_VALID(t->type)) {
2525                 btf_verifier_log_type(env, t, "Invalid type_id");
2526                 return -EINVAL;
2527         }
2528
2529         /* typedef/type_tag type must have a valid name, and other ref types,
2530          * volatile, const, restrict, should have a null name.
2531          */
2532         if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2533                 if (!t->name_off ||
2534                     !btf_name_valid_identifier(env->btf, t->name_off)) {
2535                         btf_verifier_log_type(env, t, "Invalid name");
2536                         return -EINVAL;
2537                 }
2538         } else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2539                 value = btf_name_by_offset(env->btf, t->name_off);
2540                 if (!value || !value[0]) {
2541                         btf_verifier_log_type(env, t, "Invalid name");
2542                         return -EINVAL;
2543                 }
2544         } else {
2545                 if (t->name_off) {
2546                         btf_verifier_log_type(env, t, "Invalid name");
2547                         return -EINVAL;
2548                 }
2549         }
2550
2551         btf_verifier_log_type(env, t, NULL);
2552
2553         return 0;
2554 }
2555
2556 static int btf_modifier_resolve(struct btf_verifier_env *env,
2557                                 const struct resolve_vertex *v)
2558 {
2559         const struct btf_type *t = v->t;
2560         const struct btf_type *next_type;
2561         u32 next_type_id = t->type;
2562         struct btf *btf = env->btf;
2563
2564         next_type = btf_type_by_id(btf, next_type_id);
2565         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2566                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2567                 return -EINVAL;
2568         }
2569
2570         if (!env_type_is_resolve_sink(env, next_type) &&
2571             !env_type_is_resolved(env, next_type_id))
2572                 return env_stack_push(env, next_type, next_type_id);
2573
2574         /* Figure out the resolved next_type_id with size.
2575          * They will be stored in the current modifier's
2576          * resolved_ids and resolved_sizes such that it can
2577          * save us a few type-following when we use it later (e.g. in
2578          * pretty print).
2579          */
2580         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2581                 if (env_type_is_resolved(env, next_type_id))
2582                         next_type = btf_type_id_resolve(btf, &next_type_id);
2583
2584                 /* "typedef void new_void", "const void"...etc */
2585                 if (!btf_type_is_void(next_type) &&
2586                     !btf_type_is_fwd(next_type) &&
2587                     !btf_type_is_func_proto(next_type)) {
2588                         btf_verifier_log_type(env, v->t, "Invalid type_id");
2589                         return -EINVAL;
2590                 }
2591         }
2592
2593         env_stack_pop_resolved(env, next_type_id, 0);
2594
2595         return 0;
2596 }
2597
2598 static int btf_var_resolve(struct btf_verifier_env *env,
2599                            const struct resolve_vertex *v)
2600 {
2601         const struct btf_type *next_type;
2602         const struct btf_type *t = v->t;
2603         u32 next_type_id = t->type;
2604         struct btf *btf = env->btf;
2605
2606         next_type = btf_type_by_id(btf, next_type_id);
2607         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2608                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2609                 return -EINVAL;
2610         }
2611
2612         if (!env_type_is_resolve_sink(env, next_type) &&
2613             !env_type_is_resolved(env, next_type_id))
2614                 return env_stack_push(env, next_type, next_type_id);
2615
2616         if (btf_type_is_modifier(next_type)) {
2617                 const struct btf_type *resolved_type;
2618                 u32 resolved_type_id;
2619
2620                 resolved_type_id = next_type_id;
2621                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2622
2623                 if (btf_type_is_ptr(resolved_type) &&
2624                     !env_type_is_resolve_sink(env, resolved_type) &&
2625                     !env_type_is_resolved(env, resolved_type_id))
2626                         return env_stack_push(env, resolved_type,
2627                                               resolved_type_id);
2628         }
2629
2630         /* We must resolve to something concrete at this point, no
2631          * forward types or similar that would resolve to size of
2632          * zero is allowed.
2633          */
2634         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2635                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2636                 return -EINVAL;
2637         }
2638
2639         env_stack_pop_resolved(env, next_type_id, 0);
2640
2641         return 0;
2642 }
2643
2644 static int btf_ptr_resolve(struct btf_verifier_env *env,
2645                            const struct resolve_vertex *v)
2646 {
2647         const struct btf_type *next_type;
2648         const struct btf_type *t = v->t;
2649         u32 next_type_id = t->type;
2650         struct btf *btf = env->btf;
2651
2652         next_type = btf_type_by_id(btf, next_type_id);
2653         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2654                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2655                 return -EINVAL;
2656         }
2657
2658         if (!env_type_is_resolve_sink(env, next_type) &&
2659             !env_type_is_resolved(env, next_type_id))
2660                 return env_stack_push(env, next_type, next_type_id);
2661
2662         /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2663          * the modifier may have stopped resolving when it was resolved
2664          * to a ptr (last-resolved-ptr).
2665          *
2666          * We now need to continue from the last-resolved-ptr to
2667          * ensure the last-resolved-ptr will not referring back to
2668          * the current ptr (t).
2669          */
2670         if (btf_type_is_modifier(next_type)) {
2671                 const struct btf_type *resolved_type;
2672                 u32 resolved_type_id;
2673
2674                 resolved_type_id = next_type_id;
2675                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2676
2677                 if (btf_type_is_ptr(resolved_type) &&
2678                     !env_type_is_resolve_sink(env, resolved_type) &&
2679                     !env_type_is_resolved(env, resolved_type_id))
2680                         return env_stack_push(env, resolved_type,
2681                                               resolved_type_id);
2682         }
2683
2684         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2685                 if (env_type_is_resolved(env, next_type_id))
2686                         next_type = btf_type_id_resolve(btf, &next_type_id);
2687
2688                 if (!btf_type_is_void(next_type) &&
2689                     !btf_type_is_fwd(next_type) &&
2690                     !btf_type_is_func_proto(next_type)) {
2691                         btf_verifier_log_type(env, v->t, "Invalid type_id");
2692                         return -EINVAL;
2693                 }
2694         }
2695
2696         env_stack_pop_resolved(env, next_type_id, 0);
2697
2698         return 0;
2699 }
2700
2701 static void btf_modifier_show(const struct btf *btf,
2702                               const struct btf_type *t,
2703                               u32 type_id, void *data,
2704                               u8 bits_offset, struct btf_show *show)
2705 {
2706         if (btf->resolved_ids)
2707                 t = btf_type_id_resolve(btf, &type_id);
2708         else
2709                 t = btf_type_skip_modifiers(btf, type_id, NULL);
2710
2711         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2712 }
2713
2714 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2715                          u32 type_id, void *data, u8 bits_offset,
2716                          struct btf_show *show)
2717 {
2718         t = btf_type_id_resolve(btf, &type_id);
2719
2720         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2721 }
2722
2723 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2724                          u32 type_id, void *data, u8 bits_offset,
2725                          struct btf_show *show)
2726 {
2727         void *safe_data;
2728
2729         safe_data = btf_show_start_type(show, t, type_id, data);
2730         if (!safe_data)
2731                 return;
2732
2733         /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2734         if (show->flags & BTF_SHOW_PTR_RAW)
2735                 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2736         else
2737                 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2738         btf_show_end_type(show);
2739 }
2740
2741 static void btf_ref_type_log(struct btf_verifier_env *env,
2742                              const struct btf_type *t)
2743 {
2744         btf_verifier_log(env, "type_id=%u", t->type);
2745 }
2746
2747 static struct btf_kind_operations modifier_ops = {
2748         .check_meta = btf_ref_type_check_meta,
2749         .resolve = btf_modifier_resolve,
2750         .check_member = btf_modifier_check_member,
2751         .check_kflag_member = btf_modifier_check_kflag_member,
2752         .log_details = btf_ref_type_log,
2753         .show = btf_modifier_show,
2754 };
2755
2756 static struct btf_kind_operations ptr_ops = {
2757         .check_meta = btf_ref_type_check_meta,
2758         .resolve = btf_ptr_resolve,
2759         .check_member = btf_ptr_check_member,
2760         .check_kflag_member = btf_generic_check_kflag_member,
2761         .log_details = btf_ref_type_log,
2762         .show = btf_ptr_show,
2763 };
2764
2765 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2766                               const struct btf_type *t,
2767                               u32 meta_left)
2768 {
2769         if (btf_type_vlen(t)) {
2770                 btf_verifier_log_type(env, t, "vlen != 0");
2771                 return -EINVAL;
2772         }
2773
2774         if (t->type) {
2775                 btf_verifier_log_type(env, t, "type != 0");
2776                 return -EINVAL;
2777         }
2778
2779         /* fwd type must have a valid name */
2780         if (!t->name_off ||
2781             !btf_name_valid_identifier(env->btf, t->name_off)) {
2782                 btf_verifier_log_type(env, t, "Invalid name");
2783                 return -EINVAL;
2784         }
2785
2786         btf_verifier_log_type(env, t, NULL);
2787
2788         return 0;
2789 }
2790
2791 static void btf_fwd_type_log(struct btf_verifier_env *env,
2792                              const struct btf_type *t)
2793 {
2794         btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2795 }
2796
2797 static struct btf_kind_operations fwd_ops = {
2798         .check_meta = btf_fwd_check_meta,
2799         .resolve = btf_df_resolve,
2800         .check_member = btf_df_check_member,
2801         .check_kflag_member = btf_df_check_kflag_member,
2802         .log_details = btf_fwd_type_log,
2803         .show = btf_df_show,
2804 };
2805
2806 static int btf_array_check_member(struct btf_verifier_env *env,
2807                                   const struct btf_type *struct_type,
2808                                   const struct btf_member *member,
2809                                   const struct btf_type *member_type)
2810 {
2811         u32 struct_bits_off = member->offset;
2812         u32 struct_size, bytes_offset;
2813         u32 array_type_id, array_size;
2814         struct btf *btf = env->btf;
2815
2816         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2817                 btf_verifier_log_member(env, struct_type, member,
2818                                         "Member is not byte aligned");
2819                 return -EINVAL;
2820         }
2821
2822         array_type_id = member->type;
2823         btf_type_id_size(btf, &array_type_id, &array_size);
2824         struct_size = struct_type->size;
2825         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2826         if (struct_size - bytes_offset < array_size) {
2827                 btf_verifier_log_member(env, struct_type, member,
2828                                         "Member exceeds struct_size");
2829                 return -EINVAL;
2830         }
2831
2832         return 0;
2833 }
2834
2835 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2836                                 const struct btf_type *t,
2837                                 u32 meta_left)
2838 {
2839         const struct btf_array *array = btf_type_array(t);
2840         u32 meta_needed = sizeof(*array);
2841
2842         if (meta_left < meta_needed) {
2843                 btf_verifier_log_basic(env, t,
2844                                        "meta_left:%u meta_needed:%u",
2845                                        meta_left, meta_needed);
2846                 return -EINVAL;
2847         }
2848
2849         /* array type should not have a name */
2850         if (t->name_off) {
2851                 btf_verifier_log_type(env, t, "Invalid name");
2852                 return -EINVAL;
2853         }
2854
2855         if (btf_type_vlen(t)) {
2856                 btf_verifier_log_type(env, t, "vlen != 0");
2857                 return -EINVAL;
2858         }
2859
2860         if (btf_type_kflag(t)) {
2861                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2862                 return -EINVAL;
2863         }
2864
2865         if (t->size) {
2866                 btf_verifier_log_type(env, t, "size != 0");
2867                 return -EINVAL;
2868         }
2869
2870         /* Array elem type and index type cannot be in type void,
2871          * so !array->type and !array->index_type are not allowed.
2872          */
2873         if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2874                 btf_verifier_log_type(env, t, "Invalid elem");
2875                 return -EINVAL;
2876         }
2877
2878         if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2879                 btf_verifier_log_type(env, t, "Invalid index");
2880                 return -EINVAL;
2881         }
2882
2883         btf_verifier_log_type(env, t, NULL);
2884
2885         return meta_needed;
2886 }
2887
2888 static int btf_array_resolve(struct btf_verifier_env *env,
2889                              const struct resolve_vertex *v)
2890 {
2891         const struct btf_array *array = btf_type_array(v->t);
2892         const struct btf_type *elem_type, *index_type;
2893         u32 elem_type_id, index_type_id;
2894         struct btf *btf = env->btf;
2895         u32 elem_size;
2896
2897         /* Check array->index_type */
2898         index_type_id = array->index_type;
2899         index_type = btf_type_by_id(btf, index_type_id);
2900         if (btf_type_nosize_or_null(index_type) ||
2901             btf_type_is_resolve_source_only(index_type)) {
2902                 btf_verifier_log_type(env, v->t, "Invalid index");
2903                 return -EINVAL;
2904         }
2905
2906         if (!env_type_is_resolve_sink(env, index_type) &&
2907             !env_type_is_resolved(env, index_type_id))
2908                 return env_stack_push(env, index_type, index_type_id);
2909
2910         index_type = btf_type_id_size(btf, &index_type_id, NULL);
2911         if (!index_type || !btf_type_is_int(index_type) ||
2912             !btf_type_int_is_regular(index_type)) {
2913                 btf_verifier_log_type(env, v->t, "Invalid index");
2914                 return -EINVAL;
2915         }
2916
2917         /* Check array->type */
2918         elem_type_id = array->type;
2919         elem_type = btf_type_by_id(btf, elem_type_id);
2920         if (btf_type_nosize_or_null(elem_type) ||
2921             btf_type_is_resolve_source_only(elem_type)) {
2922                 btf_verifier_log_type(env, v->t,
2923                                       "Invalid elem");
2924                 return -EINVAL;
2925         }
2926
2927         if (!env_type_is_resolve_sink(env, elem_type) &&
2928             !env_type_is_resolved(env, elem_type_id))
2929                 return env_stack_push(env, elem_type, elem_type_id);
2930
2931         elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2932         if (!elem_type) {
2933                 btf_verifier_log_type(env, v->t, "Invalid elem");
2934                 return -EINVAL;
2935         }
2936
2937         if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2938                 btf_verifier_log_type(env, v->t, "Invalid array of int");
2939                 return -EINVAL;
2940         }
2941
2942         if (array->nelems && elem_size > U32_MAX / array->nelems) {
2943                 btf_verifier_log_type(env, v->t,
2944                                       "Array size overflows U32_MAX");
2945                 return -EINVAL;
2946         }
2947
2948         env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2949
2950         return 0;
2951 }
2952
2953 static void btf_array_log(struct btf_verifier_env *env,
2954                           const struct btf_type *t)
2955 {
2956         const struct btf_array *array = btf_type_array(t);
2957
2958         btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2959                          array->type, array->index_type, array->nelems);
2960 }
2961
2962 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2963                              u32 type_id, void *data, u8 bits_offset,
2964                              struct btf_show *show)
2965 {
2966         const struct btf_array *array = btf_type_array(t);
2967         const struct btf_kind_operations *elem_ops;
2968         const struct btf_type *elem_type;
2969         u32 i, elem_size = 0, elem_type_id;
2970         u16 encoding = 0;
2971
2972         elem_type_id = array->type;
2973         elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2974         if (elem_type && btf_type_has_size(elem_type))
2975                 elem_size = elem_type->size;
2976
2977         if (elem_type && btf_type_is_int(elem_type)) {
2978                 u32 int_type = btf_type_int(elem_type);
2979
2980                 encoding = BTF_INT_ENCODING(int_type);
2981
2982                 /*
2983                  * BTF_INT_CHAR encoding never seems to be set for
2984                  * char arrays, so if size is 1 and element is
2985                  * printable as a char, we'll do that.
2986                  */
2987                 if (elem_size == 1)
2988                         encoding = BTF_INT_CHAR;
2989         }
2990
2991         if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2992                 return;
2993
2994         if (!elem_type)
2995                 goto out;
2996         elem_ops = btf_type_ops(elem_type);
2997
2998         for (i = 0; i < array->nelems; i++) {
2999
3000                 btf_show_start_array_member(show);
3001
3002                 elem_ops->show(btf, elem_type, elem_type_id, data,
3003                                bits_offset, show);
3004                 data += elem_size;
3005
3006                 btf_show_end_array_member(show);
3007
3008                 if (show->state.array_terminated)
3009                         break;
3010         }
3011 out:
3012         btf_show_end_array_type(show);
3013 }
3014
3015 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3016                            u32 type_id, void *data, u8 bits_offset,
3017                            struct btf_show *show)
3018 {
3019         const struct btf_member *m = show->state.member;
3020
3021         /*
3022          * First check if any members would be shown (are non-zero).
3023          * See comments above "struct btf_show" definition for more
3024          * details on how this works at a high-level.
3025          */
3026         if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3027                 if (!show->state.depth_check) {
3028                         show->state.depth_check = show->state.depth + 1;
3029                         show->state.depth_to_show = 0;
3030                 }
3031                 __btf_array_show(btf, t, type_id, data, bits_offset, show);
3032                 show->state.member = m;
3033
3034                 if (show->state.depth_check != show->state.depth + 1)
3035                         return;
3036                 show->state.depth_check = 0;
3037
3038                 if (show->state.depth_to_show <= show->state.depth)
3039                         return;
3040                 /*
3041                  * Reaching here indicates we have recursed and found
3042                  * non-zero array member(s).
3043                  */
3044         }
3045         __btf_array_show(btf, t, type_id, data, bits_offset, show);
3046 }
3047
3048 static struct btf_kind_operations array_ops = {
3049         .check_meta = btf_array_check_meta,
3050         .resolve = btf_array_resolve,
3051         .check_member = btf_array_check_member,
3052         .check_kflag_member = btf_generic_check_kflag_member,
3053         .log_details = btf_array_log,
3054         .show = btf_array_show,
3055 };
3056
3057 static int btf_struct_check_member(struct btf_verifier_env *env,
3058                                    const struct btf_type *struct_type,
3059                                    const struct btf_member *member,
3060                                    const struct btf_type *member_type)
3061 {
3062         u32 struct_bits_off = member->offset;
3063         u32 struct_size, bytes_offset;
3064
3065         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3066                 btf_verifier_log_member(env, struct_type, member,
3067                                         "Member is not byte aligned");
3068                 return -EINVAL;
3069         }
3070
3071         struct_size = struct_type->size;
3072         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3073         if (struct_size - bytes_offset < member_type->size) {
3074                 btf_verifier_log_member(env, struct_type, member,
3075                                         "Member exceeds struct_size");
3076                 return -EINVAL;
3077         }
3078
3079         return 0;
3080 }
3081
3082 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3083                                  const struct btf_type *t,
3084                                  u32 meta_left)
3085 {
3086         bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3087         const struct btf_member *member;
3088         u32 meta_needed, last_offset;
3089         struct btf *btf = env->btf;
3090         u32 struct_size = t->size;
3091         u32 offset;
3092         u16 i;
3093
3094         meta_needed = btf_type_vlen(t) * sizeof(*member);
3095         if (meta_left < meta_needed) {
3096                 btf_verifier_log_basic(env, t,
3097                                        "meta_left:%u meta_needed:%u",
3098                                        meta_left, meta_needed);
3099                 return -EINVAL;
3100         }
3101
3102         /* struct type either no name or a valid one */
3103         if (t->name_off &&
3104             !btf_name_valid_identifier(env->btf, t->name_off)) {
3105                 btf_verifier_log_type(env, t, "Invalid name");
3106                 return -EINVAL;
3107         }
3108
3109         btf_verifier_log_type(env, t, NULL);
3110
3111         last_offset = 0;
3112         for_each_member(i, t, member) {
3113                 if (!btf_name_offset_valid(btf, member->name_off)) {
3114                         btf_verifier_log_member(env, t, member,
3115                                                 "Invalid member name_offset:%u",
3116                                                 member->name_off);
3117                         return -EINVAL;
3118                 }
3119
3120                 /* struct member either no name or a valid one */
3121                 if (member->name_off &&
3122                     !btf_name_valid_identifier(btf, member->name_off)) {
3123                         btf_verifier_log_member(env, t, member, "Invalid name");
3124                         return -EINVAL;
3125                 }
3126                 /* A member cannot be in type void */
3127                 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3128                         btf_verifier_log_member(env, t, member,
3129                                                 "Invalid type_id");
3130                         return -EINVAL;
3131                 }
3132
3133                 offset = __btf_member_bit_offset(t, member);
3134                 if (is_union && offset) {
3135                         btf_verifier_log_member(env, t, member,
3136                                                 "Invalid member bits_offset");
3137                         return -EINVAL;
3138                 }
3139
3140                 /*
3141                  * ">" instead of ">=" because the last member could be
3142                  * "char a[0];"
3143                  */
3144                 if (last_offset > offset) {
3145                         btf_verifier_log_member(env, t, member,
3146                                                 "Invalid member bits_offset");
3147                         return -EINVAL;
3148                 }
3149
3150                 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3151                         btf_verifier_log_member(env, t, member,
3152                                                 "Member bits_offset exceeds its struct size");
3153                         return -EINVAL;
3154                 }
3155
3156                 btf_verifier_log_member(env, t, member, NULL);
3157                 last_offset = offset;
3158         }
3159
3160         return meta_needed;
3161 }
3162
3163 static int btf_struct_resolve(struct btf_verifier_env *env,
3164                               const struct resolve_vertex *v)
3165 {
3166         const struct btf_member *member;
3167         int err;
3168         u16 i;
3169
3170         /* Before continue resolving the next_member,
3171          * ensure the last member is indeed resolved to a
3172          * type with size info.
3173          */
3174         if (v->next_member) {
3175                 const struct btf_type *last_member_type;
3176                 const struct btf_member *last_member;
3177                 u32 last_member_type_id;
3178
3179                 last_member = btf_type_member(v->t) + v->next_member - 1;
3180                 last_member_type_id = last_member->type;
3181                 if (WARN_ON_ONCE(!env_type_is_resolved(env,
3182                                                        last_member_type_id)))
3183                         return -EINVAL;
3184
3185                 last_member_type = btf_type_by_id(env->btf,
3186                                                   last_member_type_id);
3187                 if (btf_type_kflag(v->t))
3188                         err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3189                                                                 last_member,
3190                                                                 last_member_type);
3191                 else
3192                         err = btf_type_ops(last_member_type)->check_member(env, v->t,
3193                                                                 last_member,
3194                                                                 last_member_type);
3195                 if (err)
3196                         return err;
3197         }
3198
3199         for_each_member_from(i, v->next_member, v->t, member) {
3200                 u32 member_type_id = member->type;
3201                 const struct btf_type *member_type = btf_type_by_id(env->btf,
3202                                                                 member_type_id);
3203
3204                 if (btf_type_nosize_or_null(member_type) ||
3205                     btf_type_is_resolve_source_only(member_type)) {
3206                         btf_verifier_log_member(env, v->t, member,
3207                                                 "Invalid member");
3208                         return -EINVAL;
3209                 }
3210
3211                 if (!env_type_is_resolve_sink(env, member_type) &&
3212                     !env_type_is_resolved(env, member_type_id)) {
3213                         env_stack_set_next_member(env, i + 1);
3214                         return env_stack_push(env, member_type, member_type_id);
3215                 }
3216
3217                 if (btf_type_kflag(v->t))
3218                         err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3219                                                                             member,
3220                                                                             member_type);
3221                 else
3222                         err = btf_type_ops(member_type)->check_member(env, v->t,
3223                                                                       member,
3224                                                                       member_type);
3225                 if (err)
3226                         return err;
3227         }
3228
3229         env_stack_pop_resolved(env, 0, 0);
3230
3231         return 0;
3232 }
3233
3234 static void btf_struct_log(struct btf_verifier_env *env,
3235                            const struct btf_type *t)
3236 {
3237         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3238 }
3239
3240 enum {
3241         BTF_FIELD_IGNORE = 0,
3242         BTF_FIELD_FOUND  = 1,
3243 };
3244
3245 struct btf_field_info {
3246         enum btf_field_type type;
3247         u32 off;
3248         union {
3249                 struct {
3250                         u32 type_id;
3251                 } kptr;
3252                 struct {
3253                         const char *node_name;
3254                         u32 value_btf_id;
3255                 } graph_root;
3256         };
3257 };
3258
3259 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3260                            u32 off, int sz, enum btf_field_type field_type,
3261                            struct btf_field_info *info)
3262 {
3263         if (!__btf_type_is_struct(t))
3264                 return BTF_FIELD_IGNORE;
3265         if (t->size != sz)
3266                 return BTF_FIELD_IGNORE;
3267         info->type = field_type;
3268         info->off = off;
3269         return BTF_FIELD_FOUND;
3270 }
3271
3272 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3273                          u32 off, int sz, struct btf_field_info *info)
3274 {
3275         enum btf_field_type type;
3276         u32 res_id;
3277
3278         /* Permit modifiers on the pointer itself */
3279         if (btf_type_is_volatile(t))
3280                 t = btf_type_by_id(btf, t->type);
3281         /* For PTR, sz is always == 8 */
3282         if (!btf_type_is_ptr(t))
3283                 return BTF_FIELD_IGNORE;
3284         t = btf_type_by_id(btf, t->type);
3285
3286         if (!btf_type_is_type_tag(t))
3287                 return BTF_FIELD_IGNORE;
3288         /* Reject extra tags */
3289         if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3290                 return -EINVAL;
3291         if (!strcmp("kptr_untrusted", __btf_name_by_offset(btf, t->name_off)))
3292                 type = BPF_KPTR_UNREF;
3293         else if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3294                 type = BPF_KPTR_REF;
3295         else
3296                 return -EINVAL;
3297
3298         /* Get the base type */
3299         t = btf_type_skip_modifiers(btf, t->type, &res_id);
3300         /* Only pointer to struct is allowed */
3301         if (!__btf_type_is_struct(t))
3302                 return -EINVAL;
3303
3304         info->type = type;
3305         info->off = off;
3306         info->kptr.type_id = res_id;
3307         return BTF_FIELD_FOUND;
3308 }
3309
3310 static const char *btf_find_decl_tag_value(const struct btf *btf,
3311                                            const struct btf_type *pt,
3312                                            int comp_idx, const char *tag_key)
3313 {
3314         int i;
3315
3316         for (i = 1; i < btf_nr_types(btf); i++) {
3317                 const struct btf_type *t = btf_type_by_id(btf, i);
3318                 int len = strlen(tag_key);
3319
3320                 if (!btf_type_is_decl_tag(t))
3321                         continue;
3322                 if (pt != btf_type_by_id(btf, t->type) ||
3323                     btf_type_decl_tag(t)->component_idx != comp_idx)
3324                         continue;
3325                 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3326                         continue;
3327                 return __btf_name_by_offset(btf, t->name_off) + len;
3328         }
3329         return NULL;
3330 }
3331
3332 static int
3333 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3334                     const struct btf_type *t, int comp_idx, u32 off,
3335                     int sz, struct btf_field_info *info,
3336                     enum btf_field_type head_type)
3337 {
3338         const char *node_field_name;
3339         const char *value_type;
3340         s32 id;
3341
3342         if (!__btf_type_is_struct(t))
3343                 return BTF_FIELD_IGNORE;
3344         if (t->size != sz)
3345                 return BTF_FIELD_IGNORE;
3346         value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3347         if (!value_type)
3348                 return -EINVAL;
3349         node_field_name = strstr(value_type, ":");
3350         if (!node_field_name)
3351                 return -EINVAL;
3352         value_type = kstrndup(value_type, node_field_name - value_type, GFP_KERNEL | __GFP_NOWARN);
3353         if (!value_type)
3354                 return -ENOMEM;
3355         id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3356         kfree(value_type);
3357         if (id < 0)
3358                 return id;
3359         node_field_name++;
3360         if (str_is_empty(node_field_name))
3361                 return -EINVAL;
3362         info->type = head_type;
3363         info->off = off;
3364         info->graph_root.value_btf_id = id;
3365         info->graph_root.node_name = node_field_name;
3366         return BTF_FIELD_FOUND;
3367 }
3368
3369 #define field_mask_test_name(field_type, field_type_str) \
3370         if (field_mask & field_type && !strcmp(name, field_type_str)) { \
3371                 type = field_type;                                      \
3372                 goto end;                                               \
3373         }
3374
3375 static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3376                               int *align, int *sz)
3377 {
3378         int type = 0;
3379
3380         if (field_mask & BPF_SPIN_LOCK) {
3381                 if (!strcmp(name, "bpf_spin_lock")) {
3382                         if (*seen_mask & BPF_SPIN_LOCK)
3383                                 return -E2BIG;
3384                         *seen_mask |= BPF_SPIN_LOCK;
3385                         type = BPF_SPIN_LOCK;
3386                         goto end;
3387                 }
3388         }
3389         if (field_mask & BPF_TIMER) {
3390                 if (!strcmp(name, "bpf_timer")) {
3391                         if (*seen_mask & BPF_TIMER)
3392                                 return -E2BIG;
3393                         *seen_mask |= BPF_TIMER;
3394                         type = BPF_TIMER;
3395                         goto end;
3396                 }
3397         }
3398         field_mask_test_name(BPF_LIST_HEAD, "bpf_list_head");
3399         field_mask_test_name(BPF_LIST_NODE, "bpf_list_node");
3400         field_mask_test_name(BPF_RB_ROOT,   "bpf_rb_root");
3401         field_mask_test_name(BPF_RB_NODE,   "bpf_rb_node");
3402         field_mask_test_name(BPF_REFCOUNT,  "bpf_refcount");
3403
3404         /* Only return BPF_KPTR when all other types with matchable names fail */
3405         if (field_mask & BPF_KPTR) {
3406                 type = BPF_KPTR_REF;
3407                 goto end;
3408         }
3409         return 0;
3410 end:
3411         *sz = btf_field_type_size(type);
3412         *align = btf_field_type_align(type);
3413         return type;
3414 }
3415
3416 #undef field_mask_test_name
3417
3418 static int btf_find_struct_field(const struct btf *btf,
3419                                  const struct btf_type *t, u32 field_mask,
3420                                  struct btf_field_info *info, int info_cnt)
3421 {
3422         int ret, idx = 0, align, sz, field_type;
3423         const struct btf_member *member;
3424         struct btf_field_info tmp;
3425         u32 i, off, seen_mask = 0;
3426
3427         for_each_member(i, t, member) {
3428                 const struct btf_type *member_type = btf_type_by_id(btf,
3429                                                                     member->type);
3430
3431                 field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3432                                                 field_mask, &seen_mask, &align, &sz);
3433                 if (field_type == 0)
3434                         continue;
3435                 if (field_type < 0)
3436                         return field_type;
3437
3438                 off = __btf_member_bit_offset(t, member);
3439                 if (off % 8)
3440                         /* valid C code cannot generate such BTF */
3441                         return -EINVAL;
3442                 off /= 8;
3443                 if (off % align)
3444                         continue;
3445
3446                 switch (field_type) {
3447                 case BPF_SPIN_LOCK:
3448                 case BPF_TIMER:
3449                 case BPF_LIST_NODE:
3450                 case BPF_RB_NODE:
3451                 case BPF_REFCOUNT:
3452                         ret = btf_find_struct(btf, member_type, off, sz, field_type,
3453                                               idx < info_cnt ? &info[idx] : &tmp);
3454                         if (ret < 0)
3455                                 return ret;
3456                         break;
3457                 case BPF_KPTR_UNREF:
3458                 case BPF_KPTR_REF:
3459                         ret = btf_find_kptr(btf, member_type, off, sz,
3460                                             idx < info_cnt ? &info[idx] : &tmp);
3461                         if (ret < 0)
3462                                 return ret;
3463                         break;
3464                 case BPF_LIST_HEAD:
3465                 case BPF_RB_ROOT:
3466                         ret = btf_find_graph_root(btf, t, member_type,
3467                                                   i, off, sz,
3468                                                   idx < info_cnt ? &info[idx] : &tmp,
3469                                                   field_type);
3470                         if (ret < 0)
3471                                 return ret;
3472                         break;
3473                 default:
3474                         return -EFAULT;
3475                 }
3476
3477                 if (ret == BTF_FIELD_IGNORE)
3478                         continue;
3479                 if (idx >= info_cnt)
3480                         return -E2BIG;
3481                 ++idx;
3482         }
3483         return idx;
3484 }
3485
3486 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3487                                 u32 field_mask, struct btf_field_info *info,
3488                                 int info_cnt)
3489 {
3490         int ret, idx = 0, align, sz, field_type;
3491         const struct btf_var_secinfo *vsi;
3492         struct btf_field_info tmp;
3493         u32 i, off, seen_mask = 0;
3494
3495         for_each_vsi(i, t, vsi) {
3496                 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3497                 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3498
3499                 field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3500                                                 field_mask, &seen_mask, &align, &sz);
3501                 if (field_type == 0)
3502                         continue;
3503                 if (field_type < 0)
3504                         return field_type;
3505
3506                 off = vsi->offset;
3507                 if (vsi->size != sz)
3508                         continue;
3509                 if (off % align)
3510                         continue;
3511
3512                 switch (field_type) {
3513                 case BPF_SPIN_LOCK:
3514                 case BPF_TIMER:
3515                 case BPF_LIST_NODE:
3516                 case BPF_RB_NODE:
3517                 case BPF_REFCOUNT:
3518                         ret = btf_find_struct(btf, var_type, off, sz, field_type,
3519                                               idx < info_cnt ? &info[idx] : &tmp);
3520                         if (ret < 0)
3521                                 return ret;
3522                         break;
3523                 case BPF_KPTR_UNREF:
3524                 case BPF_KPTR_REF:
3525                         ret = btf_find_kptr(btf, var_type, off, sz,
3526                                             idx < info_cnt ? &info[idx] : &tmp);
3527                         if (ret < 0)
3528                                 return ret;
3529                         break;
3530                 case BPF_LIST_HEAD:
3531                 case BPF_RB_ROOT:
3532                         ret = btf_find_graph_root(btf, var, var_type,
3533                                                   -1, off, sz,
3534                                                   idx < info_cnt ? &info[idx] : &tmp,
3535                                                   field_type);
3536                         if (ret < 0)
3537                                 return ret;
3538                         break;
3539                 default:
3540                         return -EFAULT;
3541                 }
3542
3543                 if (ret == BTF_FIELD_IGNORE)
3544                         continue;
3545                 if (idx >= info_cnt)
3546                         return -E2BIG;
3547                 ++idx;
3548         }
3549         return idx;
3550 }
3551
3552 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3553                           u32 field_mask, struct btf_field_info *info,
3554                           int info_cnt)
3555 {
3556         if (__btf_type_is_struct(t))
3557                 return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
3558         else if (btf_type_is_datasec(t))
3559                 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
3560         return -EINVAL;
3561 }
3562
3563 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3564                           struct btf_field_info *info)
3565 {
3566         struct module *mod = NULL;
3567         const struct btf_type *t;
3568         /* If a matching btf type is found in kernel or module BTFs, kptr_ref
3569          * is that BTF, otherwise it's program BTF
3570          */
3571         struct btf *kptr_btf;
3572         int ret;
3573         s32 id;
3574
3575         /* Find type in map BTF, and use it to look up the matching type
3576          * in vmlinux or module BTFs, by name and kind.
3577          */
3578         t = btf_type_by_id(btf, info->kptr.type_id);
3579         id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3580                              &kptr_btf);
3581         if (id == -ENOENT) {
3582                 /* btf_parse_kptr should only be called w/ btf = program BTF */
3583                 WARN_ON_ONCE(btf_is_kernel(btf));
3584
3585                 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3586                  * kptr allocated via bpf_obj_new
3587                  */
3588                 field->kptr.dtor = NULL;
3589                 id = info->kptr.type_id;
3590                 kptr_btf = (struct btf *)btf;
3591                 btf_get(kptr_btf);
3592                 goto found_dtor;
3593         }
3594         if (id < 0)
3595                 return id;
3596
3597         /* Find and stash the function pointer for the destruction function that
3598          * needs to be eventually invoked from the map free path.
3599          */
3600         if (info->type == BPF_KPTR_REF) {
3601                 const struct btf_type *dtor_func;
3602                 const char *dtor_func_name;
3603                 unsigned long addr;
3604                 s32 dtor_btf_id;
3605
3606                 /* This call also serves as a whitelist of allowed objects that
3607                  * can be used as a referenced pointer and be stored in a map at
3608                  * the same time.
3609                  */
3610                 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3611                 if (dtor_btf_id < 0) {
3612                         ret = dtor_btf_id;
3613                         goto end_btf;
3614                 }
3615
3616                 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3617                 if (!dtor_func) {
3618                         ret = -ENOENT;
3619                         goto end_btf;
3620                 }
3621
3622                 if (btf_is_module(kptr_btf)) {
3623                         mod = btf_try_get_module(kptr_btf);
3624                         if (!mod) {
3625                                 ret = -ENXIO;
3626                                 goto end_btf;
3627                         }
3628                 }
3629
3630                 /* We already verified dtor_func to be btf_type_is_func
3631                  * in register_btf_id_dtor_kfuncs.
3632                  */
3633                 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3634                 addr = kallsyms_lookup_name(dtor_func_name);
3635                 if (!addr) {
3636                         ret = -EINVAL;
3637                         goto end_mod;
3638                 }
3639                 field->kptr.dtor = (void *)addr;
3640         }
3641
3642 found_dtor:
3643         field->kptr.btf_id = id;
3644         field->kptr.btf = kptr_btf;
3645         field->kptr.module = mod;
3646         return 0;
3647 end_mod:
3648         module_put(mod);
3649 end_btf:
3650         btf_put(kptr_btf);
3651         return ret;
3652 }
3653
3654 static int btf_parse_graph_root(const struct btf *btf,
3655                                 struct btf_field *field,
3656                                 struct btf_field_info *info,
3657                                 const char *node_type_name,
3658                                 size_t node_type_align)
3659 {
3660         const struct btf_type *t, *n = NULL;
3661         const struct btf_member *member;
3662         u32 offset;
3663         int i;
3664
3665         t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3666         /* We've already checked that value_btf_id is a struct type. We
3667          * just need to figure out the offset of the list_node, and
3668          * verify its type.
3669          */
3670         for_each_member(i, t, member) {
3671                 if (strcmp(info->graph_root.node_name,
3672                            __btf_name_by_offset(btf, member->name_off)))
3673                         continue;
3674                 /* Invalid BTF, two members with same name */
3675                 if (n)
3676                         return -EINVAL;
3677                 n = btf_type_by_id(btf, member->type);
3678                 if (!__btf_type_is_struct(n))
3679                         return -EINVAL;
3680                 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3681                         return -EINVAL;
3682                 offset = __btf_member_bit_offset(n, member);
3683                 if (offset % 8)
3684                         return -EINVAL;
3685                 offset /= 8;
3686                 if (offset % node_type_align)
3687                         return -EINVAL;
3688
3689                 field->graph_root.btf = (struct btf *)btf;
3690                 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3691                 field->graph_root.node_offset = offset;
3692         }
3693         if (!n)
3694                 return -ENOENT;
3695         return 0;
3696 }
3697
3698 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3699                                struct btf_field_info *info)
3700 {
3701         return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3702                                             __alignof__(struct bpf_list_node));
3703 }
3704
3705 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3706                              struct btf_field_info *info)
3707 {
3708         return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3709                                             __alignof__(struct bpf_rb_node));
3710 }
3711
3712 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3713 {
3714         const struct btf_field *a = (const struct btf_field *)_a;
3715         const struct btf_field *b = (const struct btf_field *)_b;
3716
3717         if (a->offset < b->offset)
3718                 return -1;
3719         else if (a->offset > b->offset)
3720                 return 1;
3721         return 0;
3722 }
3723
3724 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3725                                     u32 field_mask, u32 value_size)
3726 {
3727         struct btf_field_info info_arr[BTF_FIELDS_MAX];
3728         u32 next_off = 0, field_type_size;
3729         struct btf_record *rec;
3730         int ret, i, cnt;
3731
3732         ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3733         if (ret < 0)
3734                 return ERR_PTR(ret);
3735         if (!ret)
3736                 return NULL;
3737
3738         cnt = ret;
3739         /* This needs to be kzalloc to zero out padding and unused fields, see
3740          * comment in btf_record_equal.
3741          */
3742         rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3743         if (!rec)
3744                 return ERR_PTR(-ENOMEM);
3745
3746         rec->spin_lock_off = -EINVAL;
3747         rec->timer_off = -EINVAL;
3748         rec->refcount_off = -EINVAL;
3749         for (i = 0; i < cnt; i++) {
3750                 field_type_size = btf_field_type_size(info_arr[i].type);
3751                 if (info_arr[i].off + field_type_size > value_size) {
3752                         WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3753                         ret = -EFAULT;
3754                         goto end;
3755                 }
3756                 if (info_arr[i].off < next_off) {
3757                         ret = -EEXIST;
3758                         goto end;
3759                 }
3760                 next_off = info_arr[i].off + field_type_size;
3761
3762                 rec->field_mask |= info_arr[i].type;
3763                 rec->fields[i].offset = info_arr[i].off;
3764                 rec->fields[i].type = info_arr[i].type;
3765                 rec->fields[i].size = field_type_size;
3766
3767                 switch (info_arr[i].type) {
3768                 case BPF_SPIN_LOCK:
3769                         WARN_ON_ONCE(rec->spin_lock_off >= 0);
3770                         /* Cache offset for faster lookup at runtime */
3771                         rec->spin_lock_off = rec->fields[i].offset;
3772                         break;
3773                 case BPF_TIMER:
3774                         WARN_ON_ONCE(rec->timer_off >= 0);
3775                         /* Cache offset for faster lookup at runtime */
3776                         rec->timer_off = rec->fields[i].offset;
3777                         break;
3778                 case BPF_REFCOUNT:
3779                         WARN_ON_ONCE(rec->refcount_off >= 0);
3780                         /* Cache offset for faster lookup at runtime */
3781                         rec->refcount_off = rec->fields[i].offset;
3782                         break;
3783                 case BPF_KPTR_UNREF:
3784                 case BPF_KPTR_REF:
3785                         ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3786                         if (ret < 0)
3787                                 goto end;
3788                         break;
3789                 case BPF_LIST_HEAD:
3790                         ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3791                         if (ret < 0)
3792                                 goto end;
3793                         break;
3794                 case BPF_RB_ROOT:
3795                         ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
3796                         if (ret < 0)
3797                                 goto end;
3798                         break;
3799                 case BPF_LIST_NODE:
3800                 case BPF_RB_NODE:
3801                         break;
3802                 default:
3803                         ret = -EFAULT;
3804                         goto end;
3805                 }
3806                 rec->cnt++;
3807         }
3808
3809         /* bpf_{list_head, rb_node} require bpf_spin_lock */
3810         if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
3811              btf_record_has_field(rec, BPF_RB_ROOT)) && rec->spin_lock_off < 0) {
3812                 ret = -EINVAL;
3813                 goto end;
3814         }
3815
3816         if (rec->refcount_off < 0 &&
3817             btf_record_has_field(rec, BPF_LIST_NODE) &&
3818             btf_record_has_field(rec, BPF_RB_NODE)) {
3819                 ret = -EINVAL;
3820                 goto end;
3821         }
3822
3823         sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
3824                NULL, rec);
3825
3826         return rec;
3827 end:
3828         btf_record_free(rec);
3829         return ERR_PTR(ret);
3830 }
3831
3832 #define GRAPH_ROOT_MASK (BPF_LIST_HEAD | BPF_RB_ROOT)
3833 #define GRAPH_NODE_MASK (BPF_LIST_NODE | BPF_RB_NODE)
3834
3835 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3836 {
3837         int i;
3838
3839         /* There are three types that signify ownership of some other type:
3840          *  kptr_ref, bpf_list_head, bpf_rb_root.
3841          * kptr_ref only supports storing kernel types, which can't store
3842          * references to program allocated local types.
3843          *
3844          * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
3845          * does not form cycles.
3846          */
3847         if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & GRAPH_ROOT_MASK))
3848                 return 0;
3849         for (i = 0; i < rec->cnt; i++) {
3850                 struct btf_struct_meta *meta;
3851                 u32 btf_id;
3852
3853                 if (!(rec->fields[i].type & GRAPH_ROOT_MASK))
3854                         continue;
3855                 btf_id = rec->fields[i].graph_root.value_btf_id;
3856                 meta = btf_find_struct_meta(btf, btf_id);
3857                 if (!meta)
3858                         return -EFAULT;
3859                 rec->fields[i].graph_root.value_rec = meta->record;
3860
3861                 /* We need to set value_rec for all root types, but no need
3862                  * to check ownership cycle for a type unless it's also a
3863                  * node type.
3864                  */
3865                 if (!(rec->field_mask & GRAPH_NODE_MASK))
3866                         continue;
3867
3868                 /* We need to ensure ownership acyclicity among all types. The
3869                  * proper way to do it would be to topologically sort all BTF
3870                  * IDs based on the ownership edges, since there can be multiple
3871                  * bpf_{list_head,rb_node} in a type. Instead, we use the
3872                  * following resaoning:
3873                  *
3874                  * - A type can only be owned by another type in user BTF if it
3875                  *   has a bpf_{list,rb}_node. Let's call these node types.
3876                  * - A type can only _own_ another type in user BTF if it has a
3877                  *   bpf_{list_head,rb_root}. Let's call these root types.
3878                  *
3879                  * We ensure that if a type is both a root and node, its
3880                  * element types cannot be root types.
3881                  *
3882                  * To ensure acyclicity:
3883                  *
3884                  * When A is an root type but not a node, its ownership
3885                  * chain can be:
3886                  *      A -> B -> C
3887                  * Where:
3888                  * - A is an root, e.g. has bpf_rb_root.
3889                  * - B is both a root and node, e.g. has bpf_rb_node and
3890                  *   bpf_list_head.
3891                  * - C is only an root, e.g. has bpf_list_node
3892                  *
3893                  * When A is both a root and node, some other type already
3894                  * owns it in the BTF domain, hence it can not own
3895                  * another root type through any of the ownership edges.
3896                  *      A -> B
3897                  * Where:
3898                  * - A is both an root and node.
3899                  * - B is only an node.
3900                  */
3901                 if (meta->record->field_mask & GRAPH_ROOT_MASK)
3902                         return -ELOOP;
3903         }
3904         return 0;
3905 }
3906
3907 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3908                               u32 type_id, void *data, u8 bits_offset,
3909                               struct btf_show *show)
3910 {
3911         const struct btf_member *member;
3912         void *safe_data;
3913         u32 i;
3914
3915         safe_data = btf_show_start_struct_type(show, t, type_id, data);
3916         if (!safe_data)
3917                 return;
3918
3919         for_each_member(i, t, member) {
3920                 const struct btf_type *member_type = btf_type_by_id(btf,
3921                                                                 member->type);
3922                 const struct btf_kind_operations *ops;
3923                 u32 member_offset, bitfield_size;
3924                 u32 bytes_offset;
3925                 u8 bits8_offset;
3926
3927                 btf_show_start_member(show, member);
3928
3929                 member_offset = __btf_member_bit_offset(t, member);
3930                 bitfield_size = __btf_member_bitfield_size(t, member);
3931                 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3932                 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3933                 if (bitfield_size) {
3934                         safe_data = btf_show_start_type(show, member_type,
3935                                                         member->type,
3936                                                         data + bytes_offset);
3937                         if (safe_data)
3938                                 btf_bitfield_show(safe_data,
3939                                                   bits8_offset,
3940                                                   bitfield_size, show);
3941                         btf_show_end_type(show);
3942                 } else {
3943                         ops = btf_type_ops(member_type);
3944                         ops->show(btf, member_type, member->type,
3945                                   data + bytes_offset, bits8_offset, show);
3946                 }
3947
3948                 btf_show_end_member(show);
3949         }
3950
3951         btf_show_end_struct_type(show);
3952 }
3953
3954 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3955                             u32 type_id, void *data, u8 bits_offset,
3956                             struct btf_show *show)
3957 {
3958         const struct btf_member *m = show->state.member;
3959
3960         /*
3961          * First check if any members would be shown (are non-zero).
3962          * See comments above "struct btf_show" definition for more
3963          * details on how this works at a high-level.
3964          */
3965         if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3966                 if (!show->state.depth_check) {
3967                         show->state.depth_check = show->state.depth + 1;
3968                         show->state.depth_to_show = 0;
3969                 }
3970                 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3971                 /* Restore saved member data here */
3972                 show->state.member = m;
3973                 if (show->state.depth_check != show->state.depth + 1)
3974                         return;
3975                 show->state.depth_check = 0;
3976
3977                 if (show->state.depth_to_show <= show->state.depth)
3978                         return;
3979                 /*
3980                  * Reaching here indicates we have recursed and found
3981                  * non-zero child values.
3982                  */
3983         }
3984
3985         __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3986 }
3987
3988 static struct btf_kind_operations struct_ops = {
3989         .check_meta = btf_struct_check_meta,
3990         .resolve = btf_struct_resolve,
3991         .check_member = btf_struct_check_member,
3992         .check_kflag_member = btf_generic_check_kflag_member,
3993         .log_details = btf_struct_log,
3994         .show = btf_struct_show,
3995 };
3996
3997 static int btf_enum_check_member(struct btf_verifier_env *env,
3998                                  const struct btf_type *struct_type,
3999                                  const struct btf_member *member,
4000                                  const struct btf_type *member_type)
4001 {
4002         u32 struct_bits_off = member->offset;
4003         u32 struct_size, bytes_offset;
4004
4005         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4006                 btf_verifier_log_member(env, struct_type, member,
4007                                         "Member is not byte aligned");
4008                 return -EINVAL;
4009         }
4010
4011         struct_size = struct_type->size;
4012         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4013         if (struct_size - bytes_offset < member_type->size) {
4014                 btf_verifier_log_member(env, struct_type, member,
4015                                         "Member exceeds struct_size");
4016                 return -EINVAL;
4017         }
4018
4019         return 0;
4020 }
4021
4022 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4023                                        const struct btf_type *struct_type,
4024                                        const struct btf_member *member,
4025                                        const struct btf_type *member_type)
4026 {
4027         u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4028         u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4029
4030         struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4031         nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4032         if (!nr_bits) {
4033                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4034                         btf_verifier_log_member(env, struct_type, member,
4035                                                 "Member is not byte aligned");
4036                         return -EINVAL;
4037                 }
4038
4039                 nr_bits = int_bitsize;
4040         } else if (nr_bits > int_bitsize) {
4041                 btf_verifier_log_member(env, struct_type, member,
4042                                         "Invalid member bitfield_size");
4043                 return -EINVAL;
4044         }
4045
4046         struct_size = struct_type->size;
4047         bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4048         if (struct_size < bytes_end) {
4049                 btf_verifier_log_member(env, struct_type, member,
4050                                         "Member exceeds struct_size");
4051                 return -EINVAL;
4052         }
4053
4054         return 0;
4055 }
4056
4057 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4058                                const struct btf_type *t,
4059                                u32 meta_left)
4060 {
4061         const struct btf_enum *enums = btf_type_enum(t);
4062         struct btf *btf = env->btf;
4063         const char *fmt_str;
4064         u16 i, nr_enums;
4065         u32 meta_needed;
4066
4067         nr_enums = btf_type_vlen(t);
4068         meta_needed = nr_enums * sizeof(*enums);
4069
4070         if (meta_left < meta_needed) {
4071                 btf_verifier_log_basic(env, t,
4072                                        "meta_left:%u meta_needed:%u",
4073                                        meta_left, meta_needed);
4074                 return -EINVAL;
4075         }
4076
4077         if (t->size > 8 || !is_power_of_2(t->size)) {
4078                 btf_verifier_log_type(env, t, "Unexpected size");
4079                 return -EINVAL;
4080         }
4081
4082         /* enum type either no name or a valid one */
4083         if (t->name_off &&
4084             !btf_name_valid_identifier(env->btf, t->name_off)) {
4085                 btf_verifier_log_type(env, t, "Invalid name");
4086                 return -EINVAL;
4087         }
4088
4089         btf_verifier_log_type(env, t, NULL);
4090
4091         for (i = 0; i < nr_enums; i++) {
4092                 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4093                         btf_verifier_log(env, "\tInvalid name_offset:%u",
4094                                          enums[i].name_off);
4095                         return -EINVAL;
4096                 }
4097
4098                 /* enum member must have a valid name */
4099                 if (!enums[i].name_off ||
4100                     !btf_name_valid_identifier(btf, enums[i].name_off)) {
4101                         btf_verifier_log_type(env, t, "Invalid name");
4102                         return -EINVAL;
4103                 }
4104
4105                 if (env->log.level == BPF_LOG_KERNEL)
4106                         continue;
4107                 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4108                 btf_verifier_log(env, fmt_str,
4109                                  __btf_name_by_offset(btf, enums[i].name_off),
4110                                  enums[i].val);
4111         }
4112
4113         return meta_needed;
4114 }
4115
4116 static void btf_enum_log(struct btf_verifier_env *env,
4117                          const struct btf_type *t)
4118 {
4119         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4120 }
4121
4122 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4123                           u32 type_id, void *data, u8 bits_offset,
4124                           struct btf_show *show)
4125 {
4126         const struct btf_enum *enums = btf_type_enum(t);
4127         u32 i, nr_enums = btf_type_vlen(t);
4128         void *safe_data;
4129         int v;
4130
4131         safe_data = btf_show_start_type(show, t, type_id, data);
4132         if (!safe_data)
4133                 return;
4134
4135         v = *(int *)safe_data;
4136
4137         for (i = 0; i < nr_enums; i++) {
4138                 if (v != enums[i].val)
4139                         continue;
4140
4141                 btf_show_type_value(show, "%s",
4142                                     __btf_name_by_offset(btf,
4143                                                          enums[i].name_off));
4144
4145                 btf_show_end_type(show);
4146                 return;
4147         }
4148
4149         if (btf_type_kflag(t))
4150                 btf_show_type_value(show, "%d", v);
4151         else
4152                 btf_show_type_value(show, "%u", v);
4153         btf_show_end_type(show);
4154 }
4155
4156 static struct btf_kind_operations enum_ops = {
4157         .check_meta = btf_enum_check_meta,
4158         .resolve = btf_df_resolve,
4159         .check_member = btf_enum_check_member,
4160         .check_kflag_member = btf_enum_check_kflag_member,
4161         .log_details = btf_enum_log,
4162         .show = btf_enum_show,
4163 };
4164
4165 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4166                                  const struct btf_type *t,
4167                                  u32 meta_left)
4168 {
4169         const struct btf_enum64 *enums = btf_type_enum64(t);
4170         struct btf *btf = env->btf;
4171         const char *fmt_str;
4172         u16 i, nr_enums;
4173         u32 meta_needed;
4174
4175         nr_enums = btf_type_vlen(t);
4176         meta_needed = nr_enums * sizeof(*enums);
4177
4178         if (meta_left < meta_needed) {
4179                 btf_verifier_log_basic(env, t,
4180                                        "meta_left:%u meta_needed:%u",
4181                                        meta_left, meta_needed);
4182                 return -EINVAL;
4183         }
4184
4185         if (t->size > 8 || !is_power_of_2(t->size)) {
4186                 btf_verifier_log_type(env, t, "Unexpected size");
4187                 return -EINVAL;
4188         }
4189
4190         /* enum type either no name or a valid one */
4191         if (t->name_off &&
4192             !btf_name_valid_identifier(env->btf, t->name_off)) {
4193                 btf_verifier_log_type(env, t, "Invalid name");
4194                 return -EINVAL;
4195         }
4196
4197         btf_verifier_log_type(env, t, NULL);
4198
4199         for (i = 0; i < nr_enums; i++) {
4200                 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4201                         btf_verifier_log(env, "\tInvalid name_offset:%u",
4202                                          enums[i].name_off);
4203                         return -EINVAL;
4204                 }
4205
4206                 /* enum member must have a valid name */
4207                 if (!enums[i].name_off ||
4208                     !btf_name_valid_identifier(btf, enums[i].name_off)) {
4209                         btf_verifier_log_type(env, t, "Invalid name");
4210                         return -EINVAL;
4211                 }
4212
4213                 if (env->log.level == BPF_LOG_KERNEL)
4214                         continue;
4215
4216                 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4217                 btf_verifier_log(env, fmt_str,
4218                                  __btf_name_by_offset(btf, enums[i].name_off),
4219                                  btf_enum64_value(enums + i));
4220         }
4221
4222         return meta_needed;
4223 }
4224
4225 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4226                             u32 type_id, void *data, u8 bits_offset,
4227                             struct btf_show *show)
4228 {
4229         const struct btf_enum64 *enums = btf_type_enum64(t);
4230         u32 i, nr_enums = btf_type_vlen(t);
4231         void *safe_data;
4232         s64 v;
4233
4234         safe_data = btf_show_start_type(show, t, type_id, data);
4235         if (!safe_data)
4236                 return;
4237
4238         v = *(u64 *)safe_data;
4239
4240         for (i = 0; i < nr_enums; i++) {
4241                 if (v != btf_enum64_value(enums + i))
4242                         continue;
4243
4244                 btf_show_type_value(show, "%s",
4245                                     __btf_name_by_offset(btf,
4246                                                          enums[i].name_off));
4247
4248                 btf_show_end_type(show);
4249                 return;
4250         }
4251
4252         if (btf_type_kflag(t))
4253                 btf_show_type_value(show, "%lld", v);
4254         else
4255                 btf_show_type_value(show, "%llu", v);
4256         btf_show_end_type(show);
4257 }
4258
4259 static struct btf_kind_operations enum64_ops = {
4260         .check_meta = btf_enum64_check_meta,
4261         .resolve = btf_df_resolve,
4262         .check_member = btf_enum_check_member,
4263         .check_kflag_member = btf_enum_check_kflag_member,
4264         .log_details = btf_enum_log,
4265         .show = btf_enum64_show,
4266 };
4267
4268 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4269                                      const struct btf_type *t,
4270                                      u32 meta_left)
4271 {
4272         u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4273
4274         if (meta_left < meta_needed) {
4275                 btf_verifier_log_basic(env, t,
4276                                        "meta_left:%u meta_needed:%u",
4277                                        meta_left, meta_needed);
4278                 return -EINVAL;
4279         }
4280
4281         if (t->name_off) {
4282                 btf_verifier_log_type(env, t, "Invalid name");
4283                 return -EINVAL;
4284         }
4285
4286         if (btf_type_kflag(t)) {
4287                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4288                 return -EINVAL;
4289         }
4290
4291         btf_verifier_log_type(env, t, NULL);
4292
4293         return meta_needed;
4294 }
4295
4296 static void btf_func_proto_log(struct btf_verifier_env *env,
4297                                const struct btf_type *t)
4298 {
4299         const struct btf_param *args = (const struct btf_param *)(t + 1);
4300         u16 nr_args = btf_type_vlen(t), i;
4301
4302         btf_verifier_log(env, "return=%u args=(", t->type);
4303         if (!nr_args) {
4304                 btf_verifier_log(env, "void");
4305                 goto done;
4306         }
4307
4308         if (nr_args == 1 && !args[0].type) {
4309                 /* Only one vararg */
4310                 btf_verifier_log(env, "vararg");
4311                 goto done;
4312         }
4313
4314         btf_verifier_log(env, "%u %s", args[0].type,
4315                          __btf_name_by_offset(env->btf,
4316                                               args[0].name_off));
4317         for (i = 1; i < nr_args - 1; i++)
4318                 btf_verifier_log(env, ", %u %s", args[i].type,
4319                                  __btf_name_by_offset(env->btf,
4320                                                       args[i].name_off));
4321
4322         if (nr_args > 1) {
4323                 const struct btf_param *last_arg = &args[nr_args - 1];
4324
4325                 if (last_arg->type)
4326                         btf_verifier_log(env, ", %u %s", last_arg->type,
4327                                          __btf_name_by_offset(env->btf,
4328                                                               last_arg->name_off));
4329                 else
4330                         btf_verifier_log(env, ", vararg");
4331         }
4332
4333 done:
4334         btf_verifier_log(env, ")");
4335 }
4336
4337 static struct btf_kind_operations func_proto_ops = {
4338         .check_meta = btf_func_proto_check_meta,
4339         .resolve = btf_df_resolve,
4340         /*
4341          * BTF_KIND_FUNC_PROTO cannot be directly referred by
4342          * a struct's member.
4343          *
4344          * It should be a function pointer instead.
4345          * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4346          *
4347          * Hence, there is no btf_func_check_member().
4348          */
4349         .check_member = btf_df_check_member,
4350         .check_kflag_member = btf_df_check_kflag_member,
4351         .log_details = btf_func_proto_log,
4352         .show = btf_df_show,
4353 };
4354
4355 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4356                                const struct btf_type *t,
4357                                u32 meta_left)
4358 {
4359         if (!t->name_off ||
4360             !btf_name_valid_identifier(env->btf, t->name_off)) {
4361                 btf_verifier_log_type(env, t, "Invalid name");
4362                 return -EINVAL;
4363         }
4364
4365         if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4366                 btf_verifier_log_type(env, t, "Invalid func linkage");
4367                 return -EINVAL;
4368         }
4369
4370         if (btf_type_kflag(t)) {
4371                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4372                 return -EINVAL;
4373         }
4374
4375         btf_verifier_log_type(env, t, NULL);
4376
4377         return 0;
4378 }
4379
4380 static int btf_func_resolve(struct btf_verifier_env *env,
4381                             const struct resolve_vertex *v)
4382 {
4383         const struct btf_type *t = v->t;
4384         u32 next_type_id = t->type;
4385         int err;
4386
4387         err = btf_func_check(env, t);
4388         if (err)
4389                 return err;
4390
4391         env_stack_pop_resolved(env, next_type_id, 0);
4392         return 0;
4393 }
4394
4395 static struct btf_kind_operations func_ops = {
4396         .check_meta = btf_func_check_meta,
4397         .resolve = btf_func_resolve,
4398         .check_member = btf_df_check_member,
4399         .check_kflag_member = btf_df_check_kflag_member,
4400         .log_details = btf_ref_type_log,
4401         .show = btf_df_show,
4402 };
4403
4404 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4405                               const struct btf_type *t,
4406                               u32 meta_left)
4407 {
4408         const struct btf_var *var;
4409         u32 meta_needed = sizeof(*var);
4410
4411         if (meta_left < meta_needed) {
4412                 btf_verifier_log_basic(env, t,
4413                                        "meta_left:%u meta_needed:%u",
4414                                        meta_left, meta_needed);
4415                 return -EINVAL;
4416         }
4417
4418         if (btf_type_vlen(t)) {
4419                 btf_verifier_log_type(env, t, "vlen != 0");
4420                 return -EINVAL;
4421         }
4422
4423         if (btf_type_kflag(t)) {
4424                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4425                 return -EINVAL;
4426         }
4427
4428         if (!t->name_off ||
4429             !__btf_name_valid(env->btf, t->name_off)) {
4430                 btf_verifier_log_type(env, t, "Invalid name");
4431                 return -EINVAL;
4432         }
4433
4434         /* A var cannot be in type void */
4435         if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4436                 btf_verifier_log_type(env, t, "Invalid type_id");
4437                 return -EINVAL;
4438         }
4439
4440         var = btf_type_var(t);
4441         if (var->linkage != BTF_VAR_STATIC &&
4442             var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4443                 btf_verifier_log_type(env, t, "Linkage not supported");
4444                 return -EINVAL;
4445         }
4446
4447         btf_verifier_log_type(env, t, NULL);
4448
4449         return meta_needed;
4450 }
4451
4452 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4453 {
4454         const struct btf_var *var = btf_type_var(t);
4455
4456         btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4457 }
4458
4459 static const struct btf_kind_operations var_ops = {
4460         .check_meta             = btf_var_check_meta,
4461         .resolve                = btf_var_resolve,
4462         .check_member           = btf_df_check_member,
4463         .check_kflag_member     = btf_df_check_kflag_member,
4464         .log_details            = btf_var_log,
4465         .show                   = btf_var_show,
4466 };
4467
4468 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4469                                   const struct btf_type *t,
4470                                   u32 meta_left)
4471 {
4472         const struct btf_var_secinfo *vsi;
4473         u64 last_vsi_end_off = 0, sum = 0;
4474         u32 i, meta_needed;
4475
4476         meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4477         if (meta_left < meta_needed) {
4478                 btf_verifier_log_basic(env, t,
4479                                        "meta_left:%u meta_needed:%u",
4480                                        meta_left, meta_needed);
4481                 return -EINVAL;
4482         }
4483
4484         if (!t->size) {
4485                 btf_verifier_log_type(env, t, "size == 0");
4486                 return -EINVAL;
4487         }
4488
4489         if (btf_type_kflag(t)) {
4490                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4491                 return -EINVAL;
4492         }
4493
4494         if (!t->name_off ||
4495             !btf_name_valid_section(env->btf, t->name_off)) {
4496                 btf_verifier_log_type(env, t, "Invalid name");
4497                 return -EINVAL;
4498         }
4499
4500         btf_verifier_log_type(env, t, NULL);
4501
4502         for_each_vsi(i, t, vsi) {
4503                 /* A var cannot be in type void */
4504                 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4505                         btf_verifier_log_vsi(env, t, vsi,
4506                                              "Invalid type_id");
4507                         return -EINVAL;
4508                 }
4509
4510                 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4511                         btf_verifier_log_vsi(env, t, vsi,
4512                                              "Invalid offset");
4513                         return -EINVAL;
4514                 }
4515
4516                 if (!vsi->size || vsi->size > t->size) {
4517                         btf_verifier_log_vsi(env, t, vsi,
4518                                              "Invalid size");
4519                         return -EINVAL;
4520                 }
4521
4522                 last_vsi_end_off = vsi->offset + vsi->size;
4523                 if (last_vsi_end_off > t->size) {
4524                         btf_verifier_log_vsi(env, t, vsi,
4525                                              "Invalid offset+size");
4526                         return -EINVAL;
4527                 }
4528
4529                 btf_verifier_log_vsi(env, t, vsi, NULL);
4530                 sum += vsi->size;
4531         }
4532
4533         if (t->size < sum) {
4534                 btf_verifier_log_type(env, t, "Invalid btf_info size");
4535                 return -EINVAL;
4536         }
4537
4538         return meta_needed;
4539 }
4540
4541 static int btf_datasec_resolve(struct btf_verifier_env *env,
4542                                const struct resolve_vertex *v)
4543 {
4544         const struct btf_var_secinfo *vsi;
4545         struct btf *btf = env->btf;
4546         u16 i;
4547
4548         env->resolve_mode = RESOLVE_TBD;
4549         for_each_vsi_from(i, v->next_member, v->t, vsi) {
4550                 u32 var_type_id = vsi->type, type_id, type_size = 0;
4551                 const struct btf_type *var_type = btf_type_by_id(env->btf,
4552                                                                  var_type_id);
4553                 if (!var_type || !btf_type_is_var(var_type)) {
4554                         btf_verifier_log_vsi(env, v->t, vsi,
4555                                              "Not a VAR kind member");
4556                         return -EINVAL;
4557                 }
4558
4559                 if (!env_type_is_resolve_sink(env, var_type) &&
4560                     !env_type_is_resolved(env, var_type_id)) {
4561                         env_stack_set_next_member(env, i + 1);
4562                         return env_stack_push(env, var_type, var_type_id);
4563                 }
4564
4565                 type_id = var_type->type;
4566                 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4567                         btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4568                         return -EINVAL;
4569                 }
4570
4571                 if (vsi->size < type_size) {
4572                         btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4573                         return -EINVAL;
4574                 }
4575         }
4576
4577         env_stack_pop_resolved(env, 0, 0);
4578         return 0;
4579 }
4580
4581 static void btf_datasec_log(struct btf_verifier_env *env,
4582                             const struct btf_type *t)
4583 {
4584         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4585 }
4586
4587 static void btf_datasec_show(const struct btf *btf,
4588                              const struct btf_type *t, u32 type_id,
4589                              void *data, u8 bits_offset,
4590                              struct btf_show *show)
4591 {
4592         const struct btf_var_secinfo *vsi;
4593         const struct btf_type *var;
4594         u32 i;
4595
4596         if (!btf_show_start_type(show, t, type_id, data))
4597                 return;
4598
4599         btf_show_type_value(show, "section (\"%s\") = {",
4600                             __btf_name_by_offset(btf, t->name_off));
4601         for_each_vsi(i, t, vsi) {
4602                 var = btf_type_by_id(btf, vsi->type);
4603                 if (i)
4604                         btf_show(show, ",");
4605                 btf_type_ops(var)->show(btf, var, vsi->type,
4606                                         data + vsi->offset, bits_offset, show);
4607         }
4608         btf_show_end_type(show);
4609 }
4610
4611 static const struct btf_kind_operations datasec_ops = {
4612         .check_meta             = btf_datasec_check_meta,
4613         .resolve                = btf_datasec_resolve,
4614         .check_member           = btf_df_check_member,
4615         .check_kflag_member     = btf_df_check_kflag_member,
4616         .log_details            = btf_datasec_log,
4617         .show                   = btf_datasec_show,
4618 };
4619
4620 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4621                                 const struct btf_type *t,
4622                                 u32 meta_left)
4623 {
4624         if (btf_type_vlen(t)) {
4625                 btf_verifier_log_type(env, t, "vlen != 0");
4626                 return -EINVAL;
4627         }
4628
4629         if (btf_type_kflag(t)) {
4630                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4631                 return -EINVAL;
4632         }
4633
4634         if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4635             t->size != 16) {
4636                 btf_verifier_log_type(env, t, "Invalid type_size");
4637                 return -EINVAL;
4638         }
4639
4640         btf_verifier_log_type(env, t, NULL);
4641
4642         return 0;
4643 }
4644
4645 static int btf_float_check_member(struct btf_verifier_env *env,
4646                                   const struct btf_type *struct_type,
4647                                   const struct btf_member *member,
4648                                   const struct btf_type *member_type)
4649 {
4650         u64 start_offset_bytes;
4651         u64 end_offset_bytes;
4652         u64 misalign_bits;
4653         u64 align_bytes;
4654         u64 align_bits;
4655
4656         /* Different architectures have different alignment requirements, so
4657          * here we check only for the reasonable minimum. This way we ensure
4658          * that types after CO-RE can pass the kernel BTF verifier.
4659          */
4660         align_bytes = min_t(u64, sizeof(void *), member_type->size);
4661         align_bits = align_bytes * BITS_PER_BYTE;
4662         div64_u64_rem(member->offset, align_bits, &misalign_bits);
4663         if (misalign_bits) {
4664                 btf_verifier_log_member(env, struct_type, member,
4665                                         "Member is not properly aligned");
4666                 return -EINVAL;
4667         }
4668
4669         start_offset_bytes = member->offset / BITS_PER_BYTE;
4670         end_offset_bytes = start_offset_bytes + member_type->size;
4671         if (end_offset_bytes > struct_type->size) {
4672                 btf_verifier_log_member(env, struct_type, member,
4673                                         "Member exceeds struct_size");
4674                 return -EINVAL;
4675         }
4676
4677         return 0;
4678 }
4679
4680 static void btf_float_log(struct btf_verifier_env *env,
4681                           const struct btf_type *t)
4682 {
4683         btf_verifier_log(env, "size=%u", t->size);
4684 }
4685
4686 static const struct btf_kind_operations float_ops = {
4687         .check_meta = btf_float_check_meta,
4688         .resolve = btf_df_resolve,
4689         .check_member = btf_float_check_member,
4690         .check_kflag_member = btf_generic_check_kflag_member,
4691         .log_details = btf_float_log,
4692         .show = btf_df_show,
4693 };
4694
4695 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4696                               const struct btf_type *t,
4697                               u32 meta_left)
4698 {
4699         const struct btf_decl_tag *tag;
4700         u32 meta_needed = sizeof(*tag);
4701         s32 component_idx;
4702         const char *value;
4703
4704         if (meta_left < meta_needed) {
4705                 btf_verifier_log_basic(env, t,
4706                                        "meta_left:%u meta_needed:%u",
4707                                        meta_left, meta_needed);
4708                 return -EINVAL;
4709         }
4710
4711         value = btf_name_by_offset(env->btf, t->name_off);
4712         if (!value || !value[0]) {
4713                 btf_verifier_log_type(env, t, "Invalid value");
4714                 return -EINVAL;
4715         }
4716
4717         if (btf_type_vlen(t)) {
4718                 btf_verifier_log_type(env, t, "vlen != 0");
4719                 return -EINVAL;
4720         }
4721
4722         if (btf_type_kflag(t)) {
4723                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4724                 return -EINVAL;
4725         }
4726
4727         component_idx = btf_type_decl_tag(t)->component_idx;
4728         if (component_idx < -1) {
4729                 btf_verifier_log_type(env, t, "Invalid component_idx");
4730                 return -EINVAL;
4731         }
4732
4733         btf_verifier_log_type(env, t, NULL);
4734
4735         return meta_needed;
4736 }
4737
4738 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4739                            const struct resolve_vertex *v)
4740 {
4741         const struct btf_type *next_type;
4742         const struct btf_type *t = v->t;
4743         u32 next_type_id = t->type;
4744         struct btf *btf = env->btf;
4745         s32 component_idx;
4746         u32 vlen;
4747
4748         next_type = btf_type_by_id(btf, next_type_id);
4749         if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4750                 btf_verifier_log_type(env, v->t, "Invalid type_id");
4751                 return -EINVAL;
4752         }
4753
4754         if (!env_type_is_resolve_sink(env, next_type) &&
4755             !env_type_is_resolved(env, next_type_id))
4756                 return env_stack_push(env, next_type, next_type_id);
4757
4758         component_idx = btf_type_decl_tag(t)->component_idx;
4759         if (component_idx != -1) {
4760                 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4761                         btf_verifier_log_type(env, v->t, "Invalid component_idx");
4762                         return -EINVAL;
4763                 }
4764
4765                 if (btf_type_is_struct(next_type)) {
4766                         vlen = btf_type_vlen(next_type);
4767                 } else {
4768                         /* next_type should be a function */
4769                         next_type = btf_type_by_id(btf, next_type->type);
4770                         vlen = btf_type_vlen(next_type);
4771                 }
4772
4773                 if ((u32)component_idx >= vlen) {
4774                         btf_verifier_log_type(env, v->t, "Invalid component_idx");
4775                         return -EINVAL;
4776                 }
4777         }
4778
4779         env_stack_pop_resolved(env, next_type_id, 0);
4780
4781         return 0;
4782 }
4783
4784 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4785 {
4786         btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4787                          btf_type_decl_tag(t)->component_idx);
4788 }
4789
4790 static const struct btf_kind_operations decl_tag_ops = {
4791         .check_meta = btf_decl_tag_check_meta,
4792         .resolve = btf_decl_tag_resolve,
4793         .check_member = btf_df_check_member,
4794         .check_kflag_member = btf_df_check_kflag_member,
4795         .log_details = btf_decl_tag_log,
4796         .show = btf_df_show,
4797 };
4798
4799 static int btf_func_proto_check(struct btf_verifier_env *env,
4800                                 const struct btf_type *t)
4801 {
4802         const struct btf_type *ret_type;
4803         const struct btf_param *args;
4804         const struct btf *btf;
4805         u16 nr_args, i;
4806         int err;
4807
4808         btf = env->btf;
4809         args = (const struct btf_param *)(t + 1);
4810         nr_args = btf_type_vlen(t);
4811
4812         /* Check func return type which could be "void" (t->type == 0) */
4813         if (t->type) {
4814                 u32 ret_type_id = t->type;
4815
4816                 ret_type = btf_type_by_id(btf, ret_type_id);
4817                 if (!ret_type) {
4818                         btf_verifier_log_type(env, t, "Invalid return type");
4819                         return -EINVAL;
4820                 }
4821
4822                 if (btf_type_is_resolve_source_only(ret_type)) {
4823                         btf_verifier_log_type(env, t, "Invalid return type");
4824                         return -EINVAL;
4825                 }
4826
4827                 if (btf_type_needs_resolve(ret_type) &&
4828                     !env_type_is_resolved(env, ret_type_id)) {
4829                         err = btf_resolve(env, ret_type, ret_type_id);
4830                         if (err)
4831                                 return err;
4832                 }
4833
4834                 /* Ensure the return type is a type that has a size */
4835                 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4836                         btf_verifier_log_type(env, t, "Invalid return type");
4837                         return -EINVAL;
4838                 }
4839         }
4840
4841         if (!nr_args)
4842                 return 0;
4843
4844         /* Last func arg type_id could be 0 if it is a vararg */
4845         if (!args[nr_args - 1].type) {
4846                 if (args[nr_args - 1].name_off) {
4847                         btf_verifier_log_type(env, t, "Invalid arg#%u",
4848                                               nr_args);
4849                         return -EINVAL;
4850                 }
4851                 nr_args--;
4852         }
4853
4854         for (i = 0; i < nr_args; i++) {
4855                 const struct btf_type *arg_type;
4856                 u32 arg_type_id;
4857
4858                 arg_type_id = args[i].type;
4859                 arg_type = btf_type_by_id(btf, arg_type_id);
4860                 if (!arg_type) {
4861                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4862                         return -EINVAL;
4863                 }
4864
4865                 if (btf_type_is_resolve_source_only(arg_type)) {
4866                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4867                         return -EINVAL;
4868                 }
4869
4870                 if (args[i].name_off &&
4871                     (!btf_name_offset_valid(btf, args[i].name_off) ||
4872                      !btf_name_valid_identifier(btf, args[i].name_off))) {
4873                         btf_verifier_log_type(env, t,
4874                                               "Invalid arg#%u", i + 1);
4875                         return -EINVAL;
4876                 }
4877
4878                 if (btf_type_needs_resolve(arg_type) &&
4879                     !env_type_is_resolved(env, arg_type_id)) {
4880                         err = btf_resolve(env, arg_type, arg_type_id);
4881                         if (err)
4882                                 return err;
4883                 }
4884
4885                 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4886                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4887                         return -EINVAL;
4888                 }
4889         }
4890
4891         return 0;
4892 }
4893
4894 static int btf_func_check(struct btf_verifier_env *env,
4895                           const struct btf_type *t)
4896 {
4897         const struct btf_type *proto_type;
4898         const struct btf_param *args;
4899         const struct btf *btf;
4900         u16 nr_args, i;
4901
4902         btf = env->btf;
4903         proto_type = btf_type_by_id(btf, t->type);
4904
4905         if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4906                 btf_verifier_log_type(env, t, "Invalid type_id");
4907                 return -EINVAL;
4908         }
4909
4910         args = (const struct btf_param *)(proto_type + 1);
4911         nr_args = btf_type_vlen(proto_type);
4912         for (i = 0; i < nr_args; i++) {
4913                 if (!args[i].name_off && args[i].type) {
4914                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4915                         return -EINVAL;
4916                 }
4917         }
4918
4919         return 0;
4920 }
4921
4922 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4923         [BTF_KIND_INT] = &int_ops,
4924         [BTF_KIND_PTR] = &ptr_ops,
4925         [BTF_KIND_ARRAY] = &array_ops,
4926         [BTF_KIND_STRUCT] = &struct_ops,
4927         [BTF_KIND_UNION] = &struct_ops,
4928         [BTF_KIND_ENUM] = &enum_ops,
4929         [BTF_KIND_FWD] = &fwd_ops,
4930         [BTF_KIND_TYPEDEF] = &modifier_ops,
4931         [BTF_KIND_VOLATILE] = &modifier_ops,
4932         [BTF_KIND_CONST] = &modifier_ops,
4933         [BTF_KIND_RESTRICT] = &modifier_ops,
4934         [BTF_KIND_FUNC] = &func_ops,
4935         [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4936         [BTF_KIND_VAR] = &var_ops,
4937         [BTF_KIND_DATASEC] = &datasec_ops,
4938         [BTF_KIND_FLOAT] = &float_ops,
4939         [BTF_KIND_DECL_TAG] = &decl_tag_ops,
4940         [BTF_KIND_TYPE_TAG] = &modifier_ops,
4941         [BTF_KIND_ENUM64] = &enum64_ops,
4942 };
4943
4944 static s32 btf_check_meta(struct btf_verifier_env *env,
4945                           const struct btf_type *t,
4946                           u32 meta_left)
4947 {
4948         u32 saved_meta_left = meta_left;
4949         s32 var_meta_size;
4950
4951         if (meta_left < sizeof(*t)) {
4952                 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4953                                  env->log_type_id, meta_left, sizeof(*t));
4954                 return -EINVAL;
4955         }
4956         meta_left -= sizeof(*t);
4957
4958         if (t->info & ~BTF_INFO_MASK) {
4959                 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4960                                  env->log_type_id, t->info);
4961                 return -EINVAL;
4962         }
4963
4964         if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4965             BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4966                 btf_verifier_log(env, "[%u] Invalid kind:%u",
4967                                  env->log_type_id, BTF_INFO_KIND(t->info));
4968                 return -EINVAL;
4969         }
4970
4971         if (!btf_name_offset_valid(env->btf, t->name_off)) {
4972                 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4973                                  env->log_type_id, t->name_off);
4974                 return -EINVAL;
4975         }
4976
4977         var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4978         if (var_meta_size < 0)
4979                 return var_meta_size;
4980
4981         meta_left -= var_meta_size;
4982
4983         return saved_meta_left - meta_left;
4984 }
4985
4986 static int btf_check_all_metas(struct btf_verifier_env *env)
4987 {
4988         struct btf *btf = env->btf;
4989         struct btf_header *hdr;
4990         void *cur, *end;
4991
4992         hdr = &btf->hdr;
4993         cur = btf->nohdr_data + hdr->type_off;
4994         end = cur + hdr->type_len;
4995
4996         env->log_type_id = btf->base_btf ? btf->start_id : 1;
4997         while (cur < end) {
4998                 struct btf_type *t = cur;
4999                 s32 meta_size;
5000
5001                 meta_size = btf_check_meta(env, t, end - cur);
5002                 if (meta_size < 0)
5003                         return meta_size;
5004
5005                 btf_add_type(env, t);
5006                 cur += meta_size;
5007                 env->log_type_id++;
5008         }
5009
5010         return 0;
5011 }
5012
5013 static bool btf_resolve_valid(struct btf_verifier_env *env,
5014                               const struct btf_type *t,
5015                               u32 type_id)
5016 {
5017         struct btf *btf = env->btf;
5018
5019         if (!env_type_is_resolved(env, type_id))
5020                 return false;
5021
5022         if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5023                 return !btf_resolved_type_id(btf, type_id) &&
5024                        !btf_resolved_type_size(btf, type_id);
5025
5026         if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5027                 return btf_resolved_type_id(btf, type_id) &&
5028                        !btf_resolved_type_size(btf, type_id);
5029
5030         if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5031             btf_type_is_var(t)) {
5032                 t = btf_type_id_resolve(btf, &type_id);
5033                 return t &&
5034                        !btf_type_is_modifier(t) &&
5035                        !btf_type_is_var(t) &&
5036                        !btf_type_is_datasec(t);
5037         }
5038
5039         if (btf_type_is_array(t)) {
5040                 const struct btf_array *array = btf_type_array(t);
5041                 const struct btf_type *elem_type;
5042                 u32 elem_type_id = array->type;
5043                 u32 elem_size;
5044
5045                 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5046                 return elem_type && !btf_type_is_modifier(elem_type) &&
5047                         (array->nelems * elem_size ==
5048                          btf_resolved_type_size(btf, type_id));
5049         }
5050
5051         return false;
5052 }
5053
5054 static int btf_resolve(struct btf_verifier_env *env,
5055                        const struct btf_type *t, u32 type_id)
5056 {
5057         u32 save_log_type_id = env->log_type_id;
5058         const struct resolve_vertex *v;
5059         int err = 0;
5060
5061         env->resolve_mode = RESOLVE_TBD;
5062         env_stack_push(env, t, type_id);
5063         while (!err && (v = env_stack_peak(env))) {
5064                 env->log_type_id = v->type_id;
5065                 err = btf_type_ops(v->t)->resolve(env, v);
5066         }
5067
5068         env->log_type_id = type_id;
5069         if (err == -E2BIG) {
5070                 btf_verifier_log_type(env, t,
5071                                       "Exceeded max resolving depth:%u",
5072                                       MAX_RESOLVE_DEPTH);
5073         } else if (err == -EEXIST) {
5074                 btf_verifier_log_type(env, t, "Loop detected");
5075         }
5076
5077         /* Final sanity check */
5078         if (!err && !btf_resolve_valid(env, t, type_id)) {
5079                 btf_verifier_log_type(env, t, "Invalid resolve state");
5080                 err = -EINVAL;
5081         }
5082
5083         env->log_type_id = save_log_type_id;
5084         return err;
5085 }
5086
5087 static int btf_check_all_types(struct btf_verifier_env *env)
5088 {
5089         struct btf *btf = env->btf;
5090         const struct btf_type *t;
5091         u32 type_id, i;
5092         int err;
5093
5094         err = env_resolve_init(env);
5095         if (err)
5096                 return err;
5097
5098         env->phase++;
5099         for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5100                 type_id = btf->start_id + i;
5101                 t = btf_type_by_id(btf, type_id);
5102
5103                 env->log_type_id = type_id;
5104                 if (btf_type_needs_resolve(t) &&
5105                     !env_type_is_resolved(env, type_id)) {
5106                         err = btf_resolve(env, t, type_id);
5107                         if (err)
5108                                 return err;
5109                 }
5110
5111                 if (btf_type_is_func_proto(t)) {
5112                         err = btf_func_proto_check(env, t);
5113                         if (err)
5114                                 return err;
5115                 }
5116         }
5117
5118         return 0;
5119 }
5120
5121 static int btf_parse_type_sec(struct btf_verifier_env *env)
5122 {
5123         const struct btf_header *hdr = &env->btf->hdr;
5124         int err;
5125
5126         /* Type section must align to 4 bytes */
5127         if (hdr->type_off & (sizeof(u32) - 1)) {
5128                 btf_verifier_log(env, "Unaligned type_off");
5129                 return -EINVAL;
5130         }
5131
5132         if (!env->btf->base_btf && !hdr->type_len) {
5133                 btf_verifier_log(env, "No type found");
5134                 return -EINVAL;
5135         }
5136
5137         err = btf_check_all_metas(env);
5138         if (err)
5139                 return err;
5140
5141         return btf_check_all_types(env);
5142 }
5143
5144 static int btf_parse_str_sec(struct btf_verifier_env *env)
5145 {
5146         const struct btf_header *hdr;
5147         struct btf *btf = env->btf;
5148         const char *start, *end;
5149
5150         hdr = &btf->hdr;
5151         start = btf->nohdr_data + hdr->str_off;
5152         end = start + hdr->str_len;
5153
5154         if (end != btf->data + btf->data_size) {
5155                 btf_verifier_log(env, "String section is not at the end");
5156                 return -EINVAL;
5157         }
5158
5159         btf->strings = start;
5160
5161         if (btf->base_btf && !hdr->str_len)
5162                 return 0;
5163         if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5164                 btf_verifier_log(env, "Invalid string section");
5165                 return -EINVAL;
5166         }
5167         if (!btf->base_btf && start[0]) {
5168                 btf_verifier_log(env, "Invalid string section");
5169                 return -EINVAL;
5170         }
5171
5172         return 0;
5173 }
5174
5175 static const size_t btf_sec_info_offset[] = {
5176         offsetof(struct btf_header, type_off),
5177         offsetof(struct btf_header, str_off),
5178 };
5179
5180 static int btf_sec_info_cmp(const void *a, const void *b)
5181 {
5182         const struct btf_sec_info *x = a;
5183         const struct btf_sec_info *y = b;
5184
5185         return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5186 }
5187
5188 static int btf_check_sec_info(struct btf_verifier_env *env,
5189                               u32 btf_data_size)
5190 {
5191         struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5192         u32 total, expected_total, i;
5193         const struct btf_header *hdr;
5194         const struct btf *btf;
5195
5196         btf = env->btf;
5197         hdr = &btf->hdr;
5198
5199         /* Populate the secs from hdr */
5200         for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5201                 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5202                                                    btf_sec_info_offset[i]);
5203
5204         sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5205              sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5206
5207         /* Check for gaps and overlap among sections */
5208         total = 0;
5209         expected_total = btf_data_size - hdr->hdr_len;
5210         for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5211                 if (expected_total < secs[i].off) {
5212                         btf_verifier_log(env, "Invalid section offset");
5213                         return -EINVAL;
5214                 }
5215                 if (total < secs[i].off) {
5216                         /* gap */
5217                         btf_verifier_log(env, "Unsupported section found");
5218                         return -EINVAL;
5219                 }
5220                 if (total > secs[i].off) {
5221                         btf_verifier_log(env, "Section overlap found");
5222                         return -EINVAL;
5223                 }
5224                 if (expected_total - total < secs[i].len) {
5225                         btf_verifier_log(env,
5226                                          "Total section length too long");
5227                         return -EINVAL;
5228                 }
5229                 total += secs[i].len;
5230         }
5231
5232         /* There is data other than hdr and known sections */
5233         if (expected_total != total) {
5234                 btf_verifier_log(env, "Unsupported section found");
5235                 return -EINVAL;
5236         }
5237
5238         return 0;
5239 }
5240
5241 static int btf_parse_hdr(struct btf_verifier_env *env)
5242 {
5243         u32 hdr_len, hdr_copy, btf_data_size;
5244         const struct btf_header *hdr;
5245         struct btf *btf;
5246
5247         btf = env->btf;
5248         btf_data_size = btf->data_size;
5249
5250         if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5251                 btf_verifier_log(env, "hdr_len not found");
5252                 return -EINVAL;
5253         }
5254
5255         hdr = btf->data;
5256         hdr_len = hdr->hdr_len;
5257         if (btf_data_size < hdr_len) {
5258                 btf_verifier_log(env, "btf_header not found");
5259                 return -EINVAL;
5260         }
5261
5262         /* Ensure the unsupported header fields are zero */
5263         if (hdr_len > sizeof(btf->hdr)) {
5264                 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5265                 u8 *end = btf->data + hdr_len;
5266
5267                 for (; expected_zero < end; expected_zero++) {
5268                         if (*expected_zero) {
5269                                 btf_verifier_log(env, "Unsupported btf_header");
5270                                 return -E2BIG;
5271                         }
5272                 }
5273         }
5274
5275         hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5276         memcpy(&btf->hdr, btf->data, hdr_copy);
5277
5278         hdr = &btf->hdr;
5279
5280         btf_verifier_log_hdr(env, btf_data_size);
5281
5282         if (hdr->magic != BTF_MAGIC) {
5283                 btf_verifier_log(env, "Invalid magic");
5284                 return -EINVAL;
5285         }
5286
5287         if (hdr->version != BTF_VERSION) {
5288                 btf_verifier_log(env, "Unsupported version");
5289                 return -ENOTSUPP;
5290         }
5291
5292         if (hdr->flags) {
5293                 btf_verifier_log(env, "Unsupported flags");
5294                 return -ENOTSUPP;
5295         }
5296
5297         if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5298                 btf_verifier_log(env, "No data");
5299                 return -EINVAL;
5300         }
5301
5302         return btf_check_sec_info(env, btf_data_size);
5303 }
5304
5305 static const char *alloc_obj_fields[] = {
5306         "bpf_spin_lock",
5307         "bpf_list_head",
5308         "bpf_list_node",
5309         "bpf_rb_root",
5310         "bpf_rb_node",
5311         "bpf_refcount",
5312 };
5313
5314 static struct btf_struct_metas *
5315 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5316 {
5317         union {
5318                 struct btf_id_set set;
5319                 struct {
5320                         u32 _cnt;
5321                         u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5322                 } _arr;
5323         } aof;
5324         struct btf_struct_metas *tab = NULL;
5325         int i, n, id, ret;
5326
5327         BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5328         BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5329
5330         memset(&aof, 0, sizeof(aof));
5331         for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5332                 /* Try to find whether this special type exists in user BTF, and
5333                  * if so remember its ID so we can easily find it among members
5334                  * of structs that we iterate in the next loop.
5335                  */
5336                 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5337                 if (id < 0)
5338                         continue;
5339                 aof.set.ids[aof.set.cnt++] = id;
5340         }
5341
5342         if (!aof.set.cnt)
5343                 return NULL;
5344         sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5345
5346         n = btf_nr_types(btf);
5347         for (i = 1; i < n; i++) {
5348                 struct btf_struct_metas *new_tab;
5349                 const struct btf_member *member;
5350                 struct btf_struct_meta *type;
5351                 struct btf_record *record;
5352                 const struct btf_type *t;
5353                 int j, tab_cnt;
5354
5355                 t = btf_type_by_id(btf, i);
5356                 if (!t) {
5357                         ret = -EINVAL;
5358                         goto free;
5359                 }
5360                 if (!__btf_type_is_struct(t))
5361                         continue;
5362
5363                 cond_resched();
5364
5365                 for_each_member(j, t, member) {
5366                         if (btf_id_set_contains(&aof.set, member->type))
5367                                 goto parse;
5368                 }
5369                 continue;
5370         parse:
5371                 tab_cnt = tab ? tab->cnt : 0;
5372                 new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5373                                    GFP_KERNEL | __GFP_NOWARN);
5374                 if (!new_tab) {
5375                         ret = -ENOMEM;
5376                         goto free;
5377                 }
5378                 if (!tab)
5379                         new_tab->cnt = 0;
5380                 tab = new_tab;
5381
5382                 type = &tab->types[tab->cnt];
5383                 type->btf_id = i;
5384                 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5385                                                   BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT, t->size);
5386                 /* The record cannot be unset, treat it as an error if so */
5387                 if (IS_ERR_OR_NULL(record)) {
5388                         ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5389                         goto free;
5390                 }
5391                 type->record = record;
5392                 tab->cnt++;
5393         }
5394         return tab;
5395 free:
5396         btf_struct_metas_free(tab);
5397         return ERR_PTR(ret);
5398 }
5399
5400 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5401 {
5402         struct btf_struct_metas *tab;
5403
5404         BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5405         tab = btf->struct_meta_tab;
5406         if (!tab)
5407                 return NULL;
5408         return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5409 }
5410
5411 static int btf_check_type_tags(struct btf_verifier_env *env,
5412                                struct btf *btf, int start_id)
5413 {
5414         int i, n, good_id = start_id - 1;
5415         bool in_tags;
5416
5417         n = btf_nr_types(btf);
5418         for (i = start_id; i < n; i++) {
5419                 const struct btf_type *t;
5420                 int chain_limit = 32;
5421                 u32 cur_id = i;
5422
5423                 t = btf_type_by_id(btf, i);
5424                 if (!t)
5425                         return -EINVAL;
5426                 if (!btf_type_is_modifier(t))
5427                         continue;
5428
5429                 cond_resched();
5430
5431                 in_tags = btf_type_is_type_tag(t);
5432                 while (btf_type_is_modifier(t)) {
5433                         if (!chain_limit--) {
5434                                 btf_verifier_log(env, "Max chain length or cycle detected");
5435                                 return -ELOOP;
5436                         }
5437                         if (btf_type_is_type_tag(t)) {
5438                                 if (!in_tags) {
5439                                         btf_verifier_log(env, "Type tags don't precede modifiers");
5440                                         return -EINVAL;
5441                                 }
5442                         } else if (in_tags) {
5443                                 in_tags = false;
5444                         }
5445                         if (cur_id <= good_id)
5446                                 break;
5447                         /* Move to next type */
5448                         cur_id = t->type;
5449                         t = btf_type_by_id(btf, cur_id);
5450                         if (!t)
5451                                 return -EINVAL;
5452                 }
5453                 good_id = i;
5454         }
5455         return 0;
5456 }
5457
5458 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5459 {
5460         u32 log_true_size;
5461         int err;
5462
5463         err = bpf_vlog_finalize(log, &log_true_size);
5464
5465         if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5466             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5467                                   &log_true_size, sizeof(log_true_size)))
5468                 err = -EFAULT;
5469
5470         return err;
5471 }
5472
5473 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5474 {
5475         bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5476         char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5477         struct btf_struct_metas *struct_meta_tab;
5478         struct btf_verifier_env *env = NULL;
5479         struct btf *btf = NULL;
5480         u8 *data;
5481         int err, ret;
5482
5483         if (attr->btf_size > BTF_MAX_SIZE)
5484                 return ERR_PTR(-E2BIG);
5485
5486         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5487         if (!env)
5488                 return ERR_PTR(-ENOMEM);
5489
5490         /* user could have requested verbose verifier output
5491          * and supplied buffer to store the verification trace
5492          */
5493         err = bpf_vlog_init(&env->log, attr->btf_log_level,
5494                             log_ubuf, attr->btf_log_size);
5495         if (err)
5496                 goto errout_free;
5497
5498         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5499         if (!btf) {
5500                 err = -ENOMEM;
5501                 goto errout;
5502         }
5503         env->btf = btf;
5504
5505         data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5506         if (!data) {
5507                 err = -ENOMEM;
5508                 goto errout;
5509         }
5510
5511         btf->data = data;
5512         btf->data_size = attr->btf_size;
5513
5514         if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5515                 err = -EFAULT;
5516                 goto errout;
5517         }
5518
5519         err = btf_parse_hdr(env);
5520         if (err)
5521                 goto errout;
5522
5523         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5524
5525         err = btf_parse_str_sec(env);
5526         if (err)
5527                 goto errout;
5528
5529         err = btf_parse_type_sec(env);
5530         if (err)
5531                 goto errout;
5532
5533         err = btf_check_type_tags(env, btf, 1);
5534         if (err)
5535                 goto errout;
5536
5537         struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5538         if (IS_ERR(struct_meta_tab)) {
5539                 err = PTR_ERR(struct_meta_tab);
5540                 goto errout;
5541         }
5542         btf->struct_meta_tab = struct_meta_tab;
5543
5544         if (struct_meta_tab) {
5545                 int i;
5546
5547                 for (i = 0; i < struct_meta_tab->cnt; i++) {
5548                         err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5549                         if (err < 0)
5550                                 goto errout_meta;
5551                 }
5552         }
5553
5554         err = finalize_log(&env->log, uattr, uattr_size);
5555         if (err)
5556                 goto errout_free;
5557
5558         btf_verifier_env_free(env);
5559         refcount_set(&btf->refcnt, 1);
5560         return btf;
5561
5562 errout_meta:
5563         btf_free_struct_meta_tab(btf);
5564 errout:
5565         /* overwrite err with -ENOSPC or -EFAULT */
5566         ret = finalize_log(&env->log, uattr, uattr_size);
5567         if (ret)
5568                 err = ret;
5569 errout_free:
5570         btf_verifier_env_free(env);
5571         if (btf)
5572                 btf_free(btf);
5573         return ERR_PTR(err);
5574 }
5575
5576 extern char __weak __start_BTF[];
5577 extern char __weak __stop_BTF[];
5578 extern struct btf *btf_vmlinux;
5579
5580 #define BPF_MAP_TYPE(_id, _ops)
5581 #define BPF_LINK_TYPE(_id, _name)
5582 static union {
5583         struct bpf_ctx_convert {
5584 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5585         prog_ctx_type _id##_prog; \
5586         kern_ctx_type _id##_kern;
5587 #include <linux/bpf_types.h>
5588 #undef BPF_PROG_TYPE
5589         } *__t;
5590         /* 't' is written once under lock. Read many times. */
5591         const struct btf_type *t;
5592 } bpf_ctx_convert;
5593 enum {
5594 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5595         __ctx_convert##_id,
5596 #include <linux/bpf_types.h>
5597 #undef BPF_PROG_TYPE
5598         __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5599 };
5600 static u8 bpf_ctx_convert_map[] = {
5601 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5602         [_id] = __ctx_convert##_id,
5603 #include <linux/bpf_types.h>
5604 #undef BPF_PROG_TYPE
5605         0, /* avoid empty array */
5606 };
5607 #undef BPF_MAP_TYPE
5608 #undef BPF_LINK_TYPE
5609
5610 const struct btf_member *
5611 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5612                       const struct btf_type *t, enum bpf_prog_type prog_type,
5613                       int arg)
5614 {
5615         const struct btf_type *conv_struct;
5616         const struct btf_type *ctx_struct;
5617         const struct btf_member *ctx_type;
5618         const char *tname, *ctx_tname;
5619
5620         conv_struct = bpf_ctx_convert.t;
5621         if (!conv_struct) {
5622                 bpf_log(log, "btf_vmlinux is malformed\n");
5623                 return NULL;
5624         }
5625         t = btf_type_by_id(btf, t->type);
5626         while (btf_type_is_modifier(t))
5627                 t = btf_type_by_id(btf, t->type);
5628         if (!btf_type_is_struct(t)) {
5629                 /* Only pointer to struct is supported for now.
5630                  * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5631                  * is not supported yet.
5632                  * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5633                  */
5634                 return NULL;
5635         }
5636         tname = btf_name_by_offset(btf, t->name_off);
5637         if (!tname) {
5638                 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5639                 return NULL;
5640         }
5641         /* prog_type is valid bpf program type. No need for bounds check. */
5642         ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5643         /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5644          * Like 'struct __sk_buff'
5645          */
5646         ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5647         if (!ctx_struct)
5648                 /* should not happen */
5649                 return NULL;
5650 again:
5651         ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5652         if (!ctx_tname) {
5653                 /* should not happen */
5654                 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5655                 return NULL;
5656         }
5657         /* only compare that prog's ctx type name is the same as
5658          * kernel expects. No need to compare field by field.
5659          * It's ok for bpf prog to do:
5660          * struct __sk_buff {};
5661          * int socket_filter_bpf_prog(struct __sk_buff *skb)
5662          * { // no fields of skb are ever used }
5663          */
5664         if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5665                 return ctx_type;
5666         if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5667                 return ctx_type;
5668         if (strcmp(ctx_tname, tname)) {
5669                 /* bpf_user_pt_regs_t is a typedef, so resolve it to
5670                  * underlying struct and check name again
5671                  */
5672                 if (!btf_type_is_modifier(ctx_struct))
5673                         return NULL;
5674                 while (btf_type_is_modifier(ctx_struct))
5675                         ctx_struct = btf_type_by_id(btf_vmlinux, ctx_struct->type);
5676                 goto again;
5677         }
5678         return ctx_type;
5679 }
5680
5681 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5682                                      struct btf *btf,
5683                                      const struct btf_type *t,
5684                                      enum bpf_prog_type prog_type,
5685                                      int arg)
5686 {
5687         const struct btf_member *prog_ctx_type, *kern_ctx_type;
5688
5689         prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5690         if (!prog_ctx_type)
5691                 return -ENOENT;
5692         kern_ctx_type = prog_ctx_type + 1;
5693         return kern_ctx_type->type;
5694 }
5695
5696 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5697 {
5698         const struct btf_member *kctx_member;
5699         const struct btf_type *conv_struct;
5700         const struct btf_type *kctx_type;
5701         u32 kctx_type_id;
5702
5703         conv_struct = bpf_ctx_convert.t;
5704         /* get member for kernel ctx type */
5705         kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5706         kctx_type_id = kctx_member->type;
5707         kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5708         if (!btf_type_is_struct(kctx_type)) {
5709                 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5710                 return -EINVAL;
5711         }
5712
5713         return kctx_type_id;
5714 }
5715
5716 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5717 BTF_ID(struct, bpf_ctx_convert)
5718
5719 struct btf *btf_parse_vmlinux(void)
5720 {
5721         struct btf_verifier_env *env = NULL;
5722         struct bpf_verifier_log *log;
5723         struct btf *btf = NULL;
5724         int err;
5725
5726         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5727         if (!env)
5728                 return ERR_PTR(-ENOMEM);
5729
5730         log = &env->log;
5731         log->level = BPF_LOG_KERNEL;
5732
5733         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5734         if (!btf) {
5735                 err = -ENOMEM;
5736                 goto errout;
5737         }
5738         env->btf = btf;
5739
5740         btf->data = __start_BTF;
5741         btf->data_size = __stop_BTF - __start_BTF;
5742         btf->kernel_btf = true;
5743         snprintf(btf->name, sizeof(btf->name), "vmlinux");
5744
5745         err = btf_parse_hdr(env);
5746         if (err)
5747                 goto errout;
5748
5749         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5750
5751         err = btf_parse_str_sec(env);
5752         if (err)
5753                 goto errout;
5754
5755         err = btf_check_all_metas(env);
5756         if (err)
5757                 goto errout;
5758
5759         err = btf_check_type_tags(env, btf, 1);
5760         if (err)
5761                 goto errout;
5762
5763         /* btf_parse_vmlinux() runs under bpf_verifier_lock */
5764         bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5765
5766         bpf_struct_ops_init(btf, log);
5767
5768         refcount_set(&btf->refcnt, 1);
5769
5770         err = btf_alloc_id(btf);
5771         if (err)
5772                 goto errout;
5773
5774         btf_verifier_env_free(env);
5775         return btf;
5776
5777 errout:
5778         btf_verifier_env_free(env);
5779         if (btf) {
5780                 kvfree(btf->types);
5781                 kfree(btf);
5782         }
5783         return ERR_PTR(err);
5784 }
5785
5786 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5787
5788 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5789 {
5790         struct btf_verifier_env *env = NULL;
5791         struct bpf_verifier_log *log;
5792         struct btf *btf = NULL, *base_btf;
5793         int err;
5794
5795         base_btf = bpf_get_btf_vmlinux();
5796         if (IS_ERR(base_btf))
5797                 return base_btf;
5798         if (!base_btf)
5799                 return ERR_PTR(-EINVAL);
5800
5801         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5802         if (!env)
5803                 return ERR_PTR(-ENOMEM);
5804
5805         log = &env->log;
5806         log->level = BPF_LOG_KERNEL;
5807
5808         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5809         if (!btf) {
5810                 err = -ENOMEM;
5811                 goto errout;
5812         }
5813         env->btf = btf;
5814
5815         btf->base_btf = base_btf;
5816         btf->start_id = base_btf->nr_types;
5817         btf->start_str_off = base_btf->hdr.str_len;
5818         btf->kernel_btf = true;
5819         snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5820
5821         btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5822         if (!btf->data) {
5823                 err = -ENOMEM;
5824                 goto errout;
5825         }
5826         memcpy(btf->data, data, data_size);
5827         btf->data_size = data_size;
5828
5829         err = btf_parse_hdr(env);
5830         if (err)
5831                 goto errout;
5832
5833         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5834
5835         err = btf_parse_str_sec(env);
5836         if (err)
5837                 goto errout;
5838
5839         err = btf_check_all_metas(env);
5840         if (err)
5841                 goto errout;
5842
5843         err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5844         if (err)
5845                 goto errout;
5846
5847         btf_verifier_env_free(env);
5848         refcount_set(&btf->refcnt, 1);
5849         return btf;
5850
5851 errout:
5852         btf_verifier_env_free(env);
5853         if (btf) {
5854                 kvfree(btf->data);
5855                 kvfree(btf->types);
5856                 kfree(btf);
5857         }
5858         return ERR_PTR(err);
5859 }
5860
5861 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5862
5863 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5864 {
5865         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5866
5867         if (tgt_prog)
5868                 return tgt_prog->aux->btf;
5869         else
5870                 return prog->aux->attach_btf;
5871 }
5872
5873 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5874 {
5875         /* skip modifiers */
5876         t = btf_type_skip_modifiers(btf, t->type, NULL);
5877
5878         return btf_type_is_int(t);
5879 }
5880
5881 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5882                            int off)
5883 {
5884         const struct btf_param *args;
5885         const struct btf_type *t;
5886         u32 offset = 0, nr_args;
5887         int i;
5888
5889         if (!func_proto)
5890                 return off / 8;
5891
5892         nr_args = btf_type_vlen(func_proto);
5893         args = (const struct btf_param *)(func_proto + 1);
5894         for (i = 0; i < nr_args; i++) {
5895                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5896                 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5897                 if (off < offset)
5898                         return i;
5899         }
5900
5901         t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5902         offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5903         if (off < offset)
5904                 return nr_args;
5905
5906         return nr_args + 1;
5907 }
5908
5909 static bool prog_args_trusted(const struct bpf_prog *prog)
5910 {
5911         enum bpf_attach_type atype = prog->expected_attach_type;
5912
5913         switch (prog->type) {
5914         case BPF_PROG_TYPE_TRACING:
5915                 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
5916         case BPF_PROG_TYPE_LSM:
5917                 return bpf_lsm_is_trusted(prog);
5918         case BPF_PROG_TYPE_STRUCT_OPS:
5919                 return true;
5920         default:
5921                 return false;
5922         }
5923 }
5924
5925 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5926                     const struct bpf_prog *prog,
5927                     struct bpf_insn_access_aux *info)
5928 {
5929         const struct btf_type *t = prog->aux->attach_func_proto;
5930         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5931         struct btf *btf = bpf_prog_get_target_btf(prog);
5932         const char *tname = prog->aux->attach_func_name;
5933         struct bpf_verifier_log *log = info->log;
5934         const struct btf_param *args;
5935         const char *tag_value;
5936         u32 nr_args, arg;
5937         int i, ret;
5938
5939         if (off % 8) {
5940                 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5941                         tname, off);
5942                 return false;
5943         }
5944         arg = get_ctx_arg_idx(btf, t, off);
5945         args = (const struct btf_param *)(t + 1);
5946         /* if (t == NULL) Fall back to default BPF prog with
5947          * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5948          */
5949         nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5950         if (prog->aux->attach_btf_trace) {
5951                 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5952                 args++;
5953                 nr_args--;
5954         }
5955
5956         if (arg > nr_args) {
5957                 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5958                         tname, arg + 1);
5959                 return false;
5960         }
5961
5962         if (arg == nr_args) {
5963                 switch (prog->expected_attach_type) {
5964                 case BPF_LSM_CGROUP:
5965                 case BPF_LSM_MAC:
5966                 case BPF_TRACE_FEXIT:
5967                         /* When LSM programs are attached to void LSM hooks
5968                          * they use FEXIT trampolines and when attached to
5969                          * int LSM hooks, they use MODIFY_RETURN trampolines.
5970                          *
5971                          * While the LSM programs are BPF_MODIFY_RETURN-like
5972                          * the check:
5973                          *
5974                          *      if (ret_type != 'int')
5975                          *              return -EINVAL;
5976                          *
5977                          * is _not_ done here. This is still safe as LSM hooks
5978                          * have only void and int return types.
5979                          */
5980                         if (!t)
5981                                 return true;
5982                         t = btf_type_by_id(btf, t->type);
5983                         break;
5984                 case BPF_MODIFY_RETURN:
5985                         /* For now the BPF_MODIFY_RETURN can only be attached to
5986                          * functions that return an int.
5987                          */
5988                         if (!t)
5989                                 return false;
5990
5991                         t = btf_type_skip_modifiers(btf, t->type, NULL);
5992                         if (!btf_type_is_small_int(t)) {
5993                                 bpf_log(log,
5994                                         "ret type %s not allowed for fmod_ret\n",
5995                                         btf_type_str(t));
5996                                 return false;
5997                         }
5998                         break;
5999                 default:
6000                         bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6001                                 tname, arg + 1);
6002                         return false;
6003                 }
6004         } else {
6005                 if (!t)
6006                         /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6007                         return true;
6008                 t = btf_type_by_id(btf, args[arg].type);
6009         }
6010
6011         /* skip modifiers */
6012         while (btf_type_is_modifier(t))
6013                 t = btf_type_by_id(btf, t->type);
6014         if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6015                 /* accessing a scalar */
6016                 return true;
6017         if (!btf_type_is_ptr(t)) {
6018                 bpf_log(log,
6019                         "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6020                         tname, arg,
6021                         __btf_name_by_offset(btf, t->name_off),
6022                         btf_type_str(t));
6023                 return false;
6024         }
6025
6026         /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6027         for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6028                 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6029                 u32 type, flag;
6030
6031                 type = base_type(ctx_arg_info->reg_type);
6032                 flag = type_flag(ctx_arg_info->reg_type);
6033                 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6034                     (flag & PTR_MAYBE_NULL)) {
6035                         info->reg_type = ctx_arg_info->reg_type;
6036                         return true;
6037                 }
6038         }
6039
6040         if (t->type == 0)
6041                 /* This is a pointer to void.
6042                  * It is the same as scalar from the verifier safety pov.
6043                  * No further pointer walking is allowed.
6044                  */
6045                 return true;
6046
6047         if (is_int_ptr(btf, t))
6048                 return true;
6049
6050         /* this is a pointer to another type */
6051         for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6052                 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6053
6054                 if (ctx_arg_info->offset == off) {
6055                         if (!ctx_arg_info->btf_id) {
6056                                 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6057                                 return false;
6058                         }
6059
6060                         info->reg_type = ctx_arg_info->reg_type;
6061                         info->btf = btf_vmlinux;
6062                         info->btf_id = ctx_arg_info->btf_id;
6063                         return true;
6064                 }
6065         }
6066
6067         info->reg_type = PTR_TO_BTF_ID;
6068         if (prog_args_trusted(prog))
6069                 info->reg_type |= PTR_TRUSTED;
6070
6071         if (tgt_prog) {
6072                 enum bpf_prog_type tgt_type;
6073
6074                 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6075                         tgt_type = tgt_prog->aux->saved_dst_prog_type;
6076                 else
6077                         tgt_type = tgt_prog->type;
6078
6079                 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6080                 if (ret > 0) {
6081                         info->btf = btf_vmlinux;
6082                         info->btf_id = ret;
6083                         return true;
6084                 } else {
6085                         return false;
6086                 }
6087         }
6088
6089         info->btf = btf;
6090         info->btf_id = t->type;
6091         t = btf_type_by_id(btf, t->type);
6092
6093         if (btf_type_is_type_tag(t)) {
6094                 tag_value = __btf_name_by_offset(btf, t->name_off);
6095                 if (strcmp(tag_value, "user") == 0)
6096                         info->reg_type |= MEM_USER;
6097                 if (strcmp(tag_value, "percpu") == 0)
6098                         info->reg_type |= MEM_PERCPU;
6099         }
6100
6101         /* skip modifiers */
6102         while (btf_type_is_modifier(t)) {
6103                 info->btf_id = t->type;
6104                 t = btf_type_by_id(btf, t->type);
6105         }
6106         if (!btf_type_is_struct(t)) {
6107                 bpf_log(log,
6108                         "func '%s' arg%d type %s is not a struct\n",
6109                         tname, arg, btf_type_str(t));
6110                 return false;
6111         }
6112         bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6113                 tname, arg, info->btf_id, btf_type_str(t),
6114                 __btf_name_by_offset(btf, t->name_off));
6115         return true;
6116 }
6117
6118 enum bpf_struct_walk_result {
6119         /* < 0 error */
6120         WALK_SCALAR = 0,
6121         WALK_PTR,
6122         WALK_STRUCT,
6123 };
6124
6125 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6126                            const struct btf_type *t, int off, int size,
6127                            u32 *next_btf_id, enum bpf_type_flag *flag,
6128                            const char **field_name)
6129 {
6130         u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6131         const struct btf_type *mtype, *elem_type = NULL;
6132         const struct btf_member *member;
6133         const char *tname, *mname, *tag_value;
6134         u32 vlen, elem_id, mid;
6135
6136         *flag = 0;
6137 again:
6138         tname = __btf_name_by_offset(btf, t->name_off);
6139         if (!btf_type_is_struct(t)) {
6140                 bpf_log(log, "Type '%s' is not a struct\n", tname);
6141                 return -EINVAL;
6142         }
6143
6144         vlen = btf_type_vlen(t);
6145         if (off + size > t->size) {
6146                 /* If the last element is a variable size array, we may
6147                  * need to relax the rule.
6148                  */
6149                 struct btf_array *array_elem;
6150
6151                 if (vlen == 0)
6152                         goto error;
6153
6154                 member = btf_type_member(t) + vlen - 1;
6155                 mtype = btf_type_skip_modifiers(btf, member->type,
6156                                                 NULL);
6157                 if (!btf_type_is_array(mtype))
6158                         goto error;
6159
6160                 array_elem = (struct btf_array *)(mtype + 1);
6161                 if (array_elem->nelems != 0)
6162                         goto error;
6163
6164                 moff = __btf_member_bit_offset(t, member) / 8;
6165                 if (off < moff)
6166                         goto error;
6167
6168                 /* allow structure and integer */
6169                 t = btf_type_skip_modifiers(btf, array_elem->type,
6170                                             NULL);
6171
6172                 if (btf_type_is_int(t))
6173                         return WALK_SCALAR;
6174
6175                 if (!btf_type_is_struct(t))
6176                         goto error;
6177
6178                 off = (off - moff) % t->size;
6179                 goto again;
6180
6181 error:
6182                 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6183                         tname, off, size);
6184                 return -EACCES;
6185         }
6186
6187         for_each_member(i, t, member) {
6188                 /* offset of the field in bytes */
6189                 moff = __btf_member_bit_offset(t, member) / 8;
6190                 if (off + size <= moff)
6191                         /* won't find anything, field is already too far */
6192                         break;
6193
6194                 if (__btf_member_bitfield_size(t, member)) {
6195                         u32 end_bit = __btf_member_bit_offset(t, member) +
6196                                 __btf_member_bitfield_size(t, member);
6197
6198                         /* off <= moff instead of off == moff because clang
6199                          * does not generate a BTF member for anonymous
6200                          * bitfield like the ":16" here:
6201                          * struct {
6202                          *      int :16;
6203                          *      int x:8;
6204                          * };
6205                          */
6206                         if (off <= moff &&
6207                             BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6208                                 return WALK_SCALAR;
6209
6210                         /* off may be accessing a following member
6211                          *
6212                          * or
6213                          *
6214                          * Doing partial access at either end of this
6215                          * bitfield.  Continue on this case also to
6216                          * treat it as not accessing this bitfield
6217                          * and eventually error out as field not
6218                          * found to keep it simple.
6219                          * It could be relaxed if there was a legit
6220                          * partial access case later.
6221                          */
6222                         continue;
6223                 }
6224
6225                 /* In case of "off" is pointing to holes of a struct */
6226                 if (off < moff)
6227                         break;
6228
6229                 /* type of the field */
6230                 mid = member->type;
6231                 mtype = btf_type_by_id(btf, member->type);
6232                 mname = __btf_name_by_offset(btf, member->name_off);
6233
6234                 mtype = __btf_resolve_size(btf, mtype, &msize,
6235                                            &elem_type, &elem_id, &total_nelems,
6236                                            &mid);
6237                 if (IS_ERR(mtype)) {
6238                         bpf_log(log, "field %s doesn't have size\n", mname);
6239                         return -EFAULT;
6240                 }
6241
6242                 mtrue_end = moff + msize;
6243                 if (off >= mtrue_end)
6244                         /* no overlap with member, keep iterating */
6245                         continue;
6246
6247                 if (btf_type_is_array(mtype)) {
6248                         u32 elem_idx;
6249
6250                         /* __btf_resolve_size() above helps to
6251                          * linearize a multi-dimensional array.
6252                          *
6253                          * The logic here is treating an array
6254                          * in a struct as the following way:
6255                          *
6256                          * struct outer {
6257                          *      struct inner array[2][2];
6258                          * };
6259                          *
6260                          * looks like:
6261                          *
6262                          * struct outer {
6263                          *      struct inner array_elem0;
6264                          *      struct inner array_elem1;
6265                          *      struct inner array_elem2;
6266                          *      struct inner array_elem3;
6267                          * };
6268                          *
6269                          * When accessing outer->array[1][0], it moves
6270                          * moff to "array_elem2", set mtype to
6271                          * "struct inner", and msize also becomes
6272                          * sizeof(struct inner).  Then most of the
6273                          * remaining logic will fall through without
6274                          * caring the current member is an array or
6275                          * not.
6276                          *
6277                          * Unlike mtype/msize/moff, mtrue_end does not
6278                          * change.  The naming difference ("_true") tells
6279                          * that it is not always corresponding to
6280                          * the current mtype/msize/moff.
6281                          * It is the true end of the current
6282                          * member (i.e. array in this case).  That
6283                          * will allow an int array to be accessed like
6284                          * a scratch space,
6285                          * i.e. allow access beyond the size of
6286                          *      the array's element as long as it is
6287                          *      within the mtrue_end boundary.
6288                          */
6289
6290                         /* skip empty array */
6291                         if (moff == mtrue_end)
6292                                 continue;
6293
6294                         msize /= total_nelems;
6295                         elem_idx = (off - moff) / msize;
6296                         moff += elem_idx * msize;
6297                         mtype = elem_type;
6298                         mid = elem_id;
6299                 }
6300
6301                 /* the 'off' we're looking for is either equal to start
6302                  * of this field or inside of this struct
6303                  */
6304                 if (btf_type_is_struct(mtype)) {
6305                         if (BTF_INFO_KIND(mtype->info) == BTF_KIND_UNION &&
6306                             btf_type_vlen(mtype) != 1)
6307                                 /*
6308                                  * walking unions yields untrusted pointers
6309                                  * with exception of __bpf_md_ptr and other
6310                                  * unions with a single member
6311                                  */
6312                                 *flag |= PTR_UNTRUSTED;
6313
6314                         /* our field must be inside that union or struct */
6315                         t = mtype;
6316
6317                         /* return if the offset matches the member offset */
6318                         if (off == moff) {
6319                                 *next_btf_id = mid;
6320                                 return WALK_STRUCT;
6321                         }
6322
6323                         /* adjust offset we're looking for */
6324                         off -= moff;
6325                         goto again;
6326                 }
6327
6328                 if (btf_type_is_ptr(mtype)) {
6329                         const struct btf_type *stype, *t;
6330                         enum bpf_type_flag tmp_flag = 0;
6331                         u32 id;
6332
6333                         if (msize != size || off != moff) {
6334                                 bpf_log(log,
6335                                         "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6336                                         mname, moff, tname, off, size);
6337                                 return -EACCES;
6338                         }
6339
6340                         /* check type tag */
6341                         t = btf_type_by_id(btf, mtype->type);
6342                         if (btf_type_is_type_tag(t)) {
6343                                 tag_value = __btf_name_by_offset(btf, t->name_off);
6344                                 /* check __user tag */
6345                                 if (strcmp(tag_value, "user") == 0)
6346                                         tmp_flag = MEM_USER;
6347                                 /* check __percpu tag */
6348                                 if (strcmp(tag_value, "percpu") == 0)
6349                                         tmp_flag = MEM_PERCPU;
6350                                 /* check __rcu tag */
6351                                 if (strcmp(tag_value, "rcu") == 0)
6352                                         tmp_flag = MEM_RCU;
6353                         }
6354
6355                         stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6356                         if (btf_type_is_struct(stype)) {
6357                                 *next_btf_id = id;
6358                                 *flag |= tmp_flag;
6359                                 if (field_name)
6360                                         *field_name = mname;
6361                                 return WALK_PTR;
6362                         }
6363                 }
6364
6365                 /* Allow more flexible access within an int as long as
6366                  * it is within mtrue_end.
6367                  * Since mtrue_end could be the end of an array,
6368                  * that also allows using an array of int as a scratch
6369                  * space. e.g. skb->cb[].
6370                  */
6371                 if (off + size > mtrue_end) {
6372                         bpf_log(log,
6373                                 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6374                                 mname, mtrue_end, tname, off, size);
6375                         return -EACCES;
6376                 }
6377
6378                 return WALK_SCALAR;
6379         }
6380         bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6381         return -EINVAL;
6382 }
6383
6384 int btf_struct_access(struct bpf_verifier_log *log,
6385                       const struct bpf_reg_state *reg,
6386                       int off, int size, enum bpf_access_type atype __maybe_unused,
6387                       u32 *next_btf_id, enum bpf_type_flag *flag,
6388                       const char **field_name)
6389 {
6390         const struct btf *btf = reg->btf;
6391         enum bpf_type_flag tmp_flag = 0;
6392         const struct btf_type *t;
6393         u32 id = reg->btf_id;
6394         int err;
6395
6396         while (type_is_alloc(reg->type)) {
6397                 struct btf_struct_meta *meta;
6398                 struct btf_record *rec;
6399                 int i;
6400
6401                 meta = btf_find_struct_meta(btf, id);
6402                 if (!meta)
6403                         break;
6404                 rec = meta->record;
6405                 for (i = 0; i < rec->cnt; i++) {
6406                         struct btf_field *field = &rec->fields[i];
6407                         u32 offset = field->offset;
6408                         if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6409                                 bpf_log(log,
6410                                         "direct access to %s is disallowed\n",
6411                                         btf_field_type_name(field->type));
6412                                 return -EACCES;
6413                         }
6414                 }
6415                 break;
6416         }
6417
6418         t = btf_type_by_id(btf, id);
6419         do {
6420                 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6421
6422                 switch (err) {
6423                 case WALK_PTR:
6424                         /* For local types, the destination register cannot
6425                          * become a pointer again.
6426                          */
6427                         if (type_is_alloc(reg->type))
6428                                 return SCALAR_VALUE;
6429                         /* If we found the pointer or scalar on t+off,
6430                          * we're done.
6431                          */
6432                         *next_btf_id = id;
6433                         *flag = tmp_flag;
6434                         return PTR_TO_BTF_ID;
6435                 case WALK_SCALAR:
6436                         return SCALAR_VALUE;
6437                 case WALK_STRUCT:
6438                         /* We found nested struct, so continue the search
6439                          * by diving in it. At this point the offset is
6440                          * aligned with the new type, so set it to 0.
6441                          */
6442                         t = btf_type_by_id(btf, id);
6443                         off = 0;
6444                         break;
6445                 default:
6446                         /* It's either error or unknown return value..
6447                          * scream and leave.
6448                          */
6449                         if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6450                                 return -EINVAL;
6451                         return err;
6452                 }
6453         } while (t);
6454
6455         return -EINVAL;
6456 }
6457
6458 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6459  * the same. Trivial ID check is not enough due to module BTFs, because we can
6460  * end up with two different module BTFs, but IDs point to the common type in
6461  * vmlinux BTF.
6462  */
6463 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6464                         const struct btf *btf2, u32 id2)
6465 {
6466         if (id1 != id2)
6467                 return false;
6468         if (btf1 == btf2)
6469                 return true;
6470         return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6471 }
6472
6473 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6474                           const struct btf *btf, u32 id, int off,
6475                           const struct btf *need_btf, u32 need_type_id,
6476                           bool strict)
6477 {
6478         const struct btf_type *type;
6479         enum bpf_type_flag flag;
6480         int err;
6481
6482         /* Are we already done? */
6483         if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6484                 return true;
6485         /* In case of strict type match, we do not walk struct, the top level
6486          * type match must succeed. When strict is true, off should have already
6487          * been 0.
6488          */
6489         if (strict)
6490                 return false;
6491 again:
6492         type = btf_type_by_id(btf, id);
6493         if (!type)
6494                 return false;
6495         err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6496         if (err != WALK_STRUCT)
6497                 return false;
6498
6499         /* We found nested struct object. If it matches
6500          * the requested ID, we're done. Otherwise let's
6501          * continue the search with offset 0 in the new
6502          * type.
6503          */
6504         if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6505                 off = 0;
6506                 goto again;
6507         }
6508
6509         return true;
6510 }
6511
6512 static int __get_type_size(struct btf *btf, u32 btf_id,
6513                            const struct btf_type **ret_type)
6514 {
6515         const struct btf_type *t;
6516
6517         *ret_type = btf_type_by_id(btf, 0);
6518         if (!btf_id)
6519                 /* void */
6520                 return 0;
6521         t = btf_type_by_id(btf, btf_id);
6522         while (t && btf_type_is_modifier(t))
6523                 t = btf_type_by_id(btf, t->type);
6524         if (!t)
6525                 return -EINVAL;
6526         *ret_type = t;
6527         if (btf_type_is_ptr(t))
6528                 /* kernel size of pointer. Not BPF's size of pointer*/
6529                 return sizeof(void *);
6530         if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6531                 return t->size;
6532         return -EINVAL;
6533 }
6534
6535 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6536 {
6537         u8 flags = 0;
6538
6539         if (__btf_type_is_struct(t))
6540                 flags |= BTF_FMODEL_STRUCT_ARG;
6541         if (btf_type_is_signed_int(t))
6542                 flags |= BTF_FMODEL_SIGNED_ARG;
6543
6544         return flags;
6545 }
6546
6547 int btf_distill_func_proto(struct bpf_verifier_log *log,
6548                            struct btf *btf,
6549                            const struct btf_type *func,
6550                            const char *tname,
6551                            struct btf_func_model *m)
6552 {
6553         const struct btf_param *args;
6554         const struct btf_type *t;
6555         u32 i, nargs;
6556         int ret;
6557
6558         if (!func) {
6559                 /* BTF function prototype doesn't match the verifier types.
6560                  * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6561                  */
6562                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6563                         m->arg_size[i] = 8;
6564                         m->arg_flags[i] = 0;
6565                 }
6566                 m->ret_size = 8;
6567                 m->ret_flags = 0;
6568                 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6569                 return 0;
6570         }
6571         args = (const struct btf_param *)(func + 1);
6572         nargs = btf_type_vlen(func);
6573         if (nargs > MAX_BPF_FUNC_ARGS) {
6574                 bpf_log(log,
6575                         "The function %s has %d arguments. Too many.\n",
6576                         tname, nargs);
6577                 return -EINVAL;
6578         }
6579         ret = __get_type_size(btf, func->type, &t);
6580         if (ret < 0 || __btf_type_is_struct(t)) {
6581                 bpf_log(log,
6582                         "The function %s return type %s is unsupported.\n",
6583                         tname, btf_type_str(t));
6584                 return -EINVAL;
6585         }
6586         m->ret_size = ret;
6587         m->ret_flags = __get_type_fmodel_flags(t);
6588
6589         for (i = 0; i < nargs; i++) {
6590                 if (i == nargs - 1 && args[i].type == 0) {
6591                         bpf_log(log,
6592                                 "The function %s with variable args is unsupported.\n",
6593                                 tname);
6594                         return -EINVAL;
6595                 }
6596                 ret = __get_type_size(btf, args[i].type, &t);
6597
6598                 /* No support of struct argument size greater than 16 bytes */
6599                 if (ret < 0 || ret > 16) {
6600                         bpf_log(log,
6601                                 "The function %s arg%d type %s is unsupported.\n",
6602                                 tname, i, btf_type_str(t));
6603                         return -EINVAL;
6604                 }
6605                 if (ret == 0) {
6606                         bpf_log(log,
6607                                 "The function %s has malformed void argument.\n",
6608                                 tname);
6609                         return -EINVAL;
6610                 }
6611                 m->arg_size[i] = ret;
6612                 m->arg_flags[i] = __get_type_fmodel_flags(t);
6613         }
6614         m->nr_args = nargs;
6615         return 0;
6616 }
6617
6618 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6619  * t1 points to BTF_KIND_FUNC in btf1
6620  * t2 points to BTF_KIND_FUNC in btf2
6621  * Returns:
6622  * EINVAL - function prototype mismatch
6623  * EFAULT - verifier bug
6624  * 0 - 99% match. The last 1% is validated by the verifier.
6625  */
6626 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6627                                      struct btf *btf1, const struct btf_type *t1,
6628                                      struct btf *btf2, const struct btf_type *t2)
6629 {
6630         const struct btf_param *args1, *args2;
6631         const char *fn1, *fn2, *s1, *s2;
6632         u32 nargs1, nargs2, i;
6633
6634         fn1 = btf_name_by_offset(btf1, t1->name_off);
6635         fn2 = btf_name_by_offset(btf2, t2->name_off);
6636
6637         if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6638                 bpf_log(log, "%s() is not a global function\n", fn1);
6639                 return -EINVAL;
6640         }
6641         if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6642                 bpf_log(log, "%s() is not a global function\n", fn2);
6643                 return -EINVAL;
6644         }
6645
6646         t1 = btf_type_by_id(btf1, t1->type);
6647         if (!t1 || !btf_type_is_func_proto(t1))
6648                 return -EFAULT;
6649         t2 = btf_type_by_id(btf2, t2->type);
6650         if (!t2 || !btf_type_is_func_proto(t2))
6651                 return -EFAULT;
6652
6653         args1 = (const struct btf_param *)(t1 + 1);
6654         nargs1 = btf_type_vlen(t1);
6655         args2 = (const struct btf_param *)(t2 + 1);
6656         nargs2 = btf_type_vlen(t2);
6657
6658         if (nargs1 != nargs2) {
6659                 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6660                         fn1, nargs1, fn2, nargs2);
6661                 return -EINVAL;
6662         }
6663
6664         t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6665         t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6666         if (t1->info != t2->info) {
6667                 bpf_log(log,
6668                         "Return type %s of %s() doesn't match type %s of %s()\n",
6669                         btf_type_str(t1), fn1,
6670                         btf_type_str(t2), fn2);
6671                 return -EINVAL;
6672         }
6673
6674         for (i = 0; i < nargs1; i++) {
6675                 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6676                 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6677
6678                 if (t1->info != t2->info) {
6679                         bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6680                                 i, fn1, btf_type_str(t1),
6681                                 fn2, btf_type_str(t2));
6682                         return -EINVAL;
6683                 }
6684                 if (btf_type_has_size(t1) && t1->size != t2->size) {
6685                         bpf_log(log,
6686                                 "arg%d in %s() has size %d while %s() has %d\n",
6687                                 i, fn1, t1->size,
6688                                 fn2, t2->size);
6689                         return -EINVAL;
6690                 }
6691
6692                 /* global functions are validated with scalars and pointers
6693                  * to context only. And only global functions can be replaced.
6694                  * Hence type check only those types.
6695                  */
6696                 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6697                         continue;
6698                 if (!btf_type_is_ptr(t1)) {
6699                         bpf_log(log,
6700                                 "arg%d in %s() has unrecognized type\n",
6701                                 i, fn1);
6702                         return -EINVAL;
6703                 }
6704                 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6705                 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6706                 if (!btf_type_is_struct(t1)) {
6707                         bpf_log(log,
6708                                 "arg%d in %s() is not a pointer to context\n",
6709                                 i, fn1);
6710                         return -EINVAL;
6711                 }
6712                 if (!btf_type_is_struct(t2)) {
6713                         bpf_log(log,
6714                                 "arg%d in %s() is not a pointer to context\n",
6715                                 i, fn2);
6716                         return -EINVAL;
6717                 }
6718                 /* This is an optional check to make program writing easier.
6719                  * Compare names of structs and report an error to the user.
6720                  * btf_prepare_func_args() already checked that t2 struct
6721                  * is a context type. btf_prepare_func_args() will check
6722                  * later that t1 struct is a context type as well.
6723                  */
6724                 s1 = btf_name_by_offset(btf1, t1->name_off);
6725                 s2 = btf_name_by_offset(btf2, t2->name_off);
6726                 if (strcmp(s1, s2)) {
6727                         bpf_log(log,
6728                                 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6729                                 i, fn1, s1, fn2, s2);
6730                         return -EINVAL;
6731                 }
6732         }
6733         return 0;
6734 }
6735
6736 /* Compare BTFs of given program with BTF of target program */
6737 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
6738                          struct btf *btf2, const struct btf_type *t2)
6739 {
6740         struct btf *btf1 = prog->aux->btf;
6741         const struct btf_type *t1;
6742         u32 btf_id = 0;
6743
6744         if (!prog->aux->func_info) {
6745                 bpf_log(log, "Program extension requires BTF\n");
6746                 return -EINVAL;
6747         }
6748
6749         btf_id = prog->aux->func_info[0].type_id;
6750         if (!btf_id)
6751                 return -EFAULT;
6752
6753         t1 = btf_type_by_id(btf1, btf_id);
6754         if (!t1 || !btf_type_is_func(t1))
6755                 return -EFAULT;
6756
6757         return btf_check_func_type_match(log, btf1, t1, btf2, t2);
6758 }
6759
6760 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6761                                     const struct btf *btf, u32 func_id,
6762                                     struct bpf_reg_state *regs,
6763                                     bool ptr_to_mem_ok,
6764                                     bool processing_call)
6765 {
6766         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6767         struct bpf_verifier_log *log = &env->log;
6768         const char *func_name, *ref_tname;
6769         const struct btf_type *t, *ref_t;
6770         const struct btf_param *args;
6771         u32 i, nargs, ref_id;
6772         int ret;
6773
6774         t = btf_type_by_id(btf, func_id);
6775         if (!t || !btf_type_is_func(t)) {
6776                 /* These checks were already done by the verifier while loading
6777                  * struct bpf_func_info or in add_kfunc_call().
6778                  */
6779                 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6780                         func_id);
6781                 return -EFAULT;
6782         }
6783         func_name = btf_name_by_offset(btf, t->name_off);
6784
6785         t = btf_type_by_id(btf, t->type);
6786         if (!t || !btf_type_is_func_proto(t)) {
6787                 bpf_log(log, "Invalid BTF of func %s\n", func_name);
6788                 return -EFAULT;
6789         }
6790         args = (const struct btf_param *)(t + 1);
6791         nargs = btf_type_vlen(t);
6792         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6793                 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6794                         MAX_BPF_FUNC_REG_ARGS);
6795                 return -EINVAL;
6796         }
6797
6798         /* check that BTF function arguments match actual types that the
6799          * verifier sees.
6800          */
6801         for (i = 0; i < nargs; i++) {
6802                 enum bpf_arg_type arg_type = ARG_DONTCARE;
6803                 u32 regno = i + 1;
6804                 struct bpf_reg_state *reg = &regs[regno];
6805
6806                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6807                 if (btf_type_is_scalar(t)) {
6808                         if (reg->type == SCALAR_VALUE)
6809                                 continue;
6810                         bpf_log(log, "R%d is not a scalar\n", regno);
6811                         return -EINVAL;
6812                 }
6813
6814                 if (!btf_type_is_ptr(t)) {
6815                         bpf_log(log, "Unrecognized arg#%d type %s\n",
6816                                 i, btf_type_str(t));
6817                         return -EINVAL;
6818                 }
6819
6820                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6821                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6822
6823                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6824                 if (ret < 0)
6825                         return ret;
6826
6827                 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6828                         /* If function expects ctx type in BTF check that caller
6829                          * is passing PTR_TO_CTX.
6830                          */
6831                         if (reg->type != PTR_TO_CTX) {
6832                                 bpf_log(log,
6833                                         "arg#%d expected pointer to ctx, but got %s\n",
6834                                         i, btf_type_str(t));
6835                                 return -EINVAL;
6836                         }
6837                 } else if (ptr_to_mem_ok && processing_call) {
6838                         const struct btf_type *resolve_ret;
6839                         u32 type_size;
6840
6841                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6842                         if (IS_ERR(resolve_ret)) {
6843                                 bpf_log(log,
6844                                         "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6845                                         i, btf_type_str(ref_t), ref_tname,
6846                                         PTR_ERR(resolve_ret));
6847                                 return -EINVAL;
6848                         }
6849
6850                         if (check_mem_reg(env, reg, regno, type_size))
6851                                 return -EINVAL;
6852                 } else {
6853                         bpf_log(log, "reg type unsupported for arg#%d function %s#%d\n", i,
6854                                 func_name, func_id);
6855                         return -EINVAL;
6856                 }
6857         }
6858
6859         return 0;
6860 }
6861
6862 /* Compare BTF of a function declaration with given bpf_reg_state.
6863  * Returns:
6864  * EFAULT - there is a verifier bug. Abort verification.
6865  * EINVAL - there is a type mismatch or BTF is not available.
6866  * 0 - BTF matches with what bpf_reg_state expects.
6867  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6868  */
6869 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6870                                 struct bpf_reg_state *regs)
6871 {
6872         struct bpf_prog *prog = env->prog;
6873         struct btf *btf = prog->aux->btf;
6874         bool is_global;
6875         u32 btf_id;
6876         int err;
6877
6878         if (!prog->aux->func_info)
6879                 return -EINVAL;
6880
6881         btf_id = prog->aux->func_info[subprog].type_id;
6882         if (!btf_id)
6883                 return -EFAULT;
6884
6885         if (prog->aux->func_info_aux[subprog].unreliable)
6886                 return -EINVAL;
6887
6888         is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6889         err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, false);
6890
6891         /* Compiler optimizations can remove arguments from static functions
6892          * or mismatched type can be passed into a global function.
6893          * In such cases mark the function as unreliable from BTF point of view.
6894          */
6895         if (err)
6896                 prog->aux->func_info_aux[subprog].unreliable = true;
6897         return err;
6898 }
6899
6900 /* Compare BTF of a function call with given bpf_reg_state.
6901  * Returns:
6902  * EFAULT - there is a verifier bug. Abort verification.
6903  * EINVAL - there is a type mismatch or BTF is not available.
6904  * 0 - BTF matches with what bpf_reg_state expects.
6905  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6906  *
6907  * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6908  * because btf_check_func_arg_match() is still doing both. Once that
6909  * function is split in 2, we can call from here btf_check_subprog_arg_match()
6910  * first, and then treat the calling part in a new code path.
6911  */
6912 int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6913                            struct bpf_reg_state *regs)
6914 {
6915         struct bpf_prog *prog = env->prog;
6916         struct btf *btf = prog->aux->btf;
6917         bool is_global;
6918         u32 btf_id;
6919         int err;
6920
6921         if (!prog->aux->func_info)
6922                 return -EINVAL;
6923
6924         btf_id = prog->aux->func_info[subprog].type_id;
6925         if (!btf_id)
6926                 return -EFAULT;
6927
6928         if (prog->aux->func_info_aux[subprog].unreliable)
6929                 return -EINVAL;
6930
6931         is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6932         err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, true);
6933
6934         /* Compiler optimizations can remove arguments from static functions
6935          * or mismatched type can be passed into a global function.
6936          * In such cases mark the function as unreliable from BTF point of view.
6937          */
6938         if (err)
6939                 prog->aux->func_info_aux[subprog].unreliable = true;
6940         return err;
6941 }
6942
6943 /* Convert BTF of a function into bpf_reg_state if possible
6944  * Returns:
6945  * EFAULT - there is a verifier bug. Abort verification.
6946  * EINVAL - cannot convert BTF.
6947  * 0 - Successfully converted BTF into bpf_reg_state
6948  * (either PTR_TO_CTX or SCALAR_VALUE).
6949  */
6950 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6951                           struct bpf_reg_state *regs)
6952 {
6953         struct bpf_verifier_log *log = &env->log;
6954         struct bpf_prog *prog = env->prog;
6955         enum bpf_prog_type prog_type = prog->type;
6956         struct btf *btf = prog->aux->btf;
6957         const struct btf_param *args;
6958         const struct btf_type *t, *ref_t;
6959         u32 i, nargs, btf_id;
6960         const char *tname;
6961
6962         if (!prog->aux->func_info ||
6963             prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6964                 bpf_log(log, "Verifier bug\n");
6965                 return -EFAULT;
6966         }
6967
6968         btf_id = prog->aux->func_info[subprog].type_id;
6969         if (!btf_id) {
6970                 bpf_log(log, "Global functions need valid BTF\n");
6971                 return -EFAULT;
6972         }
6973
6974         t = btf_type_by_id(btf, btf_id);
6975         if (!t || !btf_type_is_func(t)) {
6976                 /* These checks were already done by the verifier while loading
6977                  * struct bpf_func_info
6978                  */
6979                 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6980                         subprog);
6981                 return -EFAULT;
6982         }
6983         tname = btf_name_by_offset(btf, t->name_off);
6984
6985         if (log->level & BPF_LOG_LEVEL)
6986                 bpf_log(log, "Validating %s() func#%d...\n",
6987                         tname, subprog);
6988
6989         if (prog->aux->func_info_aux[subprog].unreliable) {
6990                 bpf_log(log, "Verifier bug in function %s()\n", tname);
6991                 return -EFAULT;
6992         }
6993         if (prog_type == BPF_PROG_TYPE_EXT)
6994                 prog_type = prog->aux->dst_prog->type;
6995
6996         t = btf_type_by_id(btf, t->type);
6997         if (!t || !btf_type_is_func_proto(t)) {
6998                 bpf_log(log, "Invalid type of function %s()\n", tname);
6999                 return -EFAULT;
7000         }
7001         args = (const struct btf_param *)(t + 1);
7002         nargs = btf_type_vlen(t);
7003         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7004                 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7005                         tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7006                 return -EINVAL;
7007         }
7008         /* check that function returns int */
7009         t = btf_type_by_id(btf, t->type);
7010         while (btf_type_is_modifier(t))
7011                 t = btf_type_by_id(btf, t->type);
7012         if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7013                 bpf_log(log,
7014                         "Global function %s() doesn't return scalar. Only those are supported.\n",
7015                         tname);
7016                 return -EINVAL;
7017         }
7018         /* Convert BTF function arguments into verifier types.
7019          * Only PTR_TO_CTX and SCALAR are supported atm.
7020          */
7021         for (i = 0; i < nargs; i++) {
7022                 struct bpf_reg_state *reg = &regs[i + 1];
7023
7024                 t = btf_type_by_id(btf, args[i].type);
7025                 while (btf_type_is_modifier(t))
7026                         t = btf_type_by_id(btf, t->type);
7027                 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7028                         reg->type = SCALAR_VALUE;
7029                         continue;
7030                 }
7031                 if (btf_type_is_ptr(t)) {
7032                         if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
7033                                 reg->type = PTR_TO_CTX;
7034                                 continue;
7035                         }
7036
7037                         t = btf_type_skip_modifiers(btf, t->type, NULL);
7038
7039                         ref_t = btf_resolve_size(btf, t, &reg->mem_size);
7040                         if (IS_ERR(ref_t)) {
7041                                 bpf_log(log,
7042                                     "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7043                                     i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7044                                         PTR_ERR(ref_t));
7045                                 return -EINVAL;
7046                         }
7047
7048                         reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
7049                         reg->id = ++env->id_gen;
7050
7051                         continue;
7052                 }
7053                 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7054                         i, btf_type_str(t), tname);
7055                 return -EINVAL;
7056         }
7057         return 0;
7058 }
7059
7060 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7061                           struct btf_show *show)
7062 {
7063         const struct btf_type *t = btf_type_by_id(btf, type_id);
7064
7065         show->btf = btf;
7066         memset(&show->state, 0, sizeof(show->state));
7067         memset(&show->obj, 0, sizeof(show->obj));
7068
7069         btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7070 }
7071
7072 static void btf_seq_show(struct btf_show *show, const char *fmt,
7073                          va_list args)
7074 {
7075         seq_vprintf((struct seq_file *)show->target, fmt, args);
7076 }
7077
7078 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7079                             void *obj, struct seq_file *m, u64 flags)
7080 {
7081         struct btf_show sseq;
7082
7083         sseq.target = m;
7084         sseq.showfn = btf_seq_show;
7085         sseq.flags = flags;
7086
7087         btf_type_show(btf, type_id, obj, &sseq);
7088
7089         return sseq.state.status;
7090 }
7091
7092 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7093                        struct seq_file *m)
7094 {
7095         (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7096                                        BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7097                                        BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7098 }
7099
7100 struct btf_show_snprintf {
7101         struct btf_show show;
7102         int len_left;           /* space left in string */
7103         int len;                /* length we would have written */
7104 };
7105
7106 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7107                               va_list args)
7108 {
7109         struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7110         int len;
7111
7112         len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7113
7114         if (len < 0) {
7115                 ssnprintf->len_left = 0;
7116                 ssnprintf->len = len;
7117         } else if (len >= ssnprintf->len_left) {
7118                 /* no space, drive on to get length we would have written */
7119                 ssnprintf->len_left = 0;
7120                 ssnprintf->len += len;
7121         } else {
7122                 ssnprintf->len_left -= len;
7123                 ssnprintf->len += len;
7124                 show->target += len;
7125         }
7126 }
7127
7128 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7129                            char *buf, int len, u64 flags)
7130 {
7131         struct btf_show_snprintf ssnprintf;
7132
7133         ssnprintf.show.target = buf;
7134         ssnprintf.show.flags = flags;
7135         ssnprintf.show.showfn = btf_snprintf_show;
7136         ssnprintf.len_left = len;
7137         ssnprintf.len = 0;
7138
7139         btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7140
7141         /* If we encountered an error, return it. */
7142         if (ssnprintf.show.state.status)
7143                 return ssnprintf.show.state.status;
7144
7145         /* Otherwise return length we would have written */
7146         return ssnprintf.len;
7147 }
7148
7149 #ifdef CONFIG_PROC_FS
7150 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7151 {
7152         const struct btf *btf = filp->private_data;
7153
7154         seq_printf(m, "btf_id:\t%u\n", btf->id);
7155 }
7156 #endif
7157
7158 static int btf_release(struct inode *inode, struct file *filp)
7159 {
7160         btf_put(filp->private_data);
7161         return 0;
7162 }
7163
7164 const struct file_operations btf_fops = {
7165 #ifdef CONFIG_PROC_FS
7166         .show_fdinfo    = bpf_btf_show_fdinfo,
7167 #endif
7168         .release        = btf_release,
7169 };
7170
7171 static int __btf_new_fd(struct btf *btf)
7172 {
7173         return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7174 }
7175
7176 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7177 {
7178         struct btf *btf;
7179         int ret;
7180
7181         btf = btf_parse(attr, uattr, uattr_size);
7182         if (IS_ERR(btf))
7183                 return PTR_ERR(btf);
7184
7185         ret = btf_alloc_id(btf);
7186         if (ret) {
7187                 btf_free(btf);
7188                 return ret;
7189         }
7190
7191         /*
7192          * The BTF ID is published to the userspace.
7193          * All BTF free must go through call_rcu() from
7194          * now on (i.e. free by calling btf_put()).
7195          */
7196
7197         ret = __btf_new_fd(btf);
7198         if (ret < 0)
7199                 btf_put(btf);
7200
7201         return ret;
7202 }
7203
7204 struct btf *btf_get_by_fd(int fd)
7205 {
7206         struct btf *btf;
7207         struct fd f;
7208
7209         f = fdget(fd);
7210
7211         if (!f.file)
7212                 return ERR_PTR(-EBADF);
7213
7214         if (f.file->f_op != &btf_fops) {
7215                 fdput(f);
7216                 return ERR_PTR(-EINVAL);
7217         }
7218
7219         btf = f.file->private_data;
7220         refcount_inc(&btf->refcnt);
7221         fdput(f);
7222
7223         return btf;
7224 }
7225
7226 int btf_get_info_by_fd(const struct btf *btf,
7227                        const union bpf_attr *attr,
7228                        union bpf_attr __user *uattr)
7229 {
7230         struct bpf_btf_info __user *uinfo;
7231         struct bpf_btf_info info;
7232         u32 info_copy, btf_copy;
7233         void __user *ubtf;
7234         char __user *uname;
7235         u32 uinfo_len, uname_len, name_len;
7236         int ret = 0;
7237
7238         uinfo = u64_to_user_ptr(attr->info.info);
7239         uinfo_len = attr->info.info_len;
7240
7241         info_copy = min_t(u32, uinfo_len, sizeof(info));
7242         memset(&info, 0, sizeof(info));
7243         if (copy_from_user(&info, uinfo, info_copy))
7244                 return -EFAULT;
7245
7246         info.id = btf->id;
7247         ubtf = u64_to_user_ptr(info.btf);
7248         btf_copy = min_t(u32, btf->data_size, info.btf_size);
7249         if (copy_to_user(ubtf, btf->data, btf_copy))
7250                 return -EFAULT;
7251         info.btf_size = btf->data_size;
7252
7253         info.kernel_btf = btf->kernel_btf;
7254
7255         uname = u64_to_user_ptr(info.name);
7256         uname_len = info.name_len;
7257         if (!uname ^ !uname_len)
7258                 return -EINVAL;
7259
7260         name_len = strlen(btf->name);
7261         info.name_len = name_len;
7262
7263         if (uname) {
7264                 if (uname_len >= name_len + 1) {
7265                         if (copy_to_user(uname, btf->name, name_len + 1))
7266                                 return -EFAULT;
7267                 } else {
7268                         char zero = '\0';
7269
7270                         if (copy_to_user(uname, btf->name, uname_len - 1))
7271                                 return -EFAULT;
7272                         if (put_user(zero, uname + uname_len - 1))
7273                                 return -EFAULT;
7274                         /* let user-space know about too short buffer */
7275                         ret = -ENOSPC;
7276                 }
7277         }
7278
7279         if (copy_to_user(uinfo, &info, info_copy) ||
7280             put_user(info_copy, &uattr->info.info_len))
7281                 return -EFAULT;
7282
7283         return ret;
7284 }
7285
7286 int btf_get_fd_by_id(u32 id)
7287 {
7288         struct btf *btf;
7289         int fd;
7290
7291         rcu_read_lock();
7292         btf = idr_find(&btf_idr, id);
7293         if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7294                 btf = ERR_PTR(-ENOENT);
7295         rcu_read_unlock();
7296
7297         if (IS_ERR(btf))
7298                 return PTR_ERR(btf);
7299
7300         fd = __btf_new_fd(btf);
7301         if (fd < 0)
7302                 btf_put(btf);
7303
7304         return fd;
7305 }
7306
7307 u32 btf_obj_id(const struct btf *btf)
7308 {
7309         return btf->id;
7310 }
7311
7312 bool btf_is_kernel(const struct btf *btf)
7313 {
7314         return btf->kernel_btf;
7315 }
7316
7317 bool btf_is_module(const struct btf *btf)
7318 {
7319         return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7320 }
7321
7322 enum {
7323         BTF_MODULE_F_LIVE = (1 << 0),
7324 };
7325
7326 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7327 struct btf_module {
7328         struct list_head list;
7329         struct module *module;
7330         struct btf *btf;
7331         struct bin_attribute *sysfs_attr;
7332         int flags;
7333 };
7334
7335 static LIST_HEAD(btf_modules);
7336 static DEFINE_MUTEX(btf_module_mutex);
7337
7338 static ssize_t
7339 btf_module_read(struct file *file, struct kobject *kobj,
7340                 struct bin_attribute *bin_attr,
7341                 char *buf, loff_t off, size_t len)
7342 {
7343         const struct btf *btf = bin_attr->private;
7344
7345         memcpy(buf, btf->data + off, len);
7346         return len;
7347 }
7348
7349 static void purge_cand_cache(struct btf *btf);
7350
7351 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7352                              void *module)
7353 {
7354         struct btf_module *btf_mod, *tmp;
7355         struct module *mod = module;
7356         struct btf *btf;
7357         int err = 0;
7358
7359         if (mod->btf_data_size == 0 ||
7360             (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7361              op != MODULE_STATE_GOING))
7362                 goto out;
7363
7364         switch (op) {
7365         case MODULE_STATE_COMING:
7366                 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7367                 if (!btf_mod) {
7368                         err = -ENOMEM;
7369                         goto out;
7370                 }
7371                 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7372                 if (IS_ERR(btf)) {
7373                         kfree(btf_mod);
7374                         if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7375                                 pr_warn("failed to validate module [%s] BTF: %ld\n",
7376                                         mod->name, PTR_ERR(btf));
7377                                 err = PTR_ERR(btf);
7378                         } else {
7379                                 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7380                         }
7381                         goto out;
7382                 }
7383                 err = btf_alloc_id(btf);
7384                 if (err) {
7385                         btf_free(btf);
7386                         kfree(btf_mod);
7387                         goto out;
7388                 }
7389
7390                 purge_cand_cache(NULL);
7391                 mutex_lock(&btf_module_mutex);
7392                 btf_mod->module = module;
7393                 btf_mod->btf = btf;
7394                 list_add(&btf_mod->list, &btf_modules);
7395                 mutex_unlock(&btf_module_mutex);
7396
7397                 if (IS_ENABLED(CONFIG_SYSFS)) {
7398                         struct bin_attribute *attr;
7399
7400                         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7401                         if (!attr)
7402                                 goto out;
7403
7404                         sysfs_bin_attr_init(attr);
7405                         attr->attr.name = btf->name;
7406                         attr->attr.mode = 0444;
7407                         attr->size = btf->data_size;
7408                         attr->private = btf;
7409                         attr->read = btf_module_read;
7410
7411                         err = sysfs_create_bin_file(btf_kobj, attr);
7412                         if (err) {
7413                                 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7414                                         mod->name, err);
7415                                 kfree(attr);
7416                                 err = 0;
7417                                 goto out;
7418                         }
7419
7420                         btf_mod->sysfs_attr = attr;
7421                 }
7422
7423                 break;
7424         case MODULE_STATE_LIVE:
7425                 mutex_lock(&btf_module_mutex);
7426                 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7427                         if (btf_mod->module != module)
7428                                 continue;
7429
7430                         btf_mod->flags |= BTF_MODULE_F_LIVE;
7431                         break;
7432                 }
7433                 mutex_unlock(&btf_module_mutex);
7434                 break;
7435         case MODULE_STATE_GOING:
7436                 mutex_lock(&btf_module_mutex);
7437                 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7438                         if (btf_mod->module != module)
7439                                 continue;
7440
7441                         list_del(&btf_mod->list);
7442                         if (btf_mod->sysfs_attr)
7443                                 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7444                         purge_cand_cache(btf_mod->btf);
7445                         btf_put(btf_mod->btf);
7446                         kfree(btf_mod->sysfs_attr);
7447                         kfree(btf_mod);
7448                         break;
7449                 }
7450                 mutex_unlock(&btf_module_mutex);
7451                 break;
7452         }
7453 out:
7454         return notifier_from_errno(err);
7455 }
7456
7457 static struct notifier_block btf_module_nb = {
7458         .notifier_call = btf_module_notify,
7459 };
7460
7461 static int __init btf_module_init(void)
7462 {
7463         register_module_notifier(&btf_module_nb);
7464         return 0;
7465 }
7466
7467 fs_initcall(btf_module_init);
7468 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7469
7470 struct module *btf_try_get_module(const struct btf *btf)
7471 {
7472         struct module *res = NULL;
7473 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7474         struct btf_module *btf_mod, *tmp;
7475
7476         mutex_lock(&btf_module_mutex);
7477         list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7478                 if (btf_mod->btf != btf)
7479                         continue;
7480
7481                 /* We must only consider module whose __init routine has
7482                  * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7483                  * which is set from the notifier callback for
7484                  * MODULE_STATE_LIVE.
7485                  */
7486                 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7487                         res = btf_mod->module;
7488
7489                 break;
7490         }
7491         mutex_unlock(&btf_module_mutex);
7492 #endif
7493
7494         return res;
7495 }
7496
7497 /* Returns struct btf corresponding to the struct module.
7498  * This function can return NULL or ERR_PTR.
7499  */
7500 static struct btf *btf_get_module_btf(const struct module *module)
7501 {
7502 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7503         struct btf_module *btf_mod, *tmp;
7504 #endif
7505         struct btf *btf = NULL;
7506
7507         if (!module) {
7508                 btf = bpf_get_btf_vmlinux();
7509                 if (!IS_ERR_OR_NULL(btf))
7510                         btf_get(btf);
7511                 return btf;
7512         }
7513
7514 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7515         mutex_lock(&btf_module_mutex);
7516         list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7517                 if (btf_mod->module != module)
7518                         continue;
7519
7520                 btf_get(btf_mod->btf);
7521                 btf = btf_mod->btf;
7522                 break;
7523         }
7524         mutex_unlock(&btf_module_mutex);
7525 #endif
7526
7527         return btf;
7528 }
7529
7530 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7531 {
7532         struct btf *btf = NULL;
7533         int btf_obj_fd = 0;
7534         long ret;
7535
7536         if (flags)
7537                 return -EINVAL;
7538
7539         if (name_sz <= 1 || name[name_sz - 1])
7540                 return -EINVAL;
7541
7542         ret = bpf_find_btf_id(name, kind, &btf);
7543         if (ret > 0 && btf_is_module(btf)) {
7544                 btf_obj_fd = __btf_new_fd(btf);
7545                 if (btf_obj_fd < 0) {
7546                         btf_put(btf);
7547                         return btf_obj_fd;
7548                 }
7549                 return ret | (((u64)btf_obj_fd) << 32);
7550         }
7551         if (ret > 0)
7552                 btf_put(btf);
7553         return ret;
7554 }
7555
7556 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7557         .func           = bpf_btf_find_by_name_kind,
7558         .gpl_only       = false,
7559         .ret_type       = RET_INTEGER,
7560         .arg1_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7561         .arg2_type      = ARG_CONST_SIZE,
7562         .arg3_type      = ARG_ANYTHING,
7563         .arg4_type      = ARG_ANYTHING,
7564 };
7565
7566 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7567 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7568 BTF_TRACING_TYPE_xxx
7569 #undef BTF_TRACING_TYPE
7570
7571 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
7572                                  const struct btf_type *func, u32 func_flags)
7573 {
7574         u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7575         const char *name, *sfx, *iter_name;
7576         const struct btf_param *arg;
7577         const struct btf_type *t;
7578         char exp_name[128];
7579         u32 nr_args;
7580
7581         /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
7582         if (!flags || (flags & (flags - 1)))
7583                 return -EINVAL;
7584
7585         /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
7586         nr_args = btf_type_vlen(func);
7587         if (nr_args < 1)
7588                 return -EINVAL;
7589
7590         arg = &btf_params(func)[0];
7591         t = btf_type_skip_modifiers(btf, arg->type, NULL);
7592         if (!t || !btf_type_is_ptr(t))
7593                 return -EINVAL;
7594         t = btf_type_skip_modifiers(btf, t->type, NULL);
7595         if (!t || !__btf_type_is_struct(t))
7596                 return -EINVAL;
7597
7598         name = btf_name_by_offset(btf, t->name_off);
7599         if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
7600                 return -EINVAL;
7601
7602         /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
7603          * fit nicely in stack slots
7604          */
7605         if (t->size == 0 || (t->size % 8))
7606                 return -EINVAL;
7607
7608         /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
7609          * naming pattern
7610          */
7611         iter_name = name + sizeof(ITER_PREFIX) - 1;
7612         if (flags & KF_ITER_NEW)
7613                 sfx = "new";
7614         else if (flags & KF_ITER_NEXT)
7615                 sfx = "next";
7616         else /* (flags & KF_ITER_DESTROY) */
7617                 sfx = "destroy";
7618
7619         snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
7620         if (strcmp(func_name, exp_name))
7621                 return -EINVAL;
7622
7623         /* only iter constructor should have extra arguments */
7624         if (!(flags & KF_ITER_NEW) && nr_args != 1)
7625                 return -EINVAL;
7626
7627         if (flags & KF_ITER_NEXT) {
7628                 /* bpf_iter_<type>_next() should return pointer */
7629                 t = btf_type_skip_modifiers(btf, func->type, NULL);
7630                 if (!t || !btf_type_is_ptr(t))
7631                         return -EINVAL;
7632         }
7633
7634         if (flags & KF_ITER_DESTROY) {
7635                 /* bpf_iter_<type>_destroy() should return void */
7636                 t = btf_type_by_id(btf, func->type);
7637                 if (!t || !btf_type_is_void(t))
7638                         return -EINVAL;
7639         }
7640
7641         return 0;
7642 }
7643
7644 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
7645 {
7646         const struct btf_type *func;
7647         const char *func_name;
7648         int err;
7649
7650         /* any kfunc should be FUNC -> FUNC_PROTO */
7651         func = btf_type_by_id(btf, func_id);
7652         if (!func || !btf_type_is_func(func))
7653                 return -EINVAL;
7654
7655         /* sanity check kfunc name */
7656         func_name = btf_name_by_offset(btf, func->name_off);
7657         if (!func_name || !func_name[0])
7658                 return -EINVAL;
7659
7660         func = btf_type_by_id(btf, func->type);
7661         if (!func || !btf_type_is_func_proto(func))
7662                 return -EINVAL;
7663
7664         if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
7665                 err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
7666                 if (err)
7667                         return err;
7668         }
7669
7670         return 0;
7671 }
7672
7673 /* Kernel Function (kfunc) BTF ID set registration API */
7674
7675 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7676                                   const struct btf_kfunc_id_set *kset)
7677 {
7678         struct btf_kfunc_hook_filter *hook_filter;
7679         struct btf_id_set8 *add_set = kset->set;
7680         bool vmlinux_set = !btf_is_module(btf);
7681         bool add_filter = !!kset->filter;
7682         struct btf_kfunc_set_tab *tab;
7683         struct btf_id_set8 *set;
7684         u32 set_cnt;
7685         int ret;
7686
7687         if (hook >= BTF_KFUNC_HOOK_MAX) {
7688                 ret = -EINVAL;
7689                 goto end;
7690         }
7691
7692         if (!add_set->cnt)
7693                 return 0;
7694
7695         tab = btf->kfunc_set_tab;
7696
7697         if (tab && add_filter) {
7698                 u32 i;
7699
7700                 hook_filter = &tab->hook_filters[hook];
7701                 for (i = 0; i < hook_filter->nr_filters; i++) {
7702                         if (hook_filter->filters[i] == kset->filter) {
7703                                 add_filter = false;
7704                                 break;
7705                         }
7706                 }
7707
7708                 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
7709                         ret = -E2BIG;
7710                         goto end;
7711                 }
7712         }
7713
7714         if (!tab) {
7715                 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7716                 if (!tab)
7717                         return -ENOMEM;
7718                 btf->kfunc_set_tab = tab;
7719         }
7720
7721         set = tab->sets[hook];
7722         /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7723          * for module sets.
7724          */
7725         if (WARN_ON_ONCE(set && !vmlinux_set)) {
7726                 ret = -EINVAL;
7727                 goto end;
7728         }
7729
7730         /* We don't need to allocate, concatenate, and sort module sets, because
7731          * only one is allowed per hook. Hence, we can directly assign the
7732          * pointer and return.
7733          */
7734         if (!vmlinux_set) {
7735                 tab->sets[hook] = add_set;
7736                 goto do_add_filter;
7737         }
7738
7739         /* In case of vmlinux sets, there may be more than one set being
7740          * registered per hook. To create a unified set, we allocate a new set
7741          * and concatenate all individual sets being registered. While each set
7742          * is individually sorted, they may become unsorted when concatenated,
7743          * hence re-sorting the final set again is required to make binary
7744          * searching the set using btf_id_set8_contains function work.
7745          */
7746         set_cnt = set ? set->cnt : 0;
7747
7748         if (set_cnt > U32_MAX - add_set->cnt) {
7749                 ret = -EOVERFLOW;
7750                 goto end;
7751         }
7752
7753         if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7754                 ret = -E2BIG;
7755                 goto end;
7756         }
7757
7758         /* Grow set */
7759         set = krealloc(tab->sets[hook],
7760                        offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
7761                        GFP_KERNEL | __GFP_NOWARN);
7762         if (!set) {
7763                 ret = -ENOMEM;
7764                 goto end;
7765         }
7766
7767         /* For newly allocated set, initialize set->cnt to 0 */
7768         if (!tab->sets[hook])
7769                 set->cnt = 0;
7770         tab->sets[hook] = set;
7771
7772         /* Concatenate the two sets */
7773         memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
7774         set->cnt += add_set->cnt;
7775
7776         sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
7777
7778 do_add_filter:
7779         if (add_filter) {
7780                 hook_filter = &tab->hook_filters[hook];
7781                 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
7782         }
7783         return 0;
7784 end:
7785         btf_free_kfunc_set_tab(btf);
7786         return ret;
7787 }
7788
7789 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
7790                                         enum btf_kfunc_hook hook,
7791                                         u32 kfunc_btf_id,
7792                                         const struct bpf_prog *prog)
7793 {
7794         struct btf_kfunc_hook_filter *hook_filter;
7795         struct btf_id_set8 *set;
7796         u32 *id, i;
7797
7798         if (hook >= BTF_KFUNC_HOOK_MAX)
7799                 return NULL;
7800         if (!btf->kfunc_set_tab)
7801                 return NULL;
7802         hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
7803         for (i = 0; i < hook_filter->nr_filters; i++) {
7804                 if (hook_filter->filters[i](prog, kfunc_btf_id))
7805                         return NULL;
7806         }
7807         set = btf->kfunc_set_tab->sets[hook];
7808         if (!set)
7809                 return NULL;
7810         id = btf_id_set8_contains(set, kfunc_btf_id);
7811         if (!id)
7812                 return NULL;
7813         /* The flags for BTF ID are located next to it */
7814         return id + 1;
7815 }
7816
7817 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7818 {
7819         switch (prog_type) {
7820         case BPF_PROG_TYPE_UNSPEC:
7821                 return BTF_KFUNC_HOOK_COMMON;
7822         case BPF_PROG_TYPE_XDP:
7823                 return BTF_KFUNC_HOOK_XDP;
7824         case BPF_PROG_TYPE_SCHED_CLS:
7825                 return BTF_KFUNC_HOOK_TC;
7826         case BPF_PROG_TYPE_STRUCT_OPS:
7827                 return BTF_KFUNC_HOOK_STRUCT_OPS;
7828         case BPF_PROG_TYPE_TRACING:
7829         case BPF_PROG_TYPE_LSM:
7830                 return BTF_KFUNC_HOOK_TRACING;
7831         case BPF_PROG_TYPE_SYSCALL:
7832                 return BTF_KFUNC_HOOK_SYSCALL;
7833         case BPF_PROG_TYPE_CGROUP_SKB:
7834                 return BTF_KFUNC_HOOK_CGROUP_SKB;
7835         case BPF_PROG_TYPE_SCHED_ACT:
7836                 return BTF_KFUNC_HOOK_SCHED_ACT;
7837         case BPF_PROG_TYPE_SK_SKB:
7838                 return BTF_KFUNC_HOOK_SK_SKB;
7839         case BPF_PROG_TYPE_SOCKET_FILTER:
7840                 return BTF_KFUNC_HOOK_SOCKET_FILTER;
7841         case BPF_PROG_TYPE_LWT_OUT:
7842         case BPF_PROG_TYPE_LWT_IN:
7843         case BPF_PROG_TYPE_LWT_XMIT:
7844         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
7845                 return BTF_KFUNC_HOOK_LWT;
7846         case BPF_PROG_TYPE_NETFILTER:
7847                 return BTF_KFUNC_HOOK_NETFILTER;
7848         default:
7849                 return BTF_KFUNC_HOOK_MAX;
7850         }
7851 }
7852
7853 /* Caution:
7854  * Reference to the module (obtained using btf_try_get_module) corresponding to
7855  * the struct btf *MUST* be held when calling this function from verifier
7856  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7857  * keeping the reference for the duration of the call provides the necessary
7858  * protection for looking up a well-formed btf->kfunc_set_tab.
7859  */
7860 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
7861                                u32 kfunc_btf_id,
7862                                const struct bpf_prog *prog)
7863 {
7864         enum bpf_prog_type prog_type = resolve_prog_type(prog);
7865         enum btf_kfunc_hook hook;
7866         u32 *kfunc_flags;
7867
7868         kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
7869         if (kfunc_flags)
7870                 return kfunc_flags;
7871
7872         hook = bpf_prog_type_to_kfunc_hook(prog_type);
7873         return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
7874 }
7875
7876 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
7877                                 const struct bpf_prog *prog)
7878 {
7879         return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
7880 }
7881
7882 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
7883                                        const struct btf_kfunc_id_set *kset)
7884 {
7885         struct btf *btf;
7886         int ret, i;
7887
7888         btf = btf_get_module_btf(kset->owner);
7889         if (!btf) {
7890                 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7891                         pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7892                         return -ENOENT;
7893                 }
7894                 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7895                         pr_err("missing module BTF, cannot register kfuncs\n");
7896                         return -ENOENT;
7897                 }
7898                 return 0;
7899         }
7900         if (IS_ERR(btf))
7901                 return PTR_ERR(btf);
7902
7903         for (i = 0; i < kset->set->cnt; i++) {
7904                 ret = btf_check_kfunc_protos(btf, kset->set->pairs[i].id,
7905                                              kset->set->pairs[i].flags);
7906                 if (ret)
7907                         goto err_out;
7908         }
7909
7910         ret = btf_populate_kfunc_set(btf, hook, kset);
7911
7912 err_out:
7913         btf_put(btf);
7914         return ret;
7915 }
7916
7917 /* This function must be invoked only from initcalls/module init functions */
7918 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7919                               const struct btf_kfunc_id_set *kset)
7920 {
7921         enum btf_kfunc_hook hook;
7922
7923         hook = bpf_prog_type_to_kfunc_hook(prog_type);
7924         return __register_btf_kfunc_id_set(hook, kset);
7925 }
7926 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7927
7928 /* This function must be invoked only from initcalls/module init functions */
7929 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
7930 {
7931         return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
7932 }
7933 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
7934
7935 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7936 {
7937         struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7938         struct btf_id_dtor_kfunc *dtor;
7939
7940         if (!tab)
7941                 return -ENOENT;
7942         /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7943          * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7944          */
7945         BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7946         dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7947         if (!dtor)
7948                 return -ENOENT;
7949         return dtor->kfunc_btf_id;
7950 }
7951
7952 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7953 {
7954         const struct btf_type *dtor_func, *dtor_func_proto, *t;
7955         const struct btf_param *args;
7956         s32 dtor_btf_id;
7957         u32 nr_args, i;
7958
7959         for (i = 0; i < cnt; i++) {
7960                 dtor_btf_id = dtors[i].kfunc_btf_id;
7961
7962                 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7963                 if (!dtor_func || !btf_type_is_func(dtor_func))
7964                         return -EINVAL;
7965
7966                 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7967                 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7968                         return -EINVAL;
7969
7970                 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7971                 t = btf_type_by_id(btf, dtor_func_proto->type);
7972                 if (!t || !btf_type_is_void(t))
7973                         return -EINVAL;
7974
7975                 nr_args = btf_type_vlen(dtor_func_proto);
7976                 if (nr_args != 1)
7977                         return -EINVAL;
7978                 args = btf_params(dtor_func_proto);
7979                 t = btf_type_by_id(btf, args[0].type);
7980                 /* Allow any pointer type, as width on targets Linux supports
7981                  * will be same for all pointer types (i.e. sizeof(void *))
7982                  */
7983                 if (!t || !btf_type_is_ptr(t))
7984                         return -EINVAL;
7985         }
7986         return 0;
7987 }
7988
7989 /* This function must be invoked only from initcalls/module init functions */
7990 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7991                                 struct module *owner)
7992 {
7993         struct btf_id_dtor_kfunc_tab *tab;
7994         struct btf *btf;
7995         u32 tab_cnt;
7996         int ret;
7997
7998         btf = btf_get_module_btf(owner);
7999         if (!btf) {
8000                 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
8001                         pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
8002                         return -ENOENT;
8003                 }
8004                 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
8005                         pr_err("missing module BTF, cannot register dtor kfuncs\n");
8006                         return -ENOENT;
8007                 }
8008                 return 0;
8009         }
8010         if (IS_ERR(btf))
8011                 return PTR_ERR(btf);
8012
8013         if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8014                 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8015                 ret = -E2BIG;
8016                 goto end;
8017         }
8018
8019         /* Ensure that the prototype of dtor kfuncs being registered is sane */
8020         ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8021         if (ret < 0)
8022                 goto end;
8023
8024         tab = btf->dtor_kfunc_tab;
8025         /* Only one call allowed for modules */
8026         if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8027                 ret = -EINVAL;
8028                 goto end;
8029         }
8030
8031         tab_cnt = tab ? tab->cnt : 0;
8032         if (tab_cnt > U32_MAX - add_cnt) {
8033                 ret = -EOVERFLOW;
8034                 goto end;
8035         }
8036         if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8037                 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8038                 ret = -E2BIG;
8039                 goto end;
8040         }
8041
8042         tab = krealloc(btf->dtor_kfunc_tab,
8043                        offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
8044                        GFP_KERNEL | __GFP_NOWARN);
8045         if (!tab) {
8046                 ret = -ENOMEM;
8047                 goto end;
8048         }
8049
8050         if (!btf->dtor_kfunc_tab)
8051                 tab->cnt = 0;
8052         btf->dtor_kfunc_tab = tab;
8053
8054         memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8055         tab->cnt += add_cnt;
8056
8057         sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8058
8059 end:
8060         if (ret)
8061                 btf_free_dtor_kfunc_tab(btf);
8062         btf_put(btf);
8063         return ret;
8064 }
8065 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8066
8067 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8068
8069 /* Check local and target types for compatibility. This check is used for
8070  * type-based CO-RE relocations and follow slightly different rules than
8071  * field-based relocations. This function assumes that root types were already
8072  * checked for name match. Beyond that initial root-level name check, names
8073  * are completely ignored. Compatibility rules are as follows:
8074  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8075  *     kind should match for local and target types (i.e., STRUCT is not
8076  *     compatible with UNION);
8077  *   - for ENUMs/ENUM64s, the size is ignored;
8078  *   - for INT, size and signedness are ignored;
8079  *   - for ARRAY, dimensionality is ignored, element types are checked for
8080  *     compatibility recursively;
8081  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
8082  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8083  *   - FUNC_PROTOs are compatible if they have compatible signature: same
8084  *     number of input args and compatible return and argument types.
8085  * These rules are not set in stone and probably will be adjusted as we get
8086  * more experience with using BPF CO-RE relocations.
8087  */
8088 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8089                               const struct btf *targ_btf, __u32 targ_id)
8090 {
8091         return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8092                                            MAX_TYPES_ARE_COMPAT_DEPTH);
8093 }
8094
8095 #define MAX_TYPES_MATCH_DEPTH 2
8096
8097 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8098                          const struct btf *targ_btf, u32 targ_id)
8099 {
8100         return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8101                                       MAX_TYPES_MATCH_DEPTH);
8102 }
8103
8104 static bool bpf_core_is_flavor_sep(const char *s)
8105 {
8106         /* check X___Y name pattern, where X and Y are not underscores */
8107         return s[0] != '_' &&                                 /* X */
8108                s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
8109                s[4] != '_';                                   /* Y */
8110 }
8111
8112 size_t bpf_core_essential_name_len(const char *name)
8113 {
8114         size_t n = strlen(name);
8115         int i;
8116
8117         for (i = n - 5; i >= 0; i--) {
8118                 if (bpf_core_is_flavor_sep(name + i))
8119                         return i + 1;
8120         }
8121         return n;
8122 }
8123
8124 struct bpf_cand_cache {
8125         const char *name;
8126         u32 name_len;
8127         u16 kind;
8128         u16 cnt;
8129         struct {
8130                 const struct btf *btf;
8131                 u32 id;
8132         } cands[];
8133 };
8134
8135 static void bpf_free_cands(struct bpf_cand_cache *cands)
8136 {
8137         if (!cands->cnt)
8138                 /* empty candidate array was allocated on stack */
8139                 return;
8140         kfree(cands);
8141 }
8142
8143 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8144 {
8145         kfree(cands->name);
8146         kfree(cands);
8147 }
8148
8149 #define VMLINUX_CAND_CACHE_SIZE 31
8150 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8151
8152 #define MODULE_CAND_CACHE_SIZE 31
8153 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8154
8155 static DEFINE_MUTEX(cand_cache_mutex);
8156
8157 static void __print_cand_cache(struct bpf_verifier_log *log,
8158                                struct bpf_cand_cache **cache,
8159                                int cache_size)
8160 {
8161         struct bpf_cand_cache *cc;
8162         int i, j;
8163
8164         for (i = 0; i < cache_size; i++) {
8165                 cc = cache[i];
8166                 if (!cc)
8167                         continue;
8168                 bpf_log(log, "[%d]%s(", i, cc->name);
8169                 for (j = 0; j < cc->cnt; j++) {
8170                         bpf_log(log, "%d", cc->cands[j].id);
8171                         if (j < cc->cnt - 1)
8172                                 bpf_log(log, " ");
8173                 }
8174                 bpf_log(log, "), ");
8175         }
8176 }
8177
8178 static void print_cand_cache(struct bpf_verifier_log *log)
8179 {
8180         mutex_lock(&cand_cache_mutex);
8181         bpf_log(log, "vmlinux_cand_cache:");
8182         __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8183         bpf_log(log, "\nmodule_cand_cache:");
8184         __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8185         bpf_log(log, "\n");
8186         mutex_unlock(&cand_cache_mutex);
8187 }
8188
8189 static u32 hash_cands(struct bpf_cand_cache *cands)
8190 {
8191         return jhash(cands->name, cands->name_len, 0);
8192 }
8193
8194 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8195                                                struct bpf_cand_cache **cache,
8196                                                int cache_size)
8197 {
8198         struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8199
8200         if (cc && cc->name_len == cands->name_len &&
8201             !strncmp(cc->name, cands->name, cands->name_len))
8202                 return cc;
8203         return NULL;
8204 }
8205
8206 static size_t sizeof_cands(int cnt)
8207 {
8208         return offsetof(struct bpf_cand_cache, cands[cnt]);
8209 }
8210
8211 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8212                                                   struct bpf_cand_cache **cache,
8213                                                   int cache_size)
8214 {
8215         struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8216
8217         if (*cc) {
8218                 bpf_free_cands_from_cache(*cc);
8219                 *cc = NULL;
8220         }
8221         new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8222         if (!new_cands) {
8223                 bpf_free_cands(cands);
8224                 return ERR_PTR(-ENOMEM);
8225         }
8226         /* strdup the name, since it will stay in cache.
8227          * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8228          */
8229         new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8230         bpf_free_cands(cands);
8231         if (!new_cands->name) {
8232                 kfree(new_cands);
8233                 return ERR_PTR(-ENOMEM);
8234         }
8235         *cc = new_cands;
8236         return new_cands;
8237 }
8238
8239 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8240 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8241                                int cache_size)
8242 {
8243         struct bpf_cand_cache *cc;
8244         int i, j;
8245
8246         for (i = 0; i < cache_size; i++) {
8247                 cc = cache[i];
8248                 if (!cc)
8249                         continue;
8250                 if (!btf) {
8251                         /* when new module is loaded purge all of module_cand_cache,
8252                          * since new module might have candidates with the name
8253                          * that matches cached cands.
8254                          */
8255                         bpf_free_cands_from_cache(cc);
8256                         cache[i] = NULL;
8257                         continue;
8258                 }
8259                 /* when module is unloaded purge cache entries
8260                  * that match module's btf
8261                  */
8262                 for (j = 0; j < cc->cnt; j++)
8263                         if (cc->cands[j].btf == btf) {
8264                                 bpf_free_cands_from_cache(cc);
8265                                 cache[i] = NULL;
8266                                 break;
8267                         }
8268         }
8269
8270 }
8271
8272 static void purge_cand_cache(struct btf *btf)
8273 {
8274         mutex_lock(&cand_cache_mutex);
8275         __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8276         mutex_unlock(&cand_cache_mutex);
8277 }
8278 #endif
8279
8280 static struct bpf_cand_cache *
8281 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8282                    int targ_start_id)
8283 {
8284         struct bpf_cand_cache *new_cands;
8285         const struct btf_type *t;
8286         const char *targ_name;
8287         size_t targ_essent_len;
8288         int n, i;
8289
8290         n = btf_nr_types(targ_btf);
8291         for (i = targ_start_id; i < n; i++) {
8292                 t = btf_type_by_id(targ_btf, i);
8293                 if (btf_kind(t) != cands->kind)
8294                         continue;
8295
8296                 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8297                 if (!targ_name)
8298                         continue;
8299
8300                 /* the resched point is before strncmp to make sure that search
8301                  * for non-existing name will have a chance to schedule().
8302                  */
8303                 cond_resched();
8304
8305                 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8306                         continue;
8307
8308                 targ_essent_len = bpf_core_essential_name_len(targ_name);
8309                 if (targ_essent_len != cands->name_len)
8310                         continue;
8311
8312                 /* most of the time there is only one candidate for a given kind+name pair */
8313                 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8314                 if (!new_cands) {
8315                         bpf_free_cands(cands);
8316                         return ERR_PTR(-ENOMEM);
8317                 }
8318
8319                 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8320                 bpf_free_cands(cands);
8321                 cands = new_cands;
8322                 cands->cands[cands->cnt].btf = targ_btf;
8323                 cands->cands[cands->cnt].id = i;
8324                 cands->cnt++;
8325         }
8326         return cands;
8327 }
8328
8329 static struct bpf_cand_cache *
8330 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8331 {
8332         struct bpf_cand_cache *cands, *cc, local_cand = {};
8333         const struct btf *local_btf = ctx->btf;
8334         const struct btf_type *local_type;
8335         const struct btf *main_btf;
8336         size_t local_essent_len;
8337         struct btf *mod_btf;
8338         const char *name;
8339         int id;
8340
8341         main_btf = bpf_get_btf_vmlinux();
8342         if (IS_ERR(main_btf))
8343                 return ERR_CAST(main_btf);
8344         if (!main_btf)
8345                 return ERR_PTR(-EINVAL);
8346
8347         local_type = btf_type_by_id(local_btf, local_type_id);
8348         if (!local_type)
8349                 return ERR_PTR(-EINVAL);
8350
8351         name = btf_name_by_offset(local_btf, local_type->name_off);
8352         if (str_is_empty(name))
8353                 return ERR_PTR(-EINVAL);
8354         local_essent_len = bpf_core_essential_name_len(name);
8355
8356         cands = &local_cand;
8357         cands->name = name;
8358         cands->kind = btf_kind(local_type);
8359         cands->name_len = local_essent_len;
8360
8361         cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8362         /* cands is a pointer to stack here */
8363         if (cc) {
8364                 if (cc->cnt)
8365                         return cc;
8366                 goto check_modules;
8367         }
8368
8369         /* Attempt to find target candidates in vmlinux BTF first */
8370         cands = bpf_core_add_cands(cands, main_btf, 1);
8371         if (IS_ERR(cands))
8372                 return ERR_CAST(cands);
8373
8374         /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8375
8376         /* populate cache even when cands->cnt == 0 */
8377         cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8378         if (IS_ERR(cc))
8379                 return ERR_CAST(cc);
8380
8381         /* if vmlinux BTF has any candidate, don't go for module BTFs */
8382         if (cc->cnt)
8383                 return cc;
8384
8385 check_modules:
8386         /* cands is a pointer to stack here and cands->cnt == 0 */
8387         cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8388         if (cc)
8389                 /* if cache has it return it even if cc->cnt == 0 */
8390                 return cc;
8391
8392         /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8393         spin_lock_bh(&btf_idr_lock);
8394         idr_for_each_entry(&btf_idr, mod_btf, id) {
8395                 if (!btf_is_module(mod_btf))
8396                         continue;
8397                 /* linear search could be slow hence unlock/lock
8398                  * the IDR to avoiding holding it for too long
8399                  */
8400                 btf_get(mod_btf);
8401                 spin_unlock_bh(&btf_idr_lock);
8402                 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8403                 btf_put(mod_btf);
8404                 if (IS_ERR(cands))
8405                         return ERR_CAST(cands);
8406                 spin_lock_bh(&btf_idr_lock);
8407         }
8408         spin_unlock_bh(&btf_idr_lock);
8409         /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8410          * or pointer to stack if cands->cnd == 0.
8411          * Copy it into the cache even when cands->cnt == 0 and
8412          * return the result.
8413          */
8414         return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8415 }
8416
8417 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8418                    int relo_idx, void *insn)
8419 {
8420         bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8421         struct bpf_core_cand_list cands = {};
8422         struct bpf_core_relo_res targ_res;
8423         struct bpf_core_spec *specs;
8424         int err;
8425
8426         /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8427          * into arrays of btf_ids of struct fields and array indices.
8428          */
8429         specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8430         if (!specs)
8431                 return -ENOMEM;
8432
8433         if (need_cands) {
8434                 struct bpf_cand_cache *cc;
8435                 int i;
8436
8437                 mutex_lock(&cand_cache_mutex);
8438                 cc = bpf_core_find_cands(ctx, relo->type_id);
8439                 if (IS_ERR(cc)) {
8440                         bpf_log(ctx->log, "target candidate search failed for %d\n",
8441                                 relo->type_id);
8442                         err = PTR_ERR(cc);
8443                         goto out;
8444                 }
8445                 if (cc->cnt) {
8446                         cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8447                         if (!cands.cands) {
8448                                 err = -ENOMEM;
8449                                 goto out;
8450                         }
8451                 }
8452                 for (i = 0; i < cc->cnt; i++) {
8453                         bpf_log(ctx->log,
8454                                 "CO-RE relocating %s %s: found target candidate [%d]\n",
8455                                 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8456                         cands.cands[i].btf = cc->cands[i].btf;
8457                         cands.cands[i].id = cc->cands[i].id;
8458                 }
8459                 cands.len = cc->cnt;
8460                 /* cand_cache_mutex needs to span the cache lookup and
8461                  * copy of btf pointer into bpf_core_cand_list,
8462                  * since module can be unloaded while bpf_core_calc_relo_insn
8463                  * is working with module's btf.
8464                  */
8465         }
8466
8467         err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8468                                       &targ_res);
8469         if (err)
8470                 goto out;
8471
8472         err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8473                                   &targ_res);
8474
8475 out:
8476         kfree(specs);
8477         if (need_cands) {
8478                 kfree(cands.cands);
8479                 mutex_unlock(&cand_cache_mutex);
8480                 if (ctx->log->level & BPF_LOG_LEVEL2)
8481                         print_cand_cache(ctx->log);
8482         }
8483         return err;
8484 }
8485
8486 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8487                                 const struct bpf_reg_state *reg,
8488                                 const char *field_name, u32 btf_id, const char *suffix)
8489 {
8490         struct btf *btf = reg->btf;
8491         const struct btf_type *walk_type, *safe_type;
8492         const char *tname;
8493         char safe_tname[64];
8494         long ret, safe_id;
8495         const struct btf_member *member;
8496         u32 i;
8497
8498         walk_type = btf_type_by_id(btf, reg->btf_id);
8499         if (!walk_type)
8500                 return false;
8501
8502         tname = btf_name_by_offset(btf, walk_type->name_off);
8503
8504         ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8505         if (ret < 0)
8506                 return false;
8507
8508         safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8509         if (safe_id < 0)
8510                 return false;
8511
8512         safe_type = btf_type_by_id(btf, safe_id);
8513         if (!safe_type)
8514                 return false;
8515
8516         for_each_member(i, safe_type, member) {
8517                 const char *m_name = __btf_name_by_offset(btf, member->name_off);
8518                 const struct btf_type *mtype = btf_type_by_id(btf, member->type);
8519                 u32 id;
8520
8521                 if (!btf_type_is_ptr(mtype))
8522                         continue;
8523
8524                 btf_type_skip_modifiers(btf, mtype->type, &id);
8525                 /* If we match on both type and name, the field is considered trusted. */
8526                 if (btf_id == id && !strcmp(field_name, m_name))
8527                         return true;
8528         }
8529
8530         return false;
8531 }
8532
8533 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8534                                const struct btf *reg_btf, u32 reg_id,
8535                                const struct btf *arg_btf, u32 arg_id)
8536 {
8537         const char *reg_name, *arg_name, *search_needle;
8538         const struct btf_type *reg_type, *arg_type;
8539         int reg_len, arg_len, cmp_len;
8540         size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8541
8542         reg_type = btf_type_by_id(reg_btf, reg_id);
8543         if (!reg_type)
8544                 return false;
8545
8546         arg_type = btf_type_by_id(arg_btf, arg_id);
8547         if (!arg_type)
8548                 return false;
8549
8550         reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8551         arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8552
8553         reg_len = strlen(reg_name);
8554         arg_len = strlen(arg_name);
8555
8556         /* Exactly one of the two type names may be suffixed with ___init, so
8557          * if the strings are the same size, they can't possibly be no-cast
8558          * aliases of one another. If you have two of the same type names, e.g.
8559          * they're both nf_conn___init, it would be improper to return true
8560          * because they are _not_ no-cast aliases, they are the same type.
8561          */
8562         if (reg_len == arg_len)
8563                 return false;
8564
8565         /* Either of the two names must be the other name, suffixed with ___init. */
8566         if ((reg_len != arg_len + pattern_len) &&
8567             (arg_len != reg_len + pattern_len))
8568                 return false;
8569
8570         if (reg_len < arg_len) {
8571                 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8572                 cmp_len = reg_len;
8573         } else {
8574                 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8575                 cmp_len = arg_len;
8576         }
8577
8578         if (!search_needle)
8579                 return false;
8580
8581         /* ___init suffix must come at the end of the name */
8582         if (*(search_needle + pattern_len) != '\0')
8583                 return false;
8584
8585         return !strncmp(reg_name, arg_name, cmp_len);
8586 }