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