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