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