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