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