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