bpf: Rename MEM_ALLOC to MEM_RINGBUF
[linux-2.6-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 {
f9b34818 211 BTF_KFUNC_SET_MAX_CNT = 256,
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}
84c6ac41 821EXPORT_SYMBOL_GPL(btf_type_by_id);
eb3f595d 822
4ef5f574
MKL
823/*
824 * Regular int is not a bit field and it must be either
b1e8818c 825 * u8/u16/u32/u64 or __int128.
4ef5f574
MKL
826 */
827static bool btf_type_int_is_regular(const struct btf_type *t)
828{
36fc3c8c 829 u8 nr_bits, nr_bytes;
4ef5f574
MKL
830 u32 int_data;
831
832 int_data = btf_type_int(t);
833 nr_bits = BTF_INT_BITS(int_data);
834 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
835 if (BITS_PER_BYTE_MASKED(nr_bits) ||
836 BTF_INT_OFFSET(int_data) ||
837 (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
b1e8818c
YS
838 nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
839 nr_bytes != (2 * sizeof(u64)))) {
4ef5f574
MKL
840 return false;
841 }
842
843 return true;
844}
845
9a1126b6 846/*
ffa0c1cf
YS
847 * Check that given struct member is a regular int with expected
848 * offset and size.
9a1126b6 849 */
ffa0c1cf
YS
850bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
851 const struct btf_member *m,
852 u32 expected_offset, u32 expected_size)
9a1126b6 853{
ffa0c1cf
YS
854 const struct btf_type *t;
855 u32 id, int_data;
856 u8 nr_bits;
9a1126b6 857
ffa0c1cf
YS
858 id = m->type;
859 t = btf_type_id_size(btf, &id, NULL);
860 if (!t || !btf_type_is_int(t))
9a1126b6
RG
861 return false;
862
863 int_data = btf_type_int(t);
864 nr_bits = BTF_INT_BITS(int_data);
ffa0c1cf
YS
865 if (btf_type_kflag(s)) {
866 u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
867 u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
868
869 /* if kflag set, int should be a regular int and
870 * bit offset should be at byte boundary.
871 */
872 return !bitfield_size &&
873 BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
874 BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
875 }
876
877 if (BTF_INT_OFFSET(int_data) ||
878 BITS_PER_BYTE_MASKED(m->offset) ||
879 BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
880 BITS_PER_BYTE_MASKED(nr_bits) ||
881 BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
9a1126b6
RG
882 return false;
883
884 return true;
885}
886
31d0bc81
AM
887/* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
888static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
889 u32 id)
890{
891 const struct btf_type *t = btf_type_by_id(btf, id);
892
893 while (btf_type_is_modifier(t) &&
894 BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
31d0bc81
AM
895 t = btf_type_by_id(btf, t->type);
896 }
897
898 return t;
899}
900
901#define BTF_SHOW_MAX_ITER 10
902
903#define BTF_KIND_BIT(kind) (1ULL << kind)
904
905/*
906 * Populate show->state.name with type name information.
907 * Format of type name is
908 *
909 * [.member_name = ] (type_name)
910 */
911static const char *btf_show_name(struct btf_show *show)
912{
913 /* BTF_MAX_ITER array suffixes "[]" */
914 const char *array_suffixes = "[][][][][][][][][][]";
915 const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
916 /* BTF_MAX_ITER pointer suffixes "*" */
917 const char *ptr_suffixes = "**********";
918 const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
919 const char *name = NULL, *prefix = "", *parens = "";
920 const struct btf_member *m = show->state.member;
73b6eae5 921 const struct btf_type *t;
31d0bc81
AM
922 const struct btf_array *array;
923 u32 id = show->state.type_id;
924 const char *member = NULL;
925 bool show_member = false;
926 u64 kinds = 0;
927 int i;
928
929 show->state.name[0] = '\0';
930
931 /*
932 * Don't show type name if we're showing an array member;
933 * in that case we show the array type so don't need to repeat
934 * ourselves for each member.
935 */
936 if (show->state.array_member)
937 return "";
938
939 /* Retrieve member name, if any. */
940 if (m) {
941 member = btf_name_by_offset(show->btf, m->name_off);
942 show_member = strlen(member) > 0;
943 id = m->type;
944 }
945
946 /*
947 * Start with type_id, as we have resolved the struct btf_type *
948 * via btf_modifier_show() past the parent typedef to the child
949 * struct, int etc it is defined as. In such cases, the type_id
950 * still represents the starting type while the struct btf_type *
951 * in our show->state points at the resolved type of the typedef.
952 */
953 t = btf_type_by_id(show->btf, id);
954 if (!t)
955 return "";
956
957 /*
958 * The goal here is to build up the right number of pointer and
959 * array suffixes while ensuring the type name for a typedef
960 * is represented. Along the way we accumulate a list of
961 * BTF kinds we have encountered, since these will inform later
962 * display; for example, pointer types will not require an
963 * opening "{" for struct, we will just display the pointer value.
964 *
965 * We also want to accumulate the right number of pointer or array
966 * indices in the format string while iterating until we get to
967 * the typedef/pointee/array member target type.
968 *
969 * We start by pointing at the end of pointer and array suffix
970 * strings; as we accumulate pointers and arrays we move the pointer
971 * or array string backwards so it will show the expected number of
972 * '*' or '[]' for the type. BTF_SHOW_MAX_ITER of nesting of pointers
973 * and/or arrays and typedefs are supported as a precaution.
974 *
975 * We also want to get typedef name while proceeding to resolve
976 * type it points to so that we can add parentheses if it is a
977 * "typedef struct" etc.
978 */
979 for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
980
981 switch (BTF_INFO_KIND(t->info)) {
982 case BTF_KIND_TYPEDEF:
983 if (!name)
984 name = btf_name_by_offset(show->btf,
985 t->name_off);
986 kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
987 id = t->type;
988 break;
989 case BTF_KIND_ARRAY:
990 kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
991 parens = "[";
992 if (!t)
993 return "";
994 array = btf_type_array(t);
995 if (array_suffix > array_suffixes)
996 array_suffix -= 2;
997 id = array->type;
998 break;
999 case BTF_KIND_PTR:
1000 kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1001 if (ptr_suffix > ptr_suffixes)
1002 ptr_suffix -= 1;
1003 id = t->type;
1004 break;
1005 default:
1006 id = 0;
1007 break;
1008 }
1009 if (!id)
1010 break;
1011 t = btf_type_skip_qualifiers(show->btf, id);
1012 }
1013 /* We may not be able to represent this type; bail to be safe */
1014 if (i == BTF_SHOW_MAX_ITER)
1015 return "";
1016
1017 if (!name)
1018 name = btf_name_by_offset(show->btf, t->name_off);
1019
1020 switch (BTF_INFO_KIND(t->info)) {
1021 case BTF_KIND_STRUCT:
1022 case BTF_KIND_UNION:
1023 prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1024 "struct" : "union";
1025 /* if it's an array of struct/union, parens is already set */
1026 if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1027 parens = "{";
1028 break;
1029 case BTF_KIND_ENUM:
6089fb32 1030 case BTF_KIND_ENUM64:
31d0bc81
AM
1031 prefix = "enum";
1032 break;
1033 default:
1034 break;
1035 }
1036
1037 /* pointer does not require parens */
1038 if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1039 parens = "";
1040 /* typedef does not require struct/union/enum prefix */
1041 if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1042 prefix = "";
1043
1044 if (!name)
1045 name = "";
1046
1047 /* Even if we don't want type name info, we want parentheses etc */
1048 if (show->flags & BTF_SHOW_NONAME)
1049 snprintf(show->state.name, sizeof(show->state.name), "%s",
1050 parens);
1051 else
1052 snprintf(show->state.name, sizeof(show->state.name),
1053 "%s%s%s(%s%s%s%s%s%s)%s",
1054 /* first 3 strings comprise ".member = " */
1055 show_member ? "." : "",
1056 show_member ? member : "",
1057 show_member ? " = " : "",
1058 /* ...next is our prefix (struct, enum, etc) */
1059 prefix,
1060 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1061 /* ...this is the type name itself */
1062 name,
1063 /* ...suffixed by the appropriate '*', '[]' suffixes */
1064 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1065 array_suffix, parens);
1066
1067 return show->state.name;
1068}
1069
1070static const char *__btf_show_indent(struct btf_show *show)
1071{
1072 const char *indents = " ";
1073 const char *indent = &indents[strlen(indents)];
1074
1075 if ((indent - show->state.depth) >= indents)
1076 return indent - show->state.depth;
1077 return indents;
1078}
1079
1080static const char *btf_show_indent(struct btf_show *show)
1081{
1082 return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1083}
1084
1085static const char *btf_show_newline(struct btf_show *show)
1086{
1087 return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1088}
1089
1090static const char *btf_show_delim(struct btf_show *show)
1091{
1092 if (show->state.depth == 0)
1093 return "";
1094
1095 if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1096 BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1097 return "|";
1098
1099 return ",";
1100}
1101
1102__printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1103{
1104 va_list args;
1105
1106 if (!show->state.depth_check) {
1107 va_start(args, fmt);
1108 show->showfn(show, fmt, args);
1109 va_end(args);
1110 }
1111}
1112
1113/* Macros are used here as btf_show_type_value[s]() prepends and appends
1114 * format specifiers to the format specifier passed in; these do the work of
1115 * adding indentation, delimiters etc while the caller simply has to specify
1116 * the type value(s) in the format specifier + value(s).
1117 */
1118#define btf_show_type_value(show, fmt, value) \
1119 do { \
a2a5580f
BD
1120 if ((value) != (__typeof__(value))0 || \
1121 (show->flags & BTF_SHOW_ZERO) || \
31d0bc81
AM
1122 show->state.depth == 0) { \
1123 btf_show(show, "%s%s" fmt "%s%s", \
1124 btf_show_indent(show), \
1125 btf_show_name(show), \
1126 value, btf_show_delim(show), \
1127 btf_show_newline(show)); \
1128 if (show->state.depth > show->state.depth_to_show) \
1129 show->state.depth_to_show = show->state.depth; \
1130 } \
1131 } while (0)
1132
1133#define btf_show_type_values(show, fmt, ...) \
1134 do { \
1135 btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show), \
1136 btf_show_name(show), \
1137 __VA_ARGS__, btf_show_delim(show), \
1138 btf_show_newline(show)); \
1139 if (show->state.depth > show->state.depth_to_show) \
1140 show->state.depth_to_show = show->state.depth; \
1141 } while (0)
1142
1143/* How much is left to copy to safe buffer after @data? */
1144static int btf_show_obj_size_left(struct btf_show *show, void *data)
1145{
1146 return show->obj.head + show->obj.size - data;
1147}
1148
1149/* Is object pointed to by @data of @size already copied to our safe buffer? */
1150static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1151{
1152 return data >= show->obj.data &&
1153 (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1154}
1155
1156/*
1157 * If object pointed to by @data of @size falls within our safe buffer, return
1158 * the equivalent pointer to the same safe data. Assumes
1159 * copy_from_kernel_nofault() has already happened and our safe buffer is
1160 * populated.
1161 */
1162static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1163{
1164 if (btf_show_obj_is_safe(show, data, size))
1165 return show->obj.safe + (data - show->obj.data);
1166 return NULL;
1167}
1168
1169/*
1170 * Return a safe-to-access version of data pointed to by @data.
1171 * We do this by copying the relevant amount of information
1172 * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1173 *
1174 * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1175 * safe copy is needed.
1176 *
1177 * Otherwise we need to determine if we have the required amount
1178 * of data (determined by the @data pointer and the size of the
1179 * largest base type we can encounter (represented by
1180 * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1181 * that we will be able to print some of the current object,
1182 * and if more is needed a copy will be triggered.
1183 * Some objects such as structs will not fit into the buffer;
1184 * in such cases additional copies when we iterate over their
1185 * members may be needed.
1186 *
1187 * btf_show_obj_safe() is used to return a safe buffer for
1188 * btf_show_start_type(); this ensures that as we recurse into
1189 * nested types we always have safe data for the given type.
1190 * This approach is somewhat wasteful; it's possible for example
1191 * that when iterating over a large union we'll end up copying the
1192 * same data repeatedly, but the goal is safety not performance.
1193 * We use stack data as opposed to per-CPU buffers because the
1194 * iteration over a type can take some time, and preemption handling
1195 * would greatly complicate use of the safe buffer.
1196 */
1197static void *btf_show_obj_safe(struct btf_show *show,
1198 const struct btf_type *t,
1199 void *data)
1200{
1201 const struct btf_type *rt;
1202 int size_left, size;
1203 void *safe = NULL;
1204
1205 if (show->flags & BTF_SHOW_UNSAFE)
1206 return data;
1207
1208 rt = btf_resolve_size(show->btf, t, &size);
1209 if (IS_ERR(rt)) {
1210 show->state.status = PTR_ERR(rt);
1211 return NULL;
1212 }
1213
1214 /*
1215 * Is this toplevel object? If so, set total object size and
1216 * initialize pointers. Otherwise check if we still fall within
1217 * our safe object data.
1218 */
1219 if (show->state.depth == 0) {
1220 show->obj.size = size;
1221 show->obj.head = data;
1222 } else {
1223 /*
1224 * If the size of the current object is > our remaining
1225 * safe buffer we _may_ need to do a new copy. However
1226 * consider the case of a nested struct; it's size pushes
1227 * us over the safe buffer limit, but showing any individual
1228 * struct members does not. In such cases, we don't need
1229 * to initiate a fresh copy yet; however we definitely need
1230 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1231 * in our buffer, regardless of the current object size.
1232 * The logic here is that as we resolve types we will
1233 * hit a base type at some point, and we need to be sure
1234 * the next chunk of data is safely available to display
1235 * that type info safely. We cannot rely on the size of
1236 * the current object here because it may be much larger
1237 * than our current buffer (e.g. task_struct is 8k).
1238 * All we want to do here is ensure that we can print the
1239 * next basic type, which we can if either
1240 * - the current type size is within the safe buffer; or
1241 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1242 * the safe buffer.
1243 */
1244 safe = __btf_show_obj_safe(show, data,
1245 min(size,
1246 BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1247 }
1248
1249 /*
1250 * We need a new copy to our safe object, either because we haven't
8fb33b60 1251 * yet copied and are initializing safe data, or because the data
31d0bc81
AM
1252 * we want falls outside the boundaries of the safe object.
1253 */
1254 if (!safe) {
1255 size_left = btf_show_obj_size_left(show, data);
1256 if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1257 size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1258 show->state.status = copy_from_kernel_nofault(show->obj.safe,
1259 data, size_left);
1260 if (!show->state.status) {
1261 show->obj.data = data;
1262 safe = show->obj.safe;
1263 }
1264 }
1265
1266 return safe;
1267}
1268
1269/*
1270 * Set the type we are starting to show and return a safe data pointer
1271 * to be used for showing the associated data.
1272 */
1273static void *btf_show_start_type(struct btf_show *show,
1274 const struct btf_type *t,
1275 u32 type_id, void *data)
1276{
1277 show->state.type = t;
1278 show->state.type_id = type_id;
1279 show->state.name[0] = '\0';
1280
1281 return btf_show_obj_safe(show, t, data);
1282}
1283
1284static void btf_show_end_type(struct btf_show *show)
1285{
1286 show->state.type = NULL;
1287 show->state.type_id = 0;
1288 show->state.name[0] = '\0';
1289}
1290
1291static void *btf_show_start_aggr_type(struct btf_show *show,
1292 const struct btf_type *t,
1293 u32 type_id, void *data)
1294{
1295 void *safe_data = btf_show_start_type(show, t, type_id, data);
1296
1297 if (!safe_data)
1298 return safe_data;
1299
1300 btf_show(show, "%s%s%s", btf_show_indent(show),
1301 btf_show_name(show),
1302 btf_show_newline(show));
1303 show->state.depth++;
1304 return safe_data;
1305}
1306
1307static void btf_show_end_aggr_type(struct btf_show *show,
1308 const char *suffix)
1309{
1310 show->state.depth--;
1311 btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1312 btf_show_delim(show), btf_show_newline(show));
1313 btf_show_end_type(show);
1314}
1315
1316static void btf_show_start_member(struct btf_show *show,
1317 const struct btf_member *m)
1318{
1319 show->state.member = m;
1320}
1321
1322static void btf_show_start_array_member(struct btf_show *show)
1323{
1324 show->state.array_member = 1;
1325 btf_show_start_member(show, NULL);
1326}
1327
1328static void btf_show_end_member(struct btf_show *show)
1329{
1330 show->state.member = NULL;
1331}
1332
1333static void btf_show_end_array_member(struct btf_show *show)
1334{
1335 show->state.array_member = 0;
1336 btf_show_end_member(show);
1337}
1338
1339static void *btf_show_start_array_type(struct btf_show *show,
1340 const struct btf_type *t,
1341 u32 type_id,
1342 u16 array_encoding,
1343 void *data)
1344{
1345 show->state.array_encoding = array_encoding;
1346 show->state.array_terminated = 0;
1347 return btf_show_start_aggr_type(show, t, type_id, data);
1348}
1349
1350static void btf_show_end_array_type(struct btf_show *show)
1351{
1352 show->state.array_encoding = 0;
1353 show->state.array_terminated = 0;
1354 btf_show_end_aggr_type(show, "]");
1355}
1356
1357static void *btf_show_start_struct_type(struct btf_show *show,
1358 const struct btf_type *t,
1359 u32 type_id,
1360 void *data)
1361{
1362 return btf_show_start_aggr_type(show, t, type_id, data);
1363}
1364
1365static void btf_show_end_struct_type(struct btf_show *show)
1366{
1367 btf_show_end_aggr_type(show, "}");
1368}
1369
69b693f0
MKL
1370__printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1371 const char *fmt, ...)
1372{
1373 va_list args;
1374
1375 va_start(args, fmt);
1376 bpf_verifier_vlog(log, fmt, args);
1377 va_end(args);
1378}
1379
1380__printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1381 const char *fmt, ...)
1382{
1383 struct bpf_verifier_log *log = &env->log;
1384 va_list args;
1385
1386 if (!bpf_verifier_log_needed(log))
1387 return;
1388
1389 va_start(args, fmt);
1390 bpf_verifier_vlog(log, fmt, args);
1391 va_end(args);
1392}
1393
1394__printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1395 const struct btf_type *t,
1396 bool log_details,
1397 const char *fmt, ...)
1398{
1399 struct bpf_verifier_log *log = &env->log;
69b693f0
MKL
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,
571f9738 1415 btf_type_str(t),
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 3130 const struct btf_member *last_member;
a37a3258 3131 u32 last_member_type_id;
eb3f595d
MKL
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
aa3496ac 3194enum btf_field_info_type {
42ba1308
KKD
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 {
aa3496ac 3206 enum btf_field_type type;
42ba1308 3207 u32 off;
f0c5941f
KKD
3208 union {
3209 struct {
3210 u32 type_id;
3211 } kptr;
3212 struct {
3213 const char *node_name;
3214 u32 value_btf_id;
3215 } list_head;
3216 };
42ba1308
KKD
3217};
3218
3219static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
db559117
KKD
3220 u32 off, int sz, enum btf_field_type field_type,
3221 struct btf_field_info *info)
42ba1308
KKD
3222{
3223 if (!__btf_type_is_struct(t))
61df10c7 3224 return BTF_FIELD_IGNORE;
42ba1308 3225 if (t->size != sz)
61df10c7 3226 return BTF_FIELD_IGNORE;
db559117 3227 info->type = field_type;
42ba1308 3228 info->off = off;
61df10c7
KKD
3229 return BTF_FIELD_FOUND;
3230}
3231
3232static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3233 u32 off, int sz, struct btf_field_info *info)
3234{
aa3496ac 3235 enum btf_field_type type;
61df10c7
KKD
3236 u32 res_id;
3237
23da464d
KKD
3238 /* Permit modifiers on the pointer itself */
3239 if (btf_type_is_volatile(t))
3240 t = btf_type_by_id(btf, t->type);
61df10c7
KKD
3241 /* For PTR, sz is always == 8 */
3242 if (!btf_type_is_ptr(t))
3243 return BTF_FIELD_IGNORE;
3244 t = btf_type_by_id(btf, t->type);
3245
3246 if (!btf_type_is_type_tag(t))
3247 return BTF_FIELD_IGNORE;
3248 /* Reject extra tags */
3249 if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3250 return -EINVAL;
c0a5a21c
KKD
3251 if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3252 type = BPF_KPTR_UNREF;
3253 else if (!strcmp("kptr_ref", __btf_name_by_offset(btf, t->name_off)))
3254 type = BPF_KPTR_REF;
3255 else
61df10c7
KKD
3256 return -EINVAL;
3257
3258 /* Get the base type */
3259 t = btf_type_skip_modifiers(btf, t->type, &res_id);
3260 /* Only pointer to struct is allowed */
3261 if (!__btf_type_is_struct(t))
3262 return -EINVAL;
3263
c0a5a21c 3264 info->type = type;
db559117
KKD
3265 info->off = off;
3266 info->kptr.type_id = res_id;
61df10c7 3267 return BTF_FIELD_FOUND;
42ba1308
KKD
3268}
3269
f0c5941f
KKD
3270static const char *btf_find_decl_tag_value(const struct btf *btf,
3271 const struct btf_type *pt,
3272 int comp_idx, const char *tag_key)
3273{
3274 int i;
3275
3276 for (i = 1; i < btf_nr_types(btf); i++) {
3277 const struct btf_type *t = btf_type_by_id(btf, i);
3278 int len = strlen(tag_key);
3279
3280 if (!btf_type_is_decl_tag(t))
3281 continue;
3282 if (pt != btf_type_by_id(btf, t->type) ||
3283 btf_type_decl_tag(t)->component_idx != comp_idx)
3284 continue;
3285 if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3286 continue;
3287 return __btf_name_by_offset(btf, t->name_off) + len;
3288 }
3289 return NULL;
3290}
3291
3292static int btf_find_list_head(const struct btf *btf, const struct btf_type *pt,
3293 const struct btf_type *t, int comp_idx,
3294 u32 off, int sz, struct btf_field_info *info)
3295{
3296 const char *value_type;
3297 const char *list_node;
3298 s32 id;
3299
3300 if (!__btf_type_is_struct(t))
3301 return BTF_FIELD_IGNORE;
3302 if (t->size != sz)
3303 return BTF_FIELD_IGNORE;
3304 value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3305 if (!value_type)
3306 return -EINVAL;
3307 list_node = strstr(value_type, ":");
3308 if (!list_node)
3309 return -EINVAL;
3310 value_type = kstrndup(value_type, list_node - value_type, GFP_KERNEL | __GFP_NOWARN);
3311 if (!value_type)
3312 return -ENOMEM;
3313 id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3314 kfree(value_type);
3315 if (id < 0)
3316 return id;
3317 list_node++;
3318 if (str_is_empty(list_node))
3319 return -EINVAL;
3320 info->type = BPF_LIST_HEAD;
3321 info->off = off;
3322 info->list_head.value_btf_id = id;
3323 info->list_head.node_name = list_node;
3324 return BTF_FIELD_FOUND;
3325}
3326
db559117
KKD
3327static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3328 int *align, int *sz)
3329{
3330 int type = 0;
3331
3332 if (field_mask & BPF_SPIN_LOCK) {
3333 if (!strcmp(name, "bpf_spin_lock")) {
3334 if (*seen_mask & BPF_SPIN_LOCK)
3335 return -E2BIG;
3336 *seen_mask |= BPF_SPIN_LOCK;
3337 type = BPF_SPIN_LOCK;
3338 goto end;
3339 }
3340 }
3341 if (field_mask & BPF_TIMER) {
3342 if (!strcmp(name, "bpf_timer")) {
3343 if (*seen_mask & BPF_TIMER)
3344 return -E2BIG;
3345 *seen_mask |= BPF_TIMER;
3346 type = BPF_TIMER;
3347 goto end;
3348 }
3349 }
f0c5941f
KKD
3350 if (field_mask & BPF_LIST_HEAD) {
3351 if (!strcmp(name, "bpf_list_head")) {
3352 type = BPF_LIST_HEAD;
3353 goto end;
3354 }
3355 }
db559117
KKD
3356 /* Only return BPF_KPTR when all other types with matchable names fail */
3357 if (field_mask & BPF_KPTR) {
3358 type = BPF_KPTR_REF;
3359 goto end;
3360 }
3361 return 0;
3362end:
3363 *sz = btf_field_type_size(type);
3364 *align = btf_field_type_align(type);
3365 return type;
3366}
3367
3368static int btf_find_struct_field(const struct btf *btf,
3369 const struct btf_type *t, u32 field_mask,
61df10c7 3370 struct btf_field_info *info, int info_cnt)
d83525ca 3371{
db559117 3372 int ret, idx = 0, align, sz, field_type;
d83525ca 3373 const struct btf_member *member;
61df10c7 3374 struct btf_field_info tmp;
db559117 3375 u32 i, off, seen_mask = 0;
d83525ca 3376
d83525ca
AS
3377 for_each_member(i, t, member) {
3378 const struct btf_type *member_type = btf_type_by_id(btf,
3379 member->type);
42ba1308 3380
db559117
KKD
3381 field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3382 field_mask, &seen_mask, &align, &sz);
3383 if (field_type == 0)
d83525ca 3384 continue;
db559117
KKD
3385 if (field_type < 0)
3386 return field_type;
42ba1308 3387
8293eb99 3388 off = __btf_member_bit_offset(t, member);
d83525ca
AS
3389 if (off % 8)
3390 /* valid C code cannot generate such BTF */
3391 return -EINVAL;
3392 off /= 8;
68134668 3393 if (off % align)
db559117 3394 continue;
42ba1308
KKD
3395
3396 switch (field_type) {
db559117
KKD
3397 case BPF_SPIN_LOCK:
3398 case BPF_TIMER:
3399 ret = btf_find_struct(btf, member_type, off, sz, field_type,
61df10c7
KKD
3400 idx < info_cnt ? &info[idx] : &tmp);
3401 if (ret < 0)
3402 return ret;
3403 break;
db559117
KKD
3404 case BPF_KPTR_UNREF:
3405 case BPF_KPTR_REF:
61df10c7
KKD
3406 ret = btf_find_kptr(btf, member_type, off, sz,
3407 idx < info_cnt ? &info[idx] : &tmp);
3408 if (ret < 0)
3409 return ret;
3410 break;
f0c5941f
KKD
3411 case BPF_LIST_HEAD:
3412 ret = btf_find_list_head(btf, t, member_type, i, off, sz,
3413 idx < info_cnt ? &info[idx] : &tmp);
3414 if (ret < 0)
3415 return ret;
3416 break;
42ba1308
KKD
3417 default:
3418 return -EFAULT;
3419 }
61df10c7
KKD
3420
3421 if (ret == BTF_FIELD_IGNORE)
3422 continue;
3423 if (idx >= info_cnt)
3424 return -E2BIG;
3425 ++idx;
68134668 3426 }
61df10c7 3427 return idx;
68134668
AS
3428}
3429
3430static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
db559117
KKD
3431 u32 field_mask, struct btf_field_info *info,
3432 int info_cnt)
68134668 3433{
db559117 3434 int ret, idx = 0, align, sz, field_type;
68134668 3435 const struct btf_var_secinfo *vsi;
61df10c7 3436 struct btf_field_info tmp;
db559117 3437 u32 i, off, seen_mask = 0;
68134668
AS
3438
3439 for_each_vsi(i, t, vsi) {
3440 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3441 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3442
db559117
KKD
3443 field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3444 field_mask, &seen_mask, &align, &sz);
3445 if (field_type == 0)
68134668 3446 continue;
db559117
KKD
3447 if (field_type < 0)
3448 return field_type;
3449
3450 off = vsi->offset;
68134668
AS
3451 if (vsi->size != sz)
3452 continue;
68134668 3453 if (off % align)
db559117 3454 continue;
42ba1308
KKD
3455
3456 switch (field_type) {
db559117
KKD
3457 case BPF_SPIN_LOCK:
3458 case BPF_TIMER:
3459 ret = btf_find_struct(btf, var_type, off, sz, field_type,
61df10c7
KKD
3460 idx < info_cnt ? &info[idx] : &tmp);
3461 if (ret < 0)
3462 return ret;
3463 break;
db559117
KKD
3464 case BPF_KPTR_UNREF:
3465 case BPF_KPTR_REF:
61df10c7
KKD
3466 ret = btf_find_kptr(btf, var_type, off, sz,
3467 idx < info_cnt ? &info[idx] : &tmp);
3468 if (ret < 0)
3469 return ret;
3470 break;
f0c5941f
KKD
3471 case BPF_LIST_HEAD:
3472 ret = btf_find_list_head(btf, var, var_type, -1, off, sz,
3473 idx < info_cnt ? &info[idx] : &tmp);
3474 if (ret < 0)
3475 return ret;
3476 break;
42ba1308
KKD
3477 default:
3478 return -EFAULT;
3479 }
61df10c7
KKD
3480
3481 if (ret == BTF_FIELD_IGNORE)
3482 continue;
3483 if (idx >= info_cnt)
3484 return -E2BIG;
3485 ++idx;
d83525ca 3486 }
61df10c7 3487 return idx;
d83525ca
AS
3488}
3489
68134668 3490static int btf_find_field(const struct btf *btf, const struct btf_type *t,
db559117
KKD
3491 u32 field_mask, struct btf_field_info *info,
3492 int info_cnt)
68134668 3493{
68134668 3494 if (__btf_type_is_struct(t))
db559117 3495 return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
68134668 3496 else if (btf_type_is_datasec(t))
db559117 3497 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
68134668
AS
3498 return -EINVAL;
3499}
3500
db559117
KKD
3501static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3502 struct btf_field_info *info)
68134668 3503{
db559117
KKD
3504 struct module *mod = NULL;
3505 const struct btf_type *t;
3506 struct btf *kernel_btf;
42ba1308 3507 int ret;
db559117 3508 s32 id;
42ba1308 3509
db559117
KKD
3510 /* Find type in map BTF, and use it to look up the matching type
3511 * in vmlinux or module BTFs, by name and kind.
3512 */
3513 t = btf_type_by_id(btf, info->kptr.type_id);
3514 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3515 &kernel_btf);
3516 if (id < 0)
3517 return id;
3518
3519 /* Find and stash the function pointer for the destruction function that
3520 * needs to be eventually invoked from the map free path.
3521 */
3522 if (info->type == BPF_KPTR_REF) {
3523 const struct btf_type *dtor_func;
3524 const char *dtor_func_name;
3525 unsigned long addr;
3526 s32 dtor_btf_id;
3527
3528 /* This call also serves as a whitelist of allowed objects that
3529 * can be used as a referenced pointer and be stored in a map at
3530 * the same time.
3531 */
3532 dtor_btf_id = btf_find_dtor_kfunc(kernel_btf, id);
3533 if (dtor_btf_id < 0) {
3534 ret = dtor_btf_id;
3535 goto end_btf;
3536 }
68134668 3537
db559117
KKD
3538 dtor_func = btf_type_by_id(kernel_btf, dtor_btf_id);
3539 if (!dtor_func) {
3540 ret = -ENOENT;
3541 goto end_btf;
3542 }
42ba1308 3543
db559117
KKD
3544 if (btf_is_module(kernel_btf)) {
3545 mod = btf_try_get_module(kernel_btf);
3546 if (!mod) {
3547 ret = -ENXIO;
3548 goto end_btf;
3549 }
3550 }
3551
3552 /* We already verified dtor_func to be btf_type_is_func
3553 * in register_btf_id_dtor_kfuncs.
3554 */
3555 dtor_func_name = __btf_name_by_offset(kernel_btf, dtor_func->name_off);
3556 addr = kallsyms_lookup_name(dtor_func_name);
3557 if (!addr) {
3558 ret = -EINVAL;
3559 goto end_mod;
3560 }
3561 field->kptr.dtor = (void *)addr;
3562 }
3563
3564 field->kptr.btf_id = id;
3565 field->kptr.btf = kernel_btf;
3566 field->kptr.module = mod;
3567 return 0;
3568end_mod:
3569 module_put(mod);
3570end_btf:
3571 btf_put(kernel_btf);
3572 return ret;
68134668
AS
3573}
3574
f0c5941f
KKD
3575static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3576 struct btf_field_info *info)
3577{
3578 const struct btf_type *t, *n = NULL;
3579 const struct btf_member *member;
3580 u32 offset;
3581 int i;
3582
3583 t = btf_type_by_id(btf, info->list_head.value_btf_id);
3584 /* We've already checked that value_btf_id is a struct type. We
3585 * just need to figure out the offset of the list_node, and
3586 * verify its type.
3587 */
3588 for_each_member(i, t, member) {
3589 if (strcmp(info->list_head.node_name, __btf_name_by_offset(btf, member->name_off)))
3590 continue;
3591 /* Invalid BTF, two members with same name */
3592 if (n)
3593 return -EINVAL;
3594 n = btf_type_by_id(btf, member->type);
3595 if (!__btf_type_is_struct(n))
3596 return -EINVAL;
3597 if (strcmp("bpf_list_node", __btf_name_by_offset(btf, n->name_off)))
3598 return -EINVAL;
3599 offset = __btf_member_bit_offset(n, member);
3600 if (offset % 8)
3601 return -EINVAL;
3602 offset /= 8;
3603 if (offset % __alignof__(struct bpf_list_node))
3604 return -EINVAL;
3605
3606 field->list_head.btf = (struct btf *)btf;
3607 field->list_head.value_btf_id = info->list_head.value_btf_id;
3608 field->list_head.node_offset = offset;
3609 }
3610 if (!n)
3611 return -ENOENT;
3612 return 0;
3613}
3614
db559117
KKD
3615struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3616 u32 field_mask, u32 value_size)
61df10c7 3617{
aa3496ac 3618 struct btf_field_info info_arr[BTF_FIELDS_MAX];
aa3496ac 3619 struct btf_record *rec;
f0c5941f 3620 u32 next_off = 0;
aa3496ac 3621 int ret, i, cnt;
61df10c7 3622
db559117 3623 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
61df10c7
KKD
3624 if (ret < 0)
3625 return ERR_PTR(ret);
3626 if (!ret)
3627 return NULL;
3628
aa3496ac
KKD
3629 cnt = ret;
3630 rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3631 if (!rec)
61df10c7 3632 return ERR_PTR(-ENOMEM);
61df10c7 3633
db559117
KKD
3634 rec->spin_lock_off = -EINVAL;
3635 rec->timer_off = -EINVAL;
3636 for (i = 0; i < cnt; i++) {
3637 if (info_arr[i].off + btf_field_type_size(info_arr[i].type) > value_size) {
3638 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3639 ret = -EFAULT;
61df10c7
KKD
3640 goto end;
3641 }
f0c5941f
KKD
3642 if (info_arr[i].off < next_off) {
3643 ret = -EEXIST;
3644 goto end;
3645 }
3646 next_off = info_arr[i].off + btf_field_type_size(info_arr[i].type);
61df10c7 3647
aa3496ac
KKD
3648 rec->field_mask |= info_arr[i].type;
3649 rec->fields[i].offset = info_arr[i].off;
3650 rec->fields[i].type = info_arr[i].type;
db559117
KKD
3651
3652 switch (info_arr[i].type) {
3653 case BPF_SPIN_LOCK:
3654 WARN_ON_ONCE(rec->spin_lock_off >= 0);
3655 /* Cache offset for faster lookup at runtime */
3656 rec->spin_lock_off = rec->fields[i].offset;
3657 break;
3658 case BPF_TIMER:
3659 WARN_ON_ONCE(rec->timer_off >= 0);
3660 /* Cache offset for faster lookup at runtime */
3661 rec->timer_off = rec->fields[i].offset;
3662 break;
3663 case BPF_KPTR_UNREF:
3664 case BPF_KPTR_REF:
3665 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3666 if (ret < 0)
3667 goto end;
3668 break;
f0c5941f
KKD
3669 case BPF_LIST_HEAD:
3670 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3671 if (ret < 0)
3672 goto end;
3673 break;
db559117
KKD
3674 default:
3675 ret = -EFAULT;
3676 goto end;
3677 }
aa3496ac 3678 rec->cnt++;
61df10c7 3679 }
f0c5941f
KKD
3680
3681 /* bpf_list_head requires bpf_spin_lock */
3682 if (btf_record_has_field(rec, BPF_LIST_HEAD) && rec->spin_lock_off < 0) {
3683 ret = -EINVAL;
3684 goto end;
3685 }
3686
aa3496ac 3687 return rec;
61df10c7 3688end:
aa3496ac 3689 btf_record_free(rec);
61df10c7
KKD
3690 return ERR_PTR(ret);
3691}
3692
f71b2f64
KKD
3693static int btf_field_offs_cmp(const void *_a, const void *_b, const void *priv)
3694{
3695 const u32 a = *(const u32 *)_a;
3696 const u32 b = *(const u32 *)_b;
3697
3698 if (a < b)
3699 return -1;
3700 else if (a > b)
3701 return 1;
3702 return 0;
3703}
3704
3705static void btf_field_offs_swap(void *_a, void *_b, int size, const void *priv)
3706{
3707 struct btf_field_offs *foffs = (void *)priv;
3708 u32 *off_base = foffs->field_off;
3709 u32 *a = _a, *b = _b;
3710 u8 *sz_a, *sz_b;
3711
3712 sz_a = foffs->field_sz + (a - off_base);
3713 sz_b = foffs->field_sz + (b - off_base);
3714
3715 swap(*a, *b);
3716 swap(*sz_a, *sz_b);
3717}
3718
3719struct btf_field_offs *btf_parse_field_offs(struct btf_record *rec)
3720{
3721 struct btf_field_offs *foffs;
3722 u32 i, *off;
3723 u8 *sz;
3724
3725 BUILD_BUG_ON(ARRAY_SIZE(foffs->field_off) != ARRAY_SIZE(foffs->field_sz));
2d577252 3726 if (IS_ERR_OR_NULL(rec))
f71b2f64
KKD
3727 return NULL;
3728
3729 foffs = kzalloc(sizeof(*foffs), GFP_KERNEL | __GFP_NOWARN);
3730 if (!foffs)
3731 return ERR_PTR(-ENOMEM);
3732
3733 off = foffs->field_off;
3734 sz = foffs->field_sz;
3735 for (i = 0; i < rec->cnt; i++) {
3736 off[i] = rec->fields[i].offset;
3737 sz[i] = btf_field_type_size(rec->fields[i].type);
3738 }
3739 foffs->cnt = rec->cnt;
3740
3741 if (foffs->cnt == 1)
3742 return foffs;
3743 sort_r(foffs->field_off, foffs->cnt, sizeof(foffs->field_off[0]),
3744 btf_field_offs_cmp, btf_field_offs_swap, foffs);
3745 return foffs;
3746}
3747
31d0bc81
AM
3748static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3749 u32 type_id, void *data, u8 bits_offset,
3750 struct btf_show *show)
b00b8dae 3751{
b00b8dae 3752 const struct btf_member *member;
31d0bc81 3753 void *safe_data;
b00b8dae
MKL
3754 u32 i;
3755
31d0bc81
AM
3756 safe_data = btf_show_start_struct_type(show, t, type_id, data);
3757 if (!safe_data)
3758 return;
3759
b00b8dae
MKL
3760 for_each_member(i, t, member) {
3761 const struct btf_type *member_type = btf_type_by_id(btf,
3762 member->type);
b00b8dae 3763 const struct btf_kind_operations *ops;
9d5f9f70
YS
3764 u32 member_offset, bitfield_size;
3765 u32 bytes_offset;
3766 u8 bits8_offset;
b00b8dae 3767
31d0bc81 3768 btf_show_start_member(show, member);
b00b8dae 3769
8293eb99
AS
3770 member_offset = __btf_member_bit_offset(t, member);
3771 bitfield_size = __btf_member_bitfield_size(t, member);
17e3ac81
YS
3772 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3773 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
9d5f9f70 3774 if (bitfield_size) {
31d0bc81
AM
3775 safe_data = btf_show_start_type(show, member_type,
3776 member->type,
3777 data + bytes_offset);
3778 if (safe_data)
3779 btf_bitfield_show(safe_data,
3780 bits8_offset,
3781 bitfield_size, show);
3782 btf_show_end_type(show);
9d5f9f70 3783 } else {
9d5f9f70 3784 ops = btf_type_ops(member_type);
31d0bc81
AM
3785 ops->show(btf, member_type, member->type,
3786 data + bytes_offset, bits8_offset, show);
9d5f9f70 3787 }
31d0bc81
AM
3788
3789 btf_show_end_member(show);
b00b8dae 3790 }
31d0bc81
AM
3791
3792 btf_show_end_struct_type(show);
3793}
3794
3795static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3796 u32 type_id, void *data, u8 bits_offset,
3797 struct btf_show *show)
3798{
3799 const struct btf_member *m = show->state.member;
3800
3801 /*
3802 * First check if any members would be shown (are non-zero).
3803 * See comments above "struct btf_show" definition for more
3804 * details on how this works at a high-level.
3805 */
3806 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3807 if (!show->state.depth_check) {
3808 show->state.depth_check = show->state.depth + 1;
3809 show->state.depth_to_show = 0;
3810 }
3811 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
3812 /* Restore saved member data here */
3813 show->state.member = m;
3814 if (show->state.depth_check != show->state.depth + 1)
3815 return;
3816 show->state.depth_check = 0;
3817
3818 if (show->state.depth_to_show <= show->state.depth)
3819 return;
3820 /*
3821 * Reaching here indicates we have recursed and found
3822 * non-zero child values.
3823 */
3824 }
3825
3826 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
b00b8dae
MKL
3827}
3828
69b693f0
MKL
3829static struct btf_kind_operations struct_ops = {
3830 .check_meta = btf_struct_check_meta,
eb3f595d 3831 .resolve = btf_struct_resolve,
179cde8c 3832 .check_member = btf_struct_check_member,
9d5f9f70 3833 .check_kflag_member = btf_generic_check_kflag_member,
69b693f0 3834 .log_details = btf_struct_log,
31d0bc81 3835 .show = btf_struct_show,
69b693f0
MKL
3836};
3837
179cde8c
MKL
3838static int btf_enum_check_member(struct btf_verifier_env *env,
3839 const struct btf_type *struct_type,
3840 const struct btf_member *member,
3841 const struct btf_type *member_type)
3842{
3843 u32 struct_bits_off = member->offset;
3844 u32 struct_size, bytes_offset;
3845
3846 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3847 btf_verifier_log_member(env, struct_type, member,
3848 "Member is not byte aligned");
3849 return -EINVAL;
3850 }
3851
3852 struct_size = struct_type->size;
3853 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
da6c7fae 3854 if (struct_size - bytes_offset < member_type->size) {
179cde8c
MKL
3855 btf_verifier_log_member(env, struct_type, member,
3856 "Member exceeds struct_size");
3857 return -EINVAL;
3858 }
3859
3860 return 0;
3861}
3862
9d5f9f70
YS
3863static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3864 const struct btf_type *struct_type,
3865 const struct btf_member *member,
3866 const struct btf_type *member_type)
3867{
3868 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3869 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3870
3871 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3872 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3873 if (!nr_bits) {
3874 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3875 btf_verifier_log_member(env, struct_type, member,
3876 "Member is not byte aligned");
e3439af4 3877 return -EINVAL;
9d5f9f70
YS
3878 }
3879
3880 nr_bits = int_bitsize;
3881 } else if (nr_bits > int_bitsize) {
3882 btf_verifier_log_member(env, struct_type, member,
3883 "Invalid member bitfield_size");
3884 return -EINVAL;
3885 }
3886
3887 struct_size = struct_type->size;
3888 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3889 if (struct_size < bytes_end) {
3890 btf_verifier_log_member(env, struct_type, member,
3891 "Member exceeds struct_size");
3892 return -EINVAL;
3893 }
3894
3895 return 0;
3896}
3897
69b693f0
MKL
3898static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3899 const struct btf_type *t,
3900 u32 meta_left)
3901{
3902 const struct btf_enum *enums = btf_type_enum(t);
3903 struct btf *btf = env->btf;
6089fb32 3904 const char *fmt_str;
69b693f0
MKL
3905 u16 i, nr_enums;
3906 u32 meta_needed;
3907
3908 nr_enums = btf_type_vlen(t);
3909 meta_needed = nr_enums * sizeof(*enums);
3910
3911 if (meta_left < meta_needed) {
3912 btf_verifier_log_basic(env, t,
3913 "meta_left:%u meta_needed:%u",
3914 meta_left, meta_needed);
3915 return -EINVAL;
3916 }
3917
9eea9849
AS
3918 if (t->size > 8 || !is_power_of_2(t->size)) {
3919 btf_verifier_log_type(env, t, "Unexpected size");
69b693f0
MKL
3920 return -EINVAL;
3921 }
3922
eb04bbb6
YS
3923 /* enum type either no name or a valid one */
3924 if (t->name_off &&
3925 !btf_name_valid_identifier(env->btf, t->name_off)) {
3926 btf_verifier_log_type(env, t, "Invalid name");
3927 return -EINVAL;
3928 }
3929
69b693f0
MKL
3930 btf_verifier_log_type(env, t, NULL);
3931
3932 for (i = 0; i < nr_enums; i++) {
fbcf93eb 3933 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
69b693f0 3934 btf_verifier_log(env, "\tInvalid name_offset:%u",
fbcf93eb 3935 enums[i].name_off);
69b693f0
MKL
3936 return -EINVAL;
3937 }
3938
eb04bbb6
YS
3939 /* enum member must have a valid name */
3940 if (!enums[i].name_off ||
3941 !btf_name_valid_identifier(btf, enums[i].name_off)) {
3942 btf_verifier_log_type(env, t, "Invalid name");
3943 return -EINVAL;
3944 }
3945
8580ac94
AS
3946 if (env->log.level == BPF_LOG_KERNEL)
3947 continue;
6089fb32
YS
3948 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
3949 btf_verifier_log(env, fmt_str,
23127b33 3950 __btf_name_by_offset(btf, enums[i].name_off),
69b693f0
MKL
3951 enums[i].val);
3952 }
3953
3954 return meta_needed;
3955}
3956
3957static void btf_enum_log(struct btf_verifier_env *env,
3958 const struct btf_type *t)
3959{
3960 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3961}
3962
31d0bc81
AM
3963static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3964 u32 type_id, void *data, u8 bits_offset,
3965 struct btf_show *show)
b00b8dae
MKL
3966{
3967 const struct btf_enum *enums = btf_type_enum(t);
3968 u32 i, nr_enums = btf_type_vlen(t);
31d0bc81
AM
3969 void *safe_data;
3970 int v;
3971
3972 safe_data = btf_show_start_type(show, t, type_id, data);
3973 if (!safe_data)
3974 return;
3975
3976 v = *(int *)safe_data;
b00b8dae
MKL
3977
3978 for (i = 0; i < nr_enums; i++) {
31d0bc81
AM
3979 if (v != enums[i].val)
3980 continue;
3981
3982 btf_show_type_value(show, "%s",
3983 __btf_name_by_offset(btf,
3984 enums[i].name_off));
3985
3986 btf_show_end_type(show);
3987 return;
b00b8dae
MKL
3988 }
3989
6089fb32
YS
3990 if (btf_type_kflag(t))
3991 btf_show_type_value(show, "%d", v);
3992 else
3993 btf_show_type_value(show, "%u", v);
31d0bc81 3994 btf_show_end_type(show);
b00b8dae
MKL
3995}
3996
69b693f0
MKL
3997static struct btf_kind_operations enum_ops = {
3998 .check_meta = btf_enum_check_meta,
eb3f595d 3999 .resolve = btf_df_resolve,
179cde8c 4000 .check_member = btf_enum_check_member,
9d5f9f70 4001 .check_kflag_member = btf_enum_check_kflag_member,
69b693f0 4002 .log_details = btf_enum_log,
31d0bc81 4003 .show = btf_enum_show,
69b693f0
MKL
4004};
4005
6089fb32
YS
4006static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4007 const struct btf_type *t,
4008 u32 meta_left)
4009{
4010 const struct btf_enum64 *enums = btf_type_enum64(t);
4011 struct btf *btf = env->btf;
4012 const char *fmt_str;
4013 u16 i, nr_enums;
4014 u32 meta_needed;
4015
4016 nr_enums = btf_type_vlen(t);
4017 meta_needed = nr_enums * sizeof(*enums);
4018
4019 if (meta_left < meta_needed) {
4020 btf_verifier_log_basic(env, t,
4021 "meta_left:%u meta_needed:%u",
4022 meta_left, meta_needed);
4023 return -EINVAL;
4024 }
4025
4026 if (t->size > 8 || !is_power_of_2(t->size)) {
4027 btf_verifier_log_type(env, t, "Unexpected size");
4028 return -EINVAL;
4029 }
4030
4031 /* enum type either no name or a valid one */
4032 if (t->name_off &&
4033 !btf_name_valid_identifier(env->btf, t->name_off)) {
4034 btf_verifier_log_type(env, t, "Invalid name");
4035 return -EINVAL;
4036 }
4037
4038 btf_verifier_log_type(env, t, NULL);
4039
4040 for (i = 0; i < nr_enums; i++) {
4041 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4042 btf_verifier_log(env, "\tInvalid name_offset:%u",
4043 enums[i].name_off);
4044 return -EINVAL;
4045 }
4046
4047 /* enum member must have a valid name */
4048 if (!enums[i].name_off ||
4049 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4050 btf_verifier_log_type(env, t, "Invalid name");
4051 return -EINVAL;
4052 }
4053
4054 if (env->log.level == BPF_LOG_KERNEL)
4055 continue;
4056
4057 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4058 btf_verifier_log(env, fmt_str,
4059 __btf_name_by_offset(btf, enums[i].name_off),
4060 btf_enum64_value(enums + i));
4061 }
4062
4063 return meta_needed;
4064}
4065
4066static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4067 u32 type_id, void *data, u8 bits_offset,
4068 struct btf_show *show)
4069{
4070 const struct btf_enum64 *enums = btf_type_enum64(t);
4071 u32 i, nr_enums = btf_type_vlen(t);
4072 void *safe_data;
4073 s64 v;
4074
4075 safe_data = btf_show_start_type(show, t, type_id, data);
4076 if (!safe_data)
4077 return;
4078
4079 v = *(u64 *)safe_data;
4080
4081 for (i = 0; i < nr_enums; i++) {
4082 if (v != btf_enum64_value(enums + i))
4083 continue;
4084
4085 btf_show_type_value(show, "%s",
4086 __btf_name_by_offset(btf,
4087 enums[i].name_off));
4088
4089 btf_show_end_type(show);
4090 return;
4091 }
4092
4093 if (btf_type_kflag(t))
4094 btf_show_type_value(show, "%lld", v);
4095 else
4096 btf_show_type_value(show, "%llu", v);
4097 btf_show_end_type(show);
4098}
4099
4100static struct btf_kind_operations enum64_ops = {
4101 .check_meta = btf_enum64_check_meta,
4102 .resolve = btf_df_resolve,
4103 .check_member = btf_enum_check_member,
4104 .check_kflag_member = btf_enum_check_kflag_member,
4105 .log_details = btf_enum_log,
4106 .show = btf_enum64_show,
4107};
4108
2667a262
MKL
4109static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4110 const struct btf_type *t,
4111 u32 meta_left)
4112{
4113 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4114
4115 if (meta_left < meta_needed) {
4116 btf_verifier_log_basic(env, t,
4117 "meta_left:%u meta_needed:%u",
4118 meta_left, meta_needed);
4119 return -EINVAL;
4120 }
4121
4122 if (t->name_off) {
4123 btf_verifier_log_type(env, t, "Invalid name");
4124 return -EINVAL;
4125 }
4126
9d5f9f70
YS
4127 if (btf_type_kflag(t)) {
4128 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4129 return -EINVAL;
4130 }
4131
2667a262
MKL
4132 btf_verifier_log_type(env, t, NULL);
4133
4134 return meta_needed;
4135}
4136
4137static void btf_func_proto_log(struct btf_verifier_env *env,
4138 const struct btf_type *t)
4139{
4140 const struct btf_param *args = (const struct btf_param *)(t + 1);
4141 u16 nr_args = btf_type_vlen(t), i;
4142
4143 btf_verifier_log(env, "return=%u args=(", t->type);
4144 if (!nr_args) {
4145 btf_verifier_log(env, "void");
4146 goto done;
4147 }
4148
4149 if (nr_args == 1 && !args[0].type) {
4150 /* Only one vararg */
4151 btf_verifier_log(env, "vararg");
4152 goto done;
4153 }
4154
4155 btf_verifier_log(env, "%u %s", args[0].type,
23127b33
MKL
4156 __btf_name_by_offset(env->btf,
4157 args[0].name_off));
2667a262
MKL
4158 for (i = 1; i < nr_args - 1; i++)
4159 btf_verifier_log(env, ", %u %s", args[i].type,
23127b33
MKL
4160 __btf_name_by_offset(env->btf,
4161 args[i].name_off));
2667a262
MKL
4162
4163 if (nr_args > 1) {
4164 const struct btf_param *last_arg = &args[nr_args - 1];
4165
4166 if (last_arg->type)
4167 btf_verifier_log(env, ", %u %s", last_arg->type,
23127b33
MKL
4168 __btf_name_by_offset(env->btf,
4169 last_arg->name_off));
2667a262
MKL
4170 else
4171 btf_verifier_log(env, ", vararg");
4172 }
4173
4174done:
4175 btf_verifier_log(env, ")");
4176}
4177
4178static struct btf_kind_operations func_proto_ops = {
4179 .check_meta = btf_func_proto_check_meta,
4180 .resolve = btf_df_resolve,
4181 /*
4182 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4183 * a struct's member.
4184 *
8fb33b60 4185 * It should be a function pointer instead.
2667a262
MKL
4186 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4187 *
4188 * Hence, there is no btf_func_check_member().
4189 */
4190 .check_member = btf_df_check_member,
9d5f9f70 4191 .check_kflag_member = btf_df_check_kflag_member,
2667a262 4192 .log_details = btf_func_proto_log,
31d0bc81 4193 .show = btf_df_show,
2667a262
MKL
4194};
4195
4196static s32 btf_func_check_meta(struct btf_verifier_env *env,
4197 const struct btf_type *t,
4198 u32 meta_left)
4199{
4200 if (!t->name_off ||
4201 !btf_name_valid_identifier(env->btf, t->name_off)) {
4202 btf_verifier_log_type(env, t, "Invalid name");
4203 return -EINVAL;
4204 }
4205
51c39bb1
AS
4206 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4207 btf_verifier_log_type(env, t, "Invalid func linkage");
2667a262
MKL
4208 return -EINVAL;
4209 }
4210
9d5f9f70
YS
4211 if (btf_type_kflag(t)) {
4212 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4213 return -EINVAL;
4214 }
4215
2667a262
MKL
4216 btf_verifier_log_type(env, t, NULL);
4217
4218 return 0;
4219}
4220
d7e7b42f
YS
4221static int btf_func_resolve(struct btf_verifier_env *env,
4222 const struct resolve_vertex *v)
4223{
4224 const struct btf_type *t = v->t;
4225 u32 next_type_id = t->type;
4226 int err;
4227
4228 err = btf_func_check(env, t);
4229 if (err)
4230 return err;
4231
4232 env_stack_pop_resolved(env, next_type_id, 0);
4233 return 0;
4234}
4235
2667a262
MKL
4236static struct btf_kind_operations func_ops = {
4237 .check_meta = btf_func_check_meta,
d7e7b42f 4238 .resolve = btf_func_resolve,
2667a262 4239 .check_member = btf_df_check_member,
9d5f9f70 4240 .check_kflag_member = btf_df_check_kflag_member,
2667a262 4241 .log_details = btf_ref_type_log,
31d0bc81 4242 .show = btf_df_show,
2667a262
MKL
4243};
4244
1dc92851
DB
4245static s32 btf_var_check_meta(struct btf_verifier_env *env,
4246 const struct btf_type *t,
4247 u32 meta_left)
4248{
4249 const struct btf_var *var;
4250 u32 meta_needed = sizeof(*var);
4251
4252 if (meta_left < meta_needed) {
4253 btf_verifier_log_basic(env, t,
4254 "meta_left:%u meta_needed:%u",
4255 meta_left, meta_needed);
4256 return -EINVAL;
4257 }
4258
4259 if (btf_type_vlen(t)) {
4260 btf_verifier_log_type(env, t, "vlen != 0");
4261 return -EINVAL;
4262 }
4263
4264 if (btf_type_kflag(t)) {
4265 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4266 return -EINVAL;
4267 }
4268
4269 if (!t->name_off ||
4270 !__btf_name_valid(env->btf, t->name_off, true)) {
4271 btf_verifier_log_type(env, t, "Invalid name");
4272 return -EINVAL;
4273 }
4274
4275 /* A var cannot be in type void */
4276 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4277 btf_verifier_log_type(env, t, "Invalid type_id");
4278 return -EINVAL;
4279 }
4280
4281 var = btf_type_var(t);
4282 if (var->linkage != BTF_VAR_STATIC &&
4283 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4284 btf_verifier_log_type(env, t, "Linkage not supported");
4285 return -EINVAL;
4286 }
4287
4288 btf_verifier_log_type(env, t, NULL);
4289
4290 return meta_needed;
4291}
4292
4293static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4294{
4295 const struct btf_var *var = btf_type_var(t);
4296
4297 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4298}
4299
4300static const struct btf_kind_operations var_ops = {
4301 .check_meta = btf_var_check_meta,
4302 .resolve = btf_var_resolve,
4303 .check_member = btf_df_check_member,
4304 .check_kflag_member = btf_df_check_kflag_member,
4305 .log_details = btf_var_log,
31d0bc81 4306 .show = btf_var_show,
1dc92851
DB
4307};
4308
4309static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4310 const struct btf_type *t,
4311 u32 meta_left)
4312{
4313 const struct btf_var_secinfo *vsi;
4314 u64 last_vsi_end_off = 0, sum = 0;
4315 u32 i, meta_needed;
4316
4317 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4318 if (meta_left < meta_needed) {
4319 btf_verifier_log_basic(env, t,
4320 "meta_left:%u meta_needed:%u",
4321 meta_left, meta_needed);
4322 return -EINVAL;
4323 }
4324
1dc92851
DB
4325 if (!t->size) {
4326 btf_verifier_log_type(env, t, "size == 0");
4327 return -EINVAL;
4328 }
4329
4330 if (btf_type_kflag(t)) {
4331 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4332 return -EINVAL;
4333 }
4334
4335 if (!t->name_off ||
4336 !btf_name_valid_section(env->btf, t->name_off)) {
4337 btf_verifier_log_type(env, t, "Invalid name");
4338 return -EINVAL;
4339 }
4340
4341 btf_verifier_log_type(env, t, NULL);
4342
4343 for_each_vsi(i, t, vsi) {
4344 /* A var cannot be in type void */
4345 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4346 btf_verifier_log_vsi(env, t, vsi,
4347 "Invalid type_id");
4348 return -EINVAL;
4349 }
4350
4351 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4352 btf_verifier_log_vsi(env, t, vsi,
4353 "Invalid offset");
4354 return -EINVAL;
4355 }
4356
4357 if (!vsi->size || vsi->size > t->size) {
4358 btf_verifier_log_vsi(env, t, vsi,
4359 "Invalid size");
4360 return -EINVAL;
4361 }
4362
4363 last_vsi_end_off = vsi->offset + vsi->size;
4364 if (last_vsi_end_off > t->size) {
4365 btf_verifier_log_vsi(env, t, vsi,
4366 "Invalid offset+size");
4367 return -EINVAL;
4368 }
4369
4370 btf_verifier_log_vsi(env, t, vsi, NULL);
4371 sum += vsi->size;
4372 }
4373
4374 if (t->size < sum) {
4375 btf_verifier_log_type(env, t, "Invalid btf_info size");
4376 return -EINVAL;
4377 }
4378
4379 return meta_needed;
4380}
4381
4382static int btf_datasec_resolve(struct btf_verifier_env *env,
4383 const struct resolve_vertex *v)
4384{
4385 const struct btf_var_secinfo *vsi;
4386 struct btf *btf = env->btf;
4387 u16 i;
4388
4389 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4390 u32 var_type_id = vsi->type, type_id, type_size = 0;
4391 const struct btf_type *var_type = btf_type_by_id(env->btf,
4392 var_type_id);
4393 if (!var_type || !btf_type_is_var(var_type)) {
4394 btf_verifier_log_vsi(env, v->t, vsi,
4395 "Not a VAR kind member");
4396 return -EINVAL;
4397 }
4398
4399 if (!env_type_is_resolve_sink(env, var_type) &&
4400 !env_type_is_resolved(env, var_type_id)) {
4401 env_stack_set_next_member(env, i + 1);
4402 return env_stack_push(env, var_type, var_type_id);
4403 }
4404
4405 type_id = var_type->type;
4406 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4407 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4408 return -EINVAL;
4409 }
4410
4411 if (vsi->size < type_size) {
4412 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4413 return -EINVAL;
4414 }
4415 }
4416
4417 env_stack_pop_resolved(env, 0, 0);
4418 return 0;
4419}
4420
4421static void btf_datasec_log(struct btf_verifier_env *env,
4422 const struct btf_type *t)
4423{
4424 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4425}
4426
31d0bc81
AM
4427static void btf_datasec_show(const struct btf *btf,
4428 const struct btf_type *t, u32 type_id,
4429 void *data, u8 bits_offset,
4430 struct btf_show *show)
1dc92851
DB
4431{
4432 const struct btf_var_secinfo *vsi;
4433 const struct btf_type *var;
4434 u32 i;
4435
31d0bc81
AM
4436 if (!btf_show_start_type(show, t, type_id, data))
4437 return;
4438
4439 btf_show_type_value(show, "section (\"%s\") = {",
4440 __btf_name_by_offset(btf, t->name_off));
1dc92851
DB
4441 for_each_vsi(i, t, vsi) {
4442 var = btf_type_by_id(btf, vsi->type);
4443 if (i)
31d0bc81
AM
4444 btf_show(show, ",");
4445 btf_type_ops(var)->show(btf, var, vsi->type,
4446 data + vsi->offset, bits_offset, show);
1dc92851 4447 }
31d0bc81 4448 btf_show_end_type(show);
1dc92851
DB
4449}
4450
4451static const struct btf_kind_operations datasec_ops = {
4452 .check_meta = btf_datasec_check_meta,
4453 .resolve = btf_datasec_resolve,
4454 .check_member = btf_df_check_member,
4455 .check_kflag_member = btf_df_check_kflag_member,
4456 .log_details = btf_datasec_log,
31d0bc81 4457 .show = btf_datasec_show,
1dc92851
DB
4458};
4459
b1828f0b
IL
4460static s32 btf_float_check_meta(struct btf_verifier_env *env,
4461 const struct btf_type *t,
4462 u32 meta_left)
4463{
4464 if (btf_type_vlen(t)) {
4465 btf_verifier_log_type(env, t, "vlen != 0");
4466 return -EINVAL;
4467 }
4468
4469 if (btf_type_kflag(t)) {
4470 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4471 return -EINVAL;
4472 }
4473
4474 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4475 t->size != 16) {
4476 btf_verifier_log_type(env, t, "Invalid type_size");
4477 return -EINVAL;
4478 }
4479
4480 btf_verifier_log_type(env, t, NULL);
4481
4482 return 0;
4483}
4484
4485static int btf_float_check_member(struct btf_verifier_env *env,
4486 const struct btf_type *struct_type,
4487 const struct btf_member *member,
4488 const struct btf_type *member_type)
4489{
4490 u64 start_offset_bytes;
4491 u64 end_offset_bytes;
4492 u64 misalign_bits;
4493 u64 align_bytes;
4494 u64 align_bits;
4495
4496 /* Different architectures have different alignment requirements, so
4497 * here we check only for the reasonable minimum. This way we ensure
4498 * that types after CO-RE can pass the kernel BTF verifier.
4499 */
4500 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4501 align_bits = align_bytes * BITS_PER_BYTE;
4502 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4503 if (misalign_bits) {
4504 btf_verifier_log_member(env, struct_type, member,
4505 "Member is not properly aligned");
4506 return -EINVAL;
4507 }
4508
4509 start_offset_bytes = member->offset / BITS_PER_BYTE;
4510 end_offset_bytes = start_offset_bytes + member_type->size;
4511 if (end_offset_bytes > struct_type->size) {
4512 btf_verifier_log_member(env, struct_type, member,
4513 "Member exceeds struct_size");
4514 return -EINVAL;
4515 }
4516
4517 return 0;
4518}
4519
4520static void btf_float_log(struct btf_verifier_env *env,
4521 const struct btf_type *t)
4522{
4523 btf_verifier_log(env, "size=%u", t->size);
4524}
4525
4526static const struct btf_kind_operations float_ops = {
4527 .check_meta = btf_float_check_meta,
4528 .resolve = btf_df_resolve,
4529 .check_member = btf_float_check_member,
4530 .check_kflag_member = btf_generic_check_kflag_member,
4531 .log_details = btf_float_log,
4532 .show = btf_df_show,
4533};
4534
223f903e 4535static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
b5ea834d
YS
4536 const struct btf_type *t,
4537 u32 meta_left)
4538{
223f903e 4539 const struct btf_decl_tag *tag;
b5ea834d
YS
4540 u32 meta_needed = sizeof(*tag);
4541 s32 component_idx;
4542 const char *value;
4543
4544 if (meta_left < meta_needed) {
4545 btf_verifier_log_basic(env, t,
4546 "meta_left:%u meta_needed:%u",
4547 meta_left, meta_needed);
4548 return -EINVAL;
4549 }
4550
4551 value = btf_name_by_offset(env->btf, t->name_off);
4552 if (!value || !value[0]) {
4553 btf_verifier_log_type(env, t, "Invalid value");
4554 return -EINVAL;
4555 }
4556
4557 if (btf_type_vlen(t)) {
4558 btf_verifier_log_type(env, t, "vlen != 0");
4559 return -EINVAL;
4560 }
4561
4562 if (btf_type_kflag(t)) {
4563 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4564 return -EINVAL;
4565 }
4566
223f903e 4567 component_idx = btf_type_decl_tag(t)->component_idx;
b5ea834d
YS
4568 if (component_idx < -1) {
4569 btf_verifier_log_type(env, t, "Invalid component_idx");
4570 return -EINVAL;
4571 }
4572
4573 btf_verifier_log_type(env, t, NULL);
4574
4575 return meta_needed;
4576}
4577
223f903e 4578static int btf_decl_tag_resolve(struct btf_verifier_env *env,
b5ea834d
YS
4579 const struct resolve_vertex *v)
4580{
4581 const struct btf_type *next_type;
4582 const struct btf_type *t = v->t;
4583 u32 next_type_id = t->type;
4584 struct btf *btf = env->btf;
4585 s32 component_idx;
4586 u32 vlen;
4587
4588 next_type = btf_type_by_id(btf, next_type_id);
223f903e 4589 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
b5ea834d
YS
4590 btf_verifier_log_type(env, v->t, "Invalid type_id");
4591 return -EINVAL;
4592 }
4593
4594 if (!env_type_is_resolve_sink(env, next_type) &&
4595 !env_type_is_resolved(env, next_type_id))
4596 return env_stack_push(env, next_type, next_type_id);
4597
223f903e 4598 component_idx = btf_type_decl_tag(t)->component_idx;
b5ea834d 4599 if (component_idx != -1) {
bd16dee6 4600 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
b5ea834d
YS
4601 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4602 return -EINVAL;
4603 }
4604
4605 if (btf_type_is_struct(next_type)) {
4606 vlen = btf_type_vlen(next_type);
4607 } else {
4608 /* next_type should be a function */
4609 next_type = btf_type_by_id(btf, next_type->type);
4610 vlen = btf_type_vlen(next_type);
4611 }
4612
4613 if ((u32)component_idx >= vlen) {
4614 btf_verifier_log_type(env, v->t, "Invalid component_idx");
4615 return -EINVAL;
4616 }
4617 }
4618
4619 env_stack_pop_resolved(env, next_type_id, 0);
4620
4621 return 0;
4622}
4623
223f903e 4624static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
b5ea834d
YS
4625{
4626 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
223f903e 4627 btf_type_decl_tag(t)->component_idx);
b5ea834d
YS
4628}
4629
223f903e
YS
4630static const struct btf_kind_operations decl_tag_ops = {
4631 .check_meta = btf_decl_tag_check_meta,
4632 .resolve = btf_decl_tag_resolve,
b5ea834d
YS
4633 .check_member = btf_df_check_member,
4634 .check_kflag_member = btf_df_check_kflag_member,
223f903e 4635 .log_details = btf_decl_tag_log,
b5ea834d
YS
4636 .show = btf_df_show,
4637};
4638
2667a262
MKL
4639static int btf_func_proto_check(struct btf_verifier_env *env,
4640 const struct btf_type *t)
4641{
4642 const struct btf_type *ret_type;
4643 const struct btf_param *args;
4644 const struct btf *btf;
4645 u16 nr_args, i;
4646 int err;
4647
4648 btf = env->btf;
4649 args = (const struct btf_param *)(t + 1);
4650 nr_args = btf_type_vlen(t);
4651
4652 /* Check func return type which could be "void" (t->type == 0) */
4653 if (t->type) {
4654 u32 ret_type_id = t->type;
4655
4656 ret_type = btf_type_by_id(btf, ret_type_id);
4657 if (!ret_type) {
4658 btf_verifier_log_type(env, t, "Invalid return type");
4659 return -EINVAL;
4660 }
4661
ea68376c
SF
4662 if (btf_type_is_resolve_source_only(ret_type)) {
4663 btf_verifier_log_type(env, t, "Invalid return type");
4664 return -EINVAL;
4665 }
4666
2667a262
MKL
4667 if (btf_type_needs_resolve(ret_type) &&
4668 !env_type_is_resolved(env, ret_type_id)) {
4669 err = btf_resolve(env, ret_type, ret_type_id);
4670 if (err)
4671 return err;
4672 }
4673
4674 /* Ensure the return type is a type that has a size */
4675 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4676 btf_verifier_log_type(env, t, "Invalid return type");
4677 return -EINVAL;
4678 }
4679 }
4680
4681 if (!nr_args)
4682 return 0;
4683
4684 /* Last func arg type_id could be 0 if it is a vararg */
4685 if (!args[nr_args - 1].type) {
4686 if (args[nr_args - 1].name_off) {
4687 btf_verifier_log_type(env, t, "Invalid arg#%u",
4688 nr_args);
4689 return -EINVAL;
4690 }
4691 nr_args--;
4692 }
4693
4694 err = 0;
4695 for (i = 0; i < nr_args; i++) {
4696 const struct btf_type *arg_type;
4697 u32 arg_type_id;
4698
4699 arg_type_id = args[i].type;
4700 arg_type = btf_type_by_id(btf, arg_type_id);
4701 if (!arg_type) {
4702 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4703 err = -EINVAL;
4704 break;
4705 }
4706
4707 if (args[i].name_off &&
4708 (!btf_name_offset_valid(btf, args[i].name_off) ||
4709 !btf_name_valid_identifier(btf, args[i].name_off))) {
4710 btf_verifier_log_type(env, t,
4711 "Invalid arg#%u", i + 1);
4712 err = -EINVAL;
4713 break;
4714 }
4715
4716 if (btf_type_needs_resolve(arg_type) &&
4717 !env_type_is_resolved(env, arg_type_id)) {
4718 err = btf_resolve(env, arg_type, arg_type_id);
4719 if (err)
4720 break;
4721 }
4722
4723 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4724 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4725 err = -EINVAL;
4726 break;
4727 }
4728 }
4729
4730 return err;
4731}
4732
4733static int btf_func_check(struct btf_verifier_env *env,
4734 const struct btf_type *t)
4735{
4736 const struct btf_type *proto_type;
4737 const struct btf_param *args;
4738 const struct btf *btf;
4739 u16 nr_args, i;
4740
4741 btf = env->btf;
4742 proto_type = btf_type_by_id(btf, t->type);
4743
4744 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4745 btf_verifier_log_type(env, t, "Invalid type_id");
4746 return -EINVAL;
4747 }
4748
4749 args = (const struct btf_param *)(proto_type + 1);
4750 nr_args = btf_type_vlen(proto_type);
4751 for (i = 0; i < nr_args; i++) {
4752 if (!args[i].name_off && args[i].type) {
4753 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4754 return -EINVAL;
4755 }
4756 }
4757
4758 return 0;
4759}
4760
69b693f0
MKL
4761static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4762 [BTF_KIND_INT] = &int_ops,
4763 [BTF_KIND_PTR] = &ptr_ops,
4764 [BTF_KIND_ARRAY] = &array_ops,
4765 [BTF_KIND_STRUCT] = &struct_ops,
4766 [BTF_KIND_UNION] = &struct_ops,
4767 [BTF_KIND_ENUM] = &enum_ops,
4768 [BTF_KIND_FWD] = &fwd_ops,
4769 [BTF_KIND_TYPEDEF] = &modifier_ops,
4770 [BTF_KIND_VOLATILE] = &modifier_ops,
4771 [BTF_KIND_CONST] = &modifier_ops,
4772 [BTF_KIND_RESTRICT] = &modifier_ops,
2667a262
MKL
4773 [BTF_KIND_FUNC] = &func_ops,
4774 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
1dc92851
DB
4775 [BTF_KIND_VAR] = &var_ops,
4776 [BTF_KIND_DATASEC] = &datasec_ops,
b1828f0b 4777 [BTF_KIND_FLOAT] = &float_ops,
223f903e 4778 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
8c42d2fa 4779 [BTF_KIND_TYPE_TAG] = &modifier_ops,
6089fb32 4780 [BTF_KIND_ENUM64] = &enum64_ops,
69b693f0
MKL
4781};
4782
4783static s32 btf_check_meta(struct btf_verifier_env *env,
4784 const struct btf_type *t,
4785 u32 meta_left)
4786{
4787 u32 saved_meta_left = meta_left;
4788 s32 var_meta_size;
4789
4790 if (meta_left < sizeof(*t)) {
4791 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4792 env->log_type_id, meta_left, sizeof(*t));
4793 return -EINVAL;
4794 }
4795 meta_left -= sizeof(*t);
4796
aea2f7b8
MKL
4797 if (t->info & ~BTF_INFO_MASK) {
4798 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4799 env->log_type_id, t->info);
4800 return -EINVAL;
4801 }
4802
69b693f0
MKL
4803 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4804 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4805 btf_verifier_log(env, "[%u] Invalid kind:%u",
4806 env->log_type_id, BTF_INFO_KIND(t->info));
4807 return -EINVAL;
4808 }
4809
fbcf93eb 4810 if (!btf_name_offset_valid(env->btf, t->name_off)) {
69b693f0 4811 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
fbcf93eb 4812 env->log_type_id, t->name_off);
69b693f0
MKL
4813 return -EINVAL;
4814 }
4815
4816 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4817 if (var_meta_size < 0)
4818 return var_meta_size;
4819
4820 meta_left -= var_meta_size;
4821
4822 return saved_meta_left - meta_left;
4823}
4824
4825static int btf_check_all_metas(struct btf_verifier_env *env)
4826{
4827 struct btf *btf = env->btf;
4828 struct btf_header *hdr;
4829 void *cur, *end;
4830
f80442a4 4831 hdr = &btf->hdr;
69b693f0 4832 cur = btf->nohdr_data + hdr->type_off;
4b1c5d91 4833 end = cur + hdr->type_len;
69b693f0 4834
951bb646 4835 env->log_type_id = btf->base_btf ? btf->start_id : 1;
69b693f0
MKL
4836 while (cur < end) {
4837 struct btf_type *t = cur;
4838 s32 meta_size;
4839
4840 meta_size = btf_check_meta(env, t, end - cur);
4841 if (meta_size < 0)
4842 return meta_size;
4843
4844 btf_add_type(env, t);
4845 cur += meta_size;
4846 env->log_type_id++;
4847 }
4848
4849 return 0;
4850}
4851
eb3f595d
MKL
4852static bool btf_resolve_valid(struct btf_verifier_env *env,
4853 const struct btf_type *t,
4854 u32 type_id)
4855{
4856 struct btf *btf = env->btf;
4857
4858 if (!env_type_is_resolved(env, type_id))
4859 return false;
4860
1dc92851 4861 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
951bb646
AN
4862 return !btf_resolved_type_id(btf, type_id) &&
4863 !btf_resolved_type_size(btf, type_id);
eb3f595d 4864
d7e7b42f 4865 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
b5ea834d
YS
4866 return btf_resolved_type_id(btf, type_id) &&
4867 !btf_resolved_type_size(btf, type_id);
4868
1dc92851
DB
4869 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
4870 btf_type_is_var(t)) {
eb3f595d 4871 t = btf_type_id_resolve(btf, &type_id);
1dc92851
DB
4872 return t &&
4873 !btf_type_is_modifier(t) &&
4874 !btf_type_is_var(t) &&
4875 !btf_type_is_datasec(t);
eb3f595d
MKL
4876 }
4877
4878 if (btf_type_is_array(t)) {
4879 const struct btf_array *array = btf_type_array(t);
4880 const struct btf_type *elem_type;
4881 u32 elem_type_id = array->type;
4882 u32 elem_size;
4883
4884 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
4885 return elem_type && !btf_type_is_modifier(elem_type) &&
4886 (array->nelems * elem_size ==
951bb646 4887 btf_resolved_type_size(btf, type_id));
eb3f595d
MKL
4888 }
4889
4890 return false;
4891}
4892
2667a262
MKL
4893static int btf_resolve(struct btf_verifier_env *env,
4894 const struct btf_type *t, u32 type_id)
4895{
4896 u32 save_log_type_id = env->log_type_id;
4897 const struct resolve_vertex *v;
4898 int err = 0;
4899
4900 env->resolve_mode = RESOLVE_TBD;
4901 env_stack_push(env, t, type_id);
4902 while (!err && (v = env_stack_peak(env))) {
4903 env->log_type_id = v->type_id;
4904 err = btf_type_ops(v->t)->resolve(env, v);
4905 }
4906
4907 env->log_type_id = type_id;
4908 if (err == -E2BIG) {
4909 btf_verifier_log_type(env, t,
4910 "Exceeded max resolving depth:%u",
4911 MAX_RESOLVE_DEPTH);
4912 } else if (err == -EEXIST) {
4913 btf_verifier_log_type(env, t, "Loop detected");
4914 }
4915
4916 /* Final sanity check */
4917 if (!err && !btf_resolve_valid(env, t, type_id)) {
4918 btf_verifier_log_type(env, t, "Invalid resolve state");
4919 err = -EINVAL;
4920 }
4921
4922 env->log_type_id = save_log_type_id;
4923 return err;
4924}
4925
eb3f595d
MKL
4926static int btf_check_all_types(struct btf_verifier_env *env)
4927{
4928 struct btf *btf = env->btf;
951bb646
AN
4929 const struct btf_type *t;
4930 u32 type_id, i;
eb3f595d
MKL
4931 int err;
4932
4933 err = env_resolve_init(env);
4934 if (err)
4935 return err;
4936
4937 env->phase++;
951bb646
AN
4938 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
4939 type_id = btf->start_id + i;
4940 t = btf_type_by_id(btf, type_id);
eb3f595d
MKL
4941
4942 env->log_type_id = type_id;
4943 if (btf_type_needs_resolve(t) &&
4944 !env_type_is_resolved(env, type_id)) {
4945 err = btf_resolve(env, t, type_id);
4946 if (err)
4947 return err;
4948 }
4949
2667a262
MKL
4950 if (btf_type_is_func_proto(t)) {
4951 err = btf_func_proto_check(env, t);
4952 if (err)
4953 return err;
4954 }
eb3f595d
MKL
4955 }
4956
4957 return 0;
4958}
4959
69b693f0
MKL
4960static int btf_parse_type_sec(struct btf_verifier_env *env)
4961{
f80442a4 4962 const struct btf_header *hdr = &env->btf->hdr;
eb3f595d
MKL
4963 int err;
4964
f80442a4
MKL
4965 /* Type section must align to 4 bytes */
4966 if (hdr->type_off & (sizeof(u32) - 1)) {
4967 btf_verifier_log(env, "Unaligned type_off");
4968 return -EINVAL;
4969 }
4970
951bb646 4971 if (!env->btf->base_btf && !hdr->type_len) {
f80442a4
MKL
4972 btf_verifier_log(env, "No type found");
4973 return -EINVAL;
4974 }
4975
eb3f595d
MKL
4976 err = btf_check_all_metas(env);
4977 if (err)
4978 return err;
4979
4980 return btf_check_all_types(env);
69b693f0
MKL
4981}
4982
4983static int btf_parse_str_sec(struct btf_verifier_env *env)
4984{
4985 const struct btf_header *hdr;
4986 struct btf *btf = env->btf;
4987 const char *start, *end;
4988
f80442a4 4989 hdr = &btf->hdr;
69b693f0
MKL
4990 start = btf->nohdr_data + hdr->str_off;
4991 end = start + hdr->str_len;
4992
f80442a4
MKL
4993 if (end != btf->data + btf->data_size) {
4994 btf_verifier_log(env, "String section is not at the end");
4995 return -EINVAL;
4996 }
4997
951bb646
AN
4998 btf->strings = start;
4999
5000 if (btf->base_btf && !hdr->str_len)
5001 return 0;
5002 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5003 btf_verifier_log(env, "Invalid string section");
5004 return -EINVAL;
5005 }
5006 if (!btf->base_btf && start[0]) {
69b693f0
MKL
5007 btf_verifier_log(env, "Invalid string section");
5008 return -EINVAL;
5009 }
69b693f0
MKL
5010
5011 return 0;
5012}
5013
f80442a4
MKL
5014static const size_t btf_sec_info_offset[] = {
5015 offsetof(struct btf_header, type_off),
5016 offsetof(struct btf_header, str_off),
5017};
5018
5019static int btf_sec_info_cmp(const void *a, const void *b)
69b693f0 5020{
f80442a4
MKL
5021 const struct btf_sec_info *x = a;
5022 const struct btf_sec_info *y = b;
5023
5024 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5025}
5026
5027static int btf_check_sec_info(struct btf_verifier_env *env,
5028 u32 btf_data_size)
5029{
a2889a4c 5030 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
f80442a4 5031 u32 total, expected_total, i;
69b693f0 5032 const struct btf_header *hdr;
f80442a4
MKL
5033 const struct btf *btf;
5034
5035 btf = env->btf;
5036 hdr = &btf->hdr;
5037
5038 /* Populate the secs from hdr */
a2889a4c 5039 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
f80442a4
MKL
5040 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5041 btf_sec_info_offset[i]);
5042
a2889a4c
MKL
5043 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5044 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
f80442a4
MKL
5045
5046 /* Check for gaps and overlap among sections */
5047 total = 0;
5048 expected_total = btf_data_size - hdr->hdr_len;
a2889a4c 5049 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
f80442a4
MKL
5050 if (expected_total < secs[i].off) {
5051 btf_verifier_log(env, "Invalid section offset");
5052 return -EINVAL;
5053 }
5054 if (total < secs[i].off) {
5055 /* gap */
5056 btf_verifier_log(env, "Unsupported section found");
5057 return -EINVAL;
5058 }
5059 if (total > secs[i].off) {
5060 btf_verifier_log(env, "Section overlap found");
5061 return -EINVAL;
5062 }
5063 if (expected_total - total < secs[i].len) {
5064 btf_verifier_log(env,
5065 "Total section length too long");
5066 return -EINVAL;
5067 }
5068 total += secs[i].len;
5069 }
5070
5071 /* There is data other than hdr and known sections */
5072 if (expected_total != total) {
5073 btf_verifier_log(env, "Unsupported section found");
5074 return -EINVAL;
5075 }
5076
5077 return 0;
5078}
5079
4a6998af 5080static int btf_parse_hdr(struct btf_verifier_env *env)
f80442a4 5081{
4a6998af 5082 u32 hdr_len, hdr_copy, btf_data_size;
f80442a4 5083 const struct btf_header *hdr;
f80442a4 5084 struct btf *btf;
69b693f0 5085
f80442a4 5086 btf = env->btf;
4a6998af 5087 btf_data_size = btf->data_size;
f80442a4 5088
583669ab 5089 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
f80442a4
MKL
5090 btf_verifier_log(env, "hdr_len not found");
5091 return -EINVAL;
5092 }
5093
4a6998af
ML
5094 hdr = btf->data;
5095 hdr_len = hdr->hdr_len;
f80442a4 5096 if (btf_data_size < hdr_len) {
69b693f0
MKL
5097 btf_verifier_log(env, "btf_header not found");
5098 return -EINVAL;
5099 }
5100
4a6998af
ML
5101 /* Ensure the unsupported header fields are zero */
5102 if (hdr_len > sizeof(btf->hdr)) {
5103 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5104 u8 *end = btf->data + hdr_len;
5105
5106 for (; expected_zero < end; expected_zero++) {
5107 if (*expected_zero) {
5108 btf_verifier_log(env, "Unsupported btf_header");
5109 return -E2BIG;
5110 }
5111 }
f80442a4
MKL
5112 }
5113
5114 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4a6998af 5115 memcpy(&btf->hdr, btf->data, hdr_copy);
f80442a4
MKL
5116
5117 hdr = &btf->hdr;
5118
5119 btf_verifier_log_hdr(env, btf_data_size);
69b693f0 5120
69b693f0
MKL
5121 if (hdr->magic != BTF_MAGIC) {
5122 btf_verifier_log(env, "Invalid magic");
5123 return -EINVAL;
5124 }
5125
5126 if (hdr->version != BTF_VERSION) {
5127 btf_verifier_log(env, "Unsupported version");
5128 return -ENOTSUPP;
5129 }
5130
5131 if (hdr->flags) {
5132 btf_verifier_log(env, "Unsupported flags");
5133 return -ENOTSUPP;
5134 }
5135
bcc5e616 5136 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
69b693f0
MKL
5137 btf_verifier_log(env, "No data");
5138 return -EINVAL;
5139 }
5140
3a74904c 5141 return btf_check_sec_info(env, btf_data_size);
69b693f0
MKL
5142}
5143
eb596b09
KKD
5144static int btf_check_type_tags(struct btf_verifier_env *env,
5145 struct btf *btf, int start_id)
5146{
5147 int i, n, good_id = start_id - 1;
5148 bool in_tags;
5149
5150 n = btf_nr_types(btf);
5151 for (i = start_id; i < n; i++) {
5152 const struct btf_type *t;
d1a374a1 5153 int chain_limit = 32;
eb596b09
KKD
5154 u32 cur_id = i;
5155
5156 t = btf_type_by_id(btf, i);
5157 if (!t)
5158 return -EINVAL;
5159 if (!btf_type_is_modifier(t))
5160 continue;
5161
5162 cond_resched();
5163
5164 in_tags = btf_type_is_type_tag(t);
5165 while (btf_type_is_modifier(t)) {
d1a374a1
KKD
5166 if (!chain_limit--) {
5167 btf_verifier_log(env, "Max chain length or cycle detected");
5168 return -ELOOP;
5169 }
eb596b09
KKD
5170 if (btf_type_is_type_tag(t)) {
5171 if (!in_tags) {
5172 btf_verifier_log(env, "Type tags don't precede modifiers");
5173 return -EINVAL;
5174 }
5175 } else if (in_tags) {
5176 in_tags = false;
5177 }
5178 if (cur_id <= good_id)
5179 break;
5180 /* Move to next type */
5181 cur_id = t->type;
5182 t = btf_type_by_id(btf, cur_id);
5183 if (!t)
5184 return -EINVAL;
5185 }
5186 good_id = i;
5187 }
5188 return 0;
5189}
5190
c571bd75 5191static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
69b693f0
MKL
5192 u32 log_level, char __user *log_ubuf, u32 log_size)
5193{
5194 struct btf_verifier_env *env = NULL;
5195 struct bpf_verifier_log *log;
5196 struct btf *btf = NULL;
5197 u8 *data;
5198 int err;
5199
5200 if (btf_data_size > BTF_MAX_SIZE)
5201 return ERR_PTR(-E2BIG);
5202
5203 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5204 if (!env)
5205 return ERR_PTR(-ENOMEM);
5206
5207 log = &env->log;
5208 if (log_level || log_ubuf || log_size) {
5209 /* user requested verbose verifier output
5210 * and supplied buffer to store the verification trace
5211 */
5212 log->level = log_level;
5213 log->ubuf = log_ubuf;
5214 log->len_total = log_size;
5215
5216 /* log attributes have to be sane */
866de407 5217 if (!bpf_verifier_log_attr_valid(log)) {
69b693f0
MKL
5218 err = -EINVAL;
5219 goto errout;
5220 }
5221 }
5222
5223 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5224 if (!btf) {
5225 err = -ENOMEM;
5226 goto errout;
5227 }
f80442a4
MKL
5228 env->btf = btf;
5229
69b693f0
MKL
5230 data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
5231 if (!data) {
5232 err = -ENOMEM;
5233 goto errout;
5234 }
5235
5236 btf->data = data;
5237 btf->data_size = btf_data_size;
5238
c571bd75 5239 if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
69b693f0
MKL
5240 err = -EFAULT;
5241 goto errout;
5242 }
5243
4a6998af
ML
5244 err = btf_parse_hdr(env);
5245 if (err)
5246 goto errout;
5247
5248 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5249
69b693f0
MKL
5250 err = btf_parse_str_sec(env);
5251 if (err)
5252 goto errout;
5253
5254 err = btf_parse_type_sec(env);
5255 if (err)
5256 goto errout;
5257
eb596b09
KKD
5258 err = btf_check_type_tags(env, btf, 1);
5259 if (err)
5260 goto errout;
5261
f80442a4 5262 if (log->level && bpf_verifier_log_full(log)) {
69b693f0
MKL
5263 err = -ENOSPC;
5264 goto errout;
5265 }
5266
f80442a4
MKL
5267 btf_verifier_env_free(env);
5268 refcount_set(&btf->refcnt, 1);
5269 return btf;
69b693f0
MKL
5270
5271errout:
5272 btf_verifier_env_free(env);
5273 if (btf)
5274 btf_free(btf);
5275 return ERR_PTR(err);
5276}
b00b8dae 5277
90ceddcb
FS
5278extern char __weak __start_BTF[];
5279extern char __weak __stop_BTF[];
91cc1a99
AS
5280extern struct btf *btf_vmlinux;
5281
5282#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 5283#define BPF_LINK_TYPE(_id, _name)
91cc1a99
AS
5284static union {
5285 struct bpf_ctx_convert {
5286#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5287 prog_ctx_type _id##_prog; \
5288 kern_ctx_type _id##_kern;
5289#include <linux/bpf_types.h>
5290#undef BPF_PROG_TYPE
5291 } *__t;
5292 /* 't' is written once under lock. Read many times. */
5293 const struct btf_type *t;
5294} bpf_ctx_convert;
5295enum {
5296#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5297 __ctx_convert##_id,
5298#include <linux/bpf_types.h>
5299#undef BPF_PROG_TYPE
ce27709b 5300 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
91cc1a99
AS
5301};
5302static u8 bpf_ctx_convert_map[] = {
5303#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5304 [_id] = __ctx_convert##_id,
5305#include <linux/bpf_types.h>
5306#undef BPF_PROG_TYPE
4c80c7bc 5307 0, /* avoid empty array */
91cc1a99
AS
5308};
5309#undef BPF_MAP_TYPE
f2e10bff 5310#undef BPF_LINK_TYPE
91cc1a99
AS
5311
5312static const struct btf_member *
34747c41 5313btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
51c39bb1
AS
5314 const struct btf_type *t, enum bpf_prog_type prog_type,
5315 int arg)
91cc1a99
AS
5316{
5317 const struct btf_type *conv_struct;
5318 const struct btf_type *ctx_struct;
5319 const struct btf_member *ctx_type;
5320 const char *tname, *ctx_tname;
5321
5322 conv_struct = bpf_ctx_convert.t;
5323 if (!conv_struct) {
5324 bpf_log(log, "btf_vmlinux is malformed\n");
5325 return NULL;
5326 }
5327 t = btf_type_by_id(btf, t->type);
5328 while (btf_type_is_modifier(t))
5329 t = btf_type_by_id(btf, t->type);
5330 if (!btf_type_is_struct(t)) {
5331 /* Only pointer to struct is supported for now.
5332 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5333 * is not supported yet.
5334 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5335 */
91cc1a99
AS
5336 return NULL;
5337 }
5338 tname = btf_name_by_offset(btf, t->name_off);
5339 if (!tname) {
51c39bb1 5340 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
91cc1a99
AS
5341 return NULL;
5342 }
5343 /* prog_type is valid bpf program type. No need for bounds check. */
5344 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5345 /* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5346 * Like 'struct __sk_buff'
5347 */
5348 ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5349 if (!ctx_struct)
5350 /* should not happen */
5351 return NULL;
5352 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5353 if (!ctx_tname) {
5354 /* should not happen */
5355 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5356 return NULL;
5357 }
5358 /* only compare that prog's ctx type name is the same as
5359 * kernel expects. No need to compare field by field.
5360 * It's ok for bpf prog to do:
5361 * struct __sk_buff {};
5362 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5363 * { // no fields of skb are ever used }
5364 */
5365 if (strcmp(ctx_tname, tname))
5366 return NULL;
5367 return ctx_type;
5368}
8580ac94 5369
5b92a28a
AS
5370static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5371 struct btf *btf,
5372 const struct btf_type *t,
51c39bb1
AS
5373 enum bpf_prog_type prog_type,
5374 int arg)
5b92a28a
AS
5375{
5376 const struct btf_member *prog_ctx_type, *kern_ctx_type;
5377
51c39bb1 5378 prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5b92a28a
AS
5379 if (!prog_ctx_type)
5380 return -ENOENT;
5381 kern_ctx_type = prog_ctx_type + 1;
5382 return kern_ctx_type->type;
5383}
5384
49f4e672
JO
5385BTF_ID_LIST(bpf_ctx_convert_btf_id)
5386BTF_ID(struct, bpf_ctx_convert)
5387
8580ac94
AS
5388struct btf *btf_parse_vmlinux(void)
5389{
5390 struct btf_verifier_env *env = NULL;
5391 struct bpf_verifier_log *log;
5392 struct btf *btf = NULL;
49f4e672 5393 int err;
8580ac94
AS
5394
5395 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5396 if (!env)
5397 return ERR_PTR(-ENOMEM);
5398
5399 log = &env->log;
5400 log->level = BPF_LOG_KERNEL;
5401
5402 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5403 if (!btf) {
5404 err = -ENOMEM;
5405 goto errout;
5406 }
5407 env->btf = btf;
5408
90ceddcb
FS
5409 btf->data = __start_BTF;
5410 btf->data_size = __stop_BTF - __start_BTF;
53297220
AN
5411 btf->kernel_btf = true;
5412 snprintf(btf->name, sizeof(btf->name), "vmlinux");
8580ac94
AS
5413
5414 err = btf_parse_hdr(env);
5415 if (err)
5416 goto errout;
5417
5418 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5419
5420 err = btf_parse_str_sec(env);
5421 if (err)
5422 goto errout;
5423
5424 err = btf_check_all_metas(env);
5425 if (err)
5426 goto errout;
5427
eb596b09
KKD
5428 err = btf_check_type_tags(env, btf, 1);
5429 if (err)
5430 goto errout;
5431
a2d0d62f 5432 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
49f4e672 5433 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
91cc1a99 5434
d3e42bb0 5435 bpf_struct_ops_init(btf, log);
27ae7997 5436
8580ac94 5437 refcount_set(&btf->refcnt, 1);
53297220
AN
5438
5439 err = btf_alloc_id(btf);
5440 if (err)
5441 goto errout;
5442
5443 btf_verifier_env_free(env);
8580ac94
AS
5444 return btf;
5445
5446errout:
5447 btf_verifier_env_free(env);
5448 if (btf) {
5449 kvfree(btf->types);
5450 kfree(btf);
5451 }
5452 return ERR_PTR(err);
5453}
5454
7112d127
AN
5455#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5456
36e68442
AN
5457static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5458{
5459 struct btf_verifier_env *env = NULL;
5460 struct bpf_verifier_log *log;
5461 struct btf *btf = NULL, *base_btf;
5462 int err;
5463
5464 base_btf = bpf_get_btf_vmlinux();
5465 if (IS_ERR(base_btf))
5466 return base_btf;
5467 if (!base_btf)
5468 return ERR_PTR(-EINVAL);
5469
5470 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5471 if (!env)
5472 return ERR_PTR(-ENOMEM);
5473
5474 log = &env->log;
5475 log->level = BPF_LOG_KERNEL;
5476
5477 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5478 if (!btf) {
5479 err = -ENOMEM;
5480 goto errout;
5481 }
5482 env->btf = btf;
5483
5484 btf->base_btf = base_btf;
5485 btf->start_id = base_btf->nr_types;
5486 btf->start_str_off = base_btf->hdr.str_len;
5487 btf->kernel_btf = true;
5488 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5489
5490 btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5491 if (!btf->data) {
5492 err = -ENOMEM;
5493 goto errout;
5494 }
5495 memcpy(btf->data, data, data_size);
5496 btf->data_size = data_size;
5497
5498 err = btf_parse_hdr(env);
5499 if (err)
5500 goto errout;
5501
5502 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5503
5504 err = btf_parse_str_sec(env);
5505 if (err)
5506 goto errout;
5507
5508 err = btf_check_all_metas(env);
5509 if (err)
5510 goto errout;
5511
eb596b09
KKD
5512 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5513 if (err)
5514 goto errout;
5515
36e68442
AN
5516 btf_verifier_env_free(env);
5517 refcount_set(&btf->refcnt, 1);
5518 return btf;
5519
5520errout:
5521 btf_verifier_env_free(env);
5522 if (btf) {
5523 kvfree(btf->data);
5524 kvfree(btf->types);
5525 kfree(btf);
5526 }
5527 return ERR_PTR(err);
5528}
5529
7112d127
AN
5530#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5531
5b92a28a
AS
5532struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5533{
3aac1ead 5534 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5b92a28a 5535
22dc4a0f 5536 if (tgt_prog)
5b92a28a 5537 return tgt_prog->aux->btf;
22dc4a0f
AN
5538 else
5539 return prog->aux->attach_btf;
5b92a28a
AS
5540}
5541
bb6728d7 5542static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
84ad7a7a
JO
5543{
5544 /* t comes in already as a pointer */
5545 t = btf_type_by_id(btf, t->type);
5546
5547 /* allow const */
5548 if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5549 t = btf_type_by_id(btf, t->type);
5550
bb6728d7 5551 return btf_type_is_int(t);
84ad7a7a
JO
5552}
5553
720e6a43
YS
5554static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5555 int off)
5556{
5557 const struct btf_param *args;
5558 const struct btf_type *t;
5559 u32 offset = 0, nr_args;
5560 int i;
5561
5562 if (!func_proto)
5563 return off / 8;
5564
5565 nr_args = btf_type_vlen(func_proto);
5566 args = (const struct btf_param *)(func_proto + 1);
5567 for (i = 0; i < nr_args; i++) {
5568 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5569 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5570 if (off < offset)
5571 return i;
5572 }
5573
5574 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5575 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5576 if (off < offset)
5577 return nr_args;
5578
5579 return nr_args + 1;
5580}
5581
9e15db66
AS
5582bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5583 const struct bpf_prog *prog,
5584 struct bpf_insn_access_aux *info)
5585{
38207291 5586 const struct btf_type *t = prog->aux->attach_func_proto;
3aac1ead 5587 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5b92a28a 5588 struct btf *btf = bpf_prog_get_target_btf(prog);
38207291 5589 const char *tname = prog->aux->attach_func_name;
9e15db66 5590 struct bpf_verifier_log *log = info->log;
9e15db66 5591 const struct btf_param *args;
c6f1bfe8 5592 const char *tag_value;
9e15db66 5593 u32 nr_args, arg;
3c32cc1b 5594 int i, ret;
9e15db66 5595
9e15db66 5596 if (off % 8) {
38207291 5597 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
9e15db66
AS
5598 tname, off);
5599 return false;
5600 }
720e6a43 5601 arg = get_ctx_arg_idx(btf, t, off);
9e15db66 5602 args = (const struct btf_param *)(t + 1);
523a4cf4
DB
5603 /* if (t == NULL) Fall back to default BPF prog with
5604 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5605 */
5606 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
38207291
MKL
5607 if (prog->aux->attach_btf_trace) {
5608 /* skip first 'void *__data' argument in btf_trace_##name typedef */
5609 args++;
5610 nr_args--;
5611 }
fec56f58 5612
f50b49a0
KS
5613 if (arg > nr_args) {
5614 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5615 tname, arg + 1);
5616 return false;
5617 }
5618
6ba43b76 5619 if (arg == nr_args) {
f50b49a0 5620 switch (prog->expected_attach_type) {
69fd337a 5621 case BPF_LSM_CGROUP:
f50b49a0
KS
5622 case BPF_LSM_MAC:
5623 case BPF_TRACE_FEXIT:
9e4e01df
KS
5624 /* When LSM programs are attached to void LSM hooks
5625 * they use FEXIT trampolines and when attached to
5626 * int LSM hooks, they use MODIFY_RETURN trampolines.
5627 *
5628 * While the LSM programs are BPF_MODIFY_RETURN-like
5629 * the check:
5630 *
5631 * if (ret_type != 'int')
5632 * return -EINVAL;
5633 *
5634 * is _not_ done here. This is still safe as LSM hooks
5635 * have only void and int return types.
5636 */
6ba43b76
KS
5637 if (!t)
5638 return true;
5639 t = btf_type_by_id(btf, t->type);
f50b49a0
KS
5640 break;
5641 case BPF_MODIFY_RETURN:
6ba43b76
KS
5642 /* For now the BPF_MODIFY_RETURN can only be attached to
5643 * functions that return an int.
5644 */
5645 if (!t)
5646 return false;
5647
5648 t = btf_type_skip_modifiers(btf, t->type, NULL);
a9b59159 5649 if (!btf_type_is_small_int(t)) {
6ba43b76
KS
5650 bpf_log(log,
5651 "ret type %s not allowed for fmod_ret\n",
571f9738 5652 btf_type_str(t));
6ba43b76
KS
5653 return false;
5654 }
f50b49a0
KS
5655 break;
5656 default:
5657 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5658 tname, arg + 1);
5659 return false;
6ba43b76 5660 }
fec56f58 5661 } else {
5b92a28a 5662 if (!t)
523a4cf4 5663 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
5b92a28a
AS
5664 return true;
5665 t = btf_type_by_id(btf, args[arg].type);
9e15db66 5666 }
f50b49a0 5667
9e15db66
AS
5668 /* skip modifiers */
5669 while (btf_type_is_modifier(t))
5b92a28a 5670 t = btf_type_by_id(btf, t->type);
720e6a43 5671 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
9e15db66
AS
5672 /* accessing a scalar */
5673 return true;
5674 if (!btf_type_is_ptr(t)) {
5675 bpf_log(log,
38207291 5676 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
9e15db66 5677 tname, arg,
5b92a28a 5678 __btf_name_by_offset(btf, t->name_off),
571f9738 5679 btf_type_str(t));
9e15db66
AS
5680 return false;
5681 }
afbf21dc
YS
5682
5683 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
5684 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5685 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
c25b2ae1 5686 u32 type, flag;
afbf21dc 5687
c25b2ae1
HL
5688 type = base_type(ctx_arg_info->reg_type);
5689 flag = type_flag(ctx_arg_info->reg_type);
20b2aff4 5690 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
c25b2ae1 5691 (flag & PTR_MAYBE_NULL)) {
afbf21dc
YS
5692 info->reg_type = ctx_arg_info->reg_type;
5693 return true;
5694 }
5695 }
5696
9e15db66
AS
5697 if (t->type == 0)
5698 /* This is a pointer to void.
5699 * It is the same as scalar from the verifier safety pov.
5700 * No further pointer walking is allowed.
5701 */
5702 return true;
5703
bb6728d7 5704 if (is_int_ptr(btf, t))
84ad7a7a
JO
5705 return true;
5706
9e15db66 5707 /* this is a pointer to another type */
3c32cc1b
YS
5708 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5709 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5710
5711 if (ctx_arg_info->offset == off) {
d3621642
YS
5712 if (!ctx_arg_info->btf_id) {
5713 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
5714 return false;
5715 }
5716
3c32cc1b 5717 info->reg_type = ctx_arg_info->reg_type;
22dc4a0f 5718 info->btf = btf_vmlinux;
951cf368
YS
5719 info->btf_id = ctx_arg_info->btf_id;
5720 return true;
3c32cc1b
YS
5721 }
5722 }
9e15db66 5723
951cf368 5724 info->reg_type = PTR_TO_BTF_ID;
5b92a28a 5725 if (tgt_prog) {
43bc2874
THJ
5726 enum bpf_prog_type tgt_type;
5727
5728 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
5729 tgt_type = tgt_prog->aux->saved_dst_prog_type;
5730 else
5731 tgt_type = tgt_prog->type;
5732
5733 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
5b92a28a 5734 if (ret > 0) {
22dc4a0f 5735 info->btf = btf_vmlinux;
5b92a28a
AS
5736 info->btf_id = ret;
5737 return true;
5738 } else {
5739 return false;
5740 }
5741 }
275517ff 5742
22dc4a0f 5743 info->btf = btf;
275517ff 5744 info->btf_id = t->type;
5b92a28a 5745 t = btf_type_by_id(btf, t->type);
c6f1bfe8
YS
5746
5747 if (btf_type_is_type_tag(t)) {
5748 tag_value = __btf_name_by_offset(btf, t->name_off);
5749 if (strcmp(tag_value, "user") == 0)
5750 info->reg_type |= MEM_USER;
5844101a
HL
5751 if (strcmp(tag_value, "percpu") == 0)
5752 info->reg_type |= MEM_PERCPU;
c6f1bfe8
YS
5753 }
5754
9e15db66 5755 /* skip modifiers */
275517ff
MKL
5756 while (btf_type_is_modifier(t)) {
5757 info->btf_id = t->type;
5b92a28a 5758 t = btf_type_by_id(btf, t->type);
275517ff 5759 }
9e15db66
AS
5760 if (!btf_type_is_struct(t)) {
5761 bpf_log(log,
38207291 5762 "func '%s' arg%d type %s is not a struct\n",
571f9738 5763 tname, arg, btf_type_str(t));
9e15db66
AS
5764 return false;
5765 }
38207291 5766 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
571f9738 5767 tname, arg, info->btf_id, btf_type_str(t),
5b92a28a 5768 __btf_name_by_offset(btf, t->name_off));
9e15db66
AS
5769 return true;
5770}
5771
1c6d28a6
JO
5772enum bpf_struct_walk_result {
5773 /* < 0 error */
5774 WALK_SCALAR = 0,
5775 WALK_PTR,
5776 WALK_STRUCT,
5777};
5778
22dc4a0f 5779static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
1c6d28a6 5780 const struct btf_type *t, int off, int size,
c6f1bfe8 5781 u32 *next_btf_id, enum bpf_type_flag *flag)
9e15db66 5782{
7e3617a7
MKL
5783 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
5784 const struct btf_type *mtype, *elem_type = NULL;
9e15db66 5785 const struct btf_member *member;
c6f1bfe8 5786 const char *tname, *mname, *tag_value;
1c6d28a6 5787 u32 vlen, elem_id, mid;
9e15db66
AS
5788
5789again:
22dc4a0f 5790 tname = __btf_name_by_offset(btf, t->name_off);
9e15db66 5791 if (!btf_type_is_struct(t)) {
275517ff 5792 bpf_log(log, "Type '%s' is not a struct\n", tname);
9e15db66
AS
5793 return -EINVAL;
5794 }
5795
9c5f8a10 5796 vlen = btf_type_vlen(t);
976aba00 5797 if (off + size > t->size) {
9c5f8a10
YS
5798 /* If the last element is a variable size array, we may
5799 * need to relax the rule.
5800 */
5801 struct btf_array *array_elem;
5802
5803 if (vlen == 0)
5804 goto error;
5805
5806 member = btf_type_member(t) + vlen - 1;
22dc4a0f 5807 mtype = btf_type_skip_modifiers(btf, member->type,
9c5f8a10
YS
5808 NULL);
5809 if (!btf_type_is_array(mtype))
5810 goto error;
5811
5812 array_elem = (struct btf_array *)(mtype + 1);
5813 if (array_elem->nelems != 0)
5814 goto error;
5815
8293eb99 5816 moff = __btf_member_bit_offset(t, member) / 8;
9c5f8a10
YS
5817 if (off < moff)
5818 goto error;
5819
5820 /* Only allow structure for now, can be relaxed for
5821 * other types later.
5822 */
22dc4a0f 5823 t = btf_type_skip_modifiers(btf, array_elem->type,
dafe58fc
JO
5824 NULL);
5825 if (!btf_type_is_struct(t))
9c5f8a10
YS
5826 goto error;
5827
dafe58fc
JO
5828 off = (off - moff) % t->size;
5829 goto again;
9c5f8a10
YS
5830
5831error:
976aba00
MKL
5832 bpf_log(log, "access beyond struct %s at off %u size %u\n",
5833 tname, off, size);
5834 return -EACCES;
5835 }
9e15db66 5836
976aba00 5837 for_each_member(i, t, member) {
7e3617a7 5838 /* offset of the field in bytes */
8293eb99 5839 moff = __btf_member_bit_offset(t, member) / 8;
7e3617a7 5840 if (off + size <= moff)
9e15db66
AS
5841 /* won't find anything, field is already too far */
5842 break;
976aba00 5843
8293eb99
AS
5844 if (__btf_member_bitfield_size(t, member)) {
5845 u32 end_bit = __btf_member_bit_offset(t, member) +
5846 __btf_member_bitfield_size(t, member);
976aba00
MKL
5847
5848 /* off <= moff instead of off == moff because clang
5849 * does not generate a BTF member for anonymous
5850 * bitfield like the ":16" here:
5851 * struct {
5852 * int :16;
5853 * int x:8;
5854 * };
5855 */
5856 if (off <= moff &&
5857 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
1c6d28a6 5858 return WALK_SCALAR;
976aba00
MKL
5859
5860 /* off may be accessing a following member
5861 *
5862 * or
5863 *
5864 * Doing partial access at either end of this
5865 * bitfield. Continue on this case also to
5866 * treat it as not accessing this bitfield
5867 * and eventually error out as field not
5868 * found to keep it simple.
5869 * It could be relaxed if there was a legit
5870 * partial access case later.
5871 */
5872 continue;
5873 }
5874
7e3617a7
MKL
5875 /* In case of "off" is pointing to holes of a struct */
5876 if (off < moff)
976aba00 5877 break;
9e15db66
AS
5878
5879 /* type of the field */
1c6d28a6 5880 mid = member->type;
22dc4a0f
AN
5881 mtype = btf_type_by_id(btf, member->type);
5882 mname = __btf_name_by_offset(btf, member->name_off);
9e15db66 5883
22dc4a0f 5884 mtype = __btf_resolve_size(btf, mtype, &msize,
1c6d28a6
JO
5885 &elem_type, &elem_id, &total_nelems,
5886 &mid);
7e3617a7 5887 if (IS_ERR(mtype)) {
9e15db66
AS
5888 bpf_log(log, "field %s doesn't have size\n", mname);
5889 return -EFAULT;
5890 }
7e3617a7
MKL
5891
5892 mtrue_end = moff + msize;
5893 if (off >= mtrue_end)
9e15db66
AS
5894 /* no overlap with member, keep iterating */
5895 continue;
7e3617a7
MKL
5896
5897 if (btf_type_is_array(mtype)) {
5898 u32 elem_idx;
5899
6298399b 5900 /* __btf_resolve_size() above helps to
7e3617a7
MKL
5901 * linearize a multi-dimensional array.
5902 *
5903 * The logic here is treating an array
5904 * in a struct as the following way:
5905 *
5906 * struct outer {
5907 * struct inner array[2][2];
5908 * };
5909 *
5910 * looks like:
5911 *
5912 * struct outer {
5913 * struct inner array_elem0;
5914 * struct inner array_elem1;
5915 * struct inner array_elem2;
5916 * struct inner array_elem3;
5917 * };
5918 *
5919 * When accessing outer->array[1][0], it moves
5920 * moff to "array_elem2", set mtype to
5921 * "struct inner", and msize also becomes
5922 * sizeof(struct inner). Then most of the
5923 * remaining logic will fall through without
5924 * caring the current member is an array or
5925 * not.
5926 *
5927 * Unlike mtype/msize/moff, mtrue_end does not
5928 * change. The naming difference ("_true") tells
5929 * that it is not always corresponding to
5930 * the current mtype/msize/moff.
5931 * It is the true end of the current
5932 * member (i.e. array in this case). That
5933 * will allow an int array to be accessed like
5934 * a scratch space,
5935 * i.e. allow access beyond the size of
5936 * the array's element as long as it is
5937 * within the mtrue_end boundary.
5938 */
5939
5940 /* skip empty array */
5941 if (moff == mtrue_end)
5942 continue;
5943
5944 msize /= total_nelems;
5945 elem_idx = (off - moff) / msize;
5946 moff += elem_idx * msize;
5947 mtype = elem_type;
1c6d28a6 5948 mid = elem_id;
7e3617a7
MKL
5949 }
5950
9e15db66
AS
5951 /* the 'off' we're looking for is either equal to start
5952 * of this field or inside of this struct
5953 */
5954 if (btf_type_is_struct(mtype)) {
5955 /* our field must be inside that union or struct */
5956 t = mtype;
5957
1c6d28a6
JO
5958 /* return if the offset matches the member offset */
5959 if (off == moff) {
5960 *next_btf_id = mid;
5961 return WALK_STRUCT;
5962 }
5963
9e15db66 5964 /* adjust offset we're looking for */
7e3617a7 5965 off -= moff;
9e15db66
AS
5966 goto again;
5967 }
9e15db66
AS
5968
5969 if (btf_type_is_ptr(mtype)) {
c6f1bfe8
YS
5970 const struct btf_type *stype, *t;
5971 enum bpf_type_flag tmp_flag = 0;
257af63d 5972 u32 id;
9e15db66 5973
7e3617a7
MKL
5974 if (msize != size || off != moff) {
5975 bpf_log(log,
5976 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
5977 mname, moff, tname, off, size);
5978 return -EACCES;
5979 }
c6f1bfe8 5980
5844101a 5981 /* check type tag */
c6f1bfe8
YS
5982 t = btf_type_by_id(btf, mtype->type);
5983 if (btf_type_is_type_tag(t)) {
5984 tag_value = __btf_name_by_offset(btf, t->name_off);
5844101a 5985 /* check __user tag */
c6f1bfe8
YS
5986 if (strcmp(tag_value, "user") == 0)
5987 tmp_flag = MEM_USER;
5844101a
HL
5988 /* check __percpu tag */
5989 if (strcmp(tag_value, "percpu") == 0)
5990 tmp_flag = MEM_PERCPU;
c6f1bfe8
YS
5991 }
5992
22dc4a0f 5993 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
9e15db66 5994 if (btf_type_is_struct(stype)) {
257af63d 5995 *next_btf_id = id;
c6f1bfe8 5996 *flag = tmp_flag;
1c6d28a6 5997 return WALK_PTR;
9e15db66
AS
5998 }
5999 }
7e3617a7
MKL
6000
6001 /* Allow more flexible access within an int as long as
6002 * it is within mtrue_end.
6003 * Since mtrue_end could be the end of an array,
6004 * that also allows using an array of int as a scratch
6005 * space. e.g. skb->cb[].
6006 */
6007 if (off + size > mtrue_end) {
6008 bpf_log(log,
6009 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6010 mname, mtrue_end, tname, off, size);
6011 return -EACCES;
6012 }
6013
1c6d28a6 6014 return WALK_SCALAR;
9e15db66
AS
6015 }
6016 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6017 return -EINVAL;
6018}
6019
22dc4a0f 6020int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
1c6d28a6
JO
6021 const struct btf_type *t, int off, int size,
6022 enum bpf_access_type atype __maybe_unused,
c6f1bfe8 6023 u32 *next_btf_id, enum bpf_type_flag *flag)
1c6d28a6 6024{
c6f1bfe8 6025 enum bpf_type_flag tmp_flag = 0;
1c6d28a6
JO
6026 int err;
6027 u32 id;
6028
6029 do {
c6f1bfe8 6030 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
1c6d28a6
JO
6031
6032 switch (err) {
6033 case WALK_PTR:
6034 /* If we found the pointer or scalar on t+off,
6035 * we're done.
6036 */
6037 *next_btf_id = id;
c6f1bfe8 6038 *flag = tmp_flag;
1c6d28a6
JO
6039 return PTR_TO_BTF_ID;
6040 case WALK_SCALAR:
6041 return SCALAR_VALUE;
6042 case WALK_STRUCT:
6043 /* We found nested struct, so continue the search
6044 * by diving in it. At this point the offset is
6045 * aligned with the new type, so set it to 0.
6046 */
22dc4a0f 6047 t = btf_type_by_id(btf, id);
1c6d28a6
JO
6048 off = 0;
6049 break;
6050 default:
6051 /* It's either error or unknown return value..
6052 * scream and leave.
6053 */
6054 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6055 return -EINVAL;
6056 return err;
6057 }
6058 } while (t);
6059
6060 return -EINVAL;
6061}
6062
22dc4a0f
AN
6063/* Check that two BTF types, each specified as an BTF object + id, are exactly
6064 * the same. Trivial ID check is not enough due to module BTFs, because we can
6065 * end up with two different module BTFs, but IDs point to the common type in
6066 * vmlinux BTF.
6067 */
6068static bool btf_types_are_same(const struct btf *btf1, u32 id1,
6069 const struct btf *btf2, u32 id2)
6070{
6071 if (id1 != id2)
6072 return false;
6073 if (btf1 == btf2)
6074 return true;
6075 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6076}
6077
faaf4a79 6078bool btf_struct_ids_match(struct bpf_verifier_log *log,
22dc4a0f 6079 const struct btf *btf, u32 id, int off,
2ab3b380
KKD
6080 const struct btf *need_btf, u32 need_type_id,
6081 bool strict)
faaf4a79
JO
6082{
6083 const struct btf_type *type;
c6f1bfe8 6084 enum bpf_type_flag flag;
faaf4a79
JO
6085 int err;
6086
6087 /* Are we already done? */
22dc4a0f 6088 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
faaf4a79 6089 return true;
2ab3b380
KKD
6090 /* In case of strict type match, we do not walk struct, the top level
6091 * type match must succeed. When strict is true, off should have already
6092 * been 0.
6093 */
6094 if (strict)
6095 return false;
faaf4a79 6096again:
22dc4a0f 6097 type = btf_type_by_id(btf, id);
faaf4a79
JO
6098 if (!type)
6099 return false;
c6f1bfe8 6100 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
faaf4a79
JO
6101 if (err != WALK_STRUCT)
6102 return false;
6103
6104 /* We found nested struct object. If it matches
6105 * the requested ID, we're done. Otherwise let's
6106 * continue the search with offset 0 in the new
6107 * type.
6108 */
22dc4a0f 6109 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
faaf4a79
JO
6110 off = 0;
6111 goto again;
6112 }
6113
6114 return true;
6115}
6116
fec56f58 6117static int __get_type_size(struct btf *btf, u32 btf_id,
a00ed843 6118 const struct btf_type **ret_type)
fec56f58
AS
6119{
6120 const struct btf_type *t;
6121
a00ed843 6122 *ret_type = btf_type_by_id(btf, 0);
fec56f58
AS
6123 if (!btf_id)
6124 /* void */
6125 return 0;
6126 t = btf_type_by_id(btf, btf_id);
6127 while (t && btf_type_is_modifier(t))
6128 t = btf_type_by_id(btf, t->type);
a00ed843 6129 if (!t)
fec56f58 6130 return -EINVAL;
a00ed843 6131 *ret_type = t;
fec56f58
AS
6132 if (btf_type_is_ptr(t))
6133 /* kernel size of pointer. Not BPF's size of pointer*/
6134 return sizeof(void *);
720e6a43 6135 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
fec56f58 6136 return t->size;
fec56f58
AS
6137 return -EINVAL;
6138}
6139
6140int btf_distill_func_proto(struct bpf_verifier_log *log,
6141 struct btf *btf,
6142 const struct btf_type *func,
6143 const char *tname,
6144 struct btf_func_model *m)
6145{
6146 const struct btf_param *args;
6147 const struct btf_type *t;
6148 u32 i, nargs;
6149 int ret;
6150
5b92a28a
AS
6151 if (!func) {
6152 /* BTF function prototype doesn't match the verifier types.
523a4cf4 6153 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
5b92a28a 6154 */
720e6a43 6155 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
5b92a28a 6156 m->arg_size[i] = 8;
720e6a43
YS
6157 m->arg_flags[i] = 0;
6158 }
5b92a28a 6159 m->ret_size = 8;
523a4cf4 6160 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
5b92a28a
AS
6161 return 0;
6162 }
fec56f58
AS
6163 args = (const struct btf_param *)(func + 1);
6164 nargs = btf_type_vlen(func);
c29a4920 6165 if (nargs > MAX_BPF_FUNC_ARGS) {
fec56f58
AS
6166 bpf_log(log,
6167 "The function %s has %d arguments. Too many.\n",
6168 tname, nargs);
6169 return -EINVAL;
6170 }
6171 ret = __get_type_size(btf, func->type, &t);
720e6a43 6172 if (ret < 0 || __btf_type_is_struct(t)) {
fec56f58
AS
6173 bpf_log(log,
6174 "The function %s return type %s is unsupported.\n",
571f9738 6175 tname, btf_type_str(t));
fec56f58
AS
6176 return -EINVAL;
6177 }
6178 m->ret_size = ret;
6179
6180 for (i = 0; i < nargs; i++) {
31379397
JO
6181 if (i == nargs - 1 && args[i].type == 0) {
6182 bpf_log(log,
6183 "The function %s with variable args is unsupported.\n",
6184 tname);
6185 return -EINVAL;
6186 }
fec56f58 6187 ret = __get_type_size(btf, args[i].type, &t);
720e6a43
YS
6188
6189 /* No support of struct argument size greater than 16 bytes */
6190 if (ret < 0 || ret > 16) {
fec56f58
AS
6191 bpf_log(log,
6192 "The function %s arg%d type %s is unsupported.\n",
571f9738 6193 tname, i, btf_type_str(t));
fec56f58
AS
6194 return -EINVAL;
6195 }
31379397
JO
6196 if (ret == 0) {
6197 bpf_log(log,
6198 "The function %s has malformed void argument.\n",
6199 tname);
6200 return -EINVAL;
6201 }
fec56f58 6202 m->arg_size[i] = ret;
720e6a43 6203 m->arg_flags[i] = __btf_type_is_struct(t) ? BTF_FMODEL_STRUCT_ARG : 0;
fec56f58
AS
6204 }
6205 m->nr_args = nargs;
6206 return 0;
6207}
6208
be8704ff
AS
6209/* Compare BTFs of two functions assuming only scalars and pointers to context.
6210 * t1 points to BTF_KIND_FUNC in btf1
6211 * t2 points to BTF_KIND_FUNC in btf2
6212 * Returns:
6213 * EINVAL - function prototype mismatch
6214 * EFAULT - verifier bug
6215 * 0 - 99% match. The last 1% is validated by the verifier.
6216 */
2bf0eb9b
HY
6217static int btf_check_func_type_match(struct bpf_verifier_log *log,
6218 struct btf *btf1, const struct btf_type *t1,
6219 struct btf *btf2, const struct btf_type *t2)
be8704ff
AS
6220{
6221 const struct btf_param *args1, *args2;
6222 const char *fn1, *fn2, *s1, *s2;
6223 u32 nargs1, nargs2, i;
6224
6225 fn1 = btf_name_by_offset(btf1, t1->name_off);
6226 fn2 = btf_name_by_offset(btf2, t2->name_off);
6227
6228 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6229 bpf_log(log, "%s() is not a global function\n", fn1);
6230 return -EINVAL;
6231 }
6232 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6233 bpf_log(log, "%s() is not a global function\n", fn2);
6234 return -EINVAL;
6235 }
6236
6237 t1 = btf_type_by_id(btf1, t1->type);
6238 if (!t1 || !btf_type_is_func_proto(t1))
6239 return -EFAULT;
6240 t2 = btf_type_by_id(btf2, t2->type);
6241 if (!t2 || !btf_type_is_func_proto(t2))
6242 return -EFAULT;
6243
6244 args1 = (const struct btf_param *)(t1 + 1);
6245 nargs1 = btf_type_vlen(t1);
6246 args2 = (const struct btf_param *)(t2 + 1);
6247 nargs2 = btf_type_vlen(t2);
6248
6249 if (nargs1 != nargs2) {
6250 bpf_log(log, "%s() has %d args while %s() has %d args\n",
6251 fn1, nargs1, fn2, nargs2);
6252 return -EINVAL;
6253 }
6254
6255 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6256 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6257 if (t1->info != t2->info) {
6258 bpf_log(log,
6259 "Return type %s of %s() doesn't match type %s of %s()\n",
6260 btf_type_str(t1), fn1,
6261 btf_type_str(t2), fn2);
6262 return -EINVAL;
6263 }
6264
6265 for (i = 0; i < nargs1; i++) {
6266 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6267 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6268
6269 if (t1->info != t2->info) {
6270 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6271 i, fn1, btf_type_str(t1),
6272 fn2, btf_type_str(t2));
6273 return -EINVAL;
6274 }
6275 if (btf_type_has_size(t1) && t1->size != t2->size) {
6276 bpf_log(log,
6277 "arg%d in %s() has size %d while %s() has %d\n",
6278 i, fn1, t1->size,
6279 fn2, t2->size);
6280 return -EINVAL;
6281 }
6282
6283 /* global functions are validated with scalars and pointers
6284 * to context only. And only global functions can be replaced.
6285 * Hence type check only those types.
6286 */
6089fb32 6287 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
be8704ff
AS
6288 continue;
6289 if (!btf_type_is_ptr(t1)) {
6290 bpf_log(log,
6291 "arg%d in %s() has unrecognized type\n",
6292 i, fn1);
6293 return -EINVAL;
6294 }
6295 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6296 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6297 if (!btf_type_is_struct(t1)) {
6298 bpf_log(log,
6299 "arg%d in %s() is not a pointer to context\n",
6300 i, fn1);
6301 return -EINVAL;
6302 }
6303 if (!btf_type_is_struct(t2)) {
6304 bpf_log(log,
6305 "arg%d in %s() is not a pointer to context\n",
6306 i, fn2);
6307 return -EINVAL;
6308 }
6309 /* This is an optional check to make program writing easier.
6310 * Compare names of structs and report an error to the user.
6311 * btf_prepare_func_args() already checked that t2 struct
6312 * is a context type. btf_prepare_func_args() will check
6313 * later that t1 struct is a context type as well.
6314 */
6315 s1 = btf_name_by_offset(btf1, t1->name_off);
6316 s2 = btf_name_by_offset(btf2, t2->name_off);
6317 if (strcmp(s1, s2)) {
6318 bpf_log(log,
6319 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6320 i, fn1, s1, fn2, s2);
6321 return -EINVAL;
6322 }
6323 }
6324 return 0;
6325}
6326
6327/* Compare BTFs of given program with BTF of target program */
efc68158 6328int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
be8704ff
AS
6329 struct btf *btf2, const struct btf_type *t2)
6330{
6331 struct btf *btf1 = prog->aux->btf;
6332 const struct btf_type *t1;
6333 u32 btf_id = 0;
6334
6335 if (!prog->aux->func_info) {
efc68158 6336 bpf_log(log, "Program extension requires BTF\n");
be8704ff
AS
6337 return -EINVAL;
6338 }
6339
6340 btf_id = prog->aux->func_info[0].type_id;
6341 if (!btf_id)
6342 return -EFAULT;
6343
6344 t1 = btf_type_by_id(btf1, btf_id);
6345 if (!t1 || !btf_type_is_func(t1))
6346 return -EFAULT;
6347
efc68158 6348 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
be8704ff
AS
6349}
6350
e6ac2450
MKL
6351static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6352#ifdef CONFIG_NET
6353 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6354 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6355 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6356#endif
6357};
6358
3363bd0c
KKD
6359/* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
6360static bool __btf_type_is_scalar_struct(struct bpf_verifier_log *log,
6361 const struct btf *btf,
6362 const struct btf_type *t, int rec)
6363{
6364 const struct btf_type *member_type;
6365 const struct btf_member *member;
6366 u32 i;
6367
6368 if (!btf_type_is_struct(t))
6369 return false;
6370
6371 for_each_member(i, t, member) {
6372 const struct btf_array *array;
6373
6374 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
6375 if (btf_type_is_struct(member_type)) {
6376 if (rec >= 3) {
6377 bpf_log(log, "max struct nesting depth exceeded\n");
6378 return false;
6379 }
6380 if (!__btf_type_is_scalar_struct(log, btf, member_type, rec + 1))
6381 return false;
6382 continue;
6383 }
6384 if (btf_type_is_array(member_type)) {
6385 array = btf_type_array(member_type);
6386 if (!array->nelems)
6387 return false;
6388 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
6389 if (!btf_type_is_scalar(member_type))
6390 return false;
6391 continue;
6392 }
6393 if (!btf_type_is_scalar(member_type))
6394 return false;
6395 }
6396 return true;
6397}
6398
d583691c
KKD
6399static bool is_kfunc_arg_mem_size(const struct btf *btf,
6400 const struct btf_param *arg,
6401 const struct bpf_reg_state *reg)
6402{
6403 int len, sfx_len = sizeof("__sz") - 1;
6404 const struct btf_type *t;
6405 const char *param_name;
6406
6407 t = btf_type_skip_modifiers(btf, arg->type, NULL);
6408 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
6409 return false;
6410
6411 /* In the future, this can be ported to use BTF tagging */
6412 param_name = btf_name_by_offset(btf, arg->name_off);
6413 if (str_is_empty(param_name))
6414 return false;
6415 len = strlen(param_name);
6416 if (len < sfx_len)
6417 return false;
6418 param_name += len - sfx_len;
6419 if (strncmp(param_name, "__sz", sfx_len))
6420 return false;
6421
6422 return true;
6423}
6424
eb1f7f71
BT
6425static bool btf_is_kfunc_arg_mem_size(const struct btf *btf,
6426 const struct btf_param *arg,
6427 const struct bpf_reg_state *reg,
6428 const char *name)
6429{
6430 int len, target_len = strlen(name);
6431 const struct btf_type *t;
6432 const char *param_name;
6433
6434 t = btf_type_skip_modifiers(btf, arg->type, NULL);
6435 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
6436 return false;
6437
6438 param_name = btf_name_by_offset(btf, arg->name_off);
6439 if (str_is_empty(param_name))
6440 return false;
6441 len = strlen(param_name);
6442 if (len != target_len)
6443 return false;
6444 if (strcmp(param_name, name))
6445 return false;
6446
6447 return true;
6448}
6449
34747c41
MKL
6450static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6451 const struct btf *btf, u32 func_id,
6452 struct bpf_reg_state *regs,
a4703e31 6453 bool ptr_to_mem_ok,
eb1f7f71 6454 struct bpf_kfunc_arg_meta *kfunc_meta,
95f2f26f 6455 bool processing_call)
8c1b6e69 6456{
f858c2b2 6457 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
eed807f6 6458 bool rel = false, kptr_get = false, trusted_args = false;
fa96b242 6459 bool sleepable = false;
8c1b6e69 6460 struct bpf_verifier_log *log = &env->log;
5c073f26 6461 u32 i, nargs, ref_id, ref_obj_id = 0;
3363bd0c 6462 bool is_kfunc = btf_is_kernel(btf);
34747c41 6463 const char *func_name, *ref_tname;
e5069b9c 6464 const struct btf_type *t, *ref_t;
34747c41 6465 const struct btf_param *args;
655efe50 6466 int ref_regno = 0, ret;
8c1b6e69 6467
34747c41 6468 t = btf_type_by_id(btf, func_id);
8c1b6e69 6469 if (!t || !btf_type_is_func(t)) {
51c39bb1 6470 /* These checks were already done by the verifier while loading
e6ac2450 6471 * struct bpf_func_info or in add_kfunc_call().
51c39bb1 6472 */
34747c41
MKL
6473 bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6474 func_id);
51c39bb1 6475 return -EFAULT;
8c1b6e69 6476 }
34747c41 6477 func_name = btf_name_by_offset(btf, t->name_off);
8c1b6e69
AS
6478
6479 t = btf_type_by_id(btf, t->type);
6480 if (!t || !btf_type_is_func_proto(t)) {
34747c41 6481 bpf_log(log, "Invalid BTF of func %s\n", func_name);
51c39bb1 6482 return -EFAULT;
8c1b6e69
AS
6483 }
6484 args = (const struct btf_param *)(t + 1);
6485 nargs = btf_type_vlen(t);
523a4cf4 6486 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
34747c41 6487 bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
523a4cf4 6488 MAX_BPF_FUNC_REG_ARGS);
34747c41 6489 return -EINVAL;
8c1b6e69 6490 }
e5069b9c 6491
eb1f7f71 6492 if (is_kfunc && kfunc_meta) {
a1ef1959 6493 /* Only kfunc can be release func */
eb1f7f71
BT
6494 rel = kfunc_meta->flags & KF_RELEASE;
6495 kptr_get = kfunc_meta->flags & KF_KPTR_GET;
eed807f6 6496 trusted_args = kfunc_meta->flags & KF_TRUSTED_ARGS;
eb1f7f71 6497 sleepable = kfunc_meta->flags & KF_SLEEPABLE;
a1ef1959
KKD
6498 }
6499
8c1b6e69
AS
6500 /* check that BTF function arguments match actual types that the
6501 * verifier sees.
6502 */
6503 for (i = 0; i < nargs; i++) {
8f14852e 6504 enum bpf_arg_type arg_type = ARG_DONTCARE;
34747c41
MKL
6505 u32 regno = i + 1;
6506 struct bpf_reg_state *reg = &regs[regno];
eed807f6 6507 bool obj_ptr = false;
feb4adfa 6508
34747c41
MKL
6509 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6510 if (btf_type_is_scalar(t)) {
eb1f7f71
BT
6511 if (is_kfunc && kfunc_meta) {
6512 bool is_buf_size = false;
6513
6514 /* check for any const scalar parameter of name "rdonly_buf_size"
6515 * or "rdwr_buf_size"
6516 */
6517 if (btf_is_kfunc_arg_mem_size(btf, &args[i], reg,
6518 "rdonly_buf_size")) {
6519 kfunc_meta->r0_rdonly = true;
6520 is_buf_size = true;
6521 } else if (btf_is_kfunc_arg_mem_size(btf, &args[i], reg,
6522 "rdwr_buf_size"))
6523 is_buf_size = true;
6524
6525 if (is_buf_size) {
6526 if (kfunc_meta->r0_size) {
6527 bpf_log(log, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
6528 return -EINVAL;
6529 }
6530
6531 if (!tnum_is_const(reg->var_off)) {
6532 bpf_log(log, "R%d is not a const\n", regno);
6533 return -EINVAL;
6534 }
6535
6536 kfunc_meta->r0_size = reg->var_off.value;
6537 ret = mark_chain_precision(env, regno);
6538 if (ret)
6539 return ret;
6540 }
6541 }
6542
feb4adfa 6543 if (reg->type == SCALAR_VALUE)
8c1b6e69 6544 continue;
34747c41
MKL
6545 bpf_log(log, "R%d is not a scalar\n", regno);
6546 return -EINVAL;
8c1b6e69 6547 }
34747c41
MKL
6548
6549 if (!btf_type_is_ptr(t)) {
6550 bpf_log(log, "Unrecognized arg#%d type %s\n",
6551 i, btf_type_str(t));
6552 return -EINVAL;
6553 }
6554
eed807f6
KKD
6555 /* These register types have special constraints wrt ref_obj_id
6556 * and offset checks. The rest of trusted args don't.
6557 */
6558 obj_ptr = reg->type == PTR_TO_CTX || reg->type == PTR_TO_BTF_ID ||
6559 reg2btf_ids[base_type(reg->type)];
6560
56e948ff
KKD
6561 /* Check if argument must be a referenced pointer, args + i has
6562 * been verified to be a pointer (after skipping modifiers).
eed807f6 6563 * PTR_TO_CTX is ok without having non-zero ref_obj_id.
56e948ff 6564 */
eed807f6 6565 if (is_kfunc && trusted_args && (obj_ptr && reg->type != PTR_TO_CTX) && !reg->ref_obj_id) {
56e948ff
KKD
6566 bpf_log(log, "R%d must be referenced\n", regno);
6567 return -EINVAL;
6568 }
6569
e6ac2450 6570 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
34747c41 6571 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
655efe50 6572
56e948ff 6573 /* Trusted args have the same offset checks as release arguments */
eed807f6 6574 if ((trusted_args && obj_ptr) || (rel && reg->ref_obj_id))
8f14852e
KKD
6575 arg_type |= OBJ_RELEASE;
6576 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
655efe50
KKD
6577 if (ret < 0)
6578 return ret;
6579
eb1f7f71
BT
6580 if (is_kfunc && reg->ref_obj_id) {
6581 /* Ensure only one argument is referenced PTR_TO_BTF_ID */
6582 if (ref_obj_id) {
6583 bpf_log(log, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6584 regno, reg->ref_obj_id, ref_obj_id);
6585 return -EFAULT;
6586 }
6587 ref_regno = regno;
6588 ref_obj_id = reg->ref_obj_id;
6589 }
6590
a1ef1959
KKD
6591 /* kptr_get is only true for kfunc */
6592 if (i == 0 && kptr_get) {
aa3496ac 6593 struct btf_field *kptr_field;
a1ef1959
KKD
6594
6595 if (reg->type != PTR_TO_MAP_VALUE) {
6596 bpf_log(log, "arg#0 expected pointer to map value\n");
6597 return -EINVAL;
6598 }
6599
6600 /* check_func_arg_reg_off allows var_off for
6601 * PTR_TO_MAP_VALUE, but we need fixed offset to find
6602 * off_desc.
6603 */
6604 if (!tnum_is_const(reg->var_off)) {
6605 bpf_log(log, "arg#0 must have constant offset\n");
6606 return -EINVAL;
6607 }
6608
aa3496ac
KKD
6609 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
6610 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
a1ef1959
KKD
6611 bpf_log(log, "arg#0 no referenced kptr at map value offset=%llu\n",
6612 reg->off + reg->var_off.value);
6613 return -EINVAL;
6614 }
6615
6616 if (!btf_type_is_ptr(ref_t)) {
6617 bpf_log(log, "arg#0 BTF type must be a double pointer\n");
6618 return -EINVAL;
6619 }
6620
6621 ref_t = btf_type_skip_modifiers(btf, ref_t->type, &ref_id);
6622 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6623
6624 if (!btf_type_is_struct(ref_t)) {
6625 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6626 func_name, i, btf_type_str(ref_t), ref_tname);
6627 return -EINVAL;
6628 }
aa3496ac
KKD
6629 if (!btf_struct_ids_match(log, btf, ref_id, 0, kptr_field->kptr.btf,
6630 kptr_field->kptr.btf_id, true)) {
a1ef1959
KKD
6631 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s\n",
6632 func_name, i, btf_type_str(ref_t), ref_tname);
6633 return -EINVAL;
6634 }
6635 /* rest of the arguments can be anything, like normal kfunc */
f858c2b2 6636 } else if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
3363bd0c
KKD
6637 /* If function expects ctx type in BTF check that caller
6638 * is passing PTR_TO_CTX.
6639 */
6640 if (reg->type != PTR_TO_CTX) {
6641 bpf_log(log,
6642 "arg#%d expected pointer to ctx, but got %s\n",
6643 i, btf_type_str(t));
6644 return -EINVAL;
6645 }
45ce4b4f
KKD
6646 } else if (is_kfunc && (reg->type == PTR_TO_BTF_ID ||
6647 (reg2btf_ids[base_type(reg->type)] && !type_flag(reg->type)))) {
e6ac2450
MKL
6648 const struct btf_type *reg_ref_t;
6649 const struct btf *reg_btf;
6650 const char *reg_ref_tname;
6651 u32 reg_ref_id;
6652
6653 if (!btf_type_is_struct(ref_t)) {
6654 bpf_log(log, "kernel function %s args#%d pointer type %s %s is not supported\n",
6655 func_name, i, btf_type_str(ref_t),
6656 ref_tname);
6657 return -EINVAL;
6658 }
6659
6660 if (reg->type == PTR_TO_BTF_ID) {
6661 reg_btf = reg->btf;
6662 reg_ref_id = reg->btf_id;
3363bd0c 6663 } else {
e6ac2450 6664 reg_btf = btf_vmlinux;
45ce4b4f 6665 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
e6ac2450
MKL
6666 }
6667
6668 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id,
6669 &reg_ref_id);
6670 reg_ref_tname = btf_name_by_offset(reg_btf,
6671 reg_ref_t->name_off);
6672 if (!btf_struct_ids_match(log, reg_btf, reg_ref_id,
56e948ff 6673 reg->off, btf, ref_id,
eed807f6 6674 trusted_args || (rel && reg->ref_obj_id))) {
e6ac2450
MKL
6675 bpf_log(log, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
6676 func_name, i,
6677 btf_type_str(ref_t), ref_tname,
6678 regno, btf_type_str(reg_ref_t),
6679 reg_ref_tname);
6680 return -EINVAL;
6681 }
95f2f26f 6682 } else if (ptr_to_mem_ok && processing_call) {
34747c41
MKL
6683 const struct btf_type *resolve_ret;
6684 u32 type_size;
e5069b9c 6685
3363bd0c 6686 if (is_kfunc) {
d583691c 6687 bool arg_mem_size = i + 1 < nargs && is_kfunc_arg_mem_size(btf, &args[i + 1], &regs[regno + 1]);
b8d31762
RS
6688 bool arg_dynptr = btf_type_is_struct(ref_t) &&
6689 !strcmp(ref_tname,
6690 stringify_struct(bpf_dynptr_kern));
d583691c 6691
3363bd0c
KKD
6692 /* Permit pointer to mem, but only when argument
6693 * type is pointer to scalar, or struct composed
6694 * (recursively) of scalars.
d583691c
KKD
6695 * When arg_mem_size is true, the pointer can be
6696 * void *.
b8d31762 6697 * Also permit initialized local dynamic pointers.
3363bd0c
KKD
6698 */
6699 if (!btf_type_is_scalar(ref_t) &&
d583691c 6700 !__btf_type_is_scalar_struct(log, btf, ref_t, 0) &&
b8d31762 6701 !arg_dynptr &&
d583691c 6702 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
3363bd0c 6703 bpf_log(log,
d583691c
KKD
6704 "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
6705 i, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
3363bd0c
KKD
6706 return -EINVAL;
6707 }
d583691c 6708
b8d31762
RS
6709 if (arg_dynptr) {
6710 if (reg->type != PTR_TO_STACK) {
6711 bpf_log(log, "arg#%d pointer type %s %s not to stack\n",
6712 i, btf_type_str(ref_t),
6713 ref_tname);
6714 return -EINVAL;
6715 }
6716
6717 if (!is_dynptr_reg_valid_init(env, reg)) {
6718 bpf_log(log,
6719 "arg#%d pointer type %s %s must be valid and initialized\n",
6720 i, btf_type_str(ref_t),
6721 ref_tname);
6722 return -EINVAL;
6723 }
6724
6725 if (!is_dynptr_type_expected(env, reg,
6726 ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL)) {
6727 bpf_log(log,
6728 "arg#%d pointer type %s %s points to unsupported dynamic pointer type\n",
6729 i, btf_type_str(ref_t),
6730 ref_tname);
6731 return -EINVAL;
6732 }
6733
6734 continue;
6735 }
6736
d583691c
KKD
6737 /* Check for mem, len pair */
6738 if (arg_mem_size) {
6739 if (check_kfunc_mem_size_reg(env, &regs[regno + 1], regno + 1)) {
6740 bpf_log(log, "arg#%d arg#%d memory, len pair leads to invalid memory access\n",
6741 i, i + 1);
6742 return -EINVAL;
6743 }
6744 i++;
6745 continue;
6746 }
3363bd0c
KKD
6747 }
6748
34747c41
MKL
6749 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6750 if (IS_ERR(resolve_ret)) {
e5069b9c 6751 bpf_log(log,
34747c41
MKL
6752 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6753 i, btf_type_str(ref_t), ref_tname,
6754 PTR_ERR(resolve_ret));
6755 return -EINVAL;
e5069b9c
DB
6756 }
6757
34747c41
MKL
6758 if (check_mem_reg(env, reg, regno, type_size))
6759 return -EINVAL;
6760 } else {
3363bd0c
KKD
6761 bpf_log(log, "reg type unsupported for arg#%d %sfunction %s#%d\n", i,
6762 is_kfunc ? "kernel " : "", func_name, func_id);
34747c41 6763 return -EINVAL;
8c1b6e69 6764 }
8c1b6e69 6765 }
34747c41 6766
5c073f26
KKD
6767 /* Either both are set, or neither */
6768 WARN_ON_ONCE((ref_obj_id && !ref_regno) || (!ref_obj_id && ref_regno));
24d5bb80
KKD
6769 /* We already made sure ref_obj_id is set only for one argument. We do
6770 * allow (!rel && ref_obj_id), so that passing such referenced
6771 * PTR_TO_BTF_ID to other kfuncs works. Note that rel is only true when
6772 * is_kfunc is true.
6773 */
6774 if (rel && !ref_obj_id) {
6775 bpf_log(log, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
6776 func_name);
6777 return -EINVAL;
5c073f26 6778 }
fa96b242
BT
6779
6780 if (sleepable && !env->prog->aux->sleepable) {
6781 bpf_log(log, "kernel function %s is sleepable but the program is not\n",
6782 func_name);
6783 return -EINVAL;
6784 }
6785
eb1f7f71
BT
6786 if (kfunc_meta && ref_obj_id)
6787 kfunc_meta->ref_obj_id = ref_obj_id;
6788
5c073f26
KKD
6789 /* returns argument register number > 0 in case of reference release kfunc */
6790 return rel ? ref_regno : 0;
34747c41
MKL
6791}
6792
95f2f26f 6793/* Compare BTF of a function declaration with given bpf_reg_state.
34747c41
MKL
6794 * Returns:
6795 * EFAULT - there is a verifier bug. Abort verification.
6796 * EINVAL - there is a type mismatch or BTF is not available.
6797 * 0 - BTF matches with what bpf_reg_state expects.
6798 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6799 */
6800int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6801 struct bpf_reg_state *regs)
6802{
6803 struct bpf_prog *prog = env->prog;
6804 struct btf *btf = prog->aux->btf;
6805 bool is_global;
6806 u32 btf_id;
6807 int err;
6808
6809 if (!prog->aux->func_info)
6810 return -EINVAL;
6811
6812 btf_id = prog->aux->func_info[subprog].type_id;
6813 if (!btf_id)
6814 return -EFAULT;
6815
6816 if (prog->aux->func_info_aux[subprog].unreliable)
6817 return -EINVAL;
6818
6819 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
eb1f7f71 6820 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, NULL, false);
95f2f26f
BT
6821
6822 /* Compiler optimizations can remove arguments from static functions
6823 * or mismatched type can be passed into a global function.
6824 * In such cases mark the function as unreliable from BTF point of view.
6825 */
6826 if (err)
6827 prog->aux->func_info_aux[subprog].unreliable = true;
6828 return err;
6829}
6830
6831/* Compare BTF of a function call with given bpf_reg_state.
6832 * Returns:
6833 * EFAULT - there is a verifier bug. Abort verification.
6834 * EINVAL - there is a type mismatch or BTF is not available.
6835 * 0 - BTF matches with what bpf_reg_state expects.
6836 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6837 *
6838 * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6839 * because btf_check_func_arg_match() is still doing both. Once that
6840 * function is split in 2, we can call from here btf_check_subprog_arg_match()
6841 * first, and then treat the calling part in a new code path.
6842 */
6843int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6844 struct bpf_reg_state *regs)
6845{
6846 struct bpf_prog *prog = env->prog;
6847 struct btf *btf = prog->aux->btf;
6848 bool is_global;
6849 u32 btf_id;
6850 int err;
6851
6852 if (!prog->aux->func_info)
6853 return -EINVAL;
6854
6855 btf_id = prog->aux->func_info[subprog].type_id;
6856 if (!btf_id)
6857 return -EFAULT;
6858
6859 if (prog->aux->func_info_aux[subprog].unreliable)
6860 return -EINVAL;
6861
6862 is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
eb1f7f71 6863 err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, NULL, true);
34747c41 6864
51c39bb1
AS
6865 /* Compiler optimizations can remove arguments from static functions
6866 * or mismatched type can be passed into a global function.
6867 * In such cases mark the function as unreliable from BTF point of view.
6868 */
34747c41
MKL
6869 if (err)
6870 prog->aux->func_info_aux[subprog].unreliable = true;
6871 return err;
51c39bb1
AS
6872}
6873
e6ac2450
MKL
6874int btf_check_kfunc_arg_match(struct bpf_verifier_env *env,
6875 const struct btf *btf, u32 func_id,
a4703e31 6876 struct bpf_reg_state *regs,
eb1f7f71 6877 struct bpf_kfunc_arg_meta *meta)
e6ac2450 6878{
eb1f7f71 6879 return btf_check_func_arg_match(env, btf, func_id, regs, true, meta, true);
e6ac2450
MKL
6880}
6881
51c39bb1
AS
6882/* Convert BTF of a function into bpf_reg_state if possible
6883 * Returns:
6884 * EFAULT - there is a verifier bug. Abort verification.
6885 * EINVAL - cannot convert BTF.
6886 * 0 - Successfully converted BTF into bpf_reg_state
6887 * (either PTR_TO_CTX or SCALAR_VALUE).
6888 */
6889int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
feb4adfa 6890 struct bpf_reg_state *regs)
51c39bb1
AS
6891{
6892 struct bpf_verifier_log *log = &env->log;
6893 struct bpf_prog *prog = env->prog;
be8704ff 6894 enum bpf_prog_type prog_type = prog->type;
51c39bb1
AS
6895 struct btf *btf = prog->aux->btf;
6896 const struct btf_param *args;
e5069b9c 6897 const struct btf_type *t, *ref_t;
51c39bb1
AS
6898 u32 i, nargs, btf_id;
6899 const char *tname;
6900
6901 if (!prog->aux->func_info ||
6902 prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6903 bpf_log(log, "Verifier bug\n");
6904 return -EFAULT;
6905 }
6906
6907 btf_id = prog->aux->func_info[subprog].type_id;
6908 if (!btf_id) {
6909 bpf_log(log, "Global functions need valid BTF\n");
6910 return -EFAULT;
6911 }
6912
6913 t = btf_type_by_id(btf, btf_id);
6914 if (!t || !btf_type_is_func(t)) {
6915 /* These checks were already done by the verifier while loading
6916 * struct bpf_func_info
6917 */
6918 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6919 subprog);
6920 return -EFAULT;
6921 }
6922 tname = btf_name_by_offset(btf, t->name_off);
6923
6924 if (log->level & BPF_LOG_LEVEL)
6925 bpf_log(log, "Validating %s() func#%d...\n",
6926 tname, subprog);
6927
6928 if (prog->aux->func_info_aux[subprog].unreliable) {
6929 bpf_log(log, "Verifier bug in function %s()\n", tname);
6930 return -EFAULT;
6931 }
be8704ff 6932 if (prog_type == BPF_PROG_TYPE_EXT)
3aac1ead 6933 prog_type = prog->aux->dst_prog->type;
51c39bb1
AS
6934
6935 t = btf_type_by_id(btf, t->type);
6936 if (!t || !btf_type_is_func_proto(t)) {
6937 bpf_log(log, "Invalid type of function %s()\n", tname);
6938 return -EFAULT;
6939 }
6940 args = (const struct btf_param *)(t + 1);
6941 nargs = btf_type_vlen(t);
523a4cf4
DB
6942 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6943 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
6944 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
51c39bb1
AS
6945 return -EINVAL;
6946 }
6947 /* check that function returns int */
6948 t = btf_type_by_id(btf, t->type);
6949 while (btf_type_is_modifier(t))
6950 t = btf_type_by_id(btf, t->type);
6089fb32 6951 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
51c39bb1
AS
6952 bpf_log(log,
6953 "Global function %s() doesn't return scalar. Only those are supported.\n",
6954 tname);
6955 return -EINVAL;
6956 }
6957 /* Convert BTF function arguments into verifier types.
6958 * Only PTR_TO_CTX and SCALAR are supported atm.
6959 */
6960 for (i = 0; i < nargs; i++) {
feb4adfa
DB
6961 struct bpf_reg_state *reg = &regs[i + 1];
6962
51c39bb1
AS
6963 t = btf_type_by_id(btf, args[i].type);
6964 while (btf_type_is_modifier(t))
6965 t = btf_type_by_id(btf, t->type);
6089fb32 6966 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
feb4adfa 6967 reg->type = SCALAR_VALUE;
51c39bb1
AS
6968 continue;
6969 }
e5069b9c
DB
6970 if (btf_type_is_ptr(t)) {
6971 if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6972 reg->type = PTR_TO_CTX;
6973 continue;
6974 }
6975
6976 t = btf_type_skip_modifiers(btf, t->type, NULL);
6977
6978 ref_t = btf_resolve_size(btf, t, &reg->mem_size);
6979 if (IS_ERR(ref_t)) {
6980 bpf_log(log,
6981 "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6982 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
6983 PTR_ERR(ref_t));
6984 return -EINVAL;
6985 }
6986
cf9f2f8d 6987 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
e5069b9c
DB
6988 reg->id = ++env->id_gen;
6989
51c39bb1
AS
6990 continue;
6991 }
6992 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
571f9738 6993 i, btf_type_str(t), tname);
51c39bb1
AS
6994 return -EINVAL;
6995 }
8c1b6e69
AS
6996 return 0;
6997}
6998
31d0bc81
AM
6999static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7000 struct btf_show *show)
7001{
7002 const struct btf_type *t = btf_type_by_id(btf, type_id);
7003
7004 show->btf = btf;
7005 memset(&show->state, 0, sizeof(show->state));
7006 memset(&show->obj, 0, sizeof(show->obj));
7007
7008 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7009}
7010
7011static void btf_seq_show(struct btf_show *show, const char *fmt,
7012 va_list args)
7013{
7014 seq_vprintf((struct seq_file *)show->target, fmt, args);
7015}
7016
eb411377
AM
7017int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7018 void *obj, struct seq_file *m, u64 flags)
31d0bc81
AM
7019{
7020 struct btf_show sseq;
7021
7022 sseq.target = m;
7023 sseq.showfn = btf_seq_show;
7024 sseq.flags = flags;
7025
7026 btf_type_show(btf, type_id, obj, &sseq);
7027
7028 return sseq.state.status;
7029}
7030
b00b8dae
MKL
7031void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7032 struct seq_file *m)
7033{
31d0bc81
AM
7034 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7035 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7036 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7037}
7038
7039struct btf_show_snprintf {
7040 struct btf_show show;
7041 int len_left; /* space left in string */
7042 int len; /* length we would have written */
7043};
7044
7045static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7046 va_list args)
7047{
7048 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7049 int len;
7050
7051 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7052
7053 if (len < 0) {
7054 ssnprintf->len_left = 0;
7055 ssnprintf->len = len;
58250ae3 7056 } else if (len >= ssnprintf->len_left) {
31d0bc81
AM
7057 /* no space, drive on to get length we would have written */
7058 ssnprintf->len_left = 0;
7059 ssnprintf->len += len;
7060 } else {
7061 ssnprintf->len_left -= len;
7062 ssnprintf->len += len;
7063 show->target += len;
7064 }
7065}
7066
7067int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7068 char *buf, int len, u64 flags)
7069{
7070 struct btf_show_snprintf ssnprintf;
7071
7072 ssnprintf.show.target = buf;
7073 ssnprintf.show.flags = flags;
7074 ssnprintf.show.showfn = btf_snprintf_show;
7075 ssnprintf.len_left = len;
7076 ssnprintf.len = 0;
7077
7078 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7079
c561d110 7080 /* If we encountered an error, return it. */
31d0bc81
AM
7081 if (ssnprintf.show.state.status)
7082 return ssnprintf.show.state.status;
b00b8dae 7083
31d0bc81
AM
7084 /* Otherwise return length we would have written */
7085 return ssnprintf.len;
b00b8dae 7086}
f56a653c 7087
3481e64b
QM
7088#ifdef CONFIG_PROC_FS
7089static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7090{
7091 const struct btf *btf = filp->private_data;
7092
7093 seq_printf(m, "btf_id:\t%u\n", btf->id);
7094}
7095#endif
7096
f56a653c
MKL
7097static int btf_release(struct inode *inode, struct file *filp)
7098{
7099 btf_put(filp->private_data);
7100 return 0;
7101}
7102
60197cfb 7103const struct file_operations btf_fops = {
3481e64b
QM
7104#ifdef CONFIG_PROC_FS
7105 .show_fdinfo = bpf_btf_show_fdinfo,
7106#endif
f56a653c
MKL
7107 .release = btf_release,
7108};
7109
78958fca
MKL
7110static int __btf_new_fd(struct btf *btf)
7111{
7112 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7113}
7114
c571bd75 7115int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
f56a653c
MKL
7116{
7117 struct btf *btf;
78958fca 7118 int ret;
f56a653c 7119
c571bd75 7120 btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
f56a653c
MKL
7121 attr->btf_size, attr->btf_log_level,
7122 u64_to_user_ptr(attr->btf_log_buf),
7123 attr->btf_log_size);
7124 if (IS_ERR(btf))
7125 return PTR_ERR(btf);
7126
78958fca
MKL
7127 ret = btf_alloc_id(btf);
7128 if (ret) {
7129 btf_free(btf);
7130 return ret;
7131 }
7132
7133 /*
7134 * The BTF ID is published to the userspace.
7135 * All BTF free must go through call_rcu() from
7136 * now on (i.e. free by calling btf_put()).
7137 */
7138
7139 ret = __btf_new_fd(btf);
7140 if (ret < 0)
f56a653c
MKL
7141 btf_put(btf);
7142
78958fca 7143 return ret;
f56a653c
MKL
7144}
7145
7146struct btf *btf_get_by_fd(int fd)
7147{
7148 struct btf *btf;
7149 struct fd f;
7150
7151 f = fdget(fd);
7152
7153 if (!f.file)
7154 return ERR_PTR(-EBADF);
7155
7156 if (f.file->f_op != &btf_fops) {
7157 fdput(f);
7158 return ERR_PTR(-EINVAL);
7159 }
7160
7161 btf = f.file->private_data;
78958fca 7162 refcount_inc(&btf->refcnt);
f56a653c
MKL
7163 fdput(f);
7164
7165 return btf;
7166}
60197cfb
MKL
7167
7168int btf_get_info_by_fd(const struct btf *btf,
7169 const union bpf_attr *attr,
7170 union bpf_attr __user *uattr)
7171{
62dab84c 7172 struct bpf_btf_info __user *uinfo;
5c6f2588 7173 struct bpf_btf_info info;
62dab84c
MKL
7174 u32 info_copy, btf_copy;
7175 void __user *ubtf;
53297220
AN
7176 char __user *uname;
7177 u32 uinfo_len, uname_len, name_len;
7178 int ret = 0;
60197cfb 7179
62dab84c
MKL
7180 uinfo = u64_to_user_ptr(attr->info.info);
7181 uinfo_len = attr->info.info_len;
7182
7183 info_copy = min_t(u32, uinfo_len, sizeof(info));
5c6f2588 7184 memset(&info, 0, sizeof(info));
62dab84c
MKL
7185 if (copy_from_user(&info, uinfo, info_copy))
7186 return -EFAULT;
7187
7188 info.id = btf->id;
7189 ubtf = u64_to_user_ptr(info.btf);
7190 btf_copy = min_t(u32, btf->data_size, info.btf_size);
7191 if (copy_to_user(ubtf, btf->data, btf_copy))
7192 return -EFAULT;
7193 info.btf_size = btf->data_size;
7194
53297220
AN
7195 info.kernel_btf = btf->kernel_btf;
7196
7197 uname = u64_to_user_ptr(info.name);
7198 uname_len = info.name_len;
7199 if (!uname ^ !uname_len)
7200 return -EINVAL;
7201
7202 name_len = strlen(btf->name);
7203 info.name_len = name_len;
7204
7205 if (uname) {
7206 if (uname_len >= name_len + 1) {
7207 if (copy_to_user(uname, btf->name, name_len + 1))
7208 return -EFAULT;
7209 } else {
7210 char zero = '\0';
7211
7212 if (copy_to_user(uname, btf->name, uname_len - 1))
7213 return -EFAULT;
7214 if (put_user(zero, uname + uname_len - 1))
7215 return -EFAULT;
7216 /* let user-space know about too short buffer */
7217 ret = -ENOSPC;
7218 }
7219 }
7220
62dab84c
MKL
7221 if (copy_to_user(uinfo, &info, info_copy) ||
7222 put_user(info_copy, &uattr->info.info_len))
60197cfb
MKL
7223 return -EFAULT;
7224
53297220 7225 return ret;
60197cfb 7226}
78958fca
MKL
7227
7228int btf_get_fd_by_id(u32 id)
7229{
7230 struct btf *btf;
7231 int fd;
7232
7233 rcu_read_lock();
7234 btf = idr_find(&btf_idr, id);
7235 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7236 btf = ERR_PTR(-ENOENT);
7237 rcu_read_unlock();
7238
7239 if (IS_ERR(btf))
7240 return PTR_ERR(btf);
7241
7242 fd = __btf_new_fd(btf);
7243 if (fd < 0)
7244 btf_put(btf);
7245
7246 return fd;
7247}
7248
22dc4a0f 7249u32 btf_obj_id(const struct btf *btf)
78958fca
MKL
7250{
7251 return btf->id;
7252}
eae2e83e 7253
290248a5
AN
7254bool btf_is_kernel(const struct btf *btf)
7255{
7256 return btf->kernel_btf;
7257}
7258
541c3bad
AN
7259bool btf_is_module(const struct btf *btf)
7260{
7261 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7262}
7263
eae2e83e
JO
7264static int btf_id_cmp_func(const void *a, const void *b)
7265{
7266 const int *pa = a, *pb = b;
7267
7268 return *pa - *pb;
7269}
7270
2af30f11 7271bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
eae2e83e
JO
7272{
7273 return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
7274}
36e68442 7275
a4703e31
KKD
7276static void *btf_id_set8_contains(const struct btf_id_set8 *set, u32 id)
7277{
7278 return bsearch(&id, set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func);
7279}
7280
18688de2
KKD
7281enum {
7282 BTF_MODULE_F_LIVE = (1 << 0),
7283};
7284
36e68442
AN
7285#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7286struct btf_module {
7287 struct list_head list;
7288 struct module *module;
7289 struct btf *btf;
7290 struct bin_attribute *sysfs_attr;
18688de2 7291 int flags;
36e68442
AN
7292};
7293
7294static LIST_HEAD(btf_modules);
7295static DEFINE_MUTEX(btf_module_mutex);
7296
7297static ssize_t
7298btf_module_read(struct file *file, struct kobject *kobj,
7299 struct bin_attribute *bin_attr,
7300 char *buf, loff_t off, size_t len)
7301{
7302 const struct btf *btf = bin_attr->private;
7303
7304 memcpy(buf, btf->data + off, len);
7305 return len;
7306}
7307
1e89106d
AS
7308static void purge_cand_cache(struct btf *btf);
7309
36e68442
AN
7310static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7311 void *module)
7312{
7313 struct btf_module *btf_mod, *tmp;
7314 struct module *mod = module;
7315 struct btf *btf;
7316 int err = 0;
7317
7318 if (mod->btf_data_size == 0 ||
18688de2
KKD
7319 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7320 op != MODULE_STATE_GOING))
36e68442
AN
7321 goto out;
7322
7323 switch (op) {
7324 case MODULE_STATE_COMING:
7325 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7326 if (!btf_mod) {
7327 err = -ENOMEM;
7328 goto out;
7329 }
7330 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7331 if (IS_ERR(btf)) {
7332 pr_warn("failed to validate module [%s] BTF: %ld\n",
7333 mod->name, PTR_ERR(btf));
7334 kfree(btf_mod);
5e214f2e
CB
7335 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
7336 err = PTR_ERR(btf);
36e68442
AN
7337 goto out;
7338 }
7339 err = btf_alloc_id(btf);
7340 if (err) {
7341 btf_free(btf);
7342 kfree(btf_mod);
7343 goto out;
7344 }
7345
1e89106d 7346 purge_cand_cache(NULL);
36e68442
AN
7347 mutex_lock(&btf_module_mutex);
7348 btf_mod->module = module;
7349 btf_mod->btf = btf;
7350 list_add(&btf_mod->list, &btf_modules);
7351 mutex_unlock(&btf_module_mutex);
7352
7353 if (IS_ENABLED(CONFIG_SYSFS)) {
7354 struct bin_attribute *attr;
7355
7356 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7357 if (!attr)
7358 goto out;
7359
7360 sysfs_bin_attr_init(attr);
7361 attr->attr.name = btf->name;
7362 attr->attr.mode = 0444;
7363 attr->size = btf->data_size;
7364 attr->private = btf;
7365 attr->read = btf_module_read;
7366
7367 err = sysfs_create_bin_file(btf_kobj, attr);
7368 if (err) {
7369 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7370 mod->name, err);
7371 kfree(attr);
7372 err = 0;
7373 goto out;
7374 }
7375
7376 btf_mod->sysfs_attr = attr;
7377 }
7378
18688de2
KKD
7379 break;
7380 case MODULE_STATE_LIVE:
7381 mutex_lock(&btf_module_mutex);
7382 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7383 if (btf_mod->module != module)
7384 continue;
7385
7386 btf_mod->flags |= BTF_MODULE_F_LIVE;
7387 break;
7388 }
7389 mutex_unlock(&btf_module_mutex);
36e68442
AN
7390 break;
7391 case MODULE_STATE_GOING:
7392 mutex_lock(&btf_module_mutex);
7393 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7394 if (btf_mod->module != module)
7395 continue;
7396
7397 list_del(&btf_mod->list);
7398 if (btf_mod->sysfs_attr)
7399 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
1e89106d 7400 purge_cand_cache(btf_mod->btf);
36e68442
AN
7401 btf_put(btf_mod->btf);
7402 kfree(btf_mod->sysfs_attr);
7403 kfree(btf_mod);
7404 break;
7405 }
7406 mutex_unlock(&btf_module_mutex);
7407 break;
7408 }
7409out:
7410 return notifier_from_errno(err);
7411}
7412
7413static struct notifier_block btf_module_nb = {
7414 .notifier_call = btf_module_notify,
7415};
7416
7417static int __init btf_module_init(void)
7418{
7419 register_module_notifier(&btf_module_nb);
7420 return 0;
7421}
7422
7423fs_initcall(btf_module_init);
7424#endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
541c3bad
AN
7425
7426struct module *btf_try_get_module(const struct btf *btf)
7427{
7428 struct module *res = NULL;
7429#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7430 struct btf_module *btf_mod, *tmp;
7431
7432 mutex_lock(&btf_module_mutex);
7433 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7434 if (btf_mod->btf != btf)
7435 continue;
7436
18688de2
KKD
7437 /* We must only consider module whose __init routine has
7438 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7439 * which is set from the notifier callback for
7440 * MODULE_STATE_LIVE.
7441 */
7442 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
541c3bad
AN
7443 res = btf_mod->module;
7444
7445 break;
7446 }
7447 mutex_unlock(&btf_module_mutex);
7448#endif
7449
7450 return res;
7451}
3d78417b 7452
9492450f
KKD
7453/* Returns struct btf corresponding to the struct module.
7454 * This function can return NULL or ERR_PTR.
dee872e1
KKD
7455 */
7456static struct btf *btf_get_module_btf(const struct module *module)
7457{
dee872e1
KKD
7458#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7459 struct btf_module *btf_mod, *tmp;
7460#endif
9492450f
KKD
7461 struct btf *btf = NULL;
7462
7463 if (!module) {
7464 btf = bpf_get_btf_vmlinux();
7ada3787 7465 if (!IS_ERR_OR_NULL(btf))
9492450f
KKD
7466 btf_get(btf);
7467 return btf;
7468 }
dee872e1 7469
dee872e1
KKD
7470#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7471 mutex_lock(&btf_module_mutex);
7472 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7473 if (btf_mod->module != module)
7474 continue;
7475
7476 btf_get(btf_mod->btf);
7477 btf = btf_mod->btf;
7478 break;
7479 }
7480 mutex_unlock(&btf_module_mutex);
7481#endif
7482
7483 return btf;
7484}
7485
3d78417b
AS
7486BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7487{
edc3ec09
KKD
7488 struct btf *btf = NULL;
7489 int btf_obj_fd = 0;
3d78417b
AS
7490 long ret;
7491
7492 if (flags)
7493 return -EINVAL;
7494
7495 if (name_sz <= 1 || name[name_sz - 1])
7496 return -EINVAL;
7497
edc3ec09
KKD
7498 ret = bpf_find_btf_id(name, kind, &btf);
7499 if (ret > 0 && btf_is_module(btf)) {
7500 btf_obj_fd = __btf_new_fd(btf);
7501 if (btf_obj_fd < 0) {
7502 btf_put(btf);
7503 return btf_obj_fd;
3d78417b 7504 }
edc3ec09 7505 return ret | (((u64)btf_obj_fd) << 32);
3d78417b 7506 }
edc3ec09
KKD
7507 if (ret > 0)
7508 btf_put(btf);
3d78417b
AS
7509 return ret;
7510}
7511
7512const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7513 .func = bpf_btf_find_by_name_kind,
7514 .gpl_only = false,
7515 .ret_type = RET_INTEGER,
216e3cd2 7516 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
3d78417b
AS
7517 .arg2_type = ARG_CONST_SIZE,
7518 .arg3_type = ARG_ANYTHING,
7519 .arg4_type = ARG_ANYTHING,
7520};
eb529c5b 7521
d19ddb47
SL
7522BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7523#define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7524BTF_TRACING_TYPE_xxx
7525#undef BTF_TRACING_TYPE
14f267d9 7526
dee872e1 7527/* Kernel Function (kfunc) BTF ID set registration API */
14f267d9 7528
a4703e31
KKD
7529static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7530 struct btf_id_set8 *add_set)
14f267d9 7531{
a4703e31 7532 bool vmlinux_set = !btf_is_module(btf);
dee872e1 7533 struct btf_kfunc_set_tab *tab;
a4703e31 7534 struct btf_id_set8 *set;
dee872e1
KKD
7535 u32 set_cnt;
7536 int ret;
7537
a4703e31 7538 if (hook >= BTF_KFUNC_HOOK_MAX) {
dee872e1
KKD
7539 ret = -EINVAL;
7540 goto end;
7541 }
7542
7543 if (!add_set->cnt)
7544 return 0;
7545
7546 tab = btf->kfunc_set_tab;
7547 if (!tab) {
7548 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7549 if (!tab)
7550 return -ENOMEM;
7551 btf->kfunc_set_tab = tab;
7552 }
7553
a4703e31 7554 set = tab->sets[hook];
dee872e1
KKD
7555 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
7556 * for module sets.
7557 */
7558 if (WARN_ON_ONCE(set && !vmlinux_set)) {
7559 ret = -EINVAL;
7560 goto end;
7561 }
7562
7563 /* We don't need to allocate, concatenate, and sort module sets, because
7564 * only one is allowed per hook. Hence, we can directly assign the
7565 * pointer and return.
7566 */
7567 if (!vmlinux_set) {
a4703e31 7568 tab->sets[hook] = add_set;
dee872e1
KKD
7569 return 0;
7570 }
7571
7572 /* In case of vmlinux sets, there may be more than one set being
7573 * registered per hook. To create a unified set, we allocate a new set
7574 * and concatenate all individual sets being registered. While each set
7575 * is individually sorted, they may become unsorted when concatenated,
7576 * hence re-sorting the final set again is required to make binary
a4703e31 7577 * searching the set using btf_id_set8_contains function work.
dee872e1
KKD
7578 */
7579 set_cnt = set ? set->cnt : 0;
7580
7581 if (set_cnt > U32_MAX - add_set->cnt) {
7582 ret = -EOVERFLOW;
7583 goto end;
7584 }
7585
7586 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7587 ret = -E2BIG;
7588 goto end;
7589 }
7590
7591 /* Grow set */
a4703e31
KKD
7592 set = krealloc(tab->sets[hook],
7593 offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
dee872e1
KKD
7594 GFP_KERNEL | __GFP_NOWARN);
7595 if (!set) {
7596 ret = -ENOMEM;
7597 goto end;
7598 }
7599
7600 /* For newly allocated set, initialize set->cnt to 0 */
a4703e31 7601 if (!tab->sets[hook])
dee872e1 7602 set->cnt = 0;
a4703e31 7603 tab->sets[hook] = set;
dee872e1
KKD
7604
7605 /* Concatenate the two sets */
a4703e31 7606 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
dee872e1
KKD
7607 set->cnt += add_set->cnt;
7608
a4703e31 7609 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
dee872e1
KKD
7610
7611 return 0;
7612end:
7613 btf_free_kfunc_set_tab(btf);
7614 return ret;
14f267d9 7615}
14f267d9 7616
a4703e31 7617static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
dee872e1 7618 enum btf_kfunc_hook hook,
dee872e1 7619 u32 kfunc_btf_id)
14f267d9 7620{
a4703e31
KKD
7621 struct btf_id_set8 *set;
7622 u32 *id;
14f267d9 7623
a4703e31
KKD
7624 if (hook >= BTF_KFUNC_HOOK_MAX)
7625 return NULL;
dee872e1 7626 if (!btf->kfunc_set_tab)
a4703e31
KKD
7627 return NULL;
7628 set = btf->kfunc_set_tab->sets[hook];
dee872e1 7629 if (!set)
a4703e31
KKD
7630 return NULL;
7631 id = btf_id_set8_contains(set, kfunc_btf_id);
7632 if (!id)
7633 return NULL;
7634 /* The flags for BTF ID are located next to it */
7635 return id + 1;
dee872e1
KKD
7636}
7637
7638static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7639{
7640 switch (prog_type) {
7641 case BPF_PROG_TYPE_XDP:
7642 return BTF_KFUNC_HOOK_XDP;
7643 case BPF_PROG_TYPE_SCHED_CLS:
7644 return BTF_KFUNC_HOOK_TC;
7645 case BPF_PROG_TYPE_STRUCT_OPS:
7646 return BTF_KFUNC_HOOK_STRUCT_OPS;
97949767 7647 case BPF_PROG_TYPE_TRACING:
d15bf150 7648 case BPF_PROG_TYPE_LSM:
97949767
BT
7649 return BTF_KFUNC_HOOK_TRACING;
7650 case BPF_PROG_TYPE_SYSCALL:
7651 return BTF_KFUNC_HOOK_SYSCALL;
dee872e1
KKD
7652 default:
7653 return BTF_KFUNC_HOOK_MAX;
14f267d9 7654 }
14f267d9
KKD
7655}
7656
dee872e1
KKD
7657/* Caution:
7658 * Reference to the module (obtained using btf_try_get_module) corresponding to
7659 * the struct btf *MUST* be held when calling this function from verifier
7660 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7661 * keeping the reference for the duration of the call provides the necessary
7662 * protection for looking up a well-formed btf->kfunc_set_tab.
7663 */
a4703e31 7664u32 *btf_kfunc_id_set_contains(const struct btf *btf,
dee872e1 7665 enum bpf_prog_type prog_type,
a4703e31 7666 u32 kfunc_btf_id)
dee872e1
KKD
7667{
7668 enum btf_kfunc_hook hook;
0e32dfc8 7669
dee872e1 7670 hook = bpf_prog_type_to_kfunc_hook(prog_type);
a4703e31 7671 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
dee872e1 7672}
d9847eb8 7673
dee872e1
KKD
7674/* This function must be invoked only from initcalls/module init functions */
7675int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7676 const struct btf_kfunc_id_set *kset)
7677{
7678 enum btf_kfunc_hook hook;
7679 struct btf *btf;
7680 int ret;
7681
7682 btf = btf_get_module_btf(kset->owner);
c446fdac
SF
7683 if (!btf) {
7684 if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7685 pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7686 return -ENOENT;
7687 }
7688 if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7689 pr_err("missing module BTF, cannot register kfuncs\n");
7690 return -ENOENT;
7691 }
7692 return 0;
7693 }
7694 if (IS_ERR(btf))
7695 return PTR_ERR(btf);
dee872e1
KKD
7696
7697 hook = bpf_prog_type_to_kfunc_hook(prog_type);
a4703e31 7698 ret = btf_populate_kfunc_set(btf, hook, kset->set);
9492450f 7699 btf_put(btf);
dee872e1
KKD
7700 return ret;
7701}
7702EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
be315829 7703
5ce937d6
KKD
7704s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7705{
7706 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7707 struct btf_id_dtor_kfunc *dtor;
7708
7709 if (!tab)
7710 return -ENOENT;
7711 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7712 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7713 */
7714 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7715 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7716 if (!dtor)
7717 return -ENOENT;
7718 return dtor->kfunc_btf_id;
7719}
7720
14a324f6
KKD
7721static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7722{
7723 const struct btf_type *dtor_func, *dtor_func_proto, *t;
7724 const struct btf_param *args;
7725 s32 dtor_btf_id;
7726 u32 nr_args, i;
7727
7728 for (i = 0; i < cnt; i++) {
7729 dtor_btf_id = dtors[i].kfunc_btf_id;
7730
7731 dtor_func = btf_type_by_id(btf, dtor_btf_id);
7732 if (!dtor_func || !btf_type_is_func(dtor_func))
7733 return -EINVAL;
7734
7735 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7736 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7737 return -EINVAL;
7738
7739 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7740 t = btf_type_by_id(btf, dtor_func_proto->type);
7741 if (!t || !btf_type_is_void(t))
7742 return -EINVAL;
7743
7744 nr_args = btf_type_vlen(dtor_func_proto);
7745 if (nr_args != 1)
7746 return -EINVAL;
7747 args = btf_params(dtor_func_proto);
7748 t = btf_type_by_id(btf, args[0].type);
7749 /* Allow any pointer type, as width on targets Linux supports
7750 * will be same for all pointer types (i.e. sizeof(void *))
7751 */
7752 if (!t || !btf_type_is_ptr(t))
7753 return -EINVAL;
7754 }
7755 return 0;
7756}
7757
5ce937d6
KKD
7758/* This function must be invoked only from initcalls/module init functions */
7759int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7760 struct module *owner)
7761{
7762 struct btf_id_dtor_kfunc_tab *tab;
7763 struct btf *btf;
7764 u32 tab_cnt;
7765 int ret;
7766
7767 btf = btf_get_module_btf(owner);
7768 if (!btf) {
7769 if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7770 pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7771 return -ENOENT;
7772 }
7773 if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7774 pr_err("missing module BTF, cannot register dtor kfuncs\n");
7775 return -ENOENT;
7776 }
7777 return 0;
7778 }
7779 if (IS_ERR(btf))
7780 return PTR_ERR(btf);
7781
7782 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7783 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7784 ret = -E2BIG;
7785 goto end;
7786 }
7787
14a324f6
KKD
7788 /* Ensure that the prototype of dtor kfuncs being registered is sane */
7789 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7790 if (ret < 0)
7791 goto end;
7792
5ce937d6
KKD
7793 tab = btf->dtor_kfunc_tab;
7794 /* Only one call allowed for modules */
7795 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7796 ret = -EINVAL;
7797 goto end;
7798 }
7799
7800 tab_cnt = tab ? tab->cnt : 0;
7801 if (tab_cnt > U32_MAX - add_cnt) {
7802 ret = -EOVERFLOW;
7803 goto end;
7804 }
7805 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7806 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7807 ret = -E2BIG;
7808 goto end;
7809 }
7810
7811 tab = krealloc(btf->dtor_kfunc_tab,
7812 offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7813 GFP_KERNEL | __GFP_NOWARN);
7814 if (!tab) {
7815 ret = -ENOMEM;
7816 goto end;
7817 }
7818
7819 if (!btf->dtor_kfunc_tab)
7820 tab->cnt = 0;
7821 btf->dtor_kfunc_tab = tab;
7822
7823 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7824 tab->cnt += add_cnt;
7825
7826 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7827
7828 return 0;
7829end:
7830 btf_free_dtor_kfunc_tab(btf);
7831 btf_put(btf);
7832 return ret;
7833}
7834EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7835
e70e13e7
MC
7836#define MAX_TYPES_ARE_COMPAT_DEPTH 2
7837
e70e13e7
MC
7838/* Check local and target types for compatibility. This check is used for
7839 * type-based CO-RE relocations and follow slightly different rules than
7840 * field-based relocations. This function assumes that root types were already
7841 * checked for name match. Beyond that initial root-level name check, names
7842 * are completely ignored. Compatibility rules are as follows:
6089fb32 7843 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
e70e13e7
MC
7844 * kind should match for local and target types (i.e., STRUCT is not
7845 * compatible with UNION);
6089fb32 7846 * - for ENUMs/ENUM64s, the size is ignored;
e70e13e7
MC
7847 * - for INT, size and signedness are ignored;
7848 * - for ARRAY, dimensionality is ignored, element types are checked for
7849 * compatibility recursively;
7850 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
7851 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7852 * - FUNC_PROTOs are compatible if they have compatible signature: same
7853 * number of input args and compatible return and argument types.
7854 * These rules are not set in stone and probably will be adjusted as we get
7855 * more experience with using BPF CO-RE relocations.
7856 */
29db4bea
AS
7857int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7858 const struct btf *targ_btf, __u32 targ_id)
7859{
fd75733d 7860 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
e70e13e7 7861 MAX_TYPES_ARE_COMPAT_DEPTH);
29db4bea
AS
7862}
7863
ec6209c8
DM
7864#define MAX_TYPES_MATCH_DEPTH 2
7865
7866int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
7867 const struct btf *targ_btf, u32 targ_id)
7868{
7869 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
7870 MAX_TYPES_MATCH_DEPTH);
7871}
7872
29db4bea
AS
7873static bool bpf_core_is_flavor_sep(const char *s)
7874{
7875 /* check X___Y name pattern, where X and Y are not underscores */
7876 return s[0] != '_' && /* X */
7877 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
7878 s[4] != '_'; /* Y */
7879}
7880
7881size_t bpf_core_essential_name_len(const char *name)
7882{
7883 size_t n = strlen(name);
7884 int i;
7885
7886 for (i = n - 5; i >= 0; i--) {
7887 if (bpf_core_is_flavor_sep(name + i))
7888 return i + 1;
7889 }
7890 return n;
7891}
fbd94c7a 7892
1e89106d
AS
7893struct bpf_cand_cache {
7894 const char *name;
7895 u32 name_len;
7896 u16 kind;
7897 u16 cnt;
7898 struct {
7899 const struct btf *btf;
7900 u32 id;
7901 } cands[];
7902};
7903
7904static void bpf_free_cands(struct bpf_cand_cache *cands)
7905{
7906 if (!cands->cnt)
7907 /* empty candidate array was allocated on stack */
7908 return;
7909 kfree(cands);
7910}
7911
7912static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
7913{
7914 kfree(cands->name);
7915 kfree(cands);
7916}
7917
7918#define VMLINUX_CAND_CACHE_SIZE 31
7919static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
7920
7921#define MODULE_CAND_CACHE_SIZE 31
7922static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
7923
7924static DEFINE_MUTEX(cand_cache_mutex);
7925
7926static void __print_cand_cache(struct bpf_verifier_log *log,
7927 struct bpf_cand_cache **cache,
7928 int cache_size)
7929{
7930 struct bpf_cand_cache *cc;
7931 int i, j;
7932
7933 for (i = 0; i < cache_size; i++) {
7934 cc = cache[i];
7935 if (!cc)
7936 continue;
7937 bpf_log(log, "[%d]%s(", i, cc->name);
7938 for (j = 0; j < cc->cnt; j++) {
7939 bpf_log(log, "%d", cc->cands[j].id);
7940 if (j < cc->cnt - 1)
7941 bpf_log(log, " ");
7942 }
7943 bpf_log(log, "), ");
7944 }
7945}
7946
7947static void print_cand_cache(struct bpf_verifier_log *log)
7948{
7949 mutex_lock(&cand_cache_mutex);
7950 bpf_log(log, "vmlinux_cand_cache:");
7951 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7952 bpf_log(log, "\nmodule_cand_cache:");
7953 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7954 bpf_log(log, "\n");
7955 mutex_unlock(&cand_cache_mutex);
7956}
7957
7958static u32 hash_cands(struct bpf_cand_cache *cands)
7959{
7960 return jhash(cands->name, cands->name_len, 0);
7961}
7962
7963static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
7964 struct bpf_cand_cache **cache,
7965 int cache_size)
7966{
7967 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
7968
7969 if (cc && cc->name_len == cands->name_len &&
7970 !strncmp(cc->name, cands->name, cands->name_len))
7971 return cc;
7972 return NULL;
7973}
7974
7975static size_t sizeof_cands(int cnt)
7976{
7977 return offsetof(struct bpf_cand_cache, cands[cnt]);
7978}
7979
7980static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
7981 struct bpf_cand_cache **cache,
7982 int cache_size)
7983{
7984 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
7985
7986 if (*cc) {
7987 bpf_free_cands_from_cache(*cc);
7988 *cc = NULL;
7989 }
4674f210 7990 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
1e89106d
AS
7991 if (!new_cands) {
7992 bpf_free_cands(cands);
7993 return ERR_PTR(-ENOMEM);
7994 }
1e89106d
AS
7995 /* strdup the name, since it will stay in cache.
7996 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
7997 */
7998 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
7999 bpf_free_cands(cands);
8000 if (!new_cands->name) {
8001 kfree(new_cands);
8002 return ERR_PTR(-ENOMEM);
8003 }
8004 *cc = new_cands;
8005 return new_cands;
8006}
8007
29f2e5bd 8008#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
1e89106d
AS
8009static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8010 int cache_size)
8011{
8012 struct bpf_cand_cache *cc;
8013 int i, j;
8014
8015 for (i = 0; i < cache_size; i++) {
8016 cc = cache[i];
8017 if (!cc)
8018 continue;
8019 if (!btf) {
8020 /* when new module is loaded purge all of module_cand_cache,
8021 * since new module might have candidates with the name
8022 * that matches cached cands.
8023 */
8024 bpf_free_cands_from_cache(cc);
8025 cache[i] = NULL;
8026 continue;
8027 }
8028 /* when module is unloaded purge cache entries
8029 * that match module's btf
8030 */
8031 for (j = 0; j < cc->cnt; j++)
8032 if (cc->cands[j].btf == btf) {
8033 bpf_free_cands_from_cache(cc);
8034 cache[i] = NULL;
8035 break;
8036 }
8037 }
8038
8039}
8040
8041static void purge_cand_cache(struct btf *btf)
8042{
8043 mutex_lock(&cand_cache_mutex);
8044 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8045 mutex_unlock(&cand_cache_mutex);
8046}
29f2e5bd 8047#endif
1e89106d
AS
8048
8049static struct bpf_cand_cache *
8050bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8051 int targ_start_id)
8052{
8053 struct bpf_cand_cache *new_cands;
8054 const struct btf_type *t;
8055 const char *targ_name;
8056 size_t targ_essent_len;
8057 int n, i;
8058
8059 n = btf_nr_types(targ_btf);
8060 for (i = targ_start_id; i < n; i++) {
8061 t = btf_type_by_id(targ_btf, i);
8062 if (btf_kind(t) != cands->kind)
8063 continue;
8064
8065 targ_name = btf_name_by_offset(targ_btf, t->name_off);
8066 if (!targ_name)
8067 continue;
8068
8069 /* the resched point is before strncmp to make sure that search
8070 * for non-existing name will have a chance to schedule().
8071 */
8072 cond_resched();
8073
8074 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8075 continue;
8076
8077 targ_essent_len = bpf_core_essential_name_len(targ_name);
8078 if (targ_essent_len != cands->name_len)
8079 continue;
8080
8081 /* most of the time there is only one candidate for a given kind+name pair */
8082 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8083 if (!new_cands) {
8084 bpf_free_cands(cands);
8085 return ERR_PTR(-ENOMEM);
8086 }
8087
8088 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8089 bpf_free_cands(cands);
8090 cands = new_cands;
8091 cands->cands[cands->cnt].btf = targ_btf;
8092 cands->cands[cands->cnt].id = i;
8093 cands->cnt++;
8094 }
8095 return cands;
8096}
8097
8098static struct bpf_cand_cache *
8099bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8100{
8101 struct bpf_cand_cache *cands, *cc, local_cand = {};
8102 const struct btf *local_btf = ctx->btf;
8103 const struct btf_type *local_type;
8104 const struct btf *main_btf;
8105 size_t local_essent_len;
8106 struct btf *mod_btf;
8107 const char *name;
8108 int id;
8109
8110 main_btf = bpf_get_btf_vmlinux();
8111 if (IS_ERR(main_btf))
f18a4997 8112 return ERR_CAST(main_btf);
7ada3787
KKD
8113 if (!main_btf)
8114 return ERR_PTR(-EINVAL);
1e89106d
AS
8115
8116 local_type = btf_type_by_id(local_btf, local_type_id);
8117 if (!local_type)
8118 return ERR_PTR(-EINVAL);
8119
8120 name = btf_name_by_offset(local_btf, local_type->name_off);
8121 if (str_is_empty(name))
8122 return ERR_PTR(-EINVAL);
8123 local_essent_len = bpf_core_essential_name_len(name);
8124
8125 cands = &local_cand;
8126 cands->name = name;
8127 cands->kind = btf_kind(local_type);
8128 cands->name_len = local_essent_len;
8129
8130 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8131 /* cands is a pointer to stack here */
8132 if (cc) {
8133 if (cc->cnt)
8134 return cc;
8135 goto check_modules;
8136 }
8137
8138 /* Attempt to find target candidates in vmlinux BTF first */
8139 cands = bpf_core_add_cands(cands, main_btf, 1);
8140 if (IS_ERR(cands))
f18a4997 8141 return ERR_CAST(cands);
1e89106d
AS
8142
8143 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8144
8145 /* populate cache even when cands->cnt == 0 */
8146 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8147 if (IS_ERR(cc))
f18a4997 8148 return ERR_CAST(cc);
1e89106d
AS
8149
8150 /* if vmlinux BTF has any candidate, don't go for module BTFs */
8151 if (cc->cnt)
8152 return cc;
8153
8154check_modules:
8155 /* cands is a pointer to stack here and cands->cnt == 0 */
8156 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8157 if (cc)
8158 /* if cache has it return it even if cc->cnt == 0 */
8159 return cc;
8160
8161 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8162 spin_lock_bh(&btf_idr_lock);
8163 idr_for_each_entry(&btf_idr, mod_btf, id) {
8164 if (!btf_is_module(mod_btf))
8165 continue;
8166 /* linear search could be slow hence unlock/lock
8167 * the IDR to avoiding holding it for too long
8168 */
8169 btf_get(mod_btf);
8170 spin_unlock_bh(&btf_idr_lock);
8171 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8172 if (IS_ERR(cands)) {
8173 btf_put(mod_btf);
f18a4997 8174 return ERR_CAST(cands);
1e89106d
AS
8175 }
8176 spin_lock_bh(&btf_idr_lock);
8177 btf_put(mod_btf);
8178 }
8179 spin_unlock_bh(&btf_idr_lock);
8180 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
8181 * or pointer to stack if cands->cnd == 0.
8182 * Copy it into the cache even when cands->cnt == 0 and
8183 * return the result.
8184 */
8185 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8186}
8187
fbd94c7a
AS
8188int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8189 int relo_idx, void *insn)
8190{
1e89106d
AS
8191 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8192 struct bpf_core_cand_list cands = {};
adb8fa19 8193 struct bpf_core_relo_res targ_res;
78c1f8d0 8194 struct bpf_core_spec *specs;
1e89106d
AS
8195 int err;
8196
78c1f8d0
AS
8197 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8198 * into arrays of btf_ids of struct fields and array indices.
8199 */
8200 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8201 if (!specs)
8202 return -ENOMEM;
8203
1e89106d
AS
8204 if (need_cands) {
8205 struct bpf_cand_cache *cc;
8206 int i;
8207
8208 mutex_lock(&cand_cache_mutex);
8209 cc = bpf_core_find_cands(ctx, relo->type_id);
8210 if (IS_ERR(cc)) {
8211 bpf_log(ctx->log, "target candidate search failed for %d\n",
8212 relo->type_id);
8213 err = PTR_ERR(cc);
8214 goto out;
8215 }
8216 if (cc->cnt) {
8217 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8218 if (!cands.cands) {
8219 err = -ENOMEM;
8220 goto out;
8221 }
8222 }
8223 for (i = 0; i < cc->cnt; i++) {
8224 bpf_log(ctx->log,
8225 "CO-RE relocating %s %s: found target candidate [%d]\n",
8226 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8227 cands.cands[i].btf = cc->cands[i].btf;
8228 cands.cands[i].id = cc->cands[i].id;
8229 }
8230 cands.len = cc->cnt;
8231 /* cand_cache_mutex needs to span the cache lookup and
8232 * copy of btf pointer into bpf_core_cand_list,
adb8fa19 8233 * since module can be unloaded while bpf_core_calc_relo_insn
1e89106d
AS
8234 * is working with module's btf.
8235 */
8236 }
8237
adb8fa19
MV
8238 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8239 &targ_res);
8240 if (err)
8241 goto out;
8242
8243 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8244 &targ_res);
8245
1e89106d 8246out:
78c1f8d0 8247 kfree(specs);
1e89106d
AS
8248 if (need_cands) {
8249 kfree(cands.cands);
8250 mutex_unlock(&cand_cache_mutex);
8251 if (ctx->log->level & BPF_LOG_LEVEL2)
8252 print_cand_cache(ctx->log);
8253 }
8254 return err;
fbd94c7a 8255}