GNU Linux-libre 5.15.137-gnu
[releases.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/skmsg.h>
23 #include <linux/perf_event.h>
24 #include <linux/bsearch.h>
25 #include <linux/kobject.h>
26 #include <linux/sysfs.h>
27 #include <net/sock.h>
28
29 /* BTF (BPF Type Format) is the meta data format which describes
30  * the data types of BPF program/map.  Hence, it basically focus
31  * on the C programming language which the modern BPF is primary
32  * using.
33  *
34  * ELF Section:
35  * ~~~~~~~~~~~
36  * The BTF data is stored under the ".BTF" ELF section
37  *
38  * struct btf_type:
39  * ~~~~~~~~~~~~~~~
40  * Each 'struct btf_type' object describes a C data type.
41  * Depending on the type it is describing, a 'struct btf_type'
42  * object may be followed by more data.  F.e.
43  * To describe an array, 'struct btf_type' is followed by
44  * 'struct btf_array'.
45  *
46  * 'struct btf_type' and any extra data following it are
47  * 4 bytes aligned.
48  *
49  * Type section:
50  * ~~~~~~~~~~~~~
51  * The BTF type section contains a list of 'struct btf_type' objects.
52  * Each one describes a C type.  Recall from the above section
53  * that a 'struct btf_type' object could be immediately followed by extra
54  * data in order to describe some particular C types.
55  *
56  * type_id:
57  * ~~~~~~~
58  * Each btf_type object is identified by a type_id.  The type_id
59  * is implicitly implied by the location of the btf_type object in
60  * the BTF type section.  The first one has type_id 1.  The second
61  * one has type_id 2...etc.  Hence, an earlier btf_type has
62  * a smaller type_id.
63  *
64  * A btf_type object may refer to another btf_type object by using
65  * type_id (i.e. the "type" in the "struct btf_type").
66  *
67  * NOTE that we cannot assume any reference-order.
68  * A btf_type object can refer to an earlier btf_type object
69  * but it can also refer to a later btf_type object.
70  *
71  * For example, to describe "const void *".  A btf_type
72  * object describing "const" may refer to another btf_type
73  * object describing "void *".  This type-reference is done
74  * by specifying type_id:
75  *
76  * [1] CONST (anon) type_id=2
77  * [2] PTR (anon) type_id=0
78  *
79  * The above is the btf_verifier debug log:
80  *   - Each line started with "[?]" is a btf_type object
81  *   - [?] is the type_id of the btf_type object.
82  *   - CONST/PTR is the BTF_KIND_XXX
83  *   - "(anon)" is the name of the type.  It just
84  *     happens that CONST and PTR has no name.
85  *   - type_id=XXX is the 'u32 type' in btf_type
86  *
87  * NOTE: "void" has type_id 0
88  *
89  * String section:
90  * ~~~~~~~~~~~~~~
91  * The BTF string section contains the names used by the type section.
92  * Each string is referred by an "offset" from the beginning of the
93  * string section.
94  *
95  * Each string is '\0' terminated.
96  *
97  * The first character in the string section must be '\0'
98  * which is used to mean 'anonymous'. Some btf_type may not
99  * have a name.
100  */
101
102 /* BTF verification:
103  *
104  * To verify BTF data, two passes are needed.
105  *
106  * Pass #1
107  * ~~~~~~~
108  * The first pass is to collect all btf_type objects to
109  * an array: "btf->types".
110  *
111  * Depending on the C type that a btf_type is describing,
112  * a btf_type may be followed by extra data.  We don't know
113  * how many btf_type is there, and more importantly we don't
114  * know where each btf_type is located in the type section.
115  *
116  * Without knowing the location of each type_id, most verifications
117  * cannot be done.  e.g. an earlier btf_type may refer to a later
118  * btf_type (recall the "const void *" above), so we cannot
119  * check this type-reference in the first pass.
120  *
121  * In the first pass, it still does some verifications (e.g.
122  * checking the name is a valid offset to the string section).
123  *
124  * Pass #2
125  * ~~~~~~~
126  * The main focus is to resolve a btf_type that is referring
127  * to another type.
128  *
129  * We have to ensure the referring type:
130  * 1) does exist in the BTF (i.e. in btf->types[])
131  * 2) does not cause a loop:
132  *      struct A {
133  *              struct B b;
134  *      };
135  *
136  *      struct B {
137  *              struct A a;
138  *      };
139  *
140  * btf_type_needs_resolve() decides if a btf_type needs
141  * to be resolved.
142  *
143  * The needs_resolve type implements the "resolve()" ops which
144  * essentially does a DFS and detects backedge.
145  *
146  * During resolve (or DFS), different C types have different
147  * "RESOLVED" conditions.
148  *
149  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
150  * members because a member is always referring to another
151  * type.  A struct's member can be treated as "RESOLVED" if
152  * it is referring to a BTF_KIND_PTR.  Otherwise, the
153  * following valid C struct would be rejected:
154  *
155  *      struct A {
156  *              int m;
157  *              struct A *a;
158  *      };
159  *
160  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
161  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
162  * detect a pointer loop, e.g.:
163  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
164  *                        ^                                         |
165  *                        +-----------------------------------------+
166  *
167  */
168
169 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
170 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
171 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
172 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
173 #define BITS_ROUNDUP_BYTES(bits) \
174         (BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
175
176 #define BTF_INFO_MASK 0x9f00ffff
177 #define BTF_INT_MASK 0x0fffffff
178 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
179 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
180
181 /* 16MB for 64k structs and each has 16 members and
182  * a few MB spaces for the string section.
183  * The hard limit is S32_MAX.
184  */
185 #define BTF_MAX_SIZE (16 * 1024 * 1024)
186
187 #define for_each_member_from(i, from, struct_type, member)              \
188         for (i = from, member = btf_type_member(struct_type) + from;    \
189              i < btf_type_vlen(struct_type);                            \
190              i++, member++)
191
192 #define for_each_vsi_from(i, from, struct_type, member)                         \
193         for (i = from, member = btf_type_var_secinfo(struct_type) + from;       \
194              i < btf_type_vlen(struct_type);                                    \
195              i++, member++)
196
197 DEFINE_IDR(btf_idr);
198 DEFINE_SPINLOCK(btf_idr_lock);
199
200 struct btf {
201         void *data;
202         struct btf_type **types;
203         u32 *resolved_ids;
204         u32 *resolved_sizes;
205         const char *strings;
206         void *nohdr_data;
207         struct btf_header hdr;
208         u32 nr_types; /* includes VOID for base BTF */
209         u32 types_size;
210         u32 data_size;
211         refcount_t refcnt;
212         u32 id;
213         struct rcu_head rcu;
214
215         /* split BTF support */
216         struct btf *base_btf;
217         u32 start_id; /* first type ID in this BTF (0 for base BTF) */
218         u32 start_str_off; /* first string offset (0 for base BTF) */
219         char name[MODULE_NAME_LEN];
220         bool kernel_btf;
221 };
222
223 enum verifier_phase {
224         CHECK_META,
225         CHECK_TYPE,
226 };
227
228 struct resolve_vertex {
229         const struct btf_type *t;
230         u32 type_id;
231         u16 next_member;
232 };
233
234 enum visit_state {
235         NOT_VISITED,
236         VISITED,
237         RESOLVED,
238 };
239
240 enum resolve_mode {
241         RESOLVE_TBD,    /* To Be Determined */
242         RESOLVE_PTR,    /* Resolving for Pointer */
243         RESOLVE_STRUCT_OR_ARRAY,        /* Resolving for struct/union
244                                          * or array
245                                          */
246 };
247
248 #define MAX_RESOLVE_DEPTH 32
249
250 struct btf_sec_info {
251         u32 off;
252         u32 len;
253 };
254
255 struct btf_verifier_env {
256         struct btf *btf;
257         u8 *visit_states;
258         struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
259         struct bpf_verifier_log log;
260         u32 log_type_id;
261         u32 top_stack;
262         enum verifier_phase phase;
263         enum resolve_mode resolve_mode;
264 };
265
266 static const char * const btf_kind_str[NR_BTF_KINDS] = {
267         [BTF_KIND_UNKN]         = "UNKNOWN",
268         [BTF_KIND_INT]          = "INT",
269         [BTF_KIND_PTR]          = "PTR",
270         [BTF_KIND_ARRAY]        = "ARRAY",
271         [BTF_KIND_STRUCT]       = "STRUCT",
272         [BTF_KIND_UNION]        = "UNION",
273         [BTF_KIND_ENUM]         = "ENUM",
274         [BTF_KIND_FWD]          = "FWD",
275         [BTF_KIND_TYPEDEF]      = "TYPEDEF",
276         [BTF_KIND_VOLATILE]     = "VOLATILE",
277         [BTF_KIND_CONST]        = "CONST",
278         [BTF_KIND_RESTRICT]     = "RESTRICT",
279         [BTF_KIND_FUNC]         = "FUNC",
280         [BTF_KIND_FUNC_PROTO]   = "FUNC_PROTO",
281         [BTF_KIND_VAR]          = "VAR",
282         [BTF_KIND_DATASEC]      = "DATASEC",
283         [BTF_KIND_FLOAT]        = "FLOAT",
284 };
285
286 const char *btf_type_str(const struct btf_type *t)
287 {
288         return btf_kind_str[BTF_INFO_KIND(t->info)];
289 }
290
291 /* Chunk size we use in safe copy of data to be shown. */
292 #define BTF_SHOW_OBJ_SAFE_SIZE          32
293
294 /*
295  * This is the maximum size of a base type value (equivalent to a
296  * 128-bit int); if we are at the end of our safe buffer and have
297  * less than 16 bytes space we can't be assured of being able
298  * to copy the next type safely, so in such cases we will initiate
299  * a new copy.
300  */
301 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE     16
302
303 /* Type name size */
304 #define BTF_SHOW_NAME_SIZE              80
305
306 /*
307  * Common data to all BTF show operations. Private show functions can add
308  * their own data to a structure containing a struct btf_show and consult it
309  * in the show callback.  See btf_type_show() below.
310  *
311  * One challenge with showing nested data is we want to skip 0-valued
312  * data, but in order to figure out whether a nested object is all zeros
313  * we need to walk through it.  As a result, we need to make two passes
314  * when handling structs, unions and arrays; the first path simply looks
315  * for nonzero data, while the second actually does the display.  The first
316  * pass is signalled by show->state.depth_check being set, and if we
317  * encounter a non-zero value we set show->state.depth_to_show to
318  * the depth at which we encountered it.  When we have completed the
319  * first pass, we will know if anything needs to be displayed if
320  * depth_to_show > depth.  See btf_[struct,array]_show() for the
321  * implementation of this.
322  *
323  * Another problem is we want to ensure the data for display is safe to
324  * access.  To support this, the anonymous "struct {} obj" tracks the data
325  * object and our safe copy of it.  We copy portions of the data needed
326  * to the object "copy" buffer, but because its size is limited to
327  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
328  * traverse larger objects for display.
329  *
330  * The various data type show functions all start with a call to
331  * btf_show_start_type() which returns a pointer to the safe copy
332  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
333  * raw data itself).  btf_show_obj_safe() is responsible for
334  * using copy_from_kernel_nofault() to update the safe data if necessary
335  * as we traverse the object's data.  skbuff-like semantics are
336  * used:
337  *
338  * - obj.head points to the start of the toplevel object for display
339  * - obj.size is the size of the toplevel object
340  * - obj.data points to the current point in the original data at
341  *   which our safe data starts.  obj.data will advance as we copy
342  *   portions of the data.
343  *
344  * In most cases a single copy will suffice, but larger data structures
345  * such as "struct task_struct" will require many copies.  The logic in
346  * btf_show_obj_safe() handles the logic that determines if a new
347  * copy_from_kernel_nofault() is needed.
348  */
349 struct btf_show {
350         u64 flags;
351         void *target;   /* target of show operation (seq file, buffer) */
352         void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
353         const struct btf *btf;
354         /* below are used during iteration */
355         struct {
356                 u8 depth;
357                 u8 depth_to_show;
358                 u8 depth_check;
359                 u8 array_member:1,
360                    array_terminated:1;
361                 u16 array_encoding;
362                 u32 type_id;
363                 int status;                     /* non-zero for error */
364                 const struct btf_type *type;
365                 const struct btf_member *member;
366                 char name[BTF_SHOW_NAME_SIZE];  /* space for member name/type */
367         } state;
368         struct {
369                 u32 size;
370                 void *head;
371                 void *data;
372                 u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
373         } obj;
374 };
375
376 struct btf_kind_operations {
377         s32 (*check_meta)(struct btf_verifier_env *env,
378                           const struct btf_type *t,
379                           u32 meta_left);
380         int (*resolve)(struct btf_verifier_env *env,
381                        const struct resolve_vertex *v);
382         int (*check_member)(struct btf_verifier_env *env,
383                             const struct btf_type *struct_type,
384                             const struct btf_member *member,
385                             const struct btf_type *member_type);
386         int (*check_kflag_member)(struct btf_verifier_env *env,
387                                   const struct btf_type *struct_type,
388                                   const struct btf_member *member,
389                                   const struct btf_type *member_type);
390         void (*log_details)(struct btf_verifier_env *env,
391                             const struct btf_type *t);
392         void (*show)(const struct btf *btf, const struct btf_type *t,
393                          u32 type_id, void *data, u8 bits_offsets,
394                          struct btf_show *show);
395 };
396
397 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
398 static struct btf_type btf_void;
399
400 static int btf_resolve(struct btf_verifier_env *env,
401                        const struct btf_type *t, u32 type_id);
402
403 static bool btf_type_is_modifier(const struct btf_type *t)
404 {
405         /* Some of them is not strictly a C modifier
406          * but they are grouped into the same bucket
407          * for BTF concern:
408          *   A type (t) that refers to another
409          *   type through t->type AND its size cannot
410          *   be determined without following the t->type.
411          *
412          * ptr does not fall into this bucket
413          * because its size is always sizeof(void *).
414          */
415         switch (BTF_INFO_KIND(t->info)) {
416         case BTF_KIND_TYPEDEF:
417         case BTF_KIND_VOLATILE:
418         case BTF_KIND_CONST:
419         case BTF_KIND_RESTRICT:
420                 return true;
421         }
422
423         return false;
424 }
425
426 bool btf_type_is_void(const struct btf_type *t)
427 {
428         return t == &btf_void;
429 }
430
431 static bool btf_type_is_fwd(const struct btf_type *t)
432 {
433         return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
434 }
435
436 static bool btf_type_nosize(const struct btf_type *t)
437 {
438         return btf_type_is_void(t) || btf_type_is_fwd(t) ||
439                btf_type_is_func(t) || btf_type_is_func_proto(t);
440 }
441
442 static bool btf_type_nosize_or_null(const struct btf_type *t)
443 {
444         return !t || btf_type_nosize(t);
445 }
446
447 static bool __btf_type_is_struct(const struct btf_type *t)
448 {
449         return BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT;
450 }
451
452 static bool btf_type_is_array(const struct btf_type *t)
453 {
454         return BTF_INFO_KIND(t->info) == BTF_KIND_ARRAY;
455 }
456
457 static bool btf_type_is_datasec(const struct btf_type *t)
458 {
459         return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
460 }
461
462 u32 btf_nr_types(const struct btf *btf)
463 {
464         u32 total = 0;
465
466         while (btf) {
467                 total += btf->nr_types;
468                 btf = btf->base_btf;
469         }
470
471         return total;
472 }
473
474 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
475 {
476         const struct btf_type *t;
477         const char *tname;
478         u32 i, total;
479
480         total = btf_nr_types(btf);
481         for (i = 1; i < total; i++) {
482                 t = btf_type_by_id(btf, i);
483                 if (BTF_INFO_KIND(t->info) != kind)
484                         continue;
485
486                 tname = btf_name_by_offset(btf, t->name_off);
487                 if (!strcmp(tname, name))
488                         return i;
489         }
490
491         return -ENOENT;
492 }
493
494 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
495                                                u32 id, u32 *res_id)
496 {
497         const struct btf_type *t = btf_type_by_id(btf, id);
498
499         while (btf_type_is_modifier(t)) {
500                 id = t->type;
501                 t = btf_type_by_id(btf, t->type);
502         }
503
504         if (res_id)
505                 *res_id = id;
506
507         return t;
508 }
509
510 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
511                                             u32 id, u32 *res_id)
512 {
513         const struct btf_type *t;
514
515         t = btf_type_skip_modifiers(btf, id, NULL);
516         if (!btf_type_is_ptr(t))
517                 return NULL;
518
519         return btf_type_skip_modifiers(btf, t->type, res_id);
520 }
521
522 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
523                                                  u32 id, u32 *res_id)
524 {
525         const struct btf_type *ptype;
526
527         ptype = btf_type_resolve_ptr(btf, id, res_id);
528         if (ptype && btf_type_is_func_proto(ptype))
529                 return ptype;
530
531         return NULL;
532 }
533
534 /* Types that act only as a source, not sink or intermediate
535  * type when resolving.
536  */
537 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
538 {
539         return btf_type_is_var(t) ||
540                btf_type_is_datasec(t);
541 }
542
543 /* What types need to be resolved?
544  *
545  * btf_type_is_modifier() is an obvious one.
546  *
547  * btf_type_is_struct() because its member refers to
548  * another type (through member->type).
549  *
550  * btf_type_is_var() because the variable refers to
551  * another type. btf_type_is_datasec() holds multiple
552  * btf_type_is_var() types that need resolving.
553  *
554  * btf_type_is_array() because its element (array->type)
555  * refers to another type.  Array can be thought of a
556  * special case of struct while array just has the same
557  * member-type repeated by array->nelems of times.
558  */
559 static bool btf_type_needs_resolve(const struct btf_type *t)
560 {
561         return btf_type_is_modifier(t) ||
562                btf_type_is_ptr(t) ||
563                btf_type_is_struct(t) ||
564                btf_type_is_array(t) ||
565                btf_type_is_var(t) ||
566                btf_type_is_datasec(t);
567 }
568
569 /* t->size can be used */
570 static bool btf_type_has_size(const struct btf_type *t)
571 {
572         switch (BTF_INFO_KIND(t->info)) {
573         case BTF_KIND_INT:
574         case BTF_KIND_STRUCT:
575         case BTF_KIND_UNION:
576         case BTF_KIND_ENUM:
577         case BTF_KIND_DATASEC:
578         case BTF_KIND_FLOAT:
579                 return true;
580         }
581
582         return false;
583 }
584
585 static const char *btf_int_encoding_str(u8 encoding)
586 {
587         if (encoding == 0)
588                 return "(none)";
589         else if (encoding == BTF_INT_SIGNED)
590                 return "SIGNED";
591         else if (encoding == BTF_INT_CHAR)
592                 return "CHAR";
593         else if (encoding == BTF_INT_BOOL)
594                 return "BOOL";
595         else
596                 return "UNKN";
597 }
598
599 static u32 btf_type_int(const struct btf_type *t)
600 {
601         return *(u32 *)(t + 1);
602 }
603
604 static const struct btf_array *btf_type_array(const struct btf_type *t)
605 {
606         return (const struct btf_array *)(t + 1);
607 }
608
609 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
610 {
611         return (const struct btf_enum *)(t + 1);
612 }
613
614 static const struct btf_var *btf_type_var(const struct btf_type *t)
615 {
616         return (const struct btf_var *)(t + 1);
617 }
618
619 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
620 {
621         return kind_ops[BTF_INFO_KIND(t->info)];
622 }
623
624 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
625 {
626         if (!BTF_STR_OFFSET_VALID(offset))
627                 return false;
628
629         while (offset < btf->start_str_off)
630                 btf = btf->base_btf;
631
632         offset -= btf->start_str_off;
633         return offset < btf->hdr.str_len;
634 }
635
636 static bool __btf_name_char_ok(char c, bool first)
637 {
638         if ((first ? !isalpha(c) :
639                      !isalnum(c)) &&
640             c != '_' &&
641             c != '.')
642                 return false;
643         return true;
644 }
645
646 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
647 {
648         while (offset < btf->start_str_off)
649                 btf = btf->base_btf;
650
651         offset -= btf->start_str_off;
652         if (offset < btf->hdr.str_len)
653                 return &btf->strings[offset];
654
655         return NULL;
656 }
657
658 static bool __btf_name_valid(const struct btf *btf, u32 offset)
659 {
660         /* offset must be valid */
661         const char *src = btf_str_by_offset(btf, offset);
662         const char *src_limit;
663
664         if (!__btf_name_char_ok(*src, true))
665                 return false;
666
667         /* set a limit on identifier length */
668         src_limit = src + KSYM_NAME_LEN;
669         src++;
670         while (*src && src < src_limit) {
671                 if (!__btf_name_char_ok(*src, false))
672                         return false;
673                 src++;
674         }
675
676         return !*src;
677 }
678
679 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
680 {
681         return __btf_name_valid(btf, offset);
682 }
683
684 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
685 {
686         return __btf_name_valid(btf, offset);
687 }
688
689 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
690 {
691         const char *name;
692
693         if (!offset)
694                 return "(anon)";
695
696         name = btf_str_by_offset(btf, offset);
697         return name ?: "(invalid-name-offset)";
698 }
699
700 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
701 {
702         return btf_str_by_offset(btf, offset);
703 }
704
705 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
706 {
707         while (type_id < btf->start_id)
708                 btf = btf->base_btf;
709
710         type_id -= btf->start_id;
711         if (type_id >= btf->nr_types)
712                 return NULL;
713         return btf->types[type_id];
714 }
715
716 /*
717  * Regular int is not a bit field and it must be either
718  * u8/u16/u32/u64 or __int128.
719  */
720 static bool btf_type_int_is_regular(const struct btf_type *t)
721 {
722         u8 nr_bits, nr_bytes;
723         u32 int_data;
724
725         int_data = btf_type_int(t);
726         nr_bits = BTF_INT_BITS(int_data);
727         nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
728         if (BITS_PER_BYTE_MASKED(nr_bits) ||
729             BTF_INT_OFFSET(int_data) ||
730             (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
731              nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
732              nr_bytes != (2 * sizeof(u64)))) {
733                 return false;
734         }
735
736         return true;
737 }
738
739 /*
740  * Check that given struct member is a regular int with expected
741  * offset and size.
742  */
743 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
744                            const struct btf_member *m,
745                            u32 expected_offset, u32 expected_size)
746 {
747         const struct btf_type *t;
748         u32 id, int_data;
749         u8 nr_bits;
750
751         id = m->type;
752         t = btf_type_id_size(btf, &id, NULL);
753         if (!t || !btf_type_is_int(t))
754                 return false;
755
756         int_data = btf_type_int(t);
757         nr_bits = BTF_INT_BITS(int_data);
758         if (btf_type_kflag(s)) {
759                 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
760                 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
761
762                 /* if kflag set, int should be a regular int and
763                  * bit offset should be at byte boundary.
764                  */
765                 return !bitfield_size &&
766                        BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
767                        BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
768         }
769
770         if (BTF_INT_OFFSET(int_data) ||
771             BITS_PER_BYTE_MASKED(m->offset) ||
772             BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
773             BITS_PER_BYTE_MASKED(nr_bits) ||
774             BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
775                 return false;
776
777         return true;
778 }
779
780 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
781 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
782                                                        u32 id)
783 {
784         const struct btf_type *t = btf_type_by_id(btf, id);
785
786         while (btf_type_is_modifier(t) &&
787                BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
788                 t = btf_type_by_id(btf, t->type);
789         }
790
791         return t;
792 }
793
794 #define BTF_SHOW_MAX_ITER       10
795
796 #define BTF_KIND_BIT(kind)      (1ULL << kind)
797
798 /*
799  * Populate show->state.name with type name information.
800  * Format of type name is
801  *
802  * [.member_name = ] (type_name)
803  */
804 static const char *btf_show_name(struct btf_show *show)
805 {
806         /* BTF_MAX_ITER array suffixes "[]" */
807         const char *array_suffixes = "[][][][][][][][][][]";
808         const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
809         /* BTF_MAX_ITER pointer suffixes "*" */
810         const char *ptr_suffixes = "**********";
811         const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
812         const char *name = NULL, *prefix = "", *parens = "";
813         const struct btf_member *m = show->state.member;
814         const struct btf_type *t = show->state.type;
815         const struct btf_array *array;
816         u32 id = show->state.type_id;
817         const char *member = NULL;
818         bool show_member = false;
819         u64 kinds = 0;
820         int i;
821
822         show->state.name[0] = '\0';
823
824         /*
825          * Don't show type name if we're showing an array member;
826          * in that case we show the array type so don't need to repeat
827          * ourselves for each member.
828          */
829         if (show->state.array_member)
830                 return "";
831
832         /* Retrieve member name, if any. */
833         if (m) {
834                 member = btf_name_by_offset(show->btf, m->name_off);
835                 show_member = strlen(member) > 0;
836                 id = m->type;
837         }
838
839         /*
840          * Start with type_id, as we have resolved the struct btf_type *
841          * via btf_modifier_show() past the parent typedef to the child
842          * struct, int etc it is defined as.  In such cases, the type_id
843          * still represents the starting type while the struct btf_type *
844          * in our show->state points at the resolved type of the typedef.
845          */
846         t = btf_type_by_id(show->btf, id);
847         if (!t)
848                 return "";
849
850         /*
851          * The goal here is to build up the right number of pointer and
852          * array suffixes while ensuring the type name for a typedef
853          * is represented.  Along the way we accumulate a list of
854          * BTF kinds we have encountered, since these will inform later
855          * display; for example, pointer types will not require an
856          * opening "{" for struct, we will just display the pointer value.
857          *
858          * We also want to accumulate the right number of pointer or array
859          * indices in the format string while iterating until we get to
860          * the typedef/pointee/array member target type.
861          *
862          * We start by pointing at the end of pointer and array suffix
863          * strings; as we accumulate pointers and arrays we move the pointer
864          * or array string backwards so it will show the expected number of
865          * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
866          * and/or arrays and typedefs are supported as a precaution.
867          *
868          * We also want to get typedef name while proceeding to resolve
869          * type it points to so that we can add parentheses if it is a
870          * "typedef struct" etc.
871          */
872         for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
873
874                 switch (BTF_INFO_KIND(t->info)) {
875                 case BTF_KIND_TYPEDEF:
876                         if (!name)
877                                 name = btf_name_by_offset(show->btf,
878                                                                t->name_off);
879                         kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
880                         id = t->type;
881                         break;
882                 case BTF_KIND_ARRAY:
883                         kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
884                         parens = "[";
885                         if (!t)
886                                 return "";
887                         array = btf_type_array(t);
888                         if (array_suffix > array_suffixes)
889                                 array_suffix -= 2;
890                         id = array->type;
891                         break;
892                 case BTF_KIND_PTR:
893                         kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
894                         if (ptr_suffix > ptr_suffixes)
895                                 ptr_suffix -= 1;
896                         id = t->type;
897                         break;
898                 default:
899                         id = 0;
900                         break;
901                 }
902                 if (!id)
903                         break;
904                 t = btf_type_skip_qualifiers(show->btf, id);
905         }
906         /* We may not be able to represent this type; bail to be safe */
907         if (i == BTF_SHOW_MAX_ITER)
908                 return "";
909
910         if (!name)
911                 name = btf_name_by_offset(show->btf, t->name_off);
912
913         switch (BTF_INFO_KIND(t->info)) {
914         case BTF_KIND_STRUCT:
915         case BTF_KIND_UNION:
916                 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
917                          "struct" : "union";
918                 /* if it's an array of struct/union, parens is already set */
919                 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
920                         parens = "{";
921                 break;
922         case BTF_KIND_ENUM:
923                 prefix = "enum";
924                 break;
925         default:
926                 break;
927         }
928
929         /* pointer does not require parens */
930         if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
931                 parens = "";
932         /* typedef does not require struct/union/enum prefix */
933         if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
934                 prefix = "";
935
936         if (!name)
937                 name = "";
938
939         /* Even if we don't want type name info, we want parentheses etc */
940         if (show->flags & BTF_SHOW_NONAME)
941                 snprintf(show->state.name, sizeof(show->state.name), "%s",
942                          parens);
943         else
944                 snprintf(show->state.name, sizeof(show->state.name),
945                          "%s%s%s(%s%s%s%s%s%s)%s",
946                          /* first 3 strings comprise ".member = " */
947                          show_member ? "." : "",
948                          show_member ? member : "",
949                          show_member ? " = " : "",
950                          /* ...next is our prefix (struct, enum, etc) */
951                          prefix,
952                          strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
953                          /* ...this is the type name itself */
954                          name,
955                          /* ...suffixed by the appropriate '*', '[]' suffixes */
956                          strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
957                          array_suffix, parens);
958
959         return show->state.name;
960 }
961
962 static const char *__btf_show_indent(struct btf_show *show)
963 {
964         const char *indents = "                                ";
965         const char *indent = &indents[strlen(indents)];
966
967         if ((indent - show->state.depth) >= indents)
968                 return indent - show->state.depth;
969         return indents;
970 }
971
972 static const char *btf_show_indent(struct btf_show *show)
973 {
974         return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
975 }
976
977 static const char *btf_show_newline(struct btf_show *show)
978 {
979         return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
980 }
981
982 static const char *btf_show_delim(struct btf_show *show)
983 {
984         if (show->state.depth == 0)
985                 return "";
986
987         if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
988                 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
989                 return "|";
990
991         return ",";
992 }
993
994 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
995 {
996         va_list args;
997
998         if (!show->state.depth_check) {
999                 va_start(args, fmt);
1000                 show->showfn(show, fmt, args);
1001                 va_end(args);
1002         }
1003 }
1004
1005 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1006  * format specifiers to the format specifier passed in; these do the work of
1007  * adding indentation, delimiters etc while the caller simply has to specify
1008  * the type value(s) in the format specifier + value(s).
1009  */
1010 #define btf_show_type_value(show, fmt, value)                                  \
1011         do {                                                                   \
1012                 if ((value) != 0 || (show->flags & BTF_SHOW_ZERO) ||           \
1013                     show->state.depth == 0) {                                  \
1014                         btf_show(show, "%s%s" fmt "%s%s",                      \
1015                                  btf_show_indent(show),                        \
1016                                  btf_show_name(show),                          \
1017                                  value, btf_show_delim(show),                  \
1018                                  btf_show_newline(show));                      \
1019                         if (show->state.depth > show->state.depth_to_show)     \
1020                                 show->state.depth_to_show = show->state.depth; \
1021                 }                                                              \
1022         } while (0)
1023
1024 #define btf_show_type_values(show, fmt, ...)                                   \
1025         do {                                                                   \
1026                 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1027                          btf_show_name(show),                                  \
1028                          __VA_ARGS__, btf_show_delim(show),                    \
1029                          btf_show_newline(show));                              \
1030                 if (show->state.depth > show->state.depth_to_show)             \
1031                         show->state.depth_to_show = show->state.depth;         \
1032         } while (0)
1033
1034 /* How much is left to copy to safe buffer after @data? */
1035 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1036 {
1037         return show->obj.head + show->obj.size - data;
1038 }
1039
1040 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1041 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1042 {
1043         return data >= show->obj.data &&
1044                (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1045 }
1046
1047 /*
1048  * If object pointed to by @data of @size falls within our safe buffer, return
1049  * the equivalent pointer to the same safe data.  Assumes
1050  * copy_from_kernel_nofault() has already happened and our safe buffer is
1051  * populated.
1052  */
1053 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1054 {
1055         if (btf_show_obj_is_safe(show, data, size))
1056                 return show->obj.safe + (data - show->obj.data);
1057         return NULL;
1058 }
1059
1060 /*
1061  * Return a safe-to-access version of data pointed to by @data.
1062  * We do this by copying the relevant amount of information
1063  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1064  *
1065  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1066  * safe copy is needed.
1067  *
1068  * Otherwise we need to determine if we have the required amount
1069  * of data (determined by the @data pointer and the size of the
1070  * largest base type we can encounter (represented by
1071  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1072  * that we will be able to print some of the current object,
1073  * and if more is needed a copy will be triggered.
1074  * Some objects such as structs will not fit into the buffer;
1075  * in such cases additional copies when we iterate over their
1076  * members may be needed.
1077  *
1078  * btf_show_obj_safe() is used to return a safe buffer for
1079  * btf_show_start_type(); this ensures that as we recurse into
1080  * nested types we always have safe data for the given type.
1081  * This approach is somewhat wasteful; it's possible for example
1082  * that when iterating over a large union we'll end up copying the
1083  * same data repeatedly, but the goal is safety not performance.
1084  * We use stack data as opposed to per-CPU buffers because the
1085  * iteration over a type can take some time, and preemption handling
1086  * would greatly complicate use of the safe buffer.
1087  */
1088 static void *btf_show_obj_safe(struct btf_show *show,
1089                                const struct btf_type *t,
1090                                void *data)
1091 {
1092         const struct btf_type *rt;
1093         int size_left, size;
1094         void *safe = NULL;
1095
1096         if (show->flags & BTF_SHOW_UNSAFE)
1097                 return data;
1098
1099         rt = btf_resolve_size(show->btf, t, &size);
1100         if (IS_ERR(rt)) {
1101                 show->state.status = PTR_ERR(rt);
1102                 return NULL;
1103         }
1104
1105         /*
1106          * Is this toplevel object? If so, set total object size and
1107          * initialize pointers.  Otherwise check if we still fall within
1108          * our safe object data.
1109          */
1110         if (show->state.depth == 0) {
1111                 show->obj.size = size;
1112                 show->obj.head = data;
1113         } else {
1114                 /*
1115                  * If the size of the current object is > our remaining
1116                  * safe buffer we _may_ need to do a new copy.  However
1117                  * consider the case of a nested struct; it's size pushes
1118                  * us over the safe buffer limit, but showing any individual
1119                  * struct members does not.  In such cases, we don't need
1120                  * to initiate a fresh copy yet; however we definitely need
1121                  * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1122                  * in our buffer, regardless of the current object size.
1123                  * The logic here is that as we resolve types we will
1124                  * hit a base type at some point, and we need to be sure
1125                  * the next chunk of data is safely available to display
1126                  * that type info safely.  We cannot rely on the size of
1127                  * the current object here because it may be much larger
1128                  * than our current buffer (e.g. task_struct is 8k).
1129                  * All we want to do here is ensure that we can print the
1130                  * next basic type, which we can if either
1131                  * - the current type size is within the safe buffer; or
1132                  * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1133                  *   the safe buffer.
1134                  */
1135                 safe = __btf_show_obj_safe(show, data,
1136                                            min(size,
1137                                                BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1138         }
1139
1140         /*
1141          * We need a new copy to our safe object, either because we haven't
1142          * yet copied and are initializing safe data, or because the data
1143          * we want falls outside the boundaries of the safe object.
1144          */
1145         if (!safe) {
1146                 size_left = btf_show_obj_size_left(show, data);
1147                 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1148                         size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1149                 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1150                                                               data, size_left);
1151                 if (!show->state.status) {
1152                         show->obj.data = data;
1153                         safe = show->obj.safe;
1154                 }
1155         }
1156
1157         return safe;
1158 }
1159
1160 /*
1161  * Set the type we are starting to show and return a safe data pointer
1162  * to be used for showing the associated data.
1163  */
1164 static void *btf_show_start_type(struct btf_show *show,
1165                                  const struct btf_type *t,
1166                                  u32 type_id, void *data)
1167 {
1168         show->state.type = t;
1169         show->state.type_id = type_id;
1170         show->state.name[0] = '\0';
1171
1172         return btf_show_obj_safe(show, t, data);
1173 }
1174
1175 static void btf_show_end_type(struct btf_show *show)
1176 {
1177         show->state.type = NULL;
1178         show->state.type_id = 0;
1179         show->state.name[0] = '\0';
1180 }
1181
1182 static void *btf_show_start_aggr_type(struct btf_show *show,
1183                                       const struct btf_type *t,
1184                                       u32 type_id, void *data)
1185 {
1186         void *safe_data = btf_show_start_type(show, t, type_id, data);
1187
1188         if (!safe_data)
1189                 return safe_data;
1190
1191         btf_show(show, "%s%s%s", btf_show_indent(show),
1192                  btf_show_name(show),
1193                  btf_show_newline(show));
1194         show->state.depth++;
1195         return safe_data;
1196 }
1197
1198 static void btf_show_end_aggr_type(struct btf_show *show,
1199                                    const char *suffix)
1200 {
1201         show->state.depth--;
1202         btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1203                  btf_show_delim(show), btf_show_newline(show));
1204         btf_show_end_type(show);
1205 }
1206
1207 static void btf_show_start_member(struct btf_show *show,
1208                                   const struct btf_member *m)
1209 {
1210         show->state.member = m;
1211 }
1212
1213 static void btf_show_start_array_member(struct btf_show *show)
1214 {
1215         show->state.array_member = 1;
1216         btf_show_start_member(show, NULL);
1217 }
1218
1219 static void btf_show_end_member(struct btf_show *show)
1220 {
1221         show->state.member = NULL;
1222 }
1223
1224 static void btf_show_end_array_member(struct btf_show *show)
1225 {
1226         show->state.array_member = 0;
1227         btf_show_end_member(show);
1228 }
1229
1230 static void *btf_show_start_array_type(struct btf_show *show,
1231                                        const struct btf_type *t,
1232                                        u32 type_id,
1233                                        u16 array_encoding,
1234                                        void *data)
1235 {
1236         show->state.array_encoding = array_encoding;
1237         show->state.array_terminated = 0;
1238         return btf_show_start_aggr_type(show, t, type_id, data);
1239 }
1240
1241 static void btf_show_end_array_type(struct btf_show *show)
1242 {
1243         show->state.array_encoding = 0;
1244         show->state.array_terminated = 0;
1245         btf_show_end_aggr_type(show, "]");
1246 }
1247
1248 static void *btf_show_start_struct_type(struct btf_show *show,
1249                                         const struct btf_type *t,
1250                                         u32 type_id,
1251                                         void *data)
1252 {
1253         return btf_show_start_aggr_type(show, t, type_id, data);
1254 }
1255
1256 static void btf_show_end_struct_type(struct btf_show *show)
1257 {
1258         btf_show_end_aggr_type(show, "}");
1259 }
1260
1261 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1262                                               const char *fmt, ...)
1263 {
1264         va_list args;
1265
1266         va_start(args, fmt);
1267         bpf_verifier_vlog(log, fmt, args);
1268         va_end(args);
1269 }
1270
1271 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1272                                             const char *fmt, ...)
1273 {
1274         struct bpf_verifier_log *log = &env->log;
1275         va_list args;
1276
1277         if (!bpf_verifier_log_needed(log))
1278                 return;
1279
1280         va_start(args, fmt);
1281         bpf_verifier_vlog(log, fmt, args);
1282         va_end(args);
1283 }
1284
1285 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1286                                                    const struct btf_type *t,
1287                                                    bool log_details,
1288                                                    const char *fmt, ...)
1289 {
1290         struct bpf_verifier_log *log = &env->log;
1291         u8 kind = BTF_INFO_KIND(t->info);
1292         struct btf *btf = env->btf;
1293         va_list args;
1294
1295         if (!bpf_verifier_log_needed(log))
1296                 return;
1297
1298         /* btf verifier prints all types it is processing via
1299          * btf_verifier_log_type(..., fmt = NULL).
1300          * Skip those prints for in-kernel BTF verification.
1301          */
1302         if (log->level == BPF_LOG_KERNEL && !fmt)
1303                 return;
1304
1305         __btf_verifier_log(log, "[%u] %s %s%s",
1306                            env->log_type_id,
1307                            btf_kind_str[kind],
1308                            __btf_name_by_offset(btf, t->name_off),
1309                            log_details ? " " : "");
1310
1311         if (log_details)
1312                 btf_type_ops(t)->log_details(env, t);
1313
1314         if (fmt && *fmt) {
1315                 __btf_verifier_log(log, " ");
1316                 va_start(args, fmt);
1317                 bpf_verifier_vlog(log, fmt, args);
1318                 va_end(args);
1319         }
1320
1321         __btf_verifier_log(log, "\n");
1322 }
1323
1324 #define btf_verifier_log_type(env, t, ...) \
1325         __btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1326 #define btf_verifier_log_basic(env, t, ...) \
1327         __btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1328
1329 __printf(4, 5)
1330 static void btf_verifier_log_member(struct btf_verifier_env *env,
1331                                     const struct btf_type *struct_type,
1332                                     const struct btf_member *member,
1333                                     const char *fmt, ...)
1334 {
1335         struct bpf_verifier_log *log = &env->log;
1336         struct btf *btf = env->btf;
1337         va_list args;
1338
1339         if (!bpf_verifier_log_needed(log))
1340                 return;
1341
1342         if (log->level == BPF_LOG_KERNEL && !fmt)
1343                 return;
1344         /* The CHECK_META phase already did a btf dump.
1345          *
1346          * If member is logged again, it must hit an error in
1347          * parsing this member.  It is useful to print out which
1348          * struct this member belongs to.
1349          */
1350         if (env->phase != CHECK_META)
1351                 btf_verifier_log_type(env, struct_type, NULL);
1352
1353         if (btf_type_kflag(struct_type))
1354                 __btf_verifier_log(log,
1355                                    "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1356                                    __btf_name_by_offset(btf, member->name_off),
1357                                    member->type,
1358                                    BTF_MEMBER_BITFIELD_SIZE(member->offset),
1359                                    BTF_MEMBER_BIT_OFFSET(member->offset));
1360         else
1361                 __btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1362                                    __btf_name_by_offset(btf, member->name_off),
1363                                    member->type, member->offset);
1364
1365         if (fmt && *fmt) {
1366                 __btf_verifier_log(log, " ");
1367                 va_start(args, fmt);
1368                 bpf_verifier_vlog(log, fmt, args);
1369                 va_end(args);
1370         }
1371
1372         __btf_verifier_log(log, "\n");
1373 }
1374
1375 __printf(4, 5)
1376 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1377                                  const struct btf_type *datasec_type,
1378                                  const struct btf_var_secinfo *vsi,
1379                                  const char *fmt, ...)
1380 {
1381         struct bpf_verifier_log *log = &env->log;
1382         va_list args;
1383
1384         if (!bpf_verifier_log_needed(log))
1385                 return;
1386         if (log->level == BPF_LOG_KERNEL && !fmt)
1387                 return;
1388         if (env->phase != CHECK_META)
1389                 btf_verifier_log_type(env, datasec_type, NULL);
1390
1391         __btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1392                            vsi->type, vsi->offset, vsi->size);
1393         if (fmt && *fmt) {
1394                 __btf_verifier_log(log, " ");
1395                 va_start(args, fmt);
1396                 bpf_verifier_vlog(log, fmt, args);
1397                 va_end(args);
1398         }
1399
1400         __btf_verifier_log(log, "\n");
1401 }
1402
1403 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1404                                  u32 btf_data_size)
1405 {
1406         struct bpf_verifier_log *log = &env->log;
1407         const struct btf *btf = env->btf;
1408         const struct btf_header *hdr;
1409
1410         if (!bpf_verifier_log_needed(log))
1411                 return;
1412
1413         if (log->level == BPF_LOG_KERNEL)
1414                 return;
1415         hdr = &btf->hdr;
1416         __btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1417         __btf_verifier_log(log, "version: %u\n", hdr->version);
1418         __btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1419         __btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1420         __btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1421         __btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1422         __btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1423         __btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1424         __btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1425 }
1426
1427 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1428 {
1429         struct btf *btf = env->btf;
1430
1431         if (btf->types_size == btf->nr_types) {
1432                 /* Expand 'types' array */
1433
1434                 struct btf_type **new_types;
1435                 u32 expand_by, new_size;
1436
1437                 if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1438                         btf_verifier_log(env, "Exceeded max num of types");
1439                         return -E2BIG;
1440                 }
1441
1442                 expand_by = max_t(u32, btf->types_size >> 2, 16);
1443                 new_size = min_t(u32, BTF_MAX_TYPE,
1444                                  btf->types_size + expand_by);
1445
1446                 new_types = kvcalloc(new_size, sizeof(*new_types),
1447                                      GFP_KERNEL | __GFP_NOWARN);
1448                 if (!new_types)
1449                         return -ENOMEM;
1450
1451                 if (btf->nr_types == 0) {
1452                         if (!btf->base_btf) {
1453                                 /* lazily init VOID type */
1454                                 new_types[0] = &btf_void;
1455                                 btf->nr_types++;
1456                         }
1457                 } else {
1458                         memcpy(new_types, btf->types,
1459                                sizeof(*btf->types) * btf->nr_types);
1460                 }
1461
1462                 kvfree(btf->types);
1463                 btf->types = new_types;
1464                 btf->types_size = new_size;
1465         }
1466
1467         btf->types[btf->nr_types++] = t;
1468
1469         return 0;
1470 }
1471
1472 static int btf_alloc_id(struct btf *btf)
1473 {
1474         int id;
1475
1476         idr_preload(GFP_KERNEL);
1477         spin_lock_bh(&btf_idr_lock);
1478         id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1479         if (id > 0)
1480                 btf->id = id;
1481         spin_unlock_bh(&btf_idr_lock);
1482         idr_preload_end();
1483
1484         if (WARN_ON_ONCE(!id))
1485                 return -ENOSPC;
1486
1487         return id > 0 ? 0 : id;
1488 }
1489
1490 static void btf_free_id(struct btf *btf)
1491 {
1492         unsigned long flags;
1493
1494         /*
1495          * In map-in-map, calling map_delete_elem() on outer
1496          * map will call bpf_map_put on the inner map.
1497          * It will then eventually call btf_free_id()
1498          * on the inner map.  Some of the map_delete_elem()
1499          * implementation may have irq disabled, so
1500          * we need to use the _irqsave() version instead
1501          * of the _bh() version.
1502          */
1503         spin_lock_irqsave(&btf_idr_lock, flags);
1504         idr_remove(&btf_idr, btf->id);
1505         spin_unlock_irqrestore(&btf_idr_lock, flags);
1506 }
1507
1508 static void btf_free(struct btf *btf)
1509 {
1510         kvfree(btf->types);
1511         kvfree(btf->resolved_sizes);
1512         kvfree(btf->resolved_ids);
1513         kvfree(btf->data);
1514         kfree(btf);
1515 }
1516
1517 static void btf_free_rcu(struct rcu_head *rcu)
1518 {
1519         struct btf *btf = container_of(rcu, struct btf, rcu);
1520
1521         btf_free(btf);
1522 }
1523
1524 void btf_get(struct btf *btf)
1525 {
1526         refcount_inc(&btf->refcnt);
1527 }
1528
1529 void btf_put(struct btf *btf)
1530 {
1531         if (btf && refcount_dec_and_test(&btf->refcnt)) {
1532                 btf_free_id(btf);
1533                 call_rcu(&btf->rcu, btf_free_rcu);
1534         }
1535 }
1536
1537 static int env_resolve_init(struct btf_verifier_env *env)
1538 {
1539         struct btf *btf = env->btf;
1540         u32 nr_types = btf->nr_types;
1541         u32 *resolved_sizes = NULL;
1542         u32 *resolved_ids = NULL;
1543         u8 *visit_states = NULL;
1544
1545         resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1546                                   GFP_KERNEL | __GFP_NOWARN);
1547         if (!resolved_sizes)
1548                 goto nomem;
1549
1550         resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1551                                 GFP_KERNEL | __GFP_NOWARN);
1552         if (!resolved_ids)
1553                 goto nomem;
1554
1555         visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1556                                 GFP_KERNEL | __GFP_NOWARN);
1557         if (!visit_states)
1558                 goto nomem;
1559
1560         btf->resolved_sizes = resolved_sizes;
1561         btf->resolved_ids = resolved_ids;
1562         env->visit_states = visit_states;
1563
1564         return 0;
1565
1566 nomem:
1567         kvfree(resolved_sizes);
1568         kvfree(resolved_ids);
1569         kvfree(visit_states);
1570         return -ENOMEM;
1571 }
1572
1573 static void btf_verifier_env_free(struct btf_verifier_env *env)
1574 {
1575         kvfree(env->visit_states);
1576         kfree(env);
1577 }
1578
1579 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1580                                      const struct btf_type *next_type)
1581 {
1582         switch (env->resolve_mode) {
1583         case RESOLVE_TBD:
1584                 /* int, enum or void is a sink */
1585                 return !btf_type_needs_resolve(next_type);
1586         case RESOLVE_PTR:
1587                 /* int, enum, void, struct, array, func or func_proto is a sink
1588                  * for ptr
1589                  */
1590                 return !btf_type_is_modifier(next_type) &&
1591                         !btf_type_is_ptr(next_type);
1592         case RESOLVE_STRUCT_OR_ARRAY:
1593                 /* int, enum, void, ptr, func or func_proto is a sink
1594                  * for struct and array
1595                  */
1596                 return !btf_type_is_modifier(next_type) &&
1597                         !btf_type_is_array(next_type) &&
1598                         !btf_type_is_struct(next_type);
1599         default:
1600                 BUG();
1601         }
1602 }
1603
1604 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1605                                  u32 type_id)
1606 {
1607         /* base BTF types should be resolved by now */
1608         if (type_id < env->btf->start_id)
1609                 return true;
1610
1611         return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1612 }
1613
1614 static int env_stack_push(struct btf_verifier_env *env,
1615                           const struct btf_type *t, u32 type_id)
1616 {
1617         const struct btf *btf = env->btf;
1618         struct resolve_vertex *v;
1619
1620         if (env->top_stack == MAX_RESOLVE_DEPTH)
1621                 return -E2BIG;
1622
1623         if (type_id < btf->start_id
1624             || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1625                 return -EEXIST;
1626
1627         env->visit_states[type_id - btf->start_id] = VISITED;
1628
1629         v = &env->stack[env->top_stack++];
1630         v->t = t;
1631         v->type_id = type_id;
1632         v->next_member = 0;
1633
1634         if (env->resolve_mode == RESOLVE_TBD) {
1635                 if (btf_type_is_ptr(t))
1636                         env->resolve_mode = RESOLVE_PTR;
1637                 else if (btf_type_is_struct(t) || btf_type_is_array(t))
1638                         env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1639         }
1640
1641         return 0;
1642 }
1643
1644 static void env_stack_set_next_member(struct btf_verifier_env *env,
1645                                       u16 next_member)
1646 {
1647         env->stack[env->top_stack - 1].next_member = next_member;
1648 }
1649
1650 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1651                                    u32 resolved_type_id,
1652                                    u32 resolved_size)
1653 {
1654         u32 type_id = env->stack[--(env->top_stack)].type_id;
1655         struct btf *btf = env->btf;
1656
1657         type_id -= btf->start_id; /* adjust to local type id */
1658         btf->resolved_sizes[type_id] = resolved_size;
1659         btf->resolved_ids[type_id] = resolved_type_id;
1660         env->visit_states[type_id] = RESOLVED;
1661 }
1662
1663 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1664 {
1665         return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1666 }
1667
1668 /* Resolve the size of a passed-in "type"
1669  *
1670  * type: is an array (e.g. u32 array[x][y])
1671  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1672  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1673  *             corresponds to the return type.
1674  * *elem_type: u32
1675  * *elem_id: id of u32
1676  * *total_nelems: (x * y).  Hence, individual elem size is
1677  *                (*type_size / *total_nelems)
1678  * *type_id: id of type if it's changed within the function, 0 if not
1679  *
1680  * type: is not an array (e.g. const struct X)
1681  * return type: type "struct X"
1682  * *type_size: sizeof(struct X)
1683  * *elem_type: same as return type ("struct X")
1684  * *elem_id: 0
1685  * *total_nelems: 1
1686  * *type_id: id of type if it's changed within the function, 0 if not
1687  */
1688 static const struct btf_type *
1689 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1690                    u32 *type_size, const struct btf_type **elem_type,
1691                    u32 *elem_id, u32 *total_nelems, u32 *type_id)
1692 {
1693         const struct btf_type *array_type = NULL;
1694         const struct btf_array *array = NULL;
1695         u32 i, size, nelems = 1, id = 0;
1696
1697         for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1698                 switch (BTF_INFO_KIND(type->info)) {
1699                 /* type->size can be used */
1700                 case BTF_KIND_INT:
1701                 case BTF_KIND_STRUCT:
1702                 case BTF_KIND_UNION:
1703                 case BTF_KIND_ENUM:
1704                 case BTF_KIND_FLOAT:
1705                         size = type->size;
1706                         goto resolved;
1707
1708                 case BTF_KIND_PTR:
1709                         size = sizeof(void *);
1710                         goto resolved;
1711
1712                 /* Modifiers */
1713                 case BTF_KIND_TYPEDEF:
1714                 case BTF_KIND_VOLATILE:
1715                 case BTF_KIND_CONST:
1716                 case BTF_KIND_RESTRICT:
1717                         id = type->type;
1718                         type = btf_type_by_id(btf, type->type);
1719                         break;
1720
1721                 case BTF_KIND_ARRAY:
1722                         if (!array_type)
1723                                 array_type = type;
1724                         array = btf_type_array(type);
1725                         if (nelems && array->nelems > U32_MAX / nelems)
1726                                 return ERR_PTR(-EINVAL);
1727                         nelems *= array->nelems;
1728                         type = btf_type_by_id(btf, array->type);
1729                         break;
1730
1731                 /* type without size */
1732                 default:
1733                         return ERR_PTR(-EINVAL);
1734                 }
1735         }
1736
1737         return ERR_PTR(-EINVAL);
1738
1739 resolved:
1740         if (nelems && size > U32_MAX / nelems)
1741                 return ERR_PTR(-EINVAL);
1742
1743         *type_size = nelems * size;
1744         if (total_nelems)
1745                 *total_nelems = nelems;
1746         if (elem_type)
1747                 *elem_type = type;
1748         if (elem_id)
1749                 *elem_id = array ? array->type : 0;
1750         if (type_id && id)
1751                 *type_id = id;
1752
1753         return array_type ? : type;
1754 }
1755
1756 const struct btf_type *
1757 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1758                  u32 *type_size)
1759 {
1760         return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1761 }
1762
1763 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1764 {
1765         while (type_id < btf->start_id)
1766                 btf = btf->base_btf;
1767
1768         return btf->resolved_ids[type_id - btf->start_id];
1769 }
1770
1771 /* The input param "type_id" must point to a needs_resolve type */
1772 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1773                                                   u32 *type_id)
1774 {
1775         *type_id = btf_resolved_type_id(btf, *type_id);
1776         return btf_type_by_id(btf, *type_id);
1777 }
1778
1779 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1780 {
1781         while (type_id < btf->start_id)
1782                 btf = btf->base_btf;
1783
1784         return btf->resolved_sizes[type_id - btf->start_id];
1785 }
1786
1787 const struct btf_type *btf_type_id_size(const struct btf *btf,
1788                                         u32 *type_id, u32 *ret_size)
1789 {
1790         const struct btf_type *size_type;
1791         u32 size_type_id = *type_id;
1792         u32 size = 0;
1793
1794         size_type = btf_type_by_id(btf, size_type_id);
1795         if (btf_type_nosize_or_null(size_type))
1796                 return NULL;
1797
1798         if (btf_type_has_size(size_type)) {
1799                 size = size_type->size;
1800         } else if (btf_type_is_array(size_type)) {
1801                 size = btf_resolved_type_size(btf, size_type_id);
1802         } else if (btf_type_is_ptr(size_type)) {
1803                 size = sizeof(void *);
1804         } else {
1805                 if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1806                                  !btf_type_is_var(size_type)))
1807                         return NULL;
1808
1809                 size_type_id = btf_resolved_type_id(btf, size_type_id);
1810                 size_type = btf_type_by_id(btf, size_type_id);
1811                 if (btf_type_nosize_or_null(size_type))
1812                         return NULL;
1813                 else if (btf_type_has_size(size_type))
1814                         size = size_type->size;
1815                 else if (btf_type_is_array(size_type))
1816                         size = btf_resolved_type_size(btf, size_type_id);
1817                 else if (btf_type_is_ptr(size_type))
1818                         size = sizeof(void *);
1819                 else
1820                         return NULL;
1821         }
1822
1823         *type_id = size_type_id;
1824         if (ret_size)
1825                 *ret_size = size;
1826
1827         return size_type;
1828 }
1829
1830 static int btf_df_check_member(struct btf_verifier_env *env,
1831                                const struct btf_type *struct_type,
1832                                const struct btf_member *member,
1833                                const struct btf_type *member_type)
1834 {
1835         btf_verifier_log_basic(env, struct_type,
1836                                "Unsupported check_member");
1837         return -EINVAL;
1838 }
1839
1840 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1841                                      const struct btf_type *struct_type,
1842                                      const struct btf_member *member,
1843                                      const struct btf_type *member_type)
1844 {
1845         btf_verifier_log_basic(env, struct_type,
1846                                "Unsupported check_kflag_member");
1847         return -EINVAL;
1848 }
1849
1850 /* Used for ptr, array struct/union and float type members.
1851  * int, enum and modifier types have their specific callback functions.
1852  */
1853 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1854                                           const struct btf_type *struct_type,
1855                                           const struct btf_member *member,
1856                                           const struct btf_type *member_type)
1857 {
1858         if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1859                 btf_verifier_log_member(env, struct_type, member,
1860                                         "Invalid member bitfield_size");
1861                 return -EINVAL;
1862         }
1863
1864         /* bitfield size is 0, so member->offset represents bit offset only.
1865          * It is safe to call non kflag check_member variants.
1866          */
1867         return btf_type_ops(member_type)->check_member(env, struct_type,
1868                                                        member,
1869                                                        member_type);
1870 }
1871
1872 static int btf_df_resolve(struct btf_verifier_env *env,
1873                           const struct resolve_vertex *v)
1874 {
1875         btf_verifier_log_basic(env, v->t, "Unsupported resolve");
1876         return -EINVAL;
1877 }
1878
1879 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
1880                         u32 type_id, void *data, u8 bits_offsets,
1881                         struct btf_show *show)
1882 {
1883         btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
1884 }
1885
1886 static int btf_int_check_member(struct btf_verifier_env *env,
1887                                 const struct btf_type *struct_type,
1888                                 const struct btf_member *member,
1889                                 const struct btf_type *member_type)
1890 {
1891         u32 int_data = btf_type_int(member_type);
1892         u32 struct_bits_off = member->offset;
1893         u32 struct_size = struct_type->size;
1894         u32 nr_copy_bits;
1895         u32 bytes_offset;
1896
1897         if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
1898                 btf_verifier_log_member(env, struct_type, member,
1899                                         "bits_offset exceeds U32_MAX");
1900                 return -EINVAL;
1901         }
1902
1903         struct_bits_off += BTF_INT_OFFSET(int_data);
1904         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1905         nr_copy_bits = BTF_INT_BITS(int_data) +
1906                 BITS_PER_BYTE_MASKED(struct_bits_off);
1907
1908         if (nr_copy_bits > BITS_PER_U128) {
1909                 btf_verifier_log_member(env, struct_type, member,
1910                                         "nr_copy_bits exceeds 128");
1911                 return -EINVAL;
1912         }
1913
1914         if (struct_size < bytes_offset ||
1915             struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1916                 btf_verifier_log_member(env, struct_type, member,
1917                                         "Member exceeds struct_size");
1918                 return -EINVAL;
1919         }
1920
1921         return 0;
1922 }
1923
1924 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
1925                                       const struct btf_type *struct_type,
1926                                       const struct btf_member *member,
1927                                       const struct btf_type *member_type)
1928 {
1929         u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
1930         u32 int_data = btf_type_int(member_type);
1931         u32 struct_size = struct_type->size;
1932         u32 nr_copy_bits;
1933
1934         /* a regular int type is required for the kflag int member */
1935         if (!btf_type_int_is_regular(member_type)) {
1936                 btf_verifier_log_member(env, struct_type, member,
1937                                         "Invalid member base type");
1938                 return -EINVAL;
1939         }
1940
1941         /* check sanity of bitfield size */
1942         nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
1943         struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
1944         nr_int_data_bits = BTF_INT_BITS(int_data);
1945         if (!nr_bits) {
1946                 /* Not a bitfield member, member offset must be at byte
1947                  * boundary.
1948                  */
1949                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
1950                         btf_verifier_log_member(env, struct_type, member,
1951                                                 "Invalid member offset");
1952                         return -EINVAL;
1953                 }
1954
1955                 nr_bits = nr_int_data_bits;
1956         } else if (nr_bits > nr_int_data_bits) {
1957                 btf_verifier_log_member(env, struct_type, member,
1958                                         "Invalid member bitfield_size");
1959                 return -EINVAL;
1960         }
1961
1962         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1963         nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
1964         if (nr_copy_bits > BITS_PER_U128) {
1965                 btf_verifier_log_member(env, struct_type, member,
1966                                         "nr_copy_bits exceeds 128");
1967                 return -EINVAL;
1968         }
1969
1970         if (struct_size < bytes_offset ||
1971             struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1972                 btf_verifier_log_member(env, struct_type, member,
1973                                         "Member exceeds struct_size");
1974                 return -EINVAL;
1975         }
1976
1977         return 0;
1978 }
1979
1980 static s32 btf_int_check_meta(struct btf_verifier_env *env,
1981                               const struct btf_type *t,
1982                               u32 meta_left)
1983 {
1984         u32 int_data, nr_bits, meta_needed = sizeof(int_data);
1985         u16 encoding;
1986
1987         if (meta_left < meta_needed) {
1988                 btf_verifier_log_basic(env, t,
1989                                        "meta_left:%u meta_needed:%u",
1990                                        meta_left, meta_needed);
1991                 return -EINVAL;
1992         }
1993
1994         if (btf_type_vlen(t)) {
1995                 btf_verifier_log_type(env, t, "vlen != 0");
1996                 return -EINVAL;
1997         }
1998
1999         if (btf_type_kflag(t)) {
2000                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2001                 return -EINVAL;
2002         }
2003
2004         int_data = btf_type_int(t);
2005         if (int_data & ~BTF_INT_MASK) {
2006                 btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2007                                        int_data);
2008                 return -EINVAL;
2009         }
2010
2011         nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2012
2013         if (nr_bits > BITS_PER_U128) {
2014                 btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2015                                       BITS_PER_U128);
2016                 return -EINVAL;
2017         }
2018
2019         if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2020                 btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2021                 return -EINVAL;
2022         }
2023
2024         /*
2025          * Only one of the encoding bits is allowed and it
2026          * should be sufficient for the pretty print purpose (i.e. decoding).
2027          * Multiple bits can be allowed later if it is found
2028          * to be insufficient.
2029          */
2030         encoding = BTF_INT_ENCODING(int_data);
2031         if (encoding &&
2032             encoding != BTF_INT_SIGNED &&
2033             encoding != BTF_INT_CHAR &&
2034             encoding != BTF_INT_BOOL) {
2035                 btf_verifier_log_type(env, t, "Unsupported encoding");
2036                 return -ENOTSUPP;
2037         }
2038
2039         btf_verifier_log_type(env, t, NULL);
2040
2041         return meta_needed;
2042 }
2043
2044 static void btf_int_log(struct btf_verifier_env *env,
2045                         const struct btf_type *t)
2046 {
2047         int int_data = btf_type_int(t);
2048
2049         btf_verifier_log(env,
2050                          "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2051                          t->size, BTF_INT_OFFSET(int_data),
2052                          BTF_INT_BITS(int_data),
2053                          btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2054 }
2055
2056 static void btf_int128_print(struct btf_show *show, void *data)
2057 {
2058         /* data points to a __int128 number.
2059          * Suppose
2060          *     int128_num = *(__int128 *)data;
2061          * The below formulas shows what upper_num and lower_num represents:
2062          *     upper_num = int128_num >> 64;
2063          *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2064          */
2065         u64 upper_num, lower_num;
2066
2067 #ifdef __BIG_ENDIAN_BITFIELD
2068         upper_num = *(u64 *)data;
2069         lower_num = *(u64 *)(data + 8);
2070 #else
2071         upper_num = *(u64 *)(data + 8);
2072         lower_num = *(u64 *)data;
2073 #endif
2074         if (upper_num == 0)
2075                 btf_show_type_value(show, "0x%llx", lower_num);
2076         else
2077                 btf_show_type_values(show, "0x%llx%016llx", upper_num,
2078                                      lower_num);
2079 }
2080
2081 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2082                              u16 right_shift_bits)
2083 {
2084         u64 upper_num, lower_num;
2085
2086 #ifdef __BIG_ENDIAN_BITFIELD
2087         upper_num = print_num[0];
2088         lower_num = print_num[1];
2089 #else
2090         upper_num = print_num[1];
2091         lower_num = print_num[0];
2092 #endif
2093
2094         /* shake out un-needed bits by shift/or operations */
2095         if (left_shift_bits >= 64) {
2096                 upper_num = lower_num << (left_shift_bits - 64);
2097                 lower_num = 0;
2098         } else {
2099                 upper_num = (upper_num << left_shift_bits) |
2100                             (lower_num >> (64 - left_shift_bits));
2101                 lower_num = lower_num << left_shift_bits;
2102         }
2103
2104         if (right_shift_bits >= 64) {
2105                 lower_num = upper_num >> (right_shift_bits - 64);
2106                 upper_num = 0;
2107         } else {
2108                 lower_num = (lower_num >> right_shift_bits) |
2109                             (upper_num << (64 - right_shift_bits));
2110                 upper_num = upper_num >> right_shift_bits;
2111         }
2112
2113 #ifdef __BIG_ENDIAN_BITFIELD
2114         print_num[0] = upper_num;
2115         print_num[1] = lower_num;
2116 #else
2117         print_num[0] = lower_num;
2118         print_num[1] = upper_num;
2119 #endif
2120 }
2121
2122 static void btf_bitfield_show(void *data, u8 bits_offset,
2123                               u8 nr_bits, struct btf_show *show)
2124 {
2125         u16 left_shift_bits, right_shift_bits;
2126         u8 nr_copy_bytes;
2127         u8 nr_copy_bits;
2128         u64 print_num[2] = {};
2129
2130         nr_copy_bits = nr_bits + bits_offset;
2131         nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2132
2133         memcpy(print_num, data, nr_copy_bytes);
2134
2135 #ifdef __BIG_ENDIAN_BITFIELD
2136         left_shift_bits = bits_offset;
2137 #else
2138         left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2139 #endif
2140         right_shift_bits = BITS_PER_U128 - nr_bits;
2141
2142         btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2143         btf_int128_print(show, print_num);
2144 }
2145
2146
2147 static void btf_int_bits_show(const struct btf *btf,
2148                               const struct btf_type *t,
2149                               void *data, u8 bits_offset,
2150                               struct btf_show *show)
2151 {
2152         u32 int_data = btf_type_int(t);
2153         u8 nr_bits = BTF_INT_BITS(int_data);
2154         u8 total_bits_offset;
2155
2156         /*
2157          * bits_offset is at most 7.
2158          * BTF_INT_OFFSET() cannot exceed 128 bits.
2159          */
2160         total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2161         data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2162         bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2163         btf_bitfield_show(data, bits_offset, nr_bits, show);
2164 }
2165
2166 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2167                          u32 type_id, void *data, u8 bits_offset,
2168                          struct btf_show *show)
2169 {
2170         u32 int_data = btf_type_int(t);
2171         u8 encoding = BTF_INT_ENCODING(int_data);
2172         bool sign = encoding & BTF_INT_SIGNED;
2173         u8 nr_bits = BTF_INT_BITS(int_data);
2174         void *safe_data;
2175
2176         safe_data = btf_show_start_type(show, t, type_id, data);
2177         if (!safe_data)
2178                 return;
2179
2180         if (bits_offset || BTF_INT_OFFSET(int_data) ||
2181             BITS_PER_BYTE_MASKED(nr_bits)) {
2182                 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2183                 goto out;
2184         }
2185
2186         switch (nr_bits) {
2187         case 128:
2188                 btf_int128_print(show, safe_data);
2189                 break;
2190         case 64:
2191                 if (sign)
2192                         btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2193                 else
2194                         btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2195                 break;
2196         case 32:
2197                 if (sign)
2198                         btf_show_type_value(show, "%d", *(s32 *)safe_data);
2199                 else
2200                         btf_show_type_value(show, "%u", *(u32 *)safe_data);
2201                 break;
2202         case 16:
2203                 if (sign)
2204                         btf_show_type_value(show, "%d", *(s16 *)safe_data);
2205                 else
2206                         btf_show_type_value(show, "%u", *(u16 *)safe_data);
2207                 break;
2208         case 8:
2209                 if (show->state.array_encoding == BTF_INT_CHAR) {
2210                         /* check for null terminator */
2211                         if (show->state.array_terminated)
2212                                 break;
2213                         if (*(char *)data == '\0') {
2214                                 show->state.array_terminated = 1;
2215                                 break;
2216                         }
2217                         if (isprint(*(char *)data)) {
2218                                 btf_show_type_value(show, "'%c'",
2219                                                     *(char *)safe_data);
2220                                 break;
2221                         }
2222                 }
2223                 if (sign)
2224                         btf_show_type_value(show, "%d", *(s8 *)safe_data);
2225                 else
2226                         btf_show_type_value(show, "%u", *(u8 *)safe_data);
2227                 break;
2228         default:
2229                 btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2230                 break;
2231         }
2232 out:
2233         btf_show_end_type(show);
2234 }
2235
2236 static const struct btf_kind_operations int_ops = {
2237         .check_meta = btf_int_check_meta,
2238         .resolve = btf_df_resolve,
2239         .check_member = btf_int_check_member,
2240         .check_kflag_member = btf_int_check_kflag_member,
2241         .log_details = btf_int_log,
2242         .show = btf_int_show,
2243 };
2244
2245 static int btf_modifier_check_member(struct btf_verifier_env *env,
2246                                      const struct btf_type *struct_type,
2247                                      const struct btf_member *member,
2248                                      const struct btf_type *member_type)
2249 {
2250         const struct btf_type *resolved_type;
2251         u32 resolved_type_id = member->type;
2252         struct btf_member resolved_member;
2253         struct btf *btf = env->btf;
2254
2255         resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2256         if (!resolved_type) {
2257                 btf_verifier_log_member(env, struct_type, member,
2258                                         "Invalid member");
2259                 return -EINVAL;
2260         }
2261
2262         resolved_member = *member;
2263         resolved_member.type = resolved_type_id;
2264
2265         return btf_type_ops(resolved_type)->check_member(env, struct_type,
2266                                                          &resolved_member,
2267                                                          resolved_type);
2268 }
2269
2270 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2271                                            const struct btf_type *struct_type,
2272                                            const struct btf_member *member,
2273                                            const struct btf_type *member_type)
2274 {
2275         const struct btf_type *resolved_type;
2276         u32 resolved_type_id = member->type;
2277         struct btf_member resolved_member;
2278         struct btf *btf = env->btf;
2279
2280         resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2281         if (!resolved_type) {
2282                 btf_verifier_log_member(env, struct_type, member,
2283                                         "Invalid member");
2284                 return -EINVAL;
2285         }
2286
2287         resolved_member = *member;
2288         resolved_member.type = resolved_type_id;
2289
2290         return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2291                                                                &resolved_member,
2292                                                                resolved_type);
2293 }
2294
2295 static int btf_ptr_check_member(struct btf_verifier_env *env,
2296                                 const struct btf_type *struct_type,
2297                                 const struct btf_member *member,
2298                                 const struct btf_type *member_type)
2299 {
2300         u32 struct_size, struct_bits_off, bytes_offset;
2301
2302         struct_size = struct_type->size;
2303         struct_bits_off = member->offset;
2304         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2305
2306         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2307                 btf_verifier_log_member(env, struct_type, member,
2308                                         "Member is not byte aligned");
2309                 return -EINVAL;
2310         }
2311
2312         if (struct_size - bytes_offset < sizeof(void *)) {
2313                 btf_verifier_log_member(env, struct_type, member,
2314                                         "Member exceeds struct_size");
2315                 return -EINVAL;
2316         }
2317
2318         return 0;
2319 }
2320
2321 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2322                                    const struct btf_type *t,
2323                                    u32 meta_left)
2324 {
2325         if (btf_type_vlen(t)) {
2326                 btf_verifier_log_type(env, t, "vlen != 0");
2327                 return -EINVAL;
2328         }
2329
2330         if (btf_type_kflag(t)) {
2331                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2332                 return -EINVAL;
2333         }
2334
2335         if (!BTF_TYPE_ID_VALID(t->type)) {
2336                 btf_verifier_log_type(env, t, "Invalid type_id");
2337                 return -EINVAL;
2338         }
2339
2340         /* typedef type must have a valid name, and other ref types,
2341          * volatile, const, restrict, should have a null name.
2342          */
2343         if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2344                 if (!t->name_off ||
2345                     !btf_name_valid_identifier(env->btf, t->name_off)) {
2346                         btf_verifier_log_type(env, t, "Invalid name");
2347                         return -EINVAL;
2348                 }
2349         } else {
2350                 if (t->name_off) {
2351                         btf_verifier_log_type(env, t, "Invalid name");
2352                         return -EINVAL;
2353                 }
2354         }
2355
2356         btf_verifier_log_type(env, t, NULL);
2357
2358         return 0;
2359 }
2360
2361 static int btf_modifier_resolve(struct btf_verifier_env *env,
2362                                 const struct resolve_vertex *v)
2363 {
2364         const struct btf_type *t = v->t;
2365         const struct btf_type *next_type;
2366         u32 next_type_id = t->type;
2367         struct btf *btf = env->btf;
2368
2369         next_type = btf_type_by_id(btf, next_type_id);
2370         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2371                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2372                 return -EINVAL;
2373         }
2374
2375         if (!env_type_is_resolve_sink(env, next_type) &&
2376             !env_type_is_resolved(env, next_type_id))
2377                 return env_stack_push(env, next_type, next_type_id);
2378
2379         /* Figure out the resolved next_type_id with size.
2380          * They will be stored in the current modifier's
2381          * resolved_ids and resolved_sizes such that it can
2382          * save us a few type-following when we use it later (e.g. in
2383          * pretty print).
2384          */
2385         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2386                 if (env_type_is_resolved(env, next_type_id))
2387                         next_type = btf_type_id_resolve(btf, &next_type_id);
2388
2389                 /* "typedef void new_void", "const void"...etc */
2390                 if (!btf_type_is_void(next_type) &&
2391                     !btf_type_is_fwd(next_type) &&
2392                     !btf_type_is_func_proto(next_type)) {
2393                         btf_verifier_log_type(env, v->t, "Invalid type_id");
2394                         return -EINVAL;
2395                 }
2396         }
2397
2398         env_stack_pop_resolved(env, next_type_id, 0);
2399
2400         return 0;
2401 }
2402
2403 static int btf_var_resolve(struct btf_verifier_env *env,
2404                            const struct resolve_vertex *v)
2405 {
2406         const struct btf_type *next_type;
2407         const struct btf_type *t = v->t;
2408         u32 next_type_id = t->type;
2409         struct btf *btf = env->btf;
2410
2411         next_type = btf_type_by_id(btf, next_type_id);
2412         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2413                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2414                 return -EINVAL;
2415         }
2416
2417         if (!env_type_is_resolve_sink(env, next_type) &&
2418             !env_type_is_resolved(env, next_type_id))
2419                 return env_stack_push(env, next_type, next_type_id);
2420
2421         if (btf_type_is_modifier(next_type)) {
2422                 const struct btf_type *resolved_type;
2423                 u32 resolved_type_id;
2424
2425                 resolved_type_id = next_type_id;
2426                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2427
2428                 if (btf_type_is_ptr(resolved_type) &&
2429                     !env_type_is_resolve_sink(env, resolved_type) &&
2430                     !env_type_is_resolved(env, resolved_type_id))
2431                         return env_stack_push(env, resolved_type,
2432                                               resolved_type_id);
2433         }
2434
2435         /* We must resolve to something concrete at this point, no
2436          * forward types or similar that would resolve to size of
2437          * zero is allowed.
2438          */
2439         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2440                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2441                 return -EINVAL;
2442         }
2443
2444         env_stack_pop_resolved(env, next_type_id, 0);
2445
2446         return 0;
2447 }
2448
2449 static int btf_ptr_resolve(struct btf_verifier_env *env,
2450                            const struct resolve_vertex *v)
2451 {
2452         const struct btf_type *next_type;
2453         const struct btf_type *t = v->t;
2454         u32 next_type_id = t->type;
2455         struct btf *btf = env->btf;
2456
2457         next_type = btf_type_by_id(btf, next_type_id);
2458         if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2459                 btf_verifier_log_type(env, v->t, "Invalid type_id");
2460                 return -EINVAL;
2461         }
2462
2463         if (!env_type_is_resolve_sink(env, next_type) &&
2464             !env_type_is_resolved(env, next_type_id))
2465                 return env_stack_push(env, next_type, next_type_id);
2466
2467         /* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2468          * the modifier may have stopped resolving when it was resolved
2469          * to a ptr (last-resolved-ptr).
2470          *
2471          * We now need to continue from the last-resolved-ptr to
2472          * ensure the last-resolved-ptr will not referring back to
2473          * the currenct ptr (t).
2474          */
2475         if (btf_type_is_modifier(next_type)) {
2476                 const struct btf_type *resolved_type;
2477                 u32 resolved_type_id;
2478
2479                 resolved_type_id = next_type_id;
2480                 resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2481
2482                 if (btf_type_is_ptr(resolved_type) &&
2483                     !env_type_is_resolve_sink(env, resolved_type) &&
2484                     !env_type_is_resolved(env, resolved_type_id))
2485                         return env_stack_push(env, resolved_type,
2486                                               resolved_type_id);
2487         }
2488
2489         if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2490                 if (env_type_is_resolved(env, next_type_id))
2491                         next_type = btf_type_id_resolve(btf, &next_type_id);
2492
2493                 if (!btf_type_is_void(next_type) &&
2494                     !btf_type_is_fwd(next_type) &&
2495                     !btf_type_is_func_proto(next_type)) {
2496                         btf_verifier_log_type(env, v->t, "Invalid type_id");
2497                         return -EINVAL;
2498                 }
2499         }
2500
2501         env_stack_pop_resolved(env, next_type_id, 0);
2502
2503         return 0;
2504 }
2505
2506 static void btf_modifier_show(const struct btf *btf,
2507                               const struct btf_type *t,
2508                               u32 type_id, void *data,
2509                               u8 bits_offset, struct btf_show *show)
2510 {
2511         if (btf->resolved_ids)
2512                 t = btf_type_id_resolve(btf, &type_id);
2513         else
2514                 t = btf_type_skip_modifiers(btf, type_id, NULL);
2515
2516         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2517 }
2518
2519 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2520                          u32 type_id, void *data, u8 bits_offset,
2521                          struct btf_show *show)
2522 {
2523         t = btf_type_id_resolve(btf, &type_id);
2524
2525         btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2526 }
2527
2528 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2529                          u32 type_id, void *data, u8 bits_offset,
2530                          struct btf_show *show)
2531 {
2532         void *safe_data;
2533
2534         safe_data = btf_show_start_type(show, t, type_id, data);
2535         if (!safe_data)
2536                 return;
2537
2538         /* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2539         if (show->flags & BTF_SHOW_PTR_RAW)
2540                 btf_show_type_value(show, "0x%px", *(void **)safe_data);
2541         else
2542                 btf_show_type_value(show, "0x%p", *(void **)safe_data);
2543         btf_show_end_type(show);
2544 }
2545
2546 static void btf_ref_type_log(struct btf_verifier_env *env,
2547                              const struct btf_type *t)
2548 {
2549         btf_verifier_log(env, "type_id=%u", t->type);
2550 }
2551
2552 static struct btf_kind_operations modifier_ops = {
2553         .check_meta = btf_ref_type_check_meta,
2554         .resolve = btf_modifier_resolve,
2555         .check_member = btf_modifier_check_member,
2556         .check_kflag_member = btf_modifier_check_kflag_member,
2557         .log_details = btf_ref_type_log,
2558         .show = btf_modifier_show,
2559 };
2560
2561 static struct btf_kind_operations ptr_ops = {
2562         .check_meta = btf_ref_type_check_meta,
2563         .resolve = btf_ptr_resolve,
2564         .check_member = btf_ptr_check_member,
2565         .check_kflag_member = btf_generic_check_kflag_member,
2566         .log_details = btf_ref_type_log,
2567         .show = btf_ptr_show,
2568 };
2569
2570 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2571                               const struct btf_type *t,
2572                               u32 meta_left)
2573 {
2574         if (btf_type_vlen(t)) {
2575                 btf_verifier_log_type(env, t, "vlen != 0");
2576                 return -EINVAL;
2577         }
2578
2579         if (t->type) {
2580                 btf_verifier_log_type(env, t, "type != 0");
2581                 return -EINVAL;
2582         }
2583
2584         /* fwd type must have a valid name */
2585         if (!t->name_off ||
2586             !btf_name_valid_identifier(env->btf, t->name_off)) {
2587                 btf_verifier_log_type(env, t, "Invalid name");
2588                 return -EINVAL;
2589         }
2590
2591         btf_verifier_log_type(env, t, NULL);
2592
2593         return 0;
2594 }
2595
2596 static void btf_fwd_type_log(struct btf_verifier_env *env,
2597                              const struct btf_type *t)
2598 {
2599         btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2600 }
2601
2602 static struct btf_kind_operations fwd_ops = {
2603         .check_meta = btf_fwd_check_meta,
2604         .resolve = btf_df_resolve,
2605         .check_member = btf_df_check_member,
2606         .check_kflag_member = btf_df_check_kflag_member,
2607         .log_details = btf_fwd_type_log,
2608         .show = btf_df_show,
2609 };
2610
2611 static int btf_array_check_member(struct btf_verifier_env *env,
2612                                   const struct btf_type *struct_type,
2613                                   const struct btf_member *member,
2614                                   const struct btf_type *member_type)
2615 {
2616         u32 struct_bits_off = member->offset;
2617         u32 struct_size, bytes_offset;
2618         u32 array_type_id, array_size;
2619         struct btf *btf = env->btf;
2620
2621         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2622                 btf_verifier_log_member(env, struct_type, member,
2623                                         "Member is not byte aligned");
2624                 return -EINVAL;
2625         }
2626
2627         array_type_id = member->type;
2628         btf_type_id_size(btf, &array_type_id, &array_size);
2629         struct_size = struct_type->size;
2630         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2631         if (struct_size - bytes_offset < array_size) {
2632                 btf_verifier_log_member(env, struct_type, member,
2633                                         "Member exceeds struct_size");
2634                 return -EINVAL;
2635         }
2636
2637         return 0;
2638 }
2639
2640 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2641                                 const struct btf_type *t,
2642                                 u32 meta_left)
2643 {
2644         const struct btf_array *array = btf_type_array(t);
2645         u32 meta_needed = sizeof(*array);
2646
2647         if (meta_left < meta_needed) {
2648                 btf_verifier_log_basic(env, t,
2649                                        "meta_left:%u meta_needed:%u",
2650                                        meta_left, meta_needed);
2651                 return -EINVAL;
2652         }
2653
2654         /* array type should not have a name */
2655         if (t->name_off) {
2656                 btf_verifier_log_type(env, t, "Invalid name");
2657                 return -EINVAL;
2658         }
2659
2660         if (btf_type_vlen(t)) {
2661                 btf_verifier_log_type(env, t, "vlen != 0");
2662                 return -EINVAL;
2663         }
2664
2665         if (btf_type_kflag(t)) {
2666                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2667                 return -EINVAL;
2668         }
2669
2670         if (t->size) {
2671                 btf_verifier_log_type(env, t, "size != 0");
2672                 return -EINVAL;
2673         }
2674
2675         /* Array elem type and index type cannot be in type void,
2676          * so !array->type and !array->index_type are not allowed.
2677          */
2678         if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2679                 btf_verifier_log_type(env, t, "Invalid elem");
2680                 return -EINVAL;
2681         }
2682
2683         if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2684                 btf_verifier_log_type(env, t, "Invalid index");
2685                 return -EINVAL;
2686         }
2687
2688         btf_verifier_log_type(env, t, NULL);
2689
2690         return meta_needed;
2691 }
2692
2693 static int btf_array_resolve(struct btf_verifier_env *env,
2694                              const struct resolve_vertex *v)
2695 {
2696         const struct btf_array *array = btf_type_array(v->t);
2697         const struct btf_type *elem_type, *index_type;
2698         u32 elem_type_id, index_type_id;
2699         struct btf *btf = env->btf;
2700         u32 elem_size;
2701
2702         /* Check array->index_type */
2703         index_type_id = array->index_type;
2704         index_type = btf_type_by_id(btf, index_type_id);
2705         if (btf_type_nosize_or_null(index_type) ||
2706             btf_type_is_resolve_source_only(index_type)) {
2707                 btf_verifier_log_type(env, v->t, "Invalid index");
2708                 return -EINVAL;
2709         }
2710
2711         if (!env_type_is_resolve_sink(env, index_type) &&
2712             !env_type_is_resolved(env, index_type_id))
2713                 return env_stack_push(env, index_type, index_type_id);
2714
2715         index_type = btf_type_id_size(btf, &index_type_id, NULL);
2716         if (!index_type || !btf_type_is_int(index_type) ||
2717             !btf_type_int_is_regular(index_type)) {
2718                 btf_verifier_log_type(env, v->t, "Invalid index");
2719                 return -EINVAL;
2720         }
2721
2722         /* Check array->type */
2723         elem_type_id = array->type;
2724         elem_type = btf_type_by_id(btf, elem_type_id);
2725         if (btf_type_nosize_or_null(elem_type) ||
2726             btf_type_is_resolve_source_only(elem_type)) {
2727                 btf_verifier_log_type(env, v->t,
2728                                       "Invalid elem");
2729                 return -EINVAL;
2730         }
2731
2732         if (!env_type_is_resolve_sink(env, elem_type) &&
2733             !env_type_is_resolved(env, elem_type_id))
2734                 return env_stack_push(env, elem_type, elem_type_id);
2735
2736         elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2737         if (!elem_type) {
2738                 btf_verifier_log_type(env, v->t, "Invalid elem");
2739                 return -EINVAL;
2740         }
2741
2742         if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2743                 btf_verifier_log_type(env, v->t, "Invalid array of int");
2744                 return -EINVAL;
2745         }
2746
2747         if (array->nelems && elem_size > U32_MAX / array->nelems) {
2748                 btf_verifier_log_type(env, v->t,
2749                                       "Array size overflows U32_MAX");
2750                 return -EINVAL;
2751         }
2752
2753         env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2754
2755         return 0;
2756 }
2757
2758 static void btf_array_log(struct btf_verifier_env *env,
2759                           const struct btf_type *t)
2760 {
2761         const struct btf_array *array = btf_type_array(t);
2762
2763         btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2764                          array->type, array->index_type, array->nelems);
2765 }
2766
2767 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2768                              u32 type_id, void *data, u8 bits_offset,
2769                              struct btf_show *show)
2770 {
2771         const struct btf_array *array = btf_type_array(t);
2772         const struct btf_kind_operations *elem_ops;
2773         const struct btf_type *elem_type;
2774         u32 i, elem_size = 0, elem_type_id;
2775         u16 encoding = 0;
2776
2777         elem_type_id = array->type;
2778         elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2779         if (elem_type && btf_type_has_size(elem_type))
2780                 elem_size = elem_type->size;
2781
2782         if (elem_type && btf_type_is_int(elem_type)) {
2783                 u32 int_type = btf_type_int(elem_type);
2784
2785                 encoding = BTF_INT_ENCODING(int_type);
2786
2787                 /*
2788                  * BTF_INT_CHAR encoding never seems to be set for
2789                  * char arrays, so if size is 1 and element is
2790                  * printable as a char, we'll do that.
2791                  */
2792                 if (elem_size == 1)
2793                         encoding = BTF_INT_CHAR;
2794         }
2795
2796         if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2797                 return;
2798
2799         if (!elem_type)
2800                 goto out;
2801         elem_ops = btf_type_ops(elem_type);
2802
2803         for (i = 0; i < array->nelems; i++) {
2804
2805                 btf_show_start_array_member(show);
2806
2807                 elem_ops->show(btf, elem_type, elem_type_id, data,
2808                                bits_offset, show);
2809                 data += elem_size;
2810
2811                 btf_show_end_array_member(show);
2812
2813                 if (show->state.array_terminated)
2814                         break;
2815         }
2816 out:
2817         btf_show_end_array_type(show);
2818 }
2819
2820 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2821                            u32 type_id, void *data, u8 bits_offset,
2822                            struct btf_show *show)
2823 {
2824         const struct btf_member *m = show->state.member;
2825
2826         /*
2827          * First check if any members would be shown (are non-zero).
2828          * See comments above "struct btf_show" definition for more
2829          * details on how this works at a high-level.
2830          */
2831         if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2832                 if (!show->state.depth_check) {
2833                         show->state.depth_check = show->state.depth + 1;
2834                         show->state.depth_to_show = 0;
2835                 }
2836                 __btf_array_show(btf, t, type_id, data, bits_offset, show);
2837                 show->state.member = m;
2838
2839                 if (show->state.depth_check != show->state.depth + 1)
2840                         return;
2841                 show->state.depth_check = 0;
2842
2843                 if (show->state.depth_to_show <= show->state.depth)
2844                         return;
2845                 /*
2846                  * Reaching here indicates we have recursed and found
2847                  * non-zero array member(s).
2848                  */
2849         }
2850         __btf_array_show(btf, t, type_id, data, bits_offset, show);
2851 }
2852
2853 static struct btf_kind_operations array_ops = {
2854         .check_meta = btf_array_check_meta,
2855         .resolve = btf_array_resolve,
2856         .check_member = btf_array_check_member,
2857         .check_kflag_member = btf_generic_check_kflag_member,
2858         .log_details = btf_array_log,
2859         .show = btf_array_show,
2860 };
2861
2862 static int btf_struct_check_member(struct btf_verifier_env *env,
2863                                    const struct btf_type *struct_type,
2864                                    const struct btf_member *member,
2865                                    const struct btf_type *member_type)
2866 {
2867         u32 struct_bits_off = member->offset;
2868         u32 struct_size, bytes_offset;
2869
2870         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2871                 btf_verifier_log_member(env, struct_type, member,
2872                                         "Member is not byte aligned");
2873                 return -EINVAL;
2874         }
2875
2876         struct_size = struct_type->size;
2877         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2878         if (struct_size - bytes_offset < member_type->size) {
2879                 btf_verifier_log_member(env, struct_type, member,
2880                                         "Member exceeds struct_size");
2881                 return -EINVAL;
2882         }
2883
2884         return 0;
2885 }
2886
2887 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
2888                                  const struct btf_type *t,
2889                                  u32 meta_left)
2890 {
2891         bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
2892         const struct btf_member *member;
2893         u32 meta_needed, last_offset;
2894         struct btf *btf = env->btf;
2895         u32 struct_size = t->size;
2896         u32 offset;
2897         u16 i;
2898
2899         meta_needed = btf_type_vlen(t) * sizeof(*member);
2900         if (meta_left < meta_needed) {
2901                 btf_verifier_log_basic(env, t,
2902                                        "meta_left:%u meta_needed:%u",
2903                                        meta_left, meta_needed);
2904                 return -EINVAL;
2905         }
2906
2907         /* struct type either no name or a valid one */
2908         if (t->name_off &&
2909             !btf_name_valid_identifier(env->btf, t->name_off)) {
2910                 btf_verifier_log_type(env, t, "Invalid name");
2911                 return -EINVAL;
2912         }
2913
2914         btf_verifier_log_type(env, t, NULL);
2915
2916         last_offset = 0;
2917         for_each_member(i, t, member) {
2918                 if (!btf_name_offset_valid(btf, member->name_off)) {
2919                         btf_verifier_log_member(env, t, member,
2920                                                 "Invalid member name_offset:%u",
2921                                                 member->name_off);
2922                         return -EINVAL;
2923                 }
2924
2925                 /* struct member either no name or a valid one */
2926                 if (member->name_off &&
2927                     !btf_name_valid_identifier(btf, member->name_off)) {
2928                         btf_verifier_log_member(env, t, member, "Invalid name");
2929                         return -EINVAL;
2930                 }
2931                 /* A member cannot be in type void */
2932                 if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
2933                         btf_verifier_log_member(env, t, member,
2934                                                 "Invalid type_id");
2935                         return -EINVAL;
2936                 }
2937
2938                 offset = btf_member_bit_offset(t, member);
2939                 if (is_union && offset) {
2940                         btf_verifier_log_member(env, t, member,
2941                                                 "Invalid member bits_offset");
2942                         return -EINVAL;
2943                 }
2944
2945                 /*
2946                  * ">" instead of ">=" because the last member could be
2947                  * "char a[0];"
2948                  */
2949                 if (last_offset > offset) {
2950                         btf_verifier_log_member(env, t, member,
2951                                                 "Invalid member bits_offset");
2952                         return -EINVAL;
2953                 }
2954
2955                 if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
2956                         btf_verifier_log_member(env, t, member,
2957                                                 "Member bits_offset exceeds its struct size");
2958                         return -EINVAL;
2959                 }
2960
2961                 btf_verifier_log_member(env, t, member, NULL);
2962                 last_offset = offset;
2963         }
2964
2965         return meta_needed;
2966 }
2967
2968 static int btf_struct_resolve(struct btf_verifier_env *env,
2969                               const struct resolve_vertex *v)
2970 {
2971         const struct btf_member *member;
2972         int err;
2973         u16 i;
2974
2975         /* Before continue resolving the next_member,
2976          * ensure the last member is indeed resolved to a
2977          * type with size info.
2978          */
2979         if (v->next_member) {
2980                 const struct btf_type *last_member_type;
2981                 const struct btf_member *last_member;
2982                 u32 last_member_type_id;
2983
2984                 last_member = btf_type_member(v->t) + v->next_member - 1;
2985                 last_member_type_id = last_member->type;
2986                 if (WARN_ON_ONCE(!env_type_is_resolved(env,
2987                                                        last_member_type_id)))
2988                         return -EINVAL;
2989
2990                 last_member_type = btf_type_by_id(env->btf,
2991                                                   last_member_type_id);
2992                 if (btf_type_kflag(v->t))
2993                         err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
2994                                                                 last_member,
2995                                                                 last_member_type);
2996                 else
2997                         err = btf_type_ops(last_member_type)->check_member(env, v->t,
2998                                                                 last_member,
2999                                                                 last_member_type);
3000                 if (err)
3001                         return err;
3002         }
3003
3004         for_each_member_from(i, v->next_member, v->t, member) {
3005                 u32 member_type_id = member->type;
3006                 const struct btf_type *member_type = btf_type_by_id(env->btf,
3007                                                                 member_type_id);
3008
3009                 if (btf_type_nosize_or_null(member_type) ||
3010                     btf_type_is_resolve_source_only(member_type)) {
3011                         btf_verifier_log_member(env, v->t, member,
3012                                                 "Invalid member");
3013                         return -EINVAL;
3014                 }
3015
3016                 if (!env_type_is_resolve_sink(env, member_type) &&
3017                     !env_type_is_resolved(env, member_type_id)) {
3018                         env_stack_set_next_member(env, i + 1);
3019                         return env_stack_push(env, member_type, member_type_id);
3020                 }
3021
3022                 if (btf_type_kflag(v->t))
3023                         err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3024                                                                             member,
3025                                                                             member_type);
3026                 else
3027                         err = btf_type_ops(member_type)->check_member(env, v->t,
3028                                                                       member,
3029                                                                       member_type);
3030                 if (err)
3031                         return err;
3032         }
3033
3034         env_stack_pop_resolved(env, 0, 0);
3035
3036         return 0;
3037 }
3038
3039 static void btf_struct_log(struct btf_verifier_env *env,
3040                            const struct btf_type *t)
3041 {
3042         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3043 }
3044
3045 static int btf_find_struct_field(const struct btf *btf, const struct btf_type *t,
3046                                  const char *name, int sz, int align)
3047 {
3048         const struct btf_member *member;
3049         u32 i, off = -ENOENT;
3050
3051         for_each_member(i, t, member) {
3052                 const struct btf_type *member_type = btf_type_by_id(btf,
3053                                                                     member->type);
3054                 if (!__btf_type_is_struct(member_type))
3055                         continue;
3056                 if (member_type->size != sz)
3057                         continue;
3058                 if (strcmp(__btf_name_by_offset(btf, member_type->name_off), name))
3059                         continue;
3060                 if (off != -ENOENT)
3061                         /* only one such field is allowed */
3062                         return -E2BIG;
3063                 off = btf_member_bit_offset(t, member);
3064                 if (off % 8)
3065                         /* valid C code cannot generate such BTF */
3066                         return -EINVAL;
3067                 off /= 8;
3068                 if (off % align)
3069                         return -EINVAL;
3070         }
3071         return off;
3072 }
3073
3074 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3075                                 const char *name, int sz, int align)
3076 {
3077         const struct btf_var_secinfo *vsi;
3078         u32 i, off = -ENOENT;
3079
3080         for_each_vsi(i, t, vsi) {
3081                 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3082                 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3083
3084                 if (!__btf_type_is_struct(var_type))
3085                         continue;
3086                 if (var_type->size != sz)
3087                         continue;
3088                 if (vsi->size != sz)
3089                         continue;
3090                 if (strcmp(__btf_name_by_offset(btf, var_type->name_off), name))
3091                         continue;
3092                 if (off != -ENOENT)
3093                         /* only one such field is allowed */
3094                         return -E2BIG;
3095                 off = vsi->offset;
3096                 if (off % align)
3097                         return -EINVAL;
3098         }
3099         return off;
3100 }
3101
3102 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3103                           const char *name, int sz, int align)
3104 {
3105
3106         if (__btf_type_is_struct(t))
3107                 return btf_find_struct_field(btf, t, name, sz, align);
3108         else if (btf_type_is_datasec(t))
3109                 return btf_find_datasec_var(btf, t, name, sz, align);
3110         return -EINVAL;
3111 }
3112
3113 /* find 'struct bpf_spin_lock' in map value.
3114  * return >= 0 offset if found
3115  * and < 0 in case of error
3116  */
3117 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3118 {
3119         return btf_find_field(btf, t, "bpf_spin_lock",
3120                               sizeof(struct bpf_spin_lock),
3121                               __alignof__(struct bpf_spin_lock));
3122 }
3123
3124 int btf_find_timer(const struct btf *btf, const struct btf_type *t)
3125 {
3126         return btf_find_field(btf, t, "bpf_timer",
3127                               sizeof(struct bpf_timer),
3128                               __alignof__(struct bpf_timer));
3129 }
3130
3131 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3132                               u32 type_id, void *data, u8 bits_offset,
3133                               struct btf_show *show)
3134 {
3135         const struct btf_member *member;
3136         void *safe_data;
3137         u32 i;
3138
3139         safe_data = btf_show_start_struct_type(show, t, type_id, data);
3140         if (!safe_data)
3141                 return;
3142
3143         for_each_member(i, t, member) {
3144                 const struct btf_type *member_type = btf_type_by_id(btf,
3145                                                                 member->type);
3146                 const struct btf_kind_operations *ops;
3147                 u32 member_offset, bitfield_size;
3148                 u32 bytes_offset;
3149                 u8 bits8_offset;
3150
3151                 btf_show_start_member(show, member);
3152
3153                 member_offset = btf_member_bit_offset(t, member);
3154                 bitfield_size = btf_member_bitfield_size(t, member);
3155                 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3156                 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3157                 if (bitfield_size) {
3158                         safe_data = btf_show_start_type(show, member_type,
3159                                                         member->type,
3160                                                         data + bytes_offset);
3161                         if (safe_data)
3162                                 btf_bitfield_show(safe_data,
3163                                                   bits8_offset,
3164                                                   bitfield_size, show);
3165                         btf_show_end_type(show);
3166                 } else {
3167                         ops = btf_type_ops(member_type);
3168                         ops->show(btf, member_type, member->type,
3169                                   data + bytes_offset, bits8_offset, show);
3170                 }
3171
3172                 btf_show_end_member(show);
3173         }
3174
3175         btf_show_end_struct_type(show);
3176 }
3177
3178 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3179                             u32 type_id, void *data, u8 bits_offset,
3180                             struct btf_show *show)
3181 {
3182         const struct btf_member *m = show->state.member;
3183
3184         /*
3185          * First check if any members would be shown (are non-zero).
3186          * See comments above "struct btf_show" definition for more
3187          * details on how this works at a high-level.
3188          */
3189         if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3190                 if (!show->state.depth_check) {
3191                         show->state.depth_check = show->state.depth + 1;
3192                         show->state.depth_to_show = 0;
3193                 }
3194                 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3195                 /* Restore saved member data here */
3196                 show->state.member = m;
3197                 if (show->state.depth_check != show->state.depth + 1)
3198                         return;
3199                 show->state.depth_check = 0;
3200
3201                 if (show->state.depth_to_show <= show->state.depth)
3202                         return;
3203                 /*
3204                  * Reaching here indicates we have recursed and found
3205                  * non-zero child values.
3206                  */
3207         }
3208
3209         __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3210 }
3211
3212 static struct btf_kind_operations struct_ops = {
3213         .check_meta = btf_struct_check_meta,
3214         .resolve = btf_struct_resolve,
3215         .check_member = btf_struct_check_member,
3216         .check_kflag_member = btf_generic_check_kflag_member,
3217         .log_details = btf_struct_log,
3218         .show = btf_struct_show,
3219 };
3220
3221 static int btf_enum_check_member(struct btf_verifier_env *env,
3222                                  const struct btf_type *struct_type,
3223                                  const struct btf_member *member,
3224                                  const struct btf_type *member_type)
3225 {
3226         u32 struct_bits_off = member->offset;
3227         u32 struct_size, bytes_offset;
3228
3229         if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3230                 btf_verifier_log_member(env, struct_type, member,
3231                                         "Member is not byte aligned");
3232                 return -EINVAL;
3233         }
3234
3235         struct_size = struct_type->size;
3236         bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3237         if (struct_size - bytes_offset < member_type->size) {
3238                 btf_verifier_log_member(env, struct_type, member,
3239                                         "Member exceeds struct_size");
3240                 return -EINVAL;
3241         }
3242
3243         return 0;
3244 }
3245
3246 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3247                                        const struct btf_type *struct_type,
3248                                        const struct btf_member *member,
3249                                        const struct btf_type *member_type)
3250 {
3251         u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3252         u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3253
3254         struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3255         nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3256         if (!nr_bits) {
3257                 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3258                         btf_verifier_log_member(env, struct_type, member,
3259                                                 "Member is not byte aligned");
3260                         return -EINVAL;
3261                 }
3262
3263                 nr_bits = int_bitsize;
3264         } else if (nr_bits > int_bitsize) {
3265                 btf_verifier_log_member(env, struct_type, member,
3266                                         "Invalid member bitfield_size");
3267                 return -EINVAL;
3268         }
3269
3270         struct_size = struct_type->size;
3271         bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3272         if (struct_size < bytes_end) {
3273                 btf_verifier_log_member(env, struct_type, member,
3274                                         "Member exceeds struct_size");
3275                 return -EINVAL;
3276         }
3277
3278         return 0;
3279 }
3280
3281 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3282                                const struct btf_type *t,
3283                                u32 meta_left)
3284 {
3285         const struct btf_enum *enums = btf_type_enum(t);
3286         struct btf *btf = env->btf;
3287         u16 i, nr_enums;
3288         u32 meta_needed;
3289
3290         nr_enums = btf_type_vlen(t);
3291         meta_needed = nr_enums * sizeof(*enums);
3292
3293         if (meta_left < meta_needed) {
3294                 btf_verifier_log_basic(env, t,
3295                                        "meta_left:%u meta_needed:%u",
3296                                        meta_left, meta_needed);
3297                 return -EINVAL;
3298         }
3299
3300         if (btf_type_kflag(t)) {
3301                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3302                 return -EINVAL;
3303         }
3304
3305         if (t->size > 8 || !is_power_of_2(t->size)) {
3306                 btf_verifier_log_type(env, t, "Unexpected size");
3307                 return -EINVAL;
3308         }
3309
3310         /* enum type either no name or a valid one */
3311         if (t->name_off &&
3312             !btf_name_valid_identifier(env->btf, t->name_off)) {
3313                 btf_verifier_log_type(env, t, "Invalid name");
3314                 return -EINVAL;
3315         }
3316
3317         btf_verifier_log_type(env, t, NULL);
3318
3319         for (i = 0; i < nr_enums; i++) {
3320                 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3321                         btf_verifier_log(env, "\tInvalid name_offset:%u",
3322                                          enums[i].name_off);
3323                         return -EINVAL;
3324                 }
3325
3326                 /* enum member must have a valid name */
3327                 if (!enums[i].name_off ||
3328                     !btf_name_valid_identifier(btf, enums[i].name_off)) {
3329                         btf_verifier_log_type(env, t, "Invalid name");
3330                         return -EINVAL;
3331                 }
3332
3333                 if (env->log.level == BPF_LOG_KERNEL)
3334                         continue;
3335                 btf_verifier_log(env, "\t%s val=%d\n",
3336                                  __btf_name_by_offset(btf, enums[i].name_off),
3337                                  enums[i].val);
3338         }
3339
3340         return meta_needed;
3341 }
3342
3343 static void btf_enum_log(struct btf_verifier_env *env,
3344                          const struct btf_type *t)
3345 {
3346         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3347 }
3348
3349 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3350                           u32 type_id, void *data, u8 bits_offset,
3351                           struct btf_show *show)
3352 {
3353         const struct btf_enum *enums = btf_type_enum(t);
3354         u32 i, nr_enums = btf_type_vlen(t);
3355         void *safe_data;
3356         int v;
3357
3358         safe_data = btf_show_start_type(show, t, type_id, data);
3359         if (!safe_data)
3360                 return;
3361
3362         v = *(int *)safe_data;
3363
3364         for (i = 0; i < nr_enums; i++) {
3365                 if (v != enums[i].val)
3366                         continue;
3367
3368                 btf_show_type_value(show, "%s",
3369                                     __btf_name_by_offset(btf,
3370                                                          enums[i].name_off));
3371
3372                 btf_show_end_type(show);
3373                 return;
3374         }
3375
3376         btf_show_type_value(show, "%d", v);
3377         btf_show_end_type(show);
3378 }
3379
3380 static struct btf_kind_operations enum_ops = {
3381         .check_meta = btf_enum_check_meta,
3382         .resolve = btf_df_resolve,
3383         .check_member = btf_enum_check_member,
3384         .check_kflag_member = btf_enum_check_kflag_member,
3385         .log_details = btf_enum_log,
3386         .show = btf_enum_show,
3387 };
3388
3389 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3390                                      const struct btf_type *t,
3391                                      u32 meta_left)
3392 {
3393         u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3394
3395         if (meta_left < meta_needed) {
3396                 btf_verifier_log_basic(env, t,
3397                                        "meta_left:%u meta_needed:%u",
3398                                        meta_left, meta_needed);
3399                 return -EINVAL;
3400         }
3401
3402         if (t->name_off) {
3403                 btf_verifier_log_type(env, t, "Invalid name");
3404                 return -EINVAL;
3405         }
3406
3407         if (btf_type_kflag(t)) {
3408                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3409                 return -EINVAL;
3410         }
3411
3412         btf_verifier_log_type(env, t, NULL);
3413
3414         return meta_needed;
3415 }
3416
3417 static void btf_func_proto_log(struct btf_verifier_env *env,
3418                                const struct btf_type *t)
3419 {
3420         const struct btf_param *args = (const struct btf_param *)(t + 1);
3421         u16 nr_args = btf_type_vlen(t), i;
3422
3423         btf_verifier_log(env, "return=%u args=(", t->type);
3424         if (!nr_args) {
3425                 btf_verifier_log(env, "void");
3426                 goto done;
3427         }
3428
3429         if (nr_args == 1 && !args[0].type) {
3430                 /* Only one vararg */
3431                 btf_verifier_log(env, "vararg");
3432                 goto done;
3433         }
3434
3435         btf_verifier_log(env, "%u %s", args[0].type,
3436                          __btf_name_by_offset(env->btf,
3437                                               args[0].name_off));
3438         for (i = 1; i < nr_args - 1; i++)
3439                 btf_verifier_log(env, ", %u %s", args[i].type,
3440                                  __btf_name_by_offset(env->btf,
3441                                                       args[i].name_off));
3442
3443         if (nr_args > 1) {
3444                 const struct btf_param *last_arg = &args[nr_args - 1];
3445
3446                 if (last_arg->type)
3447                         btf_verifier_log(env, ", %u %s", last_arg->type,
3448                                          __btf_name_by_offset(env->btf,
3449                                                               last_arg->name_off));
3450                 else
3451                         btf_verifier_log(env, ", vararg");
3452         }
3453
3454 done:
3455         btf_verifier_log(env, ")");
3456 }
3457
3458 static struct btf_kind_operations func_proto_ops = {
3459         .check_meta = btf_func_proto_check_meta,
3460         .resolve = btf_df_resolve,
3461         /*
3462          * BTF_KIND_FUNC_PROTO cannot be directly referred by
3463          * a struct's member.
3464          *
3465          * It should be a function pointer instead.
3466          * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3467          *
3468          * Hence, there is no btf_func_check_member().
3469          */
3470         .check_member = btf_df_check_member,
3471         .check_kflag_member = btf_df_check_kflag_member,
3472         .log_details = btf_func_proto_log,
3473         .show = btf_df_show,
3474 };
3475
3476 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3477                                const struct btf_type *t,
3478                                u32 meta_left)
3479 {
3480         if (!t->name_off ||
3481             !btf_name_valid_identifier(env->btf, t->name_off)) {
3482                 btf_verifier_log_type(env, t, "Invalid name");
3483                 return -EINVAL;
3484         }
3485
3486         if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3487                 btf_verifier_log_type(env, t, "Invalid func linkage");
3488                 return -EINVAL;
3489         }
3490
3491         if (btf_type_kflag(t)) {
3492                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3493                 return -EINVAL;
3494         }
3495
3496         btf_verifier_log_type(env, t, NULL);
3497
3498         return 0;
3499 }
3500
3501 static struct btf_kind_operations func_ops = {
3502         .check_meta = btf_func_check_meta,
3503         .resolve = btf_df_resolve,
3504         .check_member = btf_df_check_member,
3505         .check_kflag_member = btf_df_check_kflag_member,
3506         .log_details = btf_ref_type_log,
3507         .show = btf_df_show,
3508 };
3509
3510 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3511                               const struct btf_type *t,
3512                               u32 meta_left)
3513 {
3514         const struct btf_var *var;
3515         u32 meta_needed = sizeof(*var);
3516
3517         if (meta_left < meta_needed) {
3518                 btf_verifier_log_basic(env, t,
3519                                        "meta_left:%u meta_needed:%u",
3520                                        meta_left, meta_needed);
3521                 return -EINVAL;
3522         }
3523
3524         if (btf_type_vlen(t)) {
3525                 btf_verifier_log_type(env, t, "vlen != 0");
3526                 return -EINVAL;
3527         }
3528
3529         if (btf_type_kflag(t)) {
3530                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3531                 return -EINVAL;
3532         }
3533
3534         if (!t->name_off ||
3535             !__btf_name_valid(env->btf, t->name_off)) {
3536                 btf_verifier_log_type(env, t, "Invalid name");
3537                 return -EINVAL;
3538         }
3539
3540         /* A var cannot be in type void */
3541         if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3542                 btf_verifier_log_type(env, t, "Invalid type_id");
3543                 return -EINVAL;
3544         }
3545
3546         var = btf_type_var(t);
3547         if (var->linkage != BTF_VAR_STATIC &&
3548             var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3549                 btf_verifier_log_type(env, t, "Linkage not supported");
3550                 return -EINVAL;
3551         }
3552
3553         btf_verifier_log_type(env, t, NULL);
3554
3555         return meta_needed;
3556 }
3557
3558 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3559 {
3560         const struct btf_var *var = btf_type_var(t);
3561
3562         btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3563 }
3564
3565 static const struct btf_kind_operations var_ops = {
3566         .check_meta             = btf_var_check_meta,
3567         .resolve                = btf_var_resolve,
3568         .check_member           = btf_df_check_member,
3569         .check_kflag_member     = btf_df_check_kflag_member,
3570         .log_details            = btf_var_log,
3571         .show                   = btf_var_show,
3572 };
3573
3574 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3575                                   const struct btf_type *t,
3576                                   u32 meta_left)
3577 {
3578         const struct btf_var_secinfo *vsi;
3579         u64 last_vsi_end_off = 0, sum = 0;
3580         u32 i, meta_needed;
3581
3582         meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3583         if (meta_left < meta_needed) {
3584                 btf_verifier_log_basic(env, t,
3585                                        "meta_left:%u meta_needed:%u",
3586                                        meta_left, meta_needed);
3587                 return -EINVAL;
3588         }
3589
3590         if (!t->size) {
3591                 btf_verifier_log_type(env, t, "size == 0");
3592                 return -EINVAL;
3593         }
3594
3595         if (btf_type_kflag(t)) {
3596                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3597                 return -EINVAL;
3598         }
3599
3600         if (!t->name_off ||
3601             !btf_name_valid_section(env->btf, t->name_off)) {
3602                 btf_verifier_log_type(env, t, "Invalid name");
3603                 return -EINVAL;
3604         }
3605
3606         btf_verifier_log_type(env, t, NULL);
3607
3608         for_each_vsi(i, t, vsi) {
3609                 /* A var cannot be in type void */
3610                 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
3611                         btf_verifier_log_vsi(env, t, vsi,
3612                                              "Invalid type_id");
3613                         return -EINVAL;
3614                 }
3615
3616                 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
3617                         btf_verifier_log_vsi(env, t, vsi,
3618                                              "Invalid offset");
3619                         return -EINVAL;
3620                 }
3621
3622                 if (!vsi->size || vsi->size > t->size) {
3623                         btf_verifier_log_vsi(env, t, vsi,
3624                                              "Invalid size");
3625                         return -EINVAL;
3626                 }
3627
3628                 last_vsi_end_off = vsi->offset + vsi->size;
3629                 if (last_vsi_end_off > t->size) {
3630                         btf_verifier_log_vsi(env, t, vsi,
3631                                              "Invalid offset+size");
3632                         return -EINVAL;
3633                 }
3634
3635                 btf_verifier_log_vsi(env, t, vsi, NULL);
3636                 sum += vsi->size;
3637         }
3638
3639         if (t->size < sum) {
3640                 btf_verifier_log_type(env, t, "Invalid btf_info size");
3641                 return -EINVAL;
3642         }
3643
3644         return meta_needed;
3645 }
3646
3647 static int btf_datasec_resolve(struct btf_verifier_env *env,
3648                                const struct resolve_vertex *v)
3649 {
3650         const struct btf_var_secinfo *vsi;
3651         struct btf *btf = env->btf;
3652         u16 i;
3653
3654         env->resolve_mode = RESOLVE_TBD;
3655         for_each_vsi_from(i, v->next_member, v->t, vsi) {
3656                 u32 var_type_id = vsi->type, type_id, type_size = 0;
3657                 const struct btf_type *var_type = btf_type_by_id(env->btf,
3658                                                                  var_type_id);
3659                 if (!var_type || !btf_type_is_var(var_type)) {
3660                         btf_verifier_log_vsi(env, v->t, vsi,
3661                                              "Not a VAR kind member");
3662                         return -EINVAL;
3663                 }
3664
3665                 if (!env_type_is_resolve_sink(env, var_type) &&
3666                     !env_type_is_resolved(env, var_type_id)) {
3667                         env_stack_set_next_member(env, i + 1);
3668                         return env_stack_push(env, var_type, var_type_id);
3669                 }
3670
3671                 type_id = var_type->type;
3672                 if (!btf_type_id_size(btf, &type_id, &type_size)) {
3673                         btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
3674                         return -EINVAL;
3675                 }
3676
3677                 if (vsi->size < type_size) {
3678                         btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
3679                         return -EINVAL;
3680                 }
3681         }
3682
3683         env_stack_pop_resolved(env, 0, 0);
3684         return 0;
3685 }
3686
3687 static void btf_datasec_log(struct btf_verifier_env *env,
3688                             const struct btf_type *t)
3689 {
3690         btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3691 }
3692
3693 static void btf_datasec_show(const struct btf *btf,
3694                              const struct btf_type *t, u32 type_id,
3695                              void *data, u8 bits_offset,
3696                              struct btf_show *show)
3697 {
3698         const struct btf_var_secinfo *vsi;
3699         const struct btf_type *var;
3700         u32 i;
3701
3702         if (!btf_show_start_type(show, t, type_id, data))
3703                 return;
3704
3705         btf_show_type_value(show, "section (\"%s\") = {",
3706                             __btf_name_by_offset(btf, t->name_off));
3707         for_each_vsi(i, t, vsi) {
3708                 var = btf_type_by_id(btf, vsi->type);
3709                 if (i)
3710                         btf_show(show, ",");
3711                 btf_type_ops(var)->show(btf, var, vsi->type,
3712                                         data + vsi->offset, bits_offset, show);
3713         }
3714         btf_show_end_type(show);
3715 }
3716
3717 static const struct btf_kind_operations datasec_ops = {
3718         .check_meta             = btf_datasec_check_meta,
3719         .resolve                = btf_datasec_resolve,
3720         .check_member           = btf_df_check_member,
3721         .check_kflag_member     = btf_df_check_kflag_member,
3722         .log_details            = btf_datasec_log,
3723         .show                   = btf_datasec_show,
3724 };
3725
3726 static s32 btf_float_check_meta(struct btf_verifier_env *env,
3727                                 const struct btf_type *t,
3728                                 u32 meta_left)
3729 {
3730         if (btf_type_vlen(t)) {
3731                 btf_verifier_log_type(env, t, "vlen != 0");
3732                 return -EINVAL;
3733         }
3734
3735         if (btf_type_kflag(t)) {
3736                 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3737                 return -EINVAL;
3738         }
3739
3740         if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
3741             t->size != 16) {
3742                 btf_verifier_log_type(env, t, "Invalid type_size");
3743                 return -EINVAL;
3744         }
3745
3746         btf_verifier_log_type(env, t, NULL);
3747
3748         return 0;
3749 }
3750
3751 static int btf_float_check_member(struct btf_verifier_env *env,
3752                                   const struct btf_type *struct_type,
3753                                   const struct btf_member *member,
3754                                   const struct btf_type *member_type)
3755 {
3756         u64 start_offset_bytes;
3757         u64 end_offset_bytes;
3758         u64 misalign_bits;
3759         u64 align_bytes;
3760         u64 align_bits;
3761
3762         /* Different architectures have different alignment requirements, so
3763          * here we check only for the reasonable minimum. This way we ensure
3764          * that types after CO-RE can pass the kernel BTF verifier.
3765          */
3766         align_bytes = min_t(u64, sizeof(void *), member_type->size);
3767         align_bits = align_bytes * BITS_PER_BYTE;
3768         div64_u64_rem(member->offset, align_bits, &misalign_bits);
3769         if (misalign_bits) {
3770                 btf_verifier_log_member(env, struct_type, member,
3771                                         "Member is not properly aligned");
3772                 return -EINVAL;
3773         }
3774
3775         start_offset_bytes = member->offset / BITS_PER_BYTE;
3776         end_offset_bytes = start_offset_bytes + member_type->size;
3777         if (end_offset_bytes > struct_type->size) {
3778                 btf_verifier_log_member(env, struct_type, member,
3779                                         "Member exceeds struct_size");
3780                 return -EINVAL;
3781         }
3782
3783         return 0;
3784 }
3785
3786 static void btf_float_log(struct btf_verifier_env *env,
3787                           const struct btf_type *t)
3788 {
3789         btf_verifier_log(env, "size=%u", t->size);
3790 }
3791
3792 static const struct btf_kind_operations float_ops = {
3793         .check_meta = btf_float_check_meta,
3794         .resolve = btf_df_resolve,
3795         .check_member = btf_float_check_member,
3796         .check_kflag_member = btf_generic_check_kflag_member,
3797         .log_details = btf_float_log,
3798         .show = btf_df_show,
3799 };
3800
3801 static int btf_func_proto_check(struct btf_verifier_env *env,
3802                                 const struct btf_type *t)
3803 {
3804         const struct btf_type *ret_type;
3805         const struct btf_param *args;
3806         const struct btf *btf;
3807         u16 nr_args, i;
3808         int err;
3809
3810         btf = env->btf;
3811         args = (const struct btf_param *)(t + 1);
3812         nr_args = btf_type_vlen(t);
3813
3814         /* Check func return type which could be "void" (t->type == 0) */
3815         if (t->type) {
3816                 u32 ret_type_id = t->type;
3817
3818                 ret_type = btf_type_by_id(btf, ret_type_id);
3819                 if (!ret_type) {
3820                         btf_verifier_log_type(env, t, "Invalid return type");
3821                         return -EINVAL;
3822                 }
3823
3824                 if (btf_type_needs_resolve(ret_type) &&
3825                     !env_type_is_resolved(env, ret_type_id)) {
3826                         err = btf_resolve(env, ret_type, ret_type_id);
3827                         if (err)
3828                                 return err;
3829                 }
3830
3831                 /* Ensure the return type is a type that has a size */
3832                 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
3833                         btf_verifier_log_type(env, t, "Invalid return type");
3834                         return -EINVAL;
3835                 }
3836         }
3837
3838         if (!nr_args)
3839                 return 0;
3840
3841         /* Last func arg type_id could be 0 if it is a vararg */
3842         if (!args[nr_args - 1].type) {
3843                 if (args[nr_args - 1].name_off) {
3844                         btf_verifier_log_type(env, t, "Invalid arg#%u",
3845                                               nr_args);
3846                         return -EINVAL;
3847                 }
3848                 nr_args--;
3849         }
3850
3851         err = 0;
3852         for (i = 0; i < nr_args; i++) {
3853                 const struct btf_type *arg_type;
3854                 u32 arg_type_id;
3855
3856                 arg_type_id = args[i].type;
3857                 arg_type = btf_type_by_id(btf, arg_type_id);
3858                 if (!arg_type) {
3859                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3860                         err = -EINVAL;
3861                         break;
3862                 }
3863
3864                 if (btf_type_is_resolve_source_only(arg_type)) {
3865                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3866                         return -EINVAL;
3867                 }
3868
3869                 if (args[i].name_off &&
3870                     (!btf_name_offset_valid(btf, args[i].name_off) ||
3871                      !btf_name_valid_identifier(btf, args[i].name_off))) {
3872                         btf_verifier_log_type(env, t,
3873                                               "Invalid arg#%u", i + 1);
3874                         err = -EINVAL;
3875                         break;
3876                 }
3877
3878                 if (btf_type_needs_resolve(arg_type) &&
3879                     !env_type_is_resolved(env, arg_type_id)) {
3880                         err = btf_resolve(env, arg_type, arg_type_id);
3881                         if (err)
3882                                 break;
3883                 }
3884
3885                 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
3886                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3887                         err = -EINVAL;
3888                         break;
3889                 }
3890         }
3891
3892         return err;
3893 }
3894
3895 static int btf_func_check(struct btf_verifier_env *env,
3896                           const struct btf_type *t)
3897 {
3898         const struct btf_type *proto_type;
3899         const struct btf_param *args;
3900         const struct btf *btf;
3901         u16 nr_args, i;
3902
3903         btf = env->btf;
3904         proto_type = btf_type_by_id(btf, t->type);
3905
3906         if (!proto_type || !btf_type_is_func_proto(proto_type)) {
3907                 btf_verifier_log_type(env, t, "Invalid type_id");
3908                 return -EINVAL;
3909         }
3910
3911         args = (const struct btf_param *)(proto_type + 1);
3912         nr_args = btf_type_vlen(proto_type);
3913         for (i = 0; i < nr_args; i++) {
3914                 if (!args[i].name_off && args[i].type) {
3915                         btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3916                         return -EINVAL;
3917                 }
3918         }
3919
3920         return 0;
3921 }
3922
3923 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
3924         [BTF_KIND_INT] = &int_ops,
3925         [BTF_KIND_PTR] = &ptr_ops,
3926         [BTF_KIND_ARRAY] = &array_ops,
3927         [BTF_KIND_STRUCT] = &struct_ops,
3928         [BTF_KIND_UNION] = &struct_ops,
3929         [BTF_KIND_ENUM] = &enum_ops,
3930         [BTF_KIND_FWD] = &fwd_ops,
3931         [BTF_KIND_TYPEDEF] = &modifier_ops,
3932         [BTF_KIND_VOLATILE] = &modifier_ops,
3933         [BTF_KIND_CONST] = &modifier_ops,
3934         [BTF_KIND_RESTRICT] = &modifier_ops,
3935         [BTF_KIND_FUNC] = &func_ops,
3936         [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
3937         [BTF_KIND_VAR] = &var_ops,
3938         [BTF_KIND_DATASEC] = &datasec_ops,
3939         [BTF_KIND_FLOAT] = &float_ops,
3940 };
3941
3942 static s32 btf_check_meta(struct btf_verifier_env *env,
3943                           const struct btf_type *t,
3944                           u32 meta_left)
3945 {
3946         u32 saved_meta_left = meta_left;
3947         s32 var_meta_size;
3948
3949         if (meta_left < sizeof(*t)) {
3950                 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
3951                                  env->log_type_id, meta_left, sizeof(*t));
3952                 return -EINVAL;
3953         }
3954         meta_left -= sizeof(*t);
3955
3956         if (t->info & ~BTF_INFO_MASK) {
3957                 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
3958                                  env->log_type_id, t->info);
3959                 return -EINVAL;
3960         }
3961
3962         if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
3963             BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
3964                 btf_verifier_log(env, "[%u] Invalid kind:%u",
3965                                  env->log_type_id, BTF_INFO_KIND(t->info));
3966                 return -EINVAL;
3967         }
3968
3969         if (!btf_name_offset_valid(env->btf, t->name_off)) {
3970                 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
3971                                  env->log_type_id, t->name_off);
3972                 return -EINVAL;
3973         }
3974
3975         var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
3976         if (var_meta_size < 0)
3977                 return var_meta_size;
3978
3979         meta_left -= var_meta_size;
3980
3981         return saved_meta_left - meta_left;
3982 }
3983
3984 static int btf_check_all_metas(struct btf_verifier_env *env)
3985 {
3986         struct btf *btf = env->btf;
3987         struct btf_header *hdr;
3988         void *cur, *end;
3989
3990         hdr = &btf->hdr;
3991         cur = btf->nohdr_data + hdr->type_off;
3992         end = cur + hdr->type_len;
3993
3994         env->log_type_id = btf->base_btf ? btf->start_id : 1;
3995         while (cur < end) {
3996                 struct btf_type *t = cur;
3997                 s32 meta_size;
3998
3999                 meta_size = btf_check_meta(env, t, end - cur);
4000                 if (meta_size < 0)
4001                         return meta_size;
4002
4003                 btf_add_type(env, t);
4004                 cur += meta_size;
4005                 env->log_type_id++;
4006         }
4007
4008         return 0;
4009 }
4010
4011 static bool btf_resolve_valid(struct btf_verifier_env *env,
4012                               const struct btf_type *t,
4013                               u32 type_id)
4014 {
4015         struct btf *btf = env->btf;
4016
4017         if (!env_type_is_resolved(env, type_id))
4018                 return false;
4019
4020         if (btf_type_is_struct(t) || btf_type_is_datasec(t))
4021                 return !btf_resolved_type_id(btf, type_id) &&
4022                        !btf_resolved_type_size(btf, type_id);
4023
4024         if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
4025             btf_type_is_var(t)) {
4026                 t = btf_type_id_resolve(btf, &type_id);
4027                 return t &&
4028                        !btf_type_is_modifier(t) &&
4029                        !btf_type_is_var(t) &&
4030                        !btf_type_is_datasec(t);
4031         }
4032
4033         if (btf_type_is_array(t)) {
4034                 const struct btf_array *array = btf_type_array(t);
4035                 const struct btf_type *elem_type;
4036                 u32 elem_type_id = array->type;
4037                 u32 elem_size;
4038
4039                 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
4040                 return elem_type && !btf_type_is_modifier(elem_type) &&
4041                         (array->nelems * elem_size ==
4042                          btf_resolved_type_size(btf, type_id));
4043         }
4044
4045         return false;
4046 }
4047
4048 static int btf_resolve(struct btf_verifier_env *env,
4049                        const struct btf_type *t, u32 type_id)
4050 {
4051         u32 save_log_type_id = env->log_type_id;
4052         const struct resolve_vertex *v;
4053         int err = 0;
4054
4055         env->resolve_mode = RESOLVE_TBD;
4056         env_stack_push(env, t, type_id);
4057         while (!err && (v = env_stack_peak(env))) {
4058                 env->log_type_id = v->type_id;
4059                 err = btf_type_ops(v->t)->resolve(env, v);
4060         }
4061
4062         env->log_type_id = type_id;
4063         if (err == -E2BIG) {
4064                 btf_verifier_log_type(env, t,
4065                                       "Exceeded max resolving depth:%u",
4066                                       MAX_RESOLVE_DEPTH);
4067         } else if (err == -EEXIST) {
4068                 btf_verifier_log_type(env, t, "Loop detected");
4069         }
4070
4071         /* Final sanity check */
4072         if (!err && !btf_resolve_valid(env, t, type_id)) {
4073                 btf_verifier_log_type(env, t, "Invalid resolve state");
4074                 err = -EINVAL;
4075         }
4076
4077         env->log_type_id = save_log_type_id;
4078         return err;
4079 }
4080
4081 static int btf_check_all_types(struct btf_verifier_env *env)
4082 {
4083         struct btf *btf = env->btf;
4084         const struct btf_type *t;
4085         u32 type_id, i;
4086         int err;
4087
4088         err = env_resolve_init(env);
4089         if (err)
4090                 return err;
4091
4092         env->phase++;
4093         for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
4094                 type_id = btf->start_id + i;
4095                 t = btf_type_by_id(btf, type_id);
4096
4097                 env->log_type_id = type_id;
4098                 if (btf_type_needs_resolve(t) &&
4099                     !env_type_is_resolved(env, type_id)) {
4100                         err = btf_resolve(env, t, type_id);
4101                         if (err)
4102                                 return err;
4103                 }
4104
4105                 if (btf_type_is_func_proto(t)) {
4106                         err = btf_func_proto_check(env, t);
4107                         if (err)
4108                                 return err;
4109                 }
4110
4111                 if (btf_type_is_func(t)) {
4112                         err = btf_func_check(env, t);
4113                         if (err)
4114                                 return err;
4115                 }
4116         }
4117
4118         return 0;
4119 }
4120
4121 static int btf_parse_type_sec(struct btf_verifier_env *env)
4122 {
4123         const struct btf_header *hdr = &env->btf->hdr;
4124         int err;
4125
4126         /* Type section must align to 4 bytes */
4127         if (hdr->type_off & (sizeof(u32) - 1)) {
4128                 btf_verifier_log(env, "Unaligned type_off");
4129                 return -EINVAL;
4130         }
4131
4132         if (!env->btf->base_btf && !hdr->type_len) {
4133                 btf_verifier_log(env, "No type found");
4134                 return -EINVAL;
4135         }
4136
4137         err = btf_check_all_metas(env);
4138         if (err)
4139                 return err;
4140
4141         return btf_check_all_types(env);
4142 }
4143
4144 static int btf_parse_str_sec(struct btf_verifier_env *env)
4145 {
4146         const struct btf_header *hdr;
4147         struct btf *btf = env->btf;
4148         const char *start, *end;
4149
4150         hdr = &btf->hdr;
4151         start = btf->nohdr_data + hdr->str_off;
4152         end = start + hdr->str_len;
4153
4154         if (end != btf->data + btf->data_size) {
4155                 btf_verifier_log(env, "String section is not at the end");
4156                 return -EINVAL;
4157         }
4158
4159         btf->strings = start;
4160
4161         if (btf->base_btf && !hdr->str_len)
4162                 return 0;
4163         if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
4164                 btf_verifier_log(env, "Invalid string section");
4165                 return -EINVAL;
4166         }
4167         if (!btf->base_btf && start[0]) {
4168                 btf_verifier_log(env, "Invalid string section");
4169                 return -EINVAL;
4170         }
4171
4172         return 0;
4173 }
4174
4175 static const size_t btf_sec_info_offset[] = {
4176         offsetof(struct btf_header, type_off),
4177         offsetof(struct btf_header, str_off),
4178 };
4179
4180 static int btf_sec_info_cmp(const void *a, const void *b)
4181 {
4182         const struct btf_sec_info *x = a;
4183         const struct btf_sec_info *y = b;
4184
4185         return (int)(x->off - y->off) ? : (int)(x->len - y->len);
4186 }
4187
4188 static int btf_check_sec_info(struct btf_verifier_env *env,
4189                               u32 btf_data_size)
4190 {
4191         struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
4192         u32 total, expected_total, i;
4193         const struct btf_header *hdr;
4194         const struct btf *btf;
4195
4196         btf = env->btf;
4197         hdr = &btf->hdr;
4198
4199         /* Populate the secs from hdr */
4200         for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
4201                 secs[i] = *(struct btf_sec_info *)((void *)hdr +
4202                                                    btf_sec_info_offset[i]);
4203
4204         sort(secs, ARRAY_SIZE(btf_sec_info_offset),
4205              sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
4206
4207         /* Check for gaps and overlap among sections */
4208         total = 0;
4209         expected_total = btf_data_size - hdr->hdr_len;
4210         for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
4211                 if (expected_total < secs[i].off) {
4212                         btf_verifier_log(env, "Invalid section offset");
4213                         return -EINVAL;
4214                 }
4215                 if (total < secs[i].off) {
4216                         /* gap */
4217                         btf_verifier_log(env, "Unsupported section found");
4218                         return -EINVAL;
4219                 }
4220                 if (total > secs[i].off) {
4221                         btf_verifier_log(env, "Section overlap found");
4222                         return -EINVAL;
4223                 }
4224                 if (expected_total - total < secs[i].len) {
4225                         btf_verifier_log(env,
4226                                          "Total section length too long");
4227                         return -EINVAL;
4228                 }
4229                 total += secs[i].len;
4230         }
4231
4232         /* There is data other than hdr and known sections */
4233         if (expected_total != total) {
4234                 btf_verifier_log(env, "Unsupported section found");
4235                 return -EINVAL;
4236         }
4237
4238         return 0;
4239 }
4240
4241 static int btf_parse_hdr(struct btf_verifier_env *env)
4242 {
4243         u32 hdr_len, hdr_copy, btf_data_size;
4244         const struct btf_header *hdr;
4245         struct btf *btf;
4246         int err;
4247
4248         btf = env->btf;
4249         btf_data_size = btf->data_size;
4250
4251         if (btf_data_size <
4252             offsetof(struct btf_header, hdr_len) + sizeof(hdr->hdr_len)) {
4253                 btf_verifier_log(env, "hdr_len not found");
4254                 return -EINVAL;
4255         }
4256
4257         hdr = btf->data;
4258         hdr_len = hdr->hdr_len;
4259         if (btf_data_size < hdr_len) {
4260                 btf_verifier_log(env, "btf_header not found");
4261                 return -EINVAL;
4262         }
4263
4264         /* Ensure the unsupported header fields are zero */
4265         if (hdr_len > sizeof(btf->hdr)) {
4266                 u8 *expected_zero = btf->data + sizeof(btf->hdr);
4267                 u8 *end = btf->data + hdr_len;
4268
4269                 for (; expected_zero < end; expected_zero++) {
4270                         if (*expected_zero) {
4271                                 btf_verifier_log(env, "Unsupported btf_header");
4272                                 return -E2BIG;
4273                         }
4274                 }
4275         }
4276
4277         hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4278         memcpy(&btf->hdr, btf->data, hdr_copy);
4279
4280         hdr = &btf->hdr;
4281
4282         btf_verifier_log_hdr(env, btf_data_size);
4283
4284         if (hdr->magic != BTF_MAGIC) {
4285                 btf_verifier_log(env, "Invalid magic");
4286                 return -EINVAL;
4287         }
4288
4289         if (hdr->version != BTF_VERSION) {
4290                 btf_verifier_log(env, "Unsupported version");
4291                 return -ENOTSUPP;
4292         }
4293
4294         if (hdr->flags) {
4295                 btf_verifier_log(env, "Unsupported flags");
4296                 return -ENOTSUPP;
4297         }
4298
4299         if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
4300                 btf_verifier_log(env, "No data");
4301                 return -EINVAL;
4302         }
4303
4304         err = btf_check_sec_info(env, btf_data_size);
4305         if (err)
4306                 return err;
4307
4308         return 0;
4309 }
4310
4311 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
4312                              u32 log_level, char __user *log_ubuf, u32 log_size)
4313 {
4314         struct btf_verifier_env *env = NULL;
4315         struct bpf_verifier_log *log;
4316         struct btf *btf = NULL;
4317         u8 *data;
4318         int err;
4319
4320         if (btf_data_size > BTF_MAX_SIZE)
4321                 return ERR_PTR(-E2BIG);
4322
4323         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4324         if (!env)
4325                 return ERR_PTR(-ENOMEM);
4326
4327         log = &env->log;
4328         if (log_level || log_ubuf || log_size) {
4329                 /* user requested verbose verifier output
4330                  * and supplied buffer to store the verification trace
4331                  */
4332                 log->level = log_level;
4333                 log->ubuf = log_ubuf;
4334                 log->len_total = log_size;
4335
4336                 /* log attributes have to be sane */
4337                 if (!bpf_verifier_log_attr_valid(log)) {
4338                         err = -EINVAL;
4339                         goto errout;
4340                 }
4341         }
4342
4343         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4344         if (!btf) {
4345                 err = -ENOMEM;
4346                 goto errout;
4347         }
4348         env->btf = btf;
4349
4350         data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4351         if (!data) {
4352                 err = -ENOMEM;
4353                 goto errout;
4354         }
4355
4356         btf->data = data;
4357         btf->data_size = btf_data_size;
4358
4359         if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
4360                 err = -EFAULT;
4361                 goto errout;
4362         }
4363
4364         err = btf_parse_hdr(env);
4365         if (err)
4366                 goto errout;
4367
4368         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4369
4370         err = btf_parse_str_sec(env);
4371         if (err)
4372                 goto errout;
4373
4374         err = btf_parse_type_sec(env);
4375         if (err)
4376                 goto errout;
4377
4378         if (log->level && bpf_verifier_log_full(log)) {
4379                 err = -ENOSPC;
4380                 goto errout;
4381         }
4382
4383         btf_verifier_env_free(env);
4384         refcount_set(&btf->refcnt, 1);
4385         return btf;
4386
4387 errout:
4388         btf_verifier_env_free(env);
4389         if (btf)
4390                 btf_free(btf);
4391         return ERR_PTR(err);
4392 }
4393
4394 extern char __weak __start_BTF[];
4395 extern char __weak __stop_BTF[];
4396 extern struct btf *btf_vmlinux;
4397
4398 #define BPF_MAP_TYPE(_id, _ops)
4399 #define BPF_LINK_TYPE(_id, _name)
4400 static union {
4401         struct bpf_ctx_convert {
4402 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4403         prog_ctx_type _id##_prog; \
4404         kern_ctx_type _id##_kern;
4405 #include <linux/bpf_types.h>
4406 #undef BPF_PROG_TYPE
4407         } *__t;
4408         /* 't' is written once under lock. Read many times. */
4409         const struct btf_type *t;
4410 } bpf_ctx_convert;
4411 enum {
4412 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4413         __ctx_convert##_id,
4414 #include <linux/bpf_types.h>
4415 #undef BPF_PROG_TYPE
4416         __ctx_convert_unused, /* to avoid empty enum in extreme .config */
4417 };
4418 static u8 bpf_ctx_convert_map[] = {
4419 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4420         [_id] = __ctx_convert##_id,
4421 #include <linux/bpf_types.h>
4422 #undef BPF_PROG_TYPE
4423         0, /* avoid empty array */
4424 };
4425 #undef BPF_MAP_TYPE
4426 #undef BPF_LINK_TYPE
4427
4428 static const struct btf_member *
4429 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
4430                       const struct btf_type *t, enum bpf_prog_type prog_type,
4431                       int arg)
4432 {
4433         const struct btf_type *conv_struct;
4434         const struct btf_type *ctx_struct;
4435         const struct btf_member *ctx_type;
4436         const char *tname, *ctx_tname;
4437
4438         conv_struct = bpf_ctx_convert.t;
4439         if (!conv_struct) {
4440                 bpf_log(log, "btf_vmlinux is malformed\n");
4441                 return NULL;
4442         }
4443         t = btf_type_by_id(btf, t->type);
4444         while (btf_type_is_modifier(t))
4445                 t = btf_type_by_id(btf, t->type);
4446         if (!btf_type_is_struct(t)) {
4447                 /* Only pointer to struct is supported for now.
4448                  * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4449                  * is not supported yet.
4450                  * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
4451                  */
4452                 return NULL;
4453         }
4454         tname = btf_name_by_offset(btf, t->name_off);
4455         if (!tname) {
4456                 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
4457                 return NULL;
4458         }
4459         /* prog_type is valid bpf program type. No need for bounds check. */
4460         ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
4461         /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
4462          * Like 'struct __sk_buff'
4463          */
4464         ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
4465         if (!ctx_struct)
4466                 /* should not happen */
4467                 return NULL;
4468 again:
4469         ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
4470         if (!ctx_tname) {
4471                 /* should not happen */
4472                 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
4473                 return NULL;
4474         }
4475         /* only compare that prog's ctx type name is the same as
4476          * kernel expects. No need to compare field by field.
4477          * It's ok for bpf prog to do:
4478          * struct __sk_buff {};
4479          * int socket_filter_bpf_prog(struct __sk_buff *skb)
4480          * { // no fields of skb are ever used }
4481          */
4482         if (strcmp(ctx_tname, tname)) {
4483                 /* bpf_user_pt_regs_t is a typedef, so resolve it to
4484                  * underlying struct and check name again
4485                  */
4486                 if (!btf_type_is_modifier(ctx_struct))
4487                         return NULL;
4488                 while (btf_type_is_modifier(ctx_struct))
4489                         ctx_struct = btf_type_by_id(btf_vmlinux, ctx_struct->type);
4490                 goto again;
4491         }
4492         return ctx_type;
4493 }
4494
4495 static const struct bpf_map_ops * const btf_vmlinux_map_ops[] = {
4496 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
4497 #define BPF_LINK_TYPE(_id, _name)
4498 #define BPF_MAP_TYPE(_id, _ops) \
4499         [_id] = &_ops,
4500 #include <linux/bpf_types.h>
4501 #undef BPF_PROG_TYPE
4502 #undef BPF_LINK_TYPE
4503 #undef BPF_MAP_TYPE
4504 };
4505
4506 static int btf_vmlinux_map_ids_init(const struct btf *btf,
4507                                     struct bpf_verifier_log *log)
4508 {
4509         const struct bpf_map_ops *ops;
4510         int i, btf_id;
4511
4512         for (i = 0; i < ARRAY_SIZE(btf_vmlinux_map_ops); ++i) {
4513                 ops = btf_vmlinux_map_ops[i];
4514                 if (!ops || (!ops->map_btf_name && !ops->map_btf_id))
4515                         continue;
4516                 if (!ops->map_btf_name || !ops->map_btf_id) {
4517                         bpf_log(log, "map type %d is misconfigured\n", i);
4518                         return -EINVAL;
4519                 }
4520                 btf_id = btf_find_by_name_kind(btf, ops->map_btf_name,
4521                                                BTF_KIND_STRUCT);
4522                 if (btf_id < 0)
4523                         return btf_id;
4524                 *ops->map_btf_id = btf_id;
4525         }
4526
4527         return 0;
4528 }
4529
4530 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
4531                                      struct btf *btf,
4532                                      const struct btf_type *t,
4533                                      enum bpf_prog_type prog_type,
4534                                      int arg)
4535 {
4536         const struct btf_member *prog_ctx_type, *kern_ctx_type;
4537
4538         prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
4539         if (!prog_ctx_type)
4540                 return -ENOENT;
4541         kern_ctx_type = prog_ctx_type + 1;
4542         return kern_ctx_type->type;
4543 }
4544
4545 BTF_ID_LIST(bpf_ctx_convert_btf_id)
4546 BTF_ID(struct, bpf_ctx_convert)
4547
4548 struct btf *btf_parse_vmlinux(void)
4549 {
4550         struct btf_verifier_env *env = NULL;
4551         struct bpf_verifier_log *log;
4552         struct btf *btf = NULL;
4553         int err;
4554
4555         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4556         if (!env)
4557                 return ERR_PTR(-ENOMEM);
4558
4559         log = &env->log;
4560         log->level = BPF_LOG_KERNEL;
4561
4562         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4563         if (!btf) {
4564                 err = -ENOMEM;
4565                 goto errout;
4566         }
4567         env->btf = btf;
4568
4569         btf->data = __start_BTF;
4570         btf->data_size = __stop_BTF - __start_BTF;
4571         btf->kernel_btf = true;
4572         snprintf(btf->name, sizeof(btf->name), "vmlinux");
4573
4574         err = btf_parse_hdr(env);
4575         if (err)
4576                 goto errout;
4577
4578         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4579
4580         err = btf_parse_str_sec(env);
4581         if (err)
4582                 goto errout;
4583
4584         err = btf_check_all_metas(env);
4585         if (err)
4586                 goto errout;
4587
4588         /* btf_parse_vmlinux() runs under bpf_verifier_lock */
4589         bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
4590
4591         /* find bpf map structs for map_ptr access checking */
4592         err = btf_vmlinux_map_ids_init(btf, log);
4593         if (err < 0)
4594                 goto errout;
4595
4596         bpf_struct_ops_init(btf, log);
4597
4598         refcount_set(&btf->refcnt, 1);
4599
4600         err = btf_alloc_id(btf);
4601         if (err)
4602                 goto errout;
4603
4604         btf_verifier_env_free(env);
4605         return btf;
4606
4607 errout:
4608         btf_verifier_env_free(env);
4609         if (btf) {
4610                 kvfree(btf->types);
4611                 kfree(btf);
4612         }
4613         return ERR_PTR(err);
4614 }
4615
4616 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
4617
4618 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
4619 {
4620         struct btf_verifier_env *env = NULL;
4621         struct bpf_verifier_log *log;
4622         struct btf *btf = NULL, *base_btf;
4623         int err;
4624
4625         base_btf = bpf_get_btf_vmlinux();
4626         if (IS_ERR(base_btf))
4627                 return base_btf;
4628         if (!base_btf)
4629                 return ERR_PTR(-EINVAL);
4630
4631         env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4632         if (!env)
4633                 return ERR_PTR(-ENOMEM);
4634
4635         log = &env->log;
4636         log->level = BPF_LOG_KERNEL;
4637
4638         btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4639         if (!btf) {
4640                 err = -ENOMEM;
4641                 goto errout;
4642         }
4643         env->btf = btf;
4644
4645         btf->base_btf = base_btf;
4646         btf->start_id = base_btf->nr_types;
4647         btf->start_str_off = base_btf->hdr.str_len;
4648         btf->kernel_btf = true;
4649         snprintf(btf->name, sizeof(btf->name), "%s", module_name);
4650
4651         btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
4652         if (!btf->data) {
4653                 err = -ENOMEM;
4654                 goto errout;
4655         }
4656         memcpy(btf->data, data, data_size);
4657         btf->data_size = data_size;
4658
4659         err = btf_parse_hdr(env);
4660         if (err)
4661                 goto errout;
4662
4663         btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4664
4665         err = btf_parse_str_sec(env);
4666         if (err)
4667                 goto errout;
4668
4669         err = btf_check_all_metas(env);
4670         if (err)
4671                 goto errout;
4672
4673         btf_verifier_env_free(env);
4674         refcount_set(&btf->refcnt, 1);
4675         return btf;
4676
4677 errout:
4678         btf_verifier_env_free(env);
4679         if (btf) {
4680                 kvfree(btf->data);
4681                 kvfree(btf->types);
4682                 kfree(btf);
4683         }
4684         return ERR_PTR(err);
4685 }
4686
4687 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
4688
4689 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
4690 {
4691         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4692
4693         if (tgt_prog)
4694                 return tgt_prog->aux->btf;
4695         else
4696                 return prog->aux->attach_btf;
4697 }
4698
4699 static bool is_string_ptr(struct btf *btf, const struct btf_type *t)
4700 {
4701         /* t comes in already as a pointer */
4702         t = btf_type_by_id(btf, t->type);
4703
4704         /* allow const */
4705         if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
4706                 t = btf_type_by_id(btf, t->type);
4707
4708         /* char, signed char, unsigned char */
4709         return btf_type_is_int(t) && t->size == 1;
4710 }
4711
4712 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
4713                     const struct bpf_prog *prog,
4714                     struct bpf_insn_access_aux *info)
4715 {
4716         const struct btf_type *t = prog->aux->attach_func_proto;
4717         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4718         struct btf *btf = bpf_prog_get_target_btf(prog);
4719         const char *tname = prog->aux->attach_func_name;
4720         struct bpf_verifier_log *log = info->log;
4721         const struct btf_param *args;
4722         u32 nr_args, arg;
4723         int i, ret;
4724
4725         if (off % 8) {
4726                 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
4727                         tname, off);
4728                 return false;
4729         }
4730         arg = off / 8;
4731         args = (const struct btf_param *)(t + 1);
4732         /* if (t == NULL) Fall back to default BPF prog with
4733          * MAX_BPF_FUNC_REG_ARGS u64 arguments.
4734          */
4735         nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
4736         if (prog->aux->attach_btf_trace) {
4737                 /* skip first 'void *__data' argument in btf_trace_##name typedef */
4738                 args++;
4739                 nr_args--;
4740         }
4741
4742         if (arg > nr_args) {
4743                 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4744                         tname, arg + 1);
4745                 return false;
4746         }
4747
4748         if (arg == nr_args) {
4749                 switch (prog->expected_attach_type) {
4750                 case BPF_LSM_MAC:
4751                 case BPF_TRACE_FEXIT:
4752                         /* When LSM programs are attached to void LSM hooks
4753                          * they use FEXIT trampolines and when attached to
4754                          * int LSM hooks, they use MODIFY_RETURN trampolines.
4755                          *
4756                          * While the LSM programs are BPF_MODIFY_RETURN-like
4757                          * the check:
4758                          *
4759                          *      if (ret_type != 'int')
4760                          *              return -EINVAL;
4761                          *
4762                          * is _not_ done here. This is still safe as LSM hooks
4763                          * have only void and int return types.
4764                          */
4765                         if (!t)
4766                                 return true;
4767                         t = btf_type_by_id(btf, t->type);
4768                         break;
4769                 case BPF_MODIFY_RETURN:
4770                         /* For now the BPF_MODIFY_RETURN can only be attached to
4771                          * functions that return an int.
4772                          */
4773                         if (!t)
4774                                 return false;
4775
4776                         t = btf_type_skip_modifiers(btf, t->type, NULL);
4777                         if (!btf_type_is_small_int(t)) {
4778                                 bpf_log(log,
4779                                         "ret type %s not allowed for fmod_ret\n",
4780                                         btf_kind_str[BTF_INFO_KIND(t->info)]);
4781                                 return false;
4782                         }
4783                         break;
4784                 default:
4785                         bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4786                                 tname, arg + 1);
4787                         return false;
4788                 }
4789         } else {
4790                 if (!t)
4791                         /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
4792                         return true;
4793                 t = btf_type_by_id(btf, args[arg].type);
4794         }
4795
4796         /* skip modifiers */
4797         while (btf_type_is_modifier(t))
4798                 t = btf_type_by_id(btf, t->type);
4799         if (btf_type_is_small_int(t) || btf_type_is_enum(t))
4800                 /* accessing a scalar */
4801                 return true;
4802         if (!btf_type_is_ptr(t)) {
4803                 bpf_log(log,
4804                         "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
4805                         tname, arg,
4806                         __btf_name_by_offset(btf, t->name_off),
4807                         btf_kind_str[BTF_INFO_KIND(t->info)]);
4808                 return false;
4809         }
4810
4811         /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
4812         for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4813                 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4814                 u32 type, flag;
4815
4816                 type = base_type(ctx_arg_info->reg_type);
4817                 flag = type_flag(ctx_arg_info->reg_type);
4818                 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
4819                     (flag & PTR_MAYBE_NULL)) {
4820                         info->reg_type = ctx_arg_info->reg_type;
4821                         return true;
4822                 }
4823         }
4824
4825         if (t->type == 0)
4826                 /* This is a pointer to void.
4827                  * It is the same as scalar from the verifier safety pov.
4828                  * No further pointer walking is allowed.
4829                  */
4830                 return true;
4831
4832         if (is_string_ptr(btf, t))
4833                 return true;
4834
4835         /* this is a pointer to another type */
4836         for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4837                 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4838
4839                 if (ctx_arg_info->offset == off) {
4840                         if (!ctx_arg_info->btf_id) {
4841                                 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
4842                                 return false;
4843                         }
4844
4845                         info->reg_type = ctx_arg_info->reg_type;
4846                         info->btf = btf_vmlinux;
4847                         info->btf_id = ctx_arg_info->btf_id;
4848                         return true;
4849                 }
4850         }
4851
4852         info->reg_type = PTR_TO_BTF_ID;
4853         if (tgt_prog) {
4854                 enum bpf_prog_type tgt_type;
4855
4856                 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
4857                         tgt_type = tgt_prog->aux->saved_dst_prog_type;
4858                 else
4859                         tgt_type = tgt_prog->type;
4860
4861                 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
4862                 if (ret > 0) {
4863                         info->btf = btf_vmlinux;
4864                         info->btf_id = ret;
4865                         return true;
4866                 } else {
4867                         return false;
4868                 }
4869         }
4870
4871         info->btf = btf;
4872         info->btf_id = t->type;
4873         t = btf_type_by_id(btf, t->type);
4874         /* skip modifiers */
4875         while (btf_type_is_modifier(t)) {
4876                 info->btf_id = t->type;
4877                 t = btf_type_by_id(btf, t->type);
4878         }
4879         if (!btf_type_is_struct(t)) {
4880                 bpf_log(log,
4881                         "func '%s' arg%d type %s is not a struct\n",
4882                         tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
4883                 return false;
4884         }
4885         bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
4886                 tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
4887                 __btf_name_by_offset(btf, t->name_off));
4888         return true;
4889 }
4890
4891 enum bpf_struct_walk_result {
4892         /* < 0 error */
4893         WALK_SCALAR = 0,
4894         WALK_PTR,
4895         WALK_STRUCT,
4896 };
4897
4898 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
4899                            const struct btf_type *t, int off, int size,
4900                            u32 *next_btf_id)
4901 {
4902         u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
4903         const struct btf_type *mtype, *elem_type = NULL;
4904         const struct btf_member *member;
4905         const char *tname, *mname;
4906         u32 vlen, elem_id, mid;
4907
4908 again:
4909         tname = __btf_name_by_offset(btf, t->name_off);
4910         if (!btf_type_is_struct(t)) {
4911                 bpf_log(log, "Type '%s' is not a struct\n", tname);
4912                 return -EINVAL;
4913         }
4914
4915         vlen = btf_type_vlen(t);
4916         if (off + size > t->size) {
4917                 /* If the last element is a variable size array, we may
4918                  * need to relax the rule.
4919                  */
4920                 struct btf_array *array_elem;
4921
4922                 if (vlen == 0)
4923                         goto error;
4924
4925                 member = btf_type_member(t) + vlen - 1;
4926                 mtype = btf_type_skip_modifiers(btf, member->type,
4927                                                 NULL);
4928                 if (!btf_type_is_array(mtype))
4929                         goto error;
4930
4931                 array_elem = (struct btf_array *)(mtype + 1);
4932                 if (array_elem->nelems != 0)
4933                         goto error;
4934
4935                 moff = btf_member_bit_offset(t, member) / 8;
4936                 if (off < moff)
4937                         goto error;
4938
4939                 /* Only allow structure for now, can be relaxed for
4940                  * other types later.
4941                  */
4942                 t = btf_type_skip_modifiers(btf, array_elem->type,
4943                                             NULL);
4944                 if (!btf_type_is_struct(t))
4945                         goto error;
4946
4947                 off = (off - moff) % t->size;
4948                 goto again;
4949
4950 error:
4951                 bpf_log(log, "access beyond struct %s at off %u size %u\n",
4952                         tname, off, size);
4953                 return -EACCES;
4954         }
4955
4956         for_each_member(i, t, member) {
4957                 /* offset of the field in bytes */
4958                 moff = btf_member_bit_offset(t, member) / 8;
4959                 if (off + size <= moff)
4960                         /* won't find anything, field is already too far */
4961                         break;
4962
4963                 if (btf_member_bitfield_size(t, member)) {
4964                         u32 end_bit = btf_member_bit_offset(t, member) +
4965                                 btf_member_bitfield_size(t, member);
4966
4967                         /* off <= moff instead of off == moff because clang
4968                          * does not generate a BTF member for anonymous
4969                          * bitfield like the ":16" here:
4970                          * struct {
4971                          *      int :16;
4972                          *      int x:8;
4973                          * };
4974                          */
4975                         if (off <= moff &&
4976                             BITS_ROUNDUP_BYTES(end_bit) <= off + size)
4977                                 return WALK_SCALAR;
4978
4979                         /* off may be accessing a following member
4980                          *
4981                          * or
4982                          *
4983                          * Doing partial access at either end of this
4984                          * bitfield.  Continue on this case also to
4985                          * treat it as not accessing this bitfield
4986                          * and eventually error out as field not
4987                          * found to keep it simple.
4988                          * It could be relaxed if there was a legit
4989                          * partial access case later.
4990                          */
4991                         continue;
4992                 }
4993
4994                 /* In case of "off" is pointing to holes of a struct */
4995                 if (off < moff)
4996                         break;
4997
4998                 /* type of the field */
4999                 mid = member->type;
5000                 mtype = btf_type_by_id(btf, member->type);
5001                 mname = __btf_name_by_offset(btf, member->name_off);
5002
5003                 mtype = __btf_resolve_size(btf, mtype, &msize,
5004                                            &elem_type, &elem_id, &total_nelems,
5005                                            &mid);
5006                 if (IS_ERR(mtype)) {
5007                         bpf_log(log, "field %s doesn't have size\n", mname);
5008                         return -EFAULT;
5009                 }
5010
5011                 mtrue_end = moff + msize;
5012                 if (off >= mtrue_end)
5013                         /* no overlap with member, keep iterating */
5014                         continue;
5015
5016                 if (btf_type_is_array(mtype)) {
5017                         u32 elem_idx;
5018
5019                         /* __btf_resolve_size() above helps to
5020                          * linearize a multi-dimensional array.
5021                          *
5022                          * The logic here is treating an array
5023                          * in a struct as the following way:
5024                          *
5025                          * struct outer {
5026                          *      struct inner array[2][2];
5027                          * };
5028                          *
5029                          * looks like:
5030                          *
5031                          * struct outer {
5032                          *      struct inner array_elem0;
5033                          *      struct inner array_elem1;
5034                          *      struct inner array_elem2;
5035                          *      struct inner array_elem3;
5036                          * };
5037                          *
5038                          * When accessing outer->array[1][0], it moves
5039                          * moff to "array_elem2", set mtype to
5040                          * "struct inner", and msize also becomes
5041                          * sizeof(struct inner).  Then most of the
5042                          * remaining logic will fall through without
5043                          * caring the current member is an array or
5044                          * not.
5045                          *
5046                          * Unlike mtype/msize/moff, mtrue_end does not
5047                          * change.  The naming difference ("_true") tells
5048                          * that it is not always corresponding to
5049                          * the current mtype/msize/moff.
5050                          * It is the true end of the current
5051                          * member (i.e. array in this case).  That
5052                          * will allow an int array to be accessed like
5053                          * a scratch space,
5054                          * i.e. allow access beyond the size of
5055                          *      the array's element as long as it is
5056                          *      within the mtrue_end boundary.
5057                          */
5058
5059                         /* skip empty array */
5060                         if (moff == mtrue_end)
5061                                 continue;
5062
5063                         msize /= total_nelems;
5064                         elem_idx = (off - moff) / msize;
5065                         moff += elem_idx * msize;
5066                         mtype = elem_type;
5067                         mid = elem_id;
5068                 }
5069
5070                 /* the 'off' we're looking for is either equal to start
5071                  * of this field or inside of this struct
5072                  */
5073                 if (btf_type_is_struct(mtype)) {
5074                         /* our field must be inside that union or struct */
5075                         t = mtype;
5076
5077                         /* return if the offset matches the member offset */
5078                         if (off == moff) {
5079                                 *next_btf_id = mid;
5080                                 return WALK_STRUCT;
5081                         }
5082
5083                         /* adjust offset we're looking for */
5084                         off -= moff;
5085                         goto again;
5086                 }
5087
5088                 if (btf_type_is_ptr(mtype)) {
5089                         const struct btf_type *stype;
5090                         u32 id;
5091
5092                         if (msize != size || off != moff) {
5093                                 bpf_log(log,
5094                                         "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
5095                                         mname, moff, tname, off, size);
5096                                 return -EACCES;
5097                         }
5098                         stype = btf_type_skip_modifiers(btf, mtype->type, &id);
5099                         if (btf_type_is_struct(stype)) {
5100                                 *next_btf_id = id;
5101                                 return WALK_PTR;
5102                         }
5103                 }
5104
5105                 /* Allow more flexible access within an int as long as
5106                  * it is within mtrue_end.
5107                  * Since mtrue_end could be the end of an array,
5108                  * that also allows using an array of int as a scratch
5109                  * space. e.g. skb->cb[].
5110                  */
5111                 if (off + size > mtrue_end) {
5112                         bpf_log(log,
5113                                 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
5114                                 mname, mtrue_end, tname, off, size);
5115                         return -EACCES;
5116                 }
5117
5118                 return WALK_SCALAR;
5119         }
5120         bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
5121         return -EINVAL;
5122 }
5123
5124 int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
5125                       const struct btf_type *t, int off, int size,
5126                       enum bpf_access_type atype __maybe_unused,
5127                       u32 *next_btf_id)
5128 {
5129         int err;
5130         u32 id;
5131
5132         do {
5133                 err = btf_struct_walk(log, btf, t, off, size, &id);
5134
5135                 switch (err) {
5136                 case WALK_PTR:
5137                         /* If we found the pointer or scalar on t+off,
5138                          * we're done.
5139                          */
5140                         *next_btf_id = id;
5141                         return PTR_TO_BTF_ID;
5142                 case WALK_SCALAR:
5143                         return SCALAR_VALUE;
5144                 case WALK_STRUCT:
5145                         /* We found nested struct, so continue the search
5146                          * by diving in it. At this point the offset is
5147                          * aligned with the new type, so set it to 0.
5148                          */
5149                         t = btf_type_by_id(btf, id);
5150                         off = 0;
5151                         break;
5152                 default:
5153                         /* It's either error or unknown return value..
5154                          * scream and leave.
5155                          */
5156                         if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5157                                 return -EINVAL;
5158                         return err;
5159                 }
5160         } while (t);
5161
5162         return -EINVAL;
5163 }
5164
5165 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5166  * the same. Trivial ID check is not enough due to module BTFs, because we can
5167  * end up with two different module BTFs, but IDs point to the common type in
5168  * vmlinux BTF.
5169  */
5170 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5171                                const struct btf *btf2, u32 id2)
5172 {
5173         if (id1 != id2)
5174                 return false;
5175         if (btf1 == btf2)
5176                 return true;
5177         return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5178 }
5179
5180 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5181                           const struct btf *btf, u32 id, int off,
5182                           const struct btf *need_btf, u32 need_type_id)
5183 {
5184         const struct btf_type *type;
5185         int err;
5186
5187         /* Are we already done? */
5188         if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5189                 return true;
5190
5191 again:
5192         type = btf_type_by_id(btf, id);
5193         if (!type)
5194                 return false;
5195         err = btf_struct_walk(log, btf, type, off, 1, &id);
5196         if (err != WALK_STRUCT)
5197                 return false;
5198
5199         /* We found nested struct object. If it matches
5200          * the requested ID, we're done. Otherwise let's
5201          * continue the search with offset 0 in the new
5202          * type.
5203          */
5204         if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5205                 off = 0;
5206                 goto again;
5207         }
5208
5209         return true;
5210 }
5211
5212 static int __get_type_size(struct btf *btf, u32 btf_id,
5213                            const struct btf_type **bad_type)
5214 {
5215         const struct btf_type *t;
5216
5217         if (!btf_id)
5218                 /* void */
5219                 return 0;
5220         t = btf_type_by_id(btf, btf_id);
5221         while (t && btf_type_is_modifier(t))
5222                 t = btf_type_by_id(btf, t->type);
5223         if (!t) {
5224                 *bad_type = btf_type_by_id(btf, 0);
5225                 return -EINVAL;
5226         }
5227         if (btf_type_is_ptr(t))
5228                 /* kernel size of pointer. Not BPF's size of pointer*/
5229                 return sizeof(void *);
5230         if (btf_type_is_int(t) || btf_type_is_enum(t))
5231                 return t->size;
5232         *bad_type = t;
5233         return -EINVAL;
5234 }
5235
5236 int btf_distill_func_proto(struct bpf_verifier_log *log,
5237                            struct btf *btf,
5238                            const struct btf_type *func,
5239                            const char *tname,
5240                            struct btf_func_model *m)
5241 {
5242         const struct btf_param *args;
5243         const struct btf_type *t;
5244         u32 i, nargs;
5245         int ret;
5246
5247         if (!func) {
5248                 /* BTF function prototype doesn't match the verifier types.
5249                  * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
5250                  */
5251                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
5252                         m->arg_size[i] = 8;
5253                 m->ret_size = 8;
5254                 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
5255                 return 0;
5256         }
5257         args = (const struct btf_param *)(func + 1);
5258         nargs = btf_type_vlen(func);
5259         if (nargs >= MAX_BPF_FUNC_ARGS) {
5260                 bpf_log(log,
5261                         "The function %s has %d arguments. Too many.\n",
5262                         tname, nargs);
5263                 return -EINVAL;
5264         }
5265         ret = __get_type_size(btf, func->type, &t);
5266         if (ret < 0) {
5267                 bpf_log(log,
5268                         "The function %s return type %s is unsupported.\n",
5269                         tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5270                 return -EINVAL;
5271         }
5272         m->ret_size = ret;
5273
5274         for (i = 0; i < nargs; i++) {
5275                 if (i == nargs - 1 && args[i].type == 0) {
5276                         bpf_log(log,
5277                                 "The function %s with variable args is unsupported.\n",
5278                                 tname);
5279                         return -EINVAL;
5280                 }
5281                 ret = __get_type_size(btf, args[i].type, &t);
5282                 if (ret < 0) {
5283                         bpf_log(log,
5284                                 "The function %s arg%d type %s is unsupported.\n",
5285                                 tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5286                         return -EINVAL;
5287                 }
5288                 if (ret == 0) {
5289                         bpf_log(log,
5290                                 "The function %s has malformed void argument.\n",
5291                                 tname);
5292                         return -EINVAL;
5293                 }
5294                 m->arg_size[i] = ret;
5295         }
5296         m->nr_args = nargs;
5297         return 0;
5298 }
5299
5300 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5301  * t1 points to BTF_KIND_FUNC in btf1
5302  * t2 points to BTF_KIND_FUNC in btf2
5303  * Returns:
5304  * EINVAL - function prototype mismatch
5305  * EFAULT - verifier bug
5306  * 0 - 99% match. The last 1% is validated by the verifier.
5307  */
5308 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5309                                      struct btf *btf1, const struct btf_type *t1,
5310                                      struct btf *btf2, const struct btf_type *t2)
5311 {
5312         const struct btf_param *args1, *args2;
5313         const char *fn1, *fn2, *s1, *s2;
5314         u32 nargs1, nargs2, i;
5315
5316         fn1 = btf_name_by_offset(btf1, t1->name_off);
5317         fn2 = btf_name_by_offset(btf2, t2->name_off);
5318
5319         if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5320                 bpf_log(log, "%s() is not a global function\n", fn1);
5321                 return -EINVAL;
5322         }
5323         if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5324                 bpf_log(log, "%s() is not a global function\n", fn2);
5325                 return -EINVAL;
5326         }
5327
5328         t1 = btf_type_by_id(btf1, t1->type);
5329         if (!t1 || !btf_type_is_func_proto(t1))
5330                 return -EFAULT;
5331         t2 = btf_type_by_id(btf2, t2->type);
5332         if (!t2 || !btf_type_is_func_proto(t2))
5333                 return -EFAULT;
5334
5335         args1 = (const struct btf_param *)(t1 + 1);
5336         nargs1 = btf_type_vlen(t1);
5337         args2 = (const struct btf_param *)(t2 + 1);
5338         nargs2 = btf_type_vlen(t2);
5339
5340         if (nargs1 != nargs2) {
5341                 bpf_log(log, "%s() has %d args while %s() has %d args\n",
5342                         fn1, nargs1, fn2, nargs2);
5343                 return -EINVAL;
5344         }
5345
5346         t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5347         t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5348         if (t1->info != t2->info) {
5349                 bpf_log(log,
5350                         "Return type %s of %s() doesn't match type %s of %s()\n",
5351                         btf_type_str(t1), fn1,
5352                         btf_type_str(t2), fn2);
5353                 return -EINVAL;
5354         }
5355
5356         for (i = 0; i < nargs1; i++) {
5357                 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5358                 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5359
5360                 if (t1->info != t2->info) {
5361                         bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5362                                 i, fn1, btf_type_str(t1),
5363                                 fn2, btf_type_str(t2));
5364                         return -EINVAL;
5365                 }
5366                 if (btf_type_has_size(t1) && t1->size != t2->size) {
5367                         bpf_log(log,
5368                                 "arg%d in %s() has size %d while %s() has %d\n",
5369                                 i, fn1, t1->size,
5370                                 fn2, t2->size);
5371                         return -EINVAL;
5372                 }
5373
5374                 /* global functions are validated with scalars and pointers
5375                  * to context only. And only global functions can be replaced.
5376                  * Hence type check only those types.
5377                  */
5378                 if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5379                         continue;
5380                 if (!btf_type_is_ptr(t1)) {
5381                         bpf_log(log,
5382                                 "arg%d in %s() has unrecognized type\n",
5383                                 i, fn1);
5384                         return -EINVAL;
5385                 }
5386                 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5387                 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5388                 if (!btf_type_is_struct(t1)) {
5389                         bpf_log(log,
5390                                 "arg%d in %s() is not a pointer to context\n",
5391                                 i, fn1);
5392                         return -EINVAL;
5393                 }
5394                 if (!btf_type_is_struct(t2)) {
5395                         bpf_log(log,
5396                                 "arg%d in %s() is not a pointer to context\n",
5397                                 i, fn2);
5398                         return -EINVAL;
5399                 }
5400                 /* This is an optional check to make program writing easier.
5401                  * Compare names of structs and report an error to the user.
5402                  * btf_prepare_func_args() already checked that t2 struct
5403                  * is a context type. btf_prepare_func_args() will check
5404                  * later that t1 struct is a context type as well.
5405                  */
5406                 s1 = btf_name_by_offset(btf1, t1->name_off);
5407                 s2 = btf_name_by_offset(btf2, t2->name_off);
5408                 if (strcmp(s1, s2)) {
5409                         bpf_log(log,
5410                                 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5411                                 i, fn1, s1, fn2, s2);
5412                         return -EINVAL;
5413                 }
5414         }
5415         return 0;
5416 }
5417
5418 /* Compare BTFs of given program with BTF of target program */
5419 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5420                          struct btf *btf2, const struct btf_type *t2)
5421 {
5422         struct btf *btf1 = prog->aux->btf;
5423         const struct btf_type *t1;
5424         u32 btf_id = 0;
5425
5426         if (!prog->aux->func_info) {
5427                 bpf_log(log, "Program extension requires BTF\n");
5428                 return -EINVAL;
5429         }
5430
5431         btf_id = prog->aux->func_info[0].type_id;
5432         if (!btf_id)
5433                 return -EFAULT;
5434
5435         t1 = btf_type_by_id(btf1, btf_id);
5436         if (!t1 || !btf_type_is_func(t1))
5437                 return -EFAULT;
5438
5439         return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5440 }
5441
5442 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5443 #ifdef CONFIG_NET
5444         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5445         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5446         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5447 #endif
5448 };
5449
5450 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
5451                                     const struct btf *btf, u32 func_id,
5452                                     struct bpf_reg_state *regs,
5453                                     bool ptr_to_mem_ok)
5454 {
5455         enum bpf_prog_type prog_type = env->prog->type == BPF_PROG_TYPE_EXT ?
5456                 env->prog->aux->dst_prog->type : env->prog->type;
5457         struct bpf_verifier_log *log = &env->log;
5458         const char *func_name, *ref_tname;
5459         const struct btf_type *t, *ref_t;
5460         const struct btf_param *args;
5461         u32 i, nargs, ref_id;
5462
5463         t = btf_type_by_id(btf, func_id);
5464         if (!t || !btf_type_is_func(t)) {
5465                 /* These checks were already done by the verifier while loading
5466                  * struct bpf_func_info or in add_kfunc_call().
5467                  */
5468                 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
5469                         func_id);
5470                 return -EFAULT;
5471         }
5472         func_name = btf_name_by_offset(btf, t->name_off);
5473
5474         t = btf_type_by_id(btf, t->type);
5475         if (!t || !btf_type_is_func_proto(t)) {
5476                 bpf_log(log, "Invalid BTF of func %s\n", func_name);
5477                 return -EFAULT;
5478         }
5479         args = (const struct btf_param *)(t + 1);
5480         nargs = btf_type_vlen(t);
5481         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
5482                 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
5483                         MAX_BPF_FUNC_REG_ARGS);
5484                 return -EINVAL;
5485         }
5486
5487         /* check that BTF function arguments match actual types that the
5488          * verifier sees.
5489          */
5490         for (i = 0; i < nargs; i++) {
5491                 u32 regno = i + 1;
5492                 struct bpf_reg_state *reg = &regs[regno];
5493
5494                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5495                 if (btf_type_is_scalar(t)) {
5496                         if (reg->type == SCALAR_VALUE)
5497                                 continue;
5498                         bpf_log(log, "R%d is not a scalar\n", regno);
5499                         return -EINVAL;
5500                 }
5501
5502                 if (!btf_type_is_ptr(t)) {
5503                         bpf_log(log, "Unrecognized arg#%d type %s\n",
5504                                 i, btf_type_str(t));
5505                         return -EINVAL;
5506                 }
5507
5508                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
5509                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
5510                 if (btf_is_kernel(btf)) {
5511                         const struct btf_type *reg_ref_t;
5512                         const struct btf *reg_btf;
5513                         const char *reg_ref_tname;
5514                         u32 reg_ref_id;
5515
5516                         if (!btf_type_is_struct(ref_t)) {
5517                                 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
5518                                         func_name, i, btf_type_str(ref_t),
5519                                         ref_tname);
5520                                 return -EINVAL;
5521                         }
5522
5523                         if (reg->type == PTR_TO_BTF_ID) {
5524                                 reg_btf = reg->btf;
5525                                 reg_ref_id = reg->btf_id;
5526                         } else if (reg2btf_ids[base_type(reg->type)]) {
5527                                 reg_btf = btf_vmlinux;
5528                                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
5529                         } else {
5530                                 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d is not a pointer to btf_id\n",
5531                                         func_name, i,
5532                                         btf_type_str(ref_t), ref_tname, regno);
5533                                 return -EINVAL;
5534                         }
5535
5536                         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id,
5537                                                             &reg_ref_id);
5538                         reg_ref_tname = btf_name_by_offset(reg_btf,
5539                                                            reg_ref_t->name_off);
5540                         if (!btf_struct_ids_match(log, reg_btf, reg_ref_id,
5541                                                   reg->off, btf, ref_id)) {
5542                                 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
5543                                         func_name, i,
5544                                         btf_type_str(ref_t), ref_tname,
5545                                         regno, btf_type_str(reg_ref_t),
5546                                         reg_ref_tname);
5547                                 return -EINVAL;
5548                         }
5549                 } else if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5550                         /* If function expects ctx type in BTF check that caller
5551                          * is passing PTR_TO_CTX.
5552                          */
5553                         if (reg->type != PTR_TO_CTX) {
5554                                 bpf_log(log,
5555                                         "arg#%d expected pointer to ctx, but got %s\n",
5556                                         i, btf_type_str(t));
5557                                 return -EINVAL;
5558                         }
5559                         if (check_ctx_reg(env, reg, regno))
5560                                 return -EINVAL;
5561                 } else if (ptr_to_mem_ok) {
5562                         const struct btf_type *resolve_ret;
5563                         u32 type_size;
5564
5565                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
5566                         if (IS_ERR(resolve_ret)) {
5567                                 bpf_log(log,
5568                                         "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5569                                         i, btf_type_str(ref_t), ref_tname,
5570                                         PTR_ERR(resolve_ret));
5571                                 return -EINVAL;
5572                         }
5573
5574                         if (check_mem_reg(env, reg, regno, type_size))
5575                                 return -EINVAL;
5576                 } else {
5577                         return -EINVAL;
5578                 }
5579         }
5580
5581         return 0;
5582 }
5583
5584 /* Compare BTF of a function with given bpf_reg_state.
5585  * Returns:
5586  * EFAULT - there is a verifier bug. Abort verification.
5587  * EINVAL - there is a type mismatch or BTF is not available.
5588  * 0 - BTF matches with what bpf_reg_state expects.
5589  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
5590  */
5591 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
5592                                 struct bpf_reg_state *regs)
5593 {
5594         struct bpf_prog *prog = env->prog;
5595         struct btf *btf = prog->aux->btf;
5596         bool is_global;
5597         u32 btf_id;
5598         int err;
5599
5600         if (!prog->aux->func_info)
5601                 return -EINVAL;
5602
5603         btf_id = prog->aux->func_info[subprog].type_id;
5604         if (!btf_id)
5605                 return -EFAULT;
5606
5607         if (prog->aux->func_info_aux[subprog].unreliable)
5608                 return -EINVAL;
5609
5610         is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5611         err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global);
5612
5613         /* Compiler optimizations can remove arguments from static functions
5614          * or mismatched type can be passed into a global function.
5615          * In such cases mark the function as unreliable from BTF point of view.
5616          */
5617         if (err)
5618                 prog->aux->func_info_aux[subprog].unreliable = true;
5619         return err;
5620 }
5621
5622 int btf_check_kfunc_arg_match(struct bpf_verifier_env *env,
5623                               const struct btf *btf, u32 func_id,
5624                               struct bpf_reg_state *regs)
5625 {
5626         return btf_check_func_arg_match(env, btf, func_id, regs, false);
5627 }
5628
5629 /* Convert BTF of a function into bpf_reg_state if possible
5630  * Returns:
5631  * EFAULT - there is a verifier bug. Abort verification.
5632  * EINVAL - cannot convert BTF.
5633  * 0 - Successfully converted BTF into bpf_reg_state
5634  * (either PTR_TO_CTX or SCALAR_VALUE).
5635  */
5636 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
5637                           struct bpf_reg_state *regs)
5638 {
5639         struct bpf_verifier_log *log = &env->log;
5640         struct bpf_prog *prog = env->prog;
5641         enum bpf_prog_type prog_type = prog->type;
5642         struct btf *btf = prog->aux->btf;
5643         const struct btf_param *args;
5644         const struct btf_type *t, *ref_t;
5645         u32 i, nargs, btf_id;
5646         const char *tname;
5647
5648         if (!prog->aux->func_info ||
5649             prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
5650                 bpf_log(log, "Verifier bug\n");
5651                 return -EFAULT;
5652         }
5653
5654         btf_id = prog->aux->func_info[subprog].type_id;
5655         if (!btf_id) {
5656                 bpf_log(log, "Global functions need valid BTF\n");
5657                 return -EFAULT;
5658         }
5659
5660         t = btf_type_by_id(btf, btf_id);
5661         if (!t || !btf_type_is_func(t)) {
5662                 /* These checks were already done by the verifier while loading
5663                  * struct bpf_func_info
5664                  */
5665                 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5666                         subprog);
5667                 return -EFAULT;
5668         }
5669         tname = btf_name_by_offset(btf, t->name_off);
5670
5671         if (log->level & BPF_LOG_LEVEL)
5672                 bpf_log(log, "Validating %s() func#%d...\n",
5673                         tname, subprog);
5674
5675         if (prog->aux->func_info_aux[subprog].unreliable) {
5676                 bpf_log(log, "Verifier bug in function %s()\n", tname);
5677                 return -EFAULT;
5678         }
5679         if (prog_type == BPF_PROG_TYPE_EXT)
5680                 prog_type = prog->aux->dst_prog->type;
5681
5682         t = btf_type_by_id(btf, t->type);
5683         if (!t || !btf_type_is_func_proto(t)) {
5684                 bpf_log(log, "Invalid type of function %s()\n", tname);
5685                 return -EFAULT;
5686         }
5687         args = (const struct btf_param *)(t + 1);
5688         nargs = btf_type_vlen(t);
5689         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
5690                 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
5691                         tname, nargs, MAX_BPF_FUNC_REG_ARGS);
5692                 return -EINVAL;
5693         }
5694         /* check that function returns int */
5695         t = btf_type_by_id(btf, t->type);
5696         while (btf_type_is_modifier(t))
5697                 t = btf_type_by_id(btf, t->type);
5698         if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
5699                 bpf_log(log,
5700                         "Global function %s() doesn't return scalar. Only those are supported.\n",
5701                         tname);
5702                 return -EINVAL;
5703         }
5704         /* Convert BTF function arguments into verifier types.
5705          * Only PTR_TO_CTX and SCALAR are supported atm.
5706          */
5707         for (i = 0; i < nargs; i++) {
5708                 struct bpf_reg_state *reg = &regs[i + 1];
5709
5710                 t = btf_type_by_id(btf, args[i].type);
5711                 while (btf_type_is_modifier(t))
5712                         t = btf_type_by_id(btf, t->type);
5713                 if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5714                         reg->type = SCALAR_VALUE;
5715                         continue;
5716                 }
5717                 if (btf_type_is_ptr(t)) {
5718                         if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5719                                 reg->type = PTR_TO_CTX;
5720                                 continue;
5721                         }
5722
5723                         t = btf_type_skip_modifiers(btf, t->type, NULL);
5724
5725                         ref_t = btf_resolve_size(btf, t, &reg->mem_size);
5726                         if (IS_ERR(ref_t)) {
5727                                 bpf_log(log,
5728                                     "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
5729                                     i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
5730                                         PTR_ERR(ref_t));
5731                                 return -EINVAL;
5732                         }
5733
5734                         reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5735                         reg->id = ++env->id_gen;
5736
5737                         continue;
5738                 }
5739                 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
5740                         i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
5741                 return -EINVAL;
5742         }
5743         return 0;
5744 }
5745
5746 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
5747                           struct btf_show *show)
5748 {
5749         const struct btf_type *t = btf_type_by_id(btf, type_id);
5750
5751         show->btf = btf;
5752         memset(&show->state, 0, sizeof(show->state));
5753         memset(&show->obj, 0, sizeof(show->obj));
5754
5755         btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
5756 }
5757
5758 static void btf_seq_show(struct btf_show *show, const char *fmt,
5759                          va_list args)
5760 {
5761         seq_vprintf((struct seq_file *)show->target, fmt, args);
5762 }
5763
5764 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
5765                             void *obj, struct seq_file *m, u64 flags)
5766 {
5767         struct btf_show sseq;
5768
5769         sseq.target = m;
5770         sseq.showfn = btf_seq_show;
5771         sseq.flags = flags;
5772
5773         btf_type_show(btf, type_id, obj, &sseq);
5774
5775         return sseq.state.status;
5776 }
5777
5778 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
5779                        struct seq_file *m)
5780 {
5781         (void) btf_type_seq_show_flags(btf, type_id, obj, m,
5782                                        BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
5783                                        BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
5784 }
5785
5786 struct btf_show_snprintf {
5787         struct btf_show show;
5788         int len_left;           /* space left in string */
5789         int len;                /* length we would have written */
5790 };
5791
5792 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
5793                               va_list args)
5794 {
5795         struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
5796         int len;
5797
5798         len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
5799
5800         if (len < 0) {
5801                 ssnprintf->len_left = 0;
5802                 ssnprintf->len = len;
5803         } else if (len > ssnprintf->len_left) {
5804                 /* no space, drive on to get length we would have written */
5805                 ssnprintf->len_left = 0;
5806                 ssnprintf->len += len;
5807         } else {
5808                 ssnprintf->len_left -= len;
5809                 ssnprintf->len += len;
5810                 show->target += len;
5811         }
5812 }
5813
5814 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
5815                            char *buf, int len, u64 flags)
5816 {
5817         struct btf_show_snprintf ssnprintf;
5818
5819         ssnprintf.show.target = buf;
5820         ssnprintf.show.flags = flags;
5821         ssnprintf.show.showfn = btf_snprintf_show;
5822         ssnprintf.len_left = len;
5823         ssnprintf.len = 0;
5824
5825         btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
5826
5827         /* If we encontered an error, return it. */
5828         if (ssnprintf.show.state.status)
5829                 return ssnprintf.show.state.status;
5830
5831         /* Otherwise return length we would have written */
5832         return ssnprintf.len;
5833 }
5834
5835 #ifdef CONFIG_PROC_FS
5836 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
5837 {
5838         const struct btf *btf = filp->private_data;
5839
5840         seq_printf(m, "btf_id:\t%u\n", btf->id);
5841 }
5842 #endif
5843
5844 static int btf_release(struct inode *inode, struct file *filp)
5845 {
5846         btf_put(filp->private_data);
5847         return 0;
5848 }
5849
5850 const struct file_operations btf_fops = {
5851 #ifdef CONFIG_PROC_FS
5852         .show_fdinfo    = bpf_btf_show_fdinfo,
5853 #endif
5854         .release        = btf_release,
5855 };
5856
5857 static int __btf_new_fd(struct btf *btf)
5858 {
5859         return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
5860 }
5861
5862 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
5863 {
5864         struct btf *btf;
5865         int ret;
5866
5867         btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
5868                         attr->btf_size, attr->btf_log_level,
5869                         u64_to_user_ptr(attr->btf_log_buf),
5870                         attr->btf_log_size);
5871         if (IS_ERR(btf))
5872                 return PTR_ERR(btf);
5873
5874         ret = btf_alloc_id(btf);
5875         if (ret) {
5876                 btf_free(btf);
5877                 return ret;
5878         }
5879
5880         /*
5881          * The BTF ID is published to the userspace.
5882          * All BTF free must go through call_rcu() from
5883          * now on (i.e. free by calling btf_put()).
5884          */
5885
5886         ret = __btf_new_fd(btf);
5887         if (ret < 0)
5888                 btf_put(btf);
5889
5890         return ret;
5891 }
5892
5893 struct btf *btf_get_by_fd(int fd)
5894 {
5895         struct btf *btf;
5896         struct fd f;
5897
5898         f = fdget(fd);
5899
5900         if (!f.file)
5901                 return ERR_PTR(-EBADF);
5902
5903         if (f.file->f_op != &btf_fops) {
5904                 fdput(f);
5905                 return ERR_PTR(-EINVAL);
5906         }
5907
5908         btf = f.file->private_data;
5909         refcount_inc(&btf->refcnt);
5910         fdput(f);
5911
5912         return btf;
5913 }
5914
5915 int btf_get_info_by_fd(const struct btf *btf,
5916                        const union bpf_attr *attr,
5917                        union bpf_attr __user *uattr)
5918 {
5919         struct bpf_btf_info __user *uinfo;
5920         struct bpf_btf_info info;
5921         u32 info_copy, btf_copy;
5922         void __user *ubtf;
5923         char __user *uname;
5924         u32 uinfo_len, uname_len, name_len;
5925         int ret = 0;
5926
5927         uinfo = u64_to_user_ptr(attr->info.info);
5928         uinfo_len = attr->info.info_len;
5929
5930         info_copy = min_t(u32, uinfo_len, sizeof(info));
5931         memset(&info, 0, sizeof(info));
5932         if (copy_from_user(&info, uinfo, info_copy))
5933                 return -EFAULT;
5934
5935         info.id = btf->id;
5936         ubtf = u64_to_user_ptr(info.btf);
5937         btf_copy = min_t(u32, btf->data_size, info.btf_size);
5938         if (copy_to_user(ubtf, btf->data, btf_copy))
5939                 return -EFAULT;
5940         info.btf_size = btf->data_size;
5941
5942         info.kernel_btf = btf->kernel_btf;
5943
5944         uname = u64_to_user_ptr(info.name);
5945         uname_len = info.name_len;
5946         if (!uname ^ !uname_len)
5947                 return -EINVAL;
5948
5949         name_len = strlen(btf->name);
5950         info.name_len = name_len;
5951
5952         if (uname) {
5953                 if (uname_len >= name_len + 1) {
5954                         if (copy_to_user(uname, btf->name, name_len + 1))
5955                                 return -EFAULT;
5956                 } else {
5957                         char zero = '\0';
5958
5959                         if (copy_to_user(uname, btf->name, uname_len - 1))
5960                                 return -EFAULT;
5961                         if (put_user(zero, uname + uname_len - 1))
5962                                 return -EFAULT;
5963                         /* let user-space know about too short buffer */
5964                         ret = -ENOSPC;
5965                 }
5966         }
5967
5968         if (copy_to_user(uinfo, &info, info_copy) ||
5969             put_user(info_copy, &uattr->info.info_len))
5970                 return -EFAULT;
5971
5972         return ret;
5973 }
5974
5975 int btf_get_fd_by_id(u32 id)
5976 {
5977         struct btf *btf;
5978         int fd;
5979
5980         rcu_read_lock();
5981         btf = idr_find(&btf_idr, id);
5982         if (!btf || !refcount_inc_not_zero(&btf->refcnt))
5983                 btf = ERR_PTR(-ENOENT);
5984         rcu_read_unlock();
5985
5986         if (IS_ERR(btf))
5987                 return PTR_ERR(btf);
5988
5989         fd = __btf_new_fd(btf);
5990         if (fd < 0)
5991                 btf_put(btf);
5992
5993         return fd;
5994 }
5995
5996 u32 btf_obj_id(const struct btf *btf)
5997 {
5998         return btf->id;
5999 }
6000
6001 bool btf_is_kernel(const struct btf *btf)
6002 {
6003         return btf->kernel_btf;
6004 }
6005
6006 bool btf_is_module(const struct btf *btf)
6007 {
6008         return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
6009 }
6010
6011 static int btf_id_cmp_func(const void *a, const void *b)
6012 {
6013         const int *pa = a, *pb = b;
6014
6015         return *pa - *pb;
6016 }
6017
6018 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
6019 {
6020         return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
6021 }
6022
6023 enum {
6024         BTF_MODULE_F_LIVE = (1 << 0),
6025 };
6026
6027 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6028 struct btf_module {
6029         struct list_head list;
6030         struct module *module;
6031         struct btf *btf;
6032         struct bin_attribute *sysfs_attr;
6033         int flags;
6034 };
6035
6036 static LIST_HEAD(btf_modules);
6037 static DEFINE_MUTEX(btf_module_mutex);
6038
6039 static ssize_t
6040 btf_module_read(struct file *file, struct kobject *kobj,
6041                 struct bin_attribute *bin_attr,
6042                 char *buf, loff_t off, size_t len)
6043 {
6044         const struct btf *btf = bin_attr->private;
6045
6046         memcpy(buf, btf->data + off, len);
6047         return len;
6048 }
6049
6050 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
6051                              void *module)
6052 {
6053         struct btf_module *btf_mod, *tmp;
6054         struct module *mod = module;
6055         struct btf *btf;
6056         int err = 0;
6057
6058         if (mod->btf_data_size == 0 ||
6059             (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
6060              op != MODULE_STATE_GOING))
6061                 goto out;
6062
6063         switch (op) {
6064         case MODULE_STATE_COMING:
6065                 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
6066                 if (!btf_mod) {
6067                         err = -ENOMEM;
6068                         goto out;
6069                 }
6070                 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
6071                 if (IS_ERR(btf)) {
6072                         pr_warn("failed to validate module [%s] BTF: %ld\n",
6073                                 mod->name, PTR_ERR(btf));
6074                         kfree(btf_mod);
6075                         err = PTR_ERR(btf);
6076                         goto out;
6077                 }
6078                 err = btf_alloc_id(btf);
6079                 if (err) {
6080                         btf_free(btf);
6081                         kfree(btf_mod);
6082                         goto out;
6083                 }
6084
6085                 mutex_lock(&btf_module_mutex);
6086                 btf_mod->module = module;
6087                 btf_mod->btf = btf;
6088                 list_add(&btf_mod->list, &btf_modules);
6089                 mutex_unlock(&btf_module_mutex);
6090
6091                 if (IS_ENABLED(CONFIG_SYSFS)) {
6092                         struct bin_attribute *attr;
6093
6094                         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
6095                         if (!attr)
6096                                 goto out;
6097
6098                         sysfs_bin_attr_init(attr);
6099                         attr->attr.name = btf->name;
6100                         attr->attr.mode = 0444;
6101                         attr->size = btf->data_size;
6102                         attr->private = btf;
6103                         attr->read = btf_module_read;
6104
6105                         err = sysfs_create_bin_file(btf_kobj, attr);
6106                         if (err) {
6107                                 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
6108                                         mod->name, err);
6109                                 kfree(attr);
6110                                 err = 0;
6111                                 goto out;
6112                         }
6113
6114                         btf_mod->sysfs_attr = attr;
6115                 }
6116
6117                 break;
6118         case MODULE_STATE_LIVE:
6119                 mutex_lock(&btf_module_mutex);
6120                 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6121                         if (btf_mod->module != module)
6122                                 continue;
6123
6124                         btf_mod->flags |= BTF_MODULE_F_LIVE;
6125                         break;
6126                 }
6127                 mutex_unlock(&btf_module_mutex);
6128                 break;
6129         case MODULE_STATE_GOING:
6130                 mutex_lock(&btf_module_mutex);
6131                 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6132                         if (btf_mod->module != module)
6133                                 continue;
6134
6135                         list_del(&btf_mod->list);
6136                         if (btf_mod->sysfs_attr)
6137                                 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
6138                         btf_put(btf_mod->btf);
6139                         kfree(btf_mod->sysfs_attr);
6140                         kfree(btf_mod);
6141                         break;
6142                 }
6143                 mutex_unlock(&btf_module_mutex);
6144                 break;
6145         }
6146 out:
6147         return notifier_from_errno(err);
6148 }
6149
6150 static struct notifier_block btf_module_nb = {
6151         .notifier_call = btf_module_notify,
6152 };
6153
6154 static int __init btf_module_init(void)
6155 {
6156         register_module_notifier(&btf_module_nb);
6157         return 0;
6158 }
6159
6160 fs_initcall(btf_module_init);
6161 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6162
6163 struct module *btf_try_get_module(const struct btf *btf)
6164 {
6165         struct module *res = NULL;
6166 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6167         struct btf_module *btf_mod, *tmp;
6168
6169         mutex_lock(&btf_module_mutex);
6170         list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
6171                 if (btf_mod->btf != btf)
6172                         continue;
6173
6174                 /* We must only consider module whose __init routine has
6175                  * finished, hence we must check for BTF_MODULE_F_LIVE flag,
6176                  * which is set from the notifier callback for
6177                  * MODULE_STATE_LIVE.
6178                  */
6179                 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
6180                         res = btf_mod->module;
6181
6182                 break;
6183         }
6184         mutex_unlock(&btf_module_mutex);
6185 #endif
6186
6187         return res;
6188 }
6189
6190 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
6191 {
6192         struct btf *btf;
6193         long ret;
6194
6195         if (flags)
6196                 return -EINVAL;
6197
6198         if (name_sz <= 1 || name[name_sz - 1])
6199                 return -EINVAL;
6200
6201         btf = bpf_get_btf_vmlinux();
6202         if (IS_ERR(btf))
6203                 return PTR_ERR(btf);
6204
6205         ret = btf_find_by_name_kind(btf, name, kind);
6206         /* ret is never zero, since btf_find_by_name_kind returns
6207          * positive btf_id or negative error.
6208          */
6209         if (ret < 0) {
6210                 struct btf *mod_btf;
6211                 int id;
6212
6213                 /* If name is not found in vmlinux's BTF then search in module's BTFs */
6214                 spin_lock_bh(&btf_idr_lock);
6215                 idr_for_each_entry(&btf_idr, mod_btf, id) {
6216                         if (!btf_is_module(mod_btf))
6217                                 continue;
6218                         /* linear search could be slow hence unlock/lock
6219                          * the IDR to avoiding holding it for too long
6220                          */
6221                         btf_get(mod_btf);
6222                         spin_unlock_bh(&btf_idr_lock);
6223                         ret = btf_find_by_name_kind(mod_btf, name, kind);
6224                         if (ret > 0) {
6225                                 int btf_obj_fd;
6226
6227                                 btf_obj_fd = __btf_new_fd(mod_btf);
6228                                 if (btf_obj_fd < 0) {
6229                                         btf_put(mod_btf);
6230                                         return btf_obj_fd;
6231                                 }
6232                                 return ret | (((u64)btf_obj_fd) << 32);
6233                         }
6234                         spin_lock_bh(&btf_idr_lock);
6235                         btf_put(mod_btf);
6236                 }
6237                 spin_unlock_bh(&btf_idr_lock);
6238         }
6239         return ret;
6240 }
6241
6242 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
6243         .func           = bpf_btf_find_by_name_kind,
6244         .gpl_only       = false,
6245         .ret_type       = RET_INTEGER,
6246         .arg1_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
6247         .arg2_type      = ARG_CONST_SIZE,
6248         .arg3_type      = ARG_ANYTHING,
6249         .arg4_type      = ARG_ANYTHING,
6250 };
6251
6252 BTF_ID_LIST_GLOBAL_SINGLE(btf_task_struct_ids, struct, task_struct)