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