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