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