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