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