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