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