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
3481 #define field_mask_test_name(field_type, field_type_str) \
3482 if (field_mask & field_type && !strcmp(name, field_type_str)) { \
3483 type = field_type; \
3484 goto end; \
3485 }
3486
btf_get_field_type(const struct btf * btf,const struct btf_type * var_type,u32 field_mask,u32 * seen_mask,int * align,int * sz)3487 static int btf_get_field_type(const struct btf *btf, const struct btf_type *var_type,
3488 u32 field_mask, u32 *seen_mask,
3489 int *align, int *sz)
3490 {
3491 int type = 0;
3492 const char *name = __btf_name_by_offset(btf, var_type->name_off);
3493
3494 if (field_mask & BPF_SPIN_LOCK) {
3495 if (!strcmp(name, "bpf_spin_lock")) {
3496 if (*seen_mask & BPF_SPIN_LOCK)
3497 return -E2BIG;
3498 *seen_mask |= BPF_SPIN_LOCK;
3499 type = BPF_SPIN_LOCK;
3500 goto end;
3501 }
3502 }
3503 if (field_mask & BPF_RES_SPIN_LOCK) {
3504 if (!strcmp(name, "bpf_res_spin_lock")) {
3505 if (*seen_mask & BPF_RES_SPIN_LOCK)
3506 return -E2BIG;
3507 *seen_mask |= BPF_RES_SPIN_LOCK;
3508 type = BPF_RES_SPIN_LOCK;
3509 goto end;
3510 }
3511 }
3512 if (field_mask & BPF_TIMER) {
3513 if (!strcmp(name, "bpf_timer")) {
3514 if (*seen_mask & BPF_TIMER)
3515 return -E2BIG;
3516 *seen_mask |= BPF_TIMER;
3517 type = BPF_TIMER;
3518 goto end;
3519 }
3520 }
3521 if (field_mask & BPF_WORKQUEUE) {
3522 if (!strcmp(name, "bpf_wq")) {
3523 if (*seen_mask & BPF_WORKQUEUE)
3524 return -E2BIG;
3525 *seen_mask |= BPF_WORKQUEUE;
3526 type = BPF_WORKQUEUE;
3527 goto end;
3528 }
3529 }
3530 field_mask_test_name(BPF_LIST_HEAD, "bpf_list_head");
3531 field_mask_test_name(BPF_LIST_NODE, "bpf_list_node");
3532 field_mask_test_name(BPF_RB_ROOT, "bpf_rb_root");
3533 field_mask_test_name(BPF_RB_NODE, "bpf_rb_node");
3534 field_mask_test_name(BPF_REFCOUNT, "bpf_refcount");
3535
3536 /* Only return BPF_KPTR when all other types with matchable names fail */
3537 if (field_mask & (BPF_KPTR | BPF_UPTR) && !__btf_type_is_struct(var_type)) {
3538 type = BPF_KPTR_REF;
3539 goto end;
3540 }
3541 return 0;
3542 end:
3543 *sz = btf_field_type_size(type);
3544 *align = btf_field_type_align(type);
3545 return type;
3546 }
3547
3548 #undef field_mask_test_name
3549
3550 /* Repeat a number of fields for a specified number of times.
3551 *
3552 * Copy the fields starting from the first field and repeat them for
3553 * repeat_cnt times. The fields are repeated by adding the offset of each
3554 * field with
3555 * (i + 1) * elem_size
3556 * where i is the repeat index and elem_size is the size of an element.
3557 */
btf_repeat_fields(struct btf_field_info * info,int info_cnt,u32 field_cnt,u32 repeat_cnt,u32 elem_size)3558 static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
3559 u32 field_cnt, u32 repeat_cnt, u32 elem_size)
3560 {
3561 u32 i, j;
3562 u32 cur;
3563
3564 /* Ensure not repeating fields that should not be repeated. */
3565 for (i = 0; i < field_cnt; i++) {
3566 switch (info[i].type) {
3567 case BPF_KPTR_UNREF:
3568 case BPF_KPTR_REF:
3569 case BPF_KPTR_PERCPU:
3570 case BPF_UPTR:
3571 case BPF_LIST_HEAD:
3572 case BPF_RB_ROOT:
3573 break;
3574 default:
3575 return -EINVAL;
3576 }
3577 }
3578
3579 /* The type of struct size or variable size is u32,
3580 * so the multiplication will not overflow.
3581 */
3582 if (field_cnt * (repeat_cnt + 1) > info_cnt)
3583 return -E2BIG;
3584
3585 cur = field_cnt;
3586 for (i = 0; i < repeat_cnt; i++) {
3587 memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
3588 for (j = 0; j < field_cnt; j++)
3589 info[cur++].off += (i + 1) * elem_size;
3590 }
3591
3592 return 0;
3593 }
3594
3595 static int btf_find_struct_field(const struct btf *btf,
3596 const struct btf_type *t, u32 field_mask,
3597 struct btf_field_info *info, int info_cnt,
3598 u32 level);
3599
3600 /* Find special fields in the struct type of a field.
3601 *
3602 * This function is used to find fields of special types that is not a
3603 * global variable or a direct field of a struct type. It also handles the
3604 * repetition if it is the element type of an array.
3605 */
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)3606 static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
3607 u32 off, u32 nelems,
3608 u32 field_mask, struct btf_field_info *info,
3609 int info_cnt, u32 level)
3610 {
3611 int ret, err, i;
3612
3613 level++;
3614 if (level >= MAX_RESOLVE_DEPTH)
3615 return -E2BIG;
3616
3617 ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level);
3618
3619 if (ret <= 0)
3620 return ret;
3621
3622 /* Shift the offsets of the nested struct fields to the offsets
3623 * related to the container.
3624 */
3625 for (i = 0; i < ret; i++)
3626 info[i].off += off;
3627
3628 if (nelems > 1) {
3629 err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
3630 if (err == 0)
3631 ret *= nelems;
3632 else
3633 ret = err;
3634 }
3635
3636 return ret;
3637 }
3638
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)3639 static int btf_find_field_one(const struct btf *btf,
3640 const struct btf_type *var,
3641 const struct btf_type *var_type,
3642 int var_idx,
3643 u32 off, u32 expected_size,
3644 u32 field_mask, u32 *seen_mask,
3645 struct btf_field_info *info, int info_cnt,
3646 u32 level)
3647 {
3648 int ret, align, sz, field_type;
3649 struct btf_field_info tmp;
3650 const struct btf_array *array;
3651 u32 i, nelems = 1;
3652
3653 /* Walk into array types to find the element type and the number of
3654 * elements in the (flattened) array.
3655 */
3656 for (i = 0; i < MAX_RESOLVE_DEPTH && btf_type_is_array(var_type); i++) {
3657 array = btf_array(var_type);
3658 nelems *= array->nelems;
3659 var_type = btf_type_by_id(btf, array->type);
3660 }
3661 if (i == MAX_RESOLVE_DEPTH)
3662 return -E2BIG;
3663 if (nelems == 0)
3664 return 0;
3665
3666 field_type = btf_get_field_type(btf, var_type,
3667 field_mask, seen_mask, &align, &sz);
3668 /* Look into variables of struct types */
3669 if (!field_type && __btf_type_is_struct(var_type)) {
3670 sz = var_type->size;
3671 if (expected_size && expected_size != sz * nelems)
3672 return 0;
3673 ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
3674 &info[0], info_cnt, level);
3675 return ret;
3676 }
3677
3678 if (field_type == 0)
3679 return 0;
3680 if (field_type < 0)
3681 return field_type;
3682
3683 if (expected_size && expected_size != sz * nelems)
3684 return 0;
3685 if (off % align)
3686 return 0;
3687
3688 switch (field_type) {
3689 case BPF_SPIN_LOCK:
3690 case BPF_RES_SPIN_LOCK:
3691 case BPF_TIMER:
3692 case BPF_WORKQUEUE:
3693 case BPF_LIST_NODE:
3694 case BPF_RB_NODE:
3695 case BPF_REFCOUNT:
3696 ret = btf_find_struct(btf, var_type, off, sz, field_type,
3697 info_cnt ? &info[0] : &tmp);
3698 if (ret < 0)
3699 return ret;
3700 break;
3701 case BPF_KPTR_UNREF:
3702 case BPF_KPTR_REF:
3703 case BPF_KPTR_PERCPU:
3704 case BPF_UPTR:
3705 ret = btf_find_kptr(btf, var_type, off, sz,
3706 info_cnt ? &info[0] : &tmp, field_mask);
3707 if (ret < 0)
3708 return ret;
3709 break;
3710 case BPF_LIST_HEAD:
3711 case BPF_RB_ROOT:
3712 ret = btf_find_graph_root(btf, var, var_type,
3713 var_idx, off, sz,
3714 info_cnt ? &info[0] : &tmp,
3715 field_type);
3716 if (ret < 0)
3717 return ret;
3718 break;
3719 default:
3720 return -EFAULT;
3721 }
3722
3723 if (ret == BTF_FIELD_IGNORE)
3724 return 0;
3725 if (!info_cnt)
3726 return -E2BIG;
3727 if (nelems > 1) {
3728 ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
3729 if (ret < 0)
3730 return ret;
3731 }
3732 return nelems;
3733 }
3734
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)3735 static int btf_find_struct_field(const struct btf *btf,
3736 const struct btf_type *t, u32 field_mask,
3737 struct btf_field_info *info, int info_cnt,
3738 u32 level)
3739 {
3740 int ret, idx = 0;
3741 const struct btf_member *member;
3742 u32 i, off, seen_mask = 0;
3743
3744 for_each_member(i, t, member) {
3745 const struct btf_type *member_type = btf_type_by_id(btf,
3746 member->type);
3747
3748 off = __btf_member_bit_offset(t, member);
3749 if (off % 8)
3750 /* valid C code cannot generate such BTF */
3751 return -EINVAL;
3752 off /= 8;
3753
3754 ret = btf_find_field_one(btf, t, member_type, i,
3755 off, 0,
3756 field_mask, &seen_mask,
3757 &info[idx], info_cnt - idx, level);
3758 if (ret < 0)
3759 return ret;
3760 idx += ret;
3761 }
3762 return idx;
3763 }
3764
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)3765 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3766 u32 field_mask, struct btf_field_info *info,
3767 int info_cnt, u32 level)
3768 {
3769 int ret, idx = 0;
3770 const struct btf_var_secinfo *vsi;
3771 u32 i, off, seen_mask = 0;
3772
3773 for_each_vsi(i, t, vsi) {
3774 const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3775 const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3776
3777 off = vsi->offset;
3778 ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
3779 field_mask, &seen_mask,
3780 &info[idx], info_cnt - idx,
3781 level);
3782 if (ret < 0)
3783 return ret;
3784 idx += ret;
3785 }
3786 return idx;
3787 }
3788
btf_find_field(const struct btf * btf,const struct btf_type * t,u32 field_mask,struct btf_field_info * info,int info_cnt)3789 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3790 u32 field_mask, struct btf_field_info *info,
3791 int info_cnt)
3792 {
3793 if (__btf_type_is_struct(t))
3794 return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0);
3795 else if (btf_type_is_datasec(t))
3796 return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0);
3797 return -EINVAL;
3798 }
3799
3800 /* 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)3801 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3802 struct btf_field_info *info)
3803 {
3804 struct module *mod = NULL;
3805 const struct btf_type *t;
3806 /* If a matching btf type is found in kernel or module BTFs, kptr_ref
3807 * is that BTF, otherwise it's program BTF
3808 */
3809 struct btf *kptr_btf;
3810 int ret;
3811 s32 id;
3812
3813 /* Find type in map BTF, and use it to look up the matching type
3814 * in vmlinux or module BTFs, by name and kind.
3815 */
3816 t = btf_type_by_id(btf, info->kptr.type_id);
3817 id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3818 &kptr_btf);
3819 if (id == -ENOENT) {
3820 /* btf_parse_kptr should only be called w/ btf = program BTF */
3821 WARN_ON_ONCE(btf_is_kernel(btf));
3822
3823 /* Type exists only in program BTF. Assume that it's a MEM_ALLOC
3824 * kptr allocated via bpf_obj_new
3825 */
3826 field->kptr.dtor = NULL;
3827 id = info->kptr.type_id;
3828 kptr_btf = (struct btf *)btf;
3829 goto found_dtor;
3830 }
3831 if (id < 0)
3832 return id;
3833
3834 /* Find and stash the function pointer for the destruction function that
3835 * needs to be eventually invoked from the map free path.
3836 */
3837 if (info->type == BPF_KPTR_REF) {
3838 const struct btf_type *dtor_func;
3839 const char *dtor_func_name;
3840 unsigned long addr;
3841 s32 dtor_btf_id;
3842
3843 /* This call also serves as a whitelist of allowed objects that
3844 * can be used as a referenced pointer and be stored in a map at
3845 * the same time.
3846 */
3847 dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
3848 if (dtor_btf_id < 0) {
3849 ret = dtor_btf_id;
3850 goto end_btf;
3851 }
3852
3853 dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
3854 if (!dtor_func) {
3855 ret = -ENOENT;
3856 goto end_btf;
3857 }
3858
3859 if (btf_is_module(kptr_btf)) {
3860 mod = btf_try_get_module(kptr_btf);
3861 if (!mod) {
3862 ret = -ENXIO;
3863 goto end_btf;
3864 }
3865 }
3866
3867 /* We already verified dtor_func to be btf_type_is_func
3868 * in register_btf_id_dtor_kfuncs.
3869 */
3870 dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
3871 addr = kallsyms_lookup_name(dtor_func_name);
3872 if (!addr) {
3873 ret = -EINVAL;
3874 goto end_mod;
3875 }
3876 field->kptr.dtor = (void *)addr;
3877 }
3878
3879 found_dtor:
3880 field->kptr.btf_id = id;
3881 field->kptr.btf = kptr_btf;
3882 field->kptr.module = mod;
3883 return 0;
3884 end_mod:
3885 module_put(mod);
3886 end_btf:
3887 btf_put(kptr_btf);
3888 return ret;
3889 }
3890
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)3891 static int btf_parse_graph_root(const struct btf *btf,
3892 struct btf_field *field,
3893 struct btf_field_info *info,
3894 const char *node_type_name,
3895 size_t node_type_align)
3896 {
3897 const struct btf_type *t, *n = NULL;
3898 const struct btf_member *member;
3899 u32 offset;
3900 int i;
3901
3902 t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3903 /* We've already checked that value_btf_id is a struct type. We
3904 * just need to figure out the offset of the list_node, and
3905 * verify its type.
3906 */
3907 for_each_member(i, t, member) {
3908 if (strcmp(info->graph_root.node_name,
3909 __btf_name_by_offset(btf, member->name_off)))
3910 continue;
3911 /* Invalid BTF, two members with same name */
3912 if (n)
3913 return -EINVAL;
3914 n = btf_type_by_id(btf, member->type);
3915 if (!__btf_type_is_struct(n))
3916 return -EINVAL;
3917 if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
3918 return -EINVAL;
3919 offset = __btf_member_bit_offset(n, member);
3920 if (offset % 8)
3921 return -EINVAL;
3922 offset /= 8;
3923 if (offset % node_type_align)
3924 return -EINVAL;
3925
3926 field->graph_root.btf = (struct btf *)btf;
3927 field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3928 field->graph_root.node_offset = offset;
3929 }
3930 if (!n)
3931 return -ENOENT;
3932 return 0;
3933 }
3934
btf_parse_list_head(const struct btf * btf,struct btf_field * field,struct btf_field_info * info)3935 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3936 struct btf_field_info *info)
3937 {
3938 return btf_parse_graph_root(btf, field, info, "bpf_list_node",
3939 __alignof__(struct bpf_list_node));
3940 }
3941
btf_parse_rb_root(const struct btf * btf,struct btf_field * field,struct btf_field_info * info)3942 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
3943 struct btf_field_info *info)
3944 {
3945 return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
3946 __alignof__(struct bpf_rb_node));
3947 }
3948
btf_field_cmp(const void * _a,const void * _b,const void * priv)3949 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
3950 {
3951 const struct btf_field *a = (const struct btf_field *)_a;
3952 const struct btf_field *b = (const struct btf_field *)_b;
3953
3954 if (a->offset < b->offset)
3955 return -1;
3956 else if (a->offset > b->offset)
3957 return 1;
3958 return 0;
3959 }
3960
btf_parse_fields(const struct btf * btf,const struct btf_type * t,u32 field_mask,u32 value_size)3961 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3962 u32 field_mask, u32 value_size)
3963 {
3964 struct btf_field_info info_arr[BTF_FIELDS_MAX];
3965 u32 next_off = 0, field_type_size;
3966 struct btf_record *rec;
3967 int ret, i, cnt;
3968
3969 ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3970 if (ret < 0)
3971 return ERR_PTR(ret);
3972 if (!ret)
3973 return NULL;
3974
3975 cnt = ret;
3976 /* This needs to be kzalloc to zero out padding and unused fields, see
3977 * comment in btf_record_equal.
3978 */
3979 rec = kzalloc(struct_size(rec, fields, cnt), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
3980 if (!rec)
3981 return ERR_PTR(-ENOMEM);
3982
3983 rec->spin_lock_off = -EINVAL;
3984 rec->res_spin_lock_off = -EINVAL;
3985 rec->timer_off = -EINVAL;
3986 rec->wq_off = -EINVAL;
3987 rec->refcount_off = -EINVAL;
3988 for (i = 0; i < cnt; i++) {
3989 field_type_size = btf_field_type_size(info_arr[i].type);
3990 if (info_arr[i].off + field_type_size > value_size) {
3991 WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3992 ret = -EFAULT;
3993 goto end;
3994 }
3995 if (info_arr[i].off < next_off) {
3996 ret = -EEXIST;
3997 goto end;
3998 }
3999 next_off = info_arr[i].off + field_type_size;
4000
4001 rec->field_mask |= info_arr[i].type;
4002 rec->fields[i].offset = info_arr[i].off;
4003 rec->fields[i].type = info_arr[i].type;
4004 rec->fields[i].size = field_type_size;
4005
4006 switch (info_arr[i].type) {
4007 case BPF_SPIN_LOCK:
4008 WARN_ON_ONCE(rec->spin_lock_off >= 0);
4009 /* Cache offset for faster lookup at runtime */
4010 rec->spin_lock_off = rec->fields[i].offset;
4011 break;
4012 case BPF_RES_SPIN_LOCK:
4013 WARN_ON_ONCE(rec->spin_lock_off >= 0);
4014 /* Cache offset for faster lookup at runtime */
4015 rec->res_spin_lock_off = rec->fields[i].offset;
4016 break;
4017 case BPF_TIMER:
4018 WARN_ON_ONCE(rec->timer_off >= 0);
4019 /* Cache offset for faster lookup at runtime */
4020 rec->timer_off = rec->fields[i].offset;
4021 break;
4022 case BPF_WORKQUEUE:
4023 WARN_ON_ONCE(rec->wq_off >= 0);
4024 /* Cache offset for faster lookup at runtime */
4025 rec->wq_off = rec->fields[i].offset;
4026 break;
4027 case BPF_REFCOUNT:
4028 WARN_ON_ONCE(rec->refcount_off >= 0);
4029 /* Cache offset for faster lookup at runtime */
4030 rec->refcount_off = rec->fields[i].offset;
4031 break;
4032 case BPF_KPTR_UNREF:
4033 case BPF_KPTR_REF:
4034 case BPF_KPTR_PERCPU:
4035 case BPF_UPTR:
4036 ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
4037 if (ret < 0)
4038 goto end;
4039 break;
4040 case BPF_LIST_HEAD:
4041 ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
4042 if (ret < 0)
4043 goto end;
4044 break;
4045 case BPF_RB_ROOT:
4046 ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
4047 if (ret < 0)
4048 goto end;
4049 break;
4050 case BPF_LIST_NODE:
4051 case BPF_RB_NODE:
4052 break;
4053 default:
4054 ret = -EFAULT;
4055 goto end;
4056 }
4057 rec->cnt++;
4058 }
4059
4060 if (rec->spin_lock_off >= 0 && rec->res_spin_lock_off >= 0) {
4061 ret = -EINVAL;
4062 goto end;
4063 }
4064
4065 /* bpf_{list_head, rb_node} require bpf_spin_lock */
4066 if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
4067 btf_record_has_field(rec, BPF_RB_ROOT)) &&
4068 (rec->spin_lock_off < 0 && rec->res_spin_lock_off < 0)) {
4069 ret = -EINVAL;
4070 goto end;
4071 }
4072
4073 if (rec->refcount_off < 0 &&
4074 btf_record_has_field(rec, BPF_LIST_NODE) &&
4075 btf_record_has_field(rec, BPF_RB_NODE)) {
4076 ret = -EINVAL;
4077 goto end;
4078 }
4079
4080 sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
4081 NULL, rec);
4082
4083 return rec;
4084 end:
4085 btf_record_free(rec);
4086 return ERR_PTR(ret);
4087 }
4088
btf_check_and_fixup_fields(const struct btf * btf,struct btf_record * rec)4089 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
4090 {
4091 int i;
4092
4093 /* There are three types that signify ownership of some other type:
4094 * kptr_ref, bpf_list_head, bpf_rb_root.
4095 * kptr_ref only supports storing kernel types, which can't store
4096 * references to program allocated local types.
4097 *
4098 * Hence we only need to ensure that bpf_{list_head,rb_root} ownership
4099 * does not form cycles.
4100 */
4101 if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & (BPF_GRAPH_ROOT | BPF_UPTR)))
4102 return 0;
4103 for (i = 0; i < rec->cnt; i++) {
4104 struct btf_struct_meta *meta;
4105 const struct btf_type *t;
4106 u32 btf_id;
4107
4108 if (rec->fields[i].type == BPF_UPTR) {
4109 /* The uptr only supports pinning one page and cannot
4110 * point to a kernel struct
4111 */
4112 if (btf_is_kernel(rec->fields[i].kptr.btf))
4113 return -EINVAL;
4114 t = btf_type_by_id(rec->fields[i].kptr.btf,
4115 rec->fields[i].kptr.btf_id);
4116 if (!t->size)
4117 return -EINVAL;
4118 if (t->size > PAGE_SIZE)
4119 return -E2BIG;
4120 continue;
4121 }
4122
4123 if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
4124 continue;
4125 btf_id = rec->fields[i].graph_root.value_btf_id;
4126 meta = btf_find_struct_meta(btf, btf_id);
4127 if (!meta)
4128 return -EFAULT;
4129 rec->fields[i].graph_root.value_rec = meta->record;
4130
4131 /* We need to set value_rec for all root types, but no need
4132 * to check ownership cycle for a type unless it's also a
4133 * node type.
4134 */
4135 if (!(rec->field_mask & BPF_GRAPH_NODE))
4136 continue;
4137
4138 /* We need to ensure ownership acyclicity among all types. The
4139 * proper way to do it would be to topologically sort all BTF
4140 * IDs based on the ownership edges, since there can be multiple
4141 * bpf_{list_head,rb_node} in a type. Instead, we use the
4142 * following resaoning:
4143 *
4144 * - A type can only be owned by another type in user BTF if it
4145 * has a bpf_{list,rb}_node. Let's call these node types.
4146 * - A type can only _own_ another type in user BTF if it has a
4147 * bpf_{list_head,rb_root}. Let's call these root types.
4148 *
4149 * We ensure that if a type is both a root and node, its
4150 * element types cannot be root types.
4151 *
4152 * To ensure acyclicity:
4153 *
4154 * When A is an root type but not a node, its ownership
4155 * chain can be:
4156 * A -> B -> C
4157 * Where:
4158 * - A is an root, e.g. has bpf_rb_root.
4159 * - B is both a root and node, e.g. has bpf_rb_node and
4160 * bpf_list_head.
4161 * - C is only an root, e.g. has bpf_list_node
4162 *
4163 * When A is both a root and node, some other type already
4164 * owns it in the BTF domain, hence it can not own
4165 * another root type through any of the ownership edges.
4166 * A -> B
4167 * Where:
4168 * - A is both an root and node.
4169 * - B is only an node.
4170 */
4171 if (meta->record->field_mask & BPF_GRAPH_ROOT)
4172 return -ELOOP;
4173 }
4174 return 0;
4175 }
4176
__btf_struct_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4177 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
4178 u32 type_id, void *data, u8 bits_offset,
4179 struct btf_show *show)
4180 {
4181 const struct btf_member *member;
4182 void *safe_data;
4183 u32 i;
4184
4185 safe_data = btf_show_start_struct_type(show, t, type_id, data);
4186 if (!safe_data)
4187 return;
4188
4189 for_each_member(i, t, member) {
4190 const struct btf_type *member_type = btf_type_by_id(btf,
4191 member->type);
4192 const struct btf_kind_operations *ops;
4193 u32 member_offset, bitfield_size;
4194 u32 bytes_offset;
4195 u8 bits8_offset;
4196
4197 btf_show_start_member(show, member);
4198
4199 member_offset = __btf_member_bit_offset(t, member);
4200 bitfield_size = __btf_member_bitfield_size(t, member);
4201 bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4202 bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4203 if (bitfield_size) {
4204 safe_data = btf_show_start_type(show, member_type,
4205 member->type,
4206 data + bytes_offset);
4207 if (safe_data)
4208 btf_bitfield_show(safe_data,
4209 bits8_offset,
4210 bitfield_size, show);
4211 btf_show_end_type(show);
4212 } else {
4213 ops = btf_type_ops(member_type);
4214 ops->show(btf, member_type, member->type,
4215 data + bytes_offset, bits8_offset, show);
4216 }
4217
4218 btf_show_end_member(show);
4219 }
4220
4221 btf_show_end_struct_type(show);
4222 }
4223
btf_struct_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4224 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4225 u32 type_id, void *data, u8 bits_offset,
4226 struct btf_show *show)
4227 {
4228 const struct btf_member *m = show->state.member;
4229
4230 /*
4231 * First check if any members would be shown (are non-zero).
4232 * See comments above "struct btf_show" definition for more
4233 * details on how this works at a high-level.
4234 */
4235 if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4236 if (!show->state.depth_check) {
4237 show->state.depth_check = show->state.depth + 1;
4238 show->state.depth_to_show = 0;
4239 }
4240 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4241 /* Restore saved member data here */
4242 show->state.member = m;
4243 if (show->state.depth_check != show->state.depth + 1)
4244 return;
4245 show->state.depth_check = 0;
4246
4247 if (show->state.depth_to_show <= show->state.depth)
4248 return;
4249 /*
4250 * Reaching here indicates we have recursed and found
4251 * non-zero child values.
4252 */
4253 }
4254
4255 __btf_struct_show(btf, t, type_id, data, bits_offset, show);
4256 }
4257
4258 static const struct btf_kind_operations struct_ops = {
4259 .check_meta = btf_struct_check_meta,
4260 .resolve = btf_struct_resolve,
4261 .check_member = btf_struct_check_member,
4262 .check_kflag_member = btf_generic_check_kflag_member,
4263 .log_details = btf_struct_log,
4264 .show = btf_struct_show,
4265 };
4266
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)4267 static int btf_enum_check_member(struct btf_verifier_env *env,
4268 const struct btf_type *struct_type,
4269 const struct btf_member *member,
4270 const struct btf_type *member_type)
4271 {
4272 u32 struct_bits_off = member->offset;
4273 u32 struct_size, bytes_offset;
4274
4275 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4276 btf_verifier_log_member(env, struct_type, member,
4277 "Member is not byte aligned");
4278 return -EINVAL;
4279 }
4280
4281 struct_size = struct_type->size;
4282 bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4283 if (struct_size - bytes_offset < member_type->size) {
4284 btf_verifier_log_member(env, struct_type, member,
4285 "Member exceeds struct_size");
4286 return -EINVAL;
4287 }
4288
4289 return 0;
4290 }
4291
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)4292 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4293 const struct btf_type *struct_type,
4294 const struct btf_member *member,
4295 const struct btf_type *member_type)
4296 {
4297 u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4298 u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4299
4300 struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4301 nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4302 if (!nr_bits) {
4303 if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4304 btf_verifier_log_member(env, struct_type, member,
4305 "Member is not byte aligned");
4306 return -EINVAL;
4307 }
4308
4309 nr_bits = int_bitsize;
4310 } else if (nr_bits > int_bitsize) {
4311 btf_verifier_log_member(env, struct_type, member,
4312 "Invalid member bitfield_size");
4313 return -EINVAL;
4314 }
4315
4316 struct_size = struct_type->size;
4317 bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4318 if (struct_size < bytes_end) {
4319 btf_verifier_log_member(env, struct_type, member,
4320 "Member exceeds struct_size");
4321 return -EINVAL;
4322 }
4323
4324 return 0;
4325 }
4326
btf_enum_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4327 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4328 const struct btf_type *t,
4329 u32 meta_left)
4330 {
4331 const struct btf_enum *enums = btf_type_enum(t);
4332 struct btf *btf = env->btf;
4333 const char *fmt_str;
4334 u16 i, nr_enums;
4335 u32 meta_needed;
4336
4337 nr_enums = btf_type_vlen(t);
4338 meta_needed = nr_enums * sizeof(*enums);
4339
4340 if (meta_left < meta_needed) {
4341 btf_verifier_log_basic(env, t,
4342 "meta_left:%u meta_needed:%u",
4343 meta_left, meta_needed);
4344 return -EINVAL;
4345 }
4346
4347 if (t->size > 8 || !is_power_of_2(t->size)) {
4348 btf_verifier_log_type(env, t, "Unexpected size");
4349 return -EINVAL;
4350 }
4351
4352 /* enum type either no name or a valid one */
4353 if (t->name_off &&
4354 !btf_name_valid_identifier(env->btf, t->name_off)) {
4355 btf_verifier_log_type(env, t, "Invalid name");
4356 return -EINVAL;
4357 }
4358
4359 btf_verifier_log_type(env, t, NULL);
4360
4361 for (i = 0; i < nr_enums; i++) {
4362 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4363 btf_verifier_log(env, "\tInvalid name_offset:%u",
4364 enums[i].name_off);
4365 return -EINVAL;
4366 }
4367
4368 /* enum member must have a valid name */
4369 if (!enums[i].name_off ||
4370 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4371 btf_verifier_log_type(env, t, "Invalid name");
4372 return -EINVAL;
4373 }
4374
4375 if (env->log.level == BPF_LOG_KERNEL)
4376 continue;
4377 fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4378 btf_verifier_log(env, fmt_str,
4379 __btf_name_by_offset(btf, enums[i].name_off),
4380 enums[i].val);
4381 }
4382
4383 return meta_needed;
4384 }
4385
btf_enum_log(struct btf_verifier_env * env,const struct btf_type * t)4386 static void btf_enum_log(struct btf_verifier_env *env,
4387 const struct btf_type *t)
4388 {
4389 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4390 }
4391
btf_enum_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4392 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4393 u32 type_id, void *data, u8 bits_offset,
4394 struct btf_show *show)
4395 {
4396 const struct btf_enum *enums = btf_type_enum(t);
4397 u32 i, nr_enums = btf_type_vlen(t);
4398 void *safe_data;
4399 int v;
4400
4401 safe_data = btf_show_start_type(show, t, type_id, data);
4402 if (!safe_data)
4403 return;
4404
4405 v = *(int *)safe_data;
4406
4407 for (i = 0; i < nr_enums; i++) {
4408 if (v != enums[i].val)
4409 continue;
4410
4411 btf_show_type_value(show, "%s",
4412 __btf_name_by_offset(btf,
4413 enums[i].name_off));
4414
4415 btf_show_end_type(show);
4416 return;
4417 }
4418
4419 if (btf_type_kflag(t))
4420 btf_show_type_value(show, "%d", v);
4421 else
4422 btf_show_type_value(show, "%u", v);
4423 btf_show_end_type(show);
4424 }
4425
4426 static const struct btf_kind_operations enum_ops = {
4427 .check_meta = btf_enum_check_meta,
4428 .resolve = btf_df_resolve,
4429 .check_member = btf_enum_check_member,
4430 .check_kflag_member = btf_enum_check_kflag_member,
4431 .log_details = btf_enum_log,
4432 .show = btf_enum_show,
4433 };
4434
btf_enum64_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4435 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4436 const struct btf_type *t,
4437 u32 meta_left)
4438 {
4439 const struct btf_enum64 *enums = btf_type_enum64(t);
4440 struct btf *btf = env->btf;
4441 const char *fmt_str;
4442 u16 i, nr_enums;
4443 u32 meta_needed;
4444
4445 nr_enums = btf_type_vlen(t);
4446 meta_needed = nr_enums * sizeof(*enums);
4447
4448 if (meta_left < meta_needed) {
4449 btf_verifier_log_basic(env, t,
4450 "meta_left:%u meta_needed:%u",
4451 meta_left, meta_needed);
4452 return -EINVAL;
4453 }
4454
4455 if (t->size > 8 || !is_power_of_2(t->size)) {
4456 btf_verifier_log_type(env, t, "Unexpected size");
4457 return -EINVAL;
4458 }
4459
4460 /* enum type either no name or a valid one */
4461 if (t->name_off &&
4462 !btf_name_valid_identifier(env->btf, t->name_off)) {
4463 btf_verifier_log_type(env, t, "Invalid name");
4464 return -EINVAL;
4465 }
4466
4467 btf_verifier_log_type(env, t, NULL);
4468
4469 for (i = 0; i < nr_enums; i++) {
4470 if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4471 btf_verifier_log(env, "\tInvalid name_offset:%u",
4472 enums[i].name_off);
4473 return -EINVAL;
4474 }
4475
4476 /* enum member must have a valid name */
4477 if (!enums[i].name_off ||
4478 !btf_name_valid_identifier(btf, enums[i].name_off)) {
4479 btf_verifier_log_type(env, t, "Invalid name");
4480 return -EINVAL;
4481 }
4482
4483 if (env->log.level == BPF_LOG_KERNEL)
4484 continue;
4485
4486 fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4487 btf_verifier_log(env, fmt_str,
4488 __btf_name_by_offset(btf, enums[i].name_off),
4489 btf_enum64_value(enums + i));
4490 }
4491
4492 return meta_needed;
4493 }
4494
btf_enum64_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4495 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4496 u32 type_id, void *data, u8 bits_offset,
4497 struct btf_show *show)
4498 {
4499 const struct btf_enum64 *enums = btf_type_enum64(t);
4500 u32 i, nr_enums = btf_type_vlen(t);
4501 void *safe_data;
4502 s64 v;
4503
4504 safe_data = btf_show_start_type(show, t, type_id, data);
4505 if (!safe_data)
4506 return;
4507
4508 v = *(u64 *)safe_data;
4509
4510 for (i = 0; i < nr_enums; i++) {
4511 if (v != btf_enum64_value(enums + i))
4512 continue;
4513
4514 btf_show_type_value(show, "%s",
4515 __btf_name_by_offset(btf,
4516 enums[i].name_off));
4517
4518 btf_show_end_type(show);
4519 return;
4520 }
4521
4522 if (btf_type_kflag(t))
4523 btf_show_type_value(show, "%lld", v);
4524 else
4525 btf_show_type_value(show, "%llu", v);
4526 btf_show_end_type(show);
4527 }
4528
4529 static const struct btf_kind_operations enum64_ops = {
4530 .check_meta = btf_enum64_check_meta,
4531 .resolve = btf_df_resolve,
4532 .check_member = btf_enum_check_member,
4533 .check_kflag_member = btf_enum_check_kflag_member,
4534 .log_details = btf_enum_log,
4535 .show = btf_enum64_show,
4536 };
4537
btf_func_proto_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4538 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4539 const struct btf_type *t,
4540 u32 meta_left)
4541 {
4542 u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4543
4544 if (meta_left < meta_needed) {
4545 btf_verifier_log_basic(env, t,
4546 "meta_left:%u meta_needed:%u",
4547 meta_left, meta_needed);
4548 return -EINVAL;
4549 }
4550
4551 if (t->name_off) {
4552 btf_verifier_log_type(env, t, "Invalid name");
4553 return -EINVAL;
4554 }
4555
4556 if (btf_type_kflag(t)) {
4557 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4558 return -EINVAL;
4559 }
4560
4561 btf_verifier_log_type(env, t, NULL);
4562
4563 return meta_needed;
4564 }
4565
btf_func_proto_log(struct btf_verifier_env * env,const struct btf_type * t)4566 static void btf_func_proto_log(struct btf_verifier_env *env,
4567 const struct btf_type *t)
4568 {
4569 const struct btf_param *args = (const struct btf_param *)(t + 1);
4570 u16 nr_args = btf_type_vlen(t), i;
4571
4572 btf_verifier_log(env, "return=%u args=(", t->type);
4573 if (!nr_args) {
4574 btf_verifier_log(env, "void");
4575 goto done;
4576 }
4577
4578 if (nr_args == 1 && !args[0].type) {
4579 /* Only one vararg */
4580 btf_verifier_log(env, "vararg");
4581 goto done;
4582 }
4583
4584 btf_verifier_log(env, "%u %s", args[0].type,
4585 __btf_name_by_offset(env->btf,
4586 args[0].name_off));
4587 for (i = 1; i < nr_args - 1; i++)
4588 btf_verifier_log(env, ", %u %s", args[i].type,
4589 __btf_name_by_offset(env->btf,
4590 args[i].name_off));
4591
4592 if (nr_args > 1) {
4593 const struct btf_param *last_arg = &args[nr_args - 1];
4594
4595 if (last_arg->type)
4596 btf_verifier_log(env, ", %u %s", last_arg->type,
4597 __btf_name_by_offset(env->btf,
4598 last_arg->name_off));
4599 else
4600 btf_verifier_log(env, ", vararg");
4601 }
4602
4603 done:
4604 btf_verifier_log(env, ")");
4605 }
4606
4607 static const struct btf_kind_operations func_proto_ops = {
4608 .check_meta = btf_func_proto_check_meta,
4609 .resolve = btf_df_resolve,
4610 /*
4611 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4612 * a struct's member.
4613 *
4614 * It should be a function pointer instead.
4615 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4616 *
4617 * Hence, there is no btf_func_check_member().
4618 */
4619 .check_member = btf_df_check_member,
4620 .check_kflag_member = btf_df_check_kflag_member,
4621 .log_details = btf_func_proto_log,
4622 .show = btf_df_show,
4623 };
4624
btf_func_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4625 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4626 const struct btf_type *t,
4627 u32 meta_left)
4628 {
4629 if (!t->name_off ||
4630 !btf_name_valid_identifier(env->btf, t->name_off)) {
4631 btf_verifier_log_type(env, t, "Invalid name");
4632 return -EINVAL;
4633 }
4634
4635 if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4636 btf_verifier_log_type(env, t, "Invalid func linkage");
4637 return -EINVAL;
4638 }
4639
4640 if (btf_type_kflag(t)) {
4641 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4642 return -EINVAL;
4643 }
4644
4645 btf_verifier_log_type(env, t, NULL);
4646
4647 return 0;
4648 }
4649
btf_func_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)4650 static int btf_func_resolve(struct btf_verifier_env *env,
4651 const struct resolve_vertex *v)
4652 {
4653 const struct btf_type *t = v->t;
4654 u32 next_type_id = t->type;
4655 int err;
4656
4657 err = btf_func_check(env, t);
4658 if (err)
4659 return err;
4660
4661 env_stack_pop_resolved(env, next_type_id, 0);
4662 return 0;
4663 }
4664
4665 static const struct btf_kind_operations func_ops = {
4666 .check_meta = btf_func_check_meta,
4667 .resolve = btf_func_resolve,
4668 .check_member = btf_df_check_member,
4669 .check_kflag_member = btf_df_check_kflag_member,
4670 .log_details = btf_ref_type_log,
4671 .show = btf_df_show,
4672 };
4673
btf_var_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4674 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4675 const struct btf_type *t,
4676 u32 meta_left)
4677 {
4678 const struct btf_var *var;
4679 u32 meta_needed = sizeof(*var);
4680
4681 if (meta_left < meta_needed) {
4682 btf_verifier_log_basic(env, t,
4683 "meta_left:%u meta_needed:%u",
4684 meta_left, meta_needed);
4685 return -EINVAL;
4686 }
4687
4688 if (btf_type_vlen(t)) {
4689 btf_verifier_log_type(env, t, "vlen != 0");
4690 return -EINVAL;
4691 }
4692
4693 if (btf_type_kflag(t)) {
4694 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4695 return -EINVAL;
4696 }
4697
4698 if (!t->name_off ||
4699 !btf_name_valid_identifier(env->btf, t->name_off)) {
4700 btf_verifier_log_type(env, t, "Invalid name");
4701 return -EINVAL;
4702 }
4703
4704 /* A var cannot be in type void */
4705 if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4706 btf_verifier_log_type(env, t, "Invalid type_id");
4707 return -EINVAL;
4708 }
4709
4710 var = btf_type_var(t);
4711 if (var->linkage != BTF_VAR_STATIC &&
4712 var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4713 btf_verifier_log_type(env, t, "Linkage not supported");
4714 return -EINVAL;
4715 }
4716
4717 btf_verifier_log_type(env, t, NULL);
4718
4719 return meta_needed;
4720 }
4721
btf_var_log(struct btf_verifier_env * env,const struct btf_type * t)4722 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4723 {
4724 const struct btf_var *var = btf_type_var(t);
4725
4726 btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4727 }
4728
4729 static const struct btf_kind_operations var_ops = {
4730 .check_meta = btf_var_check_meta,
4731 .resolve = btf_var_resolve,
4732 .check_member = btf_df_check_member,
4733 .check_kflag_member = btf_df_check_kflag_member,
4734 .log_details = btf_var_log,
4735 .show = btf_var_show,
4736 };
4737
btf_datasec_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4738 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4739 const struct btf_type *t,
4740 u32 meta_left)
4741 {
4742 const struct btf_var_secinfo *vsi;
4743 u64 last_vsi_end_off = 0, sum = 0;
4744 u32 i, meta_needed;
4745
4746 meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4747 if (meta_left < meta_needed) {
4748 btf_verifier_log_basic(env, t,
4749 "meta_left:%u meta_needed:%u",
4750 meta_left, meta_needed);
4751 return -EINVAL;
4752 }
4753
4754 if (!t->size) {
4755 btf_verifier_log_type(env, t, "size == 0");
4756 return -EINVAL;
4757 }
4758
4759 if (btf_type_kflag(t)) {
4760 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4761 return -EINVAL;
4762 }
4763
4764 if (!t->name_off ||
4765 !btf_name_valid_section(env->btf, t->name_off)) {
4766 btf_verifier_log_type(env, t, "Invalid name");
4767 return -EINVAL;
4768 }
4769
4770 btf_verifier_log_type(env, t, NULL);
4771
4772 for_each_vsi(i, t, vsi) {
4773 /* A var cannot be in type void */
4774 if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4775 btf_verifier_log_vsi(env, t, vsi,
4776 "Invalid type_id");
4777 return -EINVAL;
4778 }
4779
4780 if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4781 btf_verifier_log_vsi(env, t, vsi,
4782 "Invalid offset");
4783 return -EINVAL;
4784 }
4785
4786 if (!vsi->size || vsi->size > t->size) {
4787 btf_verifier_log_vsi(env, t, vsi,
4788 "Invalid size");
4789 return -EINVAL;
4790 }
4791
4792 last_vsi_end_off = vsi->offset + vsi->size;
4793 if (last_vsi_end_off > t->size) {
4794 btf_verifier_log_vsi(env, t, vsi,
4795 "Invalid offset+size");
4796 return -EINVAL;
4797 }
4798
4799 btf_verifier_log_vsi(env, t, vsi, NULL);
4800 sum += vsi->size;
4801 }
4802
4803 if (t->size < sum) {
4804 btf_verifier_log_type(env, t, "Invalid btf_info size");
4805 return -EINVAL;
4806 }
4807
4808 return meta_needed;
4809 }
4810
btf_datasec_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)4811 static int btf_datasec_resolve(struct btf_verifier_env *env,
4812 const struct resolve_vertex *v)
4813 {
4814 const struct btf_var_secinfo *vsi;
4815 struct btf *btf = env->btf;
4816 u16 i;
4817
4818 env->resolve_mode = RESOLVE_TBD;
4819 for_each_vsi_from(i, v->next_member, v->t, vsi) {
4820 u32 var_type_id = vsi->type, type_id, type_size = 0;
4821 const struct btf_type *var_type = btf_type_by_id(env->btf,
4822 var_type_id);
4823 if (!var_type || !btf_type_is_var(var_type)) {
4824 btf_verifier_log_vsi(env, v->t, vsi,
4825 "Not a VAR kind member");
4826 return -EINVAL;
4827 }
4828
4829 if (!env_type_is_resolve_sink(env, var_type) &&
4830 !env_type_is_resolved(env, var_type_id)) {
4831 env_stack_set_next_member(env, i + 1);
4832 return env_stack_push(env, var_type, var_type_id);
4833 }
4834
4835 type_id = var_type->type;
4836 if (!btf_type_id_size(btf, &type_id, &type_size)) {
4837 btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4838 return -EINVAL;
4839 }
4840
4841 if (vsi->size < type_size) {
4842 btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4843 return -EINVAL;
4844 }
4845 }
4846
4847 env_stack_pop_resolved(env, 0, 0);
4848 return 0;
4849 }
4850
btf_datasec_log(struct btf_verifier_env * env,const struct btf_type * t)4851 static void btf_datasec_log(struct btf_verifier_env *env,
4852 const struct btf_type *t)
4853 {
4854 btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4855 }
4856
btf_datasec_show(const struct btf * btf,const struct btf_type * t,u32 type_id,void * data,u8 bits_offset,struct btf_show * show)4857 static void btf_datasec_show(const struct btf *btf,
4858 const struct btf_type *t, u32 type_id,
4859 void *data, u8 bits_offset,
4860 struct btf_show *show)
4861 {
4862 const struct btf_var_secinfo *vsi;
4863 const struct btf_type *var;
4864 u32 i;
4865
4866 if (!btf_show_start_type(show, t, type_id, data))
4867 return;
4868
4869 btf_show_type_value(show, "section (\"%s\") = {",
4870 __btf_name_by_offset(btf, t->name_off));
4871 for_each_vsi(i, t, vsi) {
4872 var = btf_type_by_id(btf, vsi->type);
4873 if (i)
4874 btf_show(show, ",");
4875 btf_type_ops(var)->show(btf, var, vsi->type,
4876 data + vsi->offset, bits_offset, show);
4877 }
4878 btf_show_end_type(show);
4879 }
4880
4881 static const struct btf_kind_operations datasec_ops = {
4882 .check_meta = btf_datasec_check_meta,
4883 .resolve = btf_datasec_resolve,
4884 .check_member = btf_df_check_member,
4885 .check_kflag_member = btf_df_check_kflag_member,
4886 .log_details = btf_datasec_log,
4887 .show = btf_datasec_show,
4888 };
4889
btf_float_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4890 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4891 const struct btf_type *t,
4892 u32 meta_left)
4893 {
4894 if (btf_type_vlen(t)) {
4895 btf_verifier_log_type(env, t, "vlen != 0");
4896 return -EINVAL;
4897 }
4898
4899 if (btf_type_kflag(t)) {
4900 btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4901 return -EINVAL;
4902 }
4903
4904 if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4905 t->size != 16) {
4906 btf_verifier_log_type(env, t, "Invalid type_size");
4907 return -EINVAL;
4908 }
4909
4910 btf_verifier_log_type(env, t, NULL);
4911
4912 return 0;
4913 }
4914
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)4915 static int btf_float_check_member(struct btf_verifier_env *env,
4916 const struct btf_type *struct_type,
4917 const struct btf_member *member,
4918 const struct btf_type *member_type)
4919 {
4920 u64 start_offset_bytes;
4921 u64 end_offset_bytes;
4922 u64 misalign_bits;
4923 u64 align_bytes;
4924 u64 align_bits;
4925
4926 /* Different architectures have different alignment requirements, so
4927 * here we check only for the reasonable minimum. This way we ensure
4928 * that types after CO-RE can pass the kernel BTF verifier.
4929 */
4930 align_bytes = min_t(u64, sizeof(void *), member_type->size);
4931 align_bits = align_bytes * BITS_PER_BYTE;
4932 div64_u64_rem(member->offset, align_bits, &misalign_bits);
4933 if (misalign_bits) {
4934 btf_verifier_log_member(env, struct_type, member,
4935 "Member is not properly aligned");
4936 return -EINVAL;
4937 }
4938
4939 start_offset_bytes = member->offset / BITS_PER_BYTE;
4940 end_offset_bytes = start_offset_bytes + member_type->size;
4941 if (end_offset_bytes > struct_type->size) {
4942 btf_verifier_log_member(env, struct_type, member,
4943 "Member exceeds struct_size");
4944 return -EINVAL;
4945 }
4946
4947 return 0;
4948 }
4949
btf_float_log(struct btf_verifier_env * env,const struct btf_type * t)4950 static void btf_float_log(struct btf_verifier_env *env,
4951 const struct btf_type *t)
4952 {
4953 btf_verifier_log(env, "size=%u", t->size);
4954 }
4955
4956 static const struct btf_kind_operations float_ops = {
4957 .check_meta = btf_float_check_meta,
4958 .resolve = btf_df_resolve,
4959 .check_member = btf_float_check_member,
4960 .check_kflag_member = btf_generic_check_kflag_member,
4961 .log_details = btf_float_log,
4962 .show = btf_df_show,
4963 };
4964
btf_decl_tag_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)4965 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4966 const struct btf_type *t,
4967 u32 meta_left)
4968 {
4969 const struct btf_decl_tag *tag;
4970 u32 meta_needed = sizeof(*tag);
4971 s32 component_idx;
4972 const char *value;
4973
4974 if (meta_left < meta_needed) {
4975 btf_verifier_log_basic(env, t,
4976 "meta_left:%u meta_needed:%u",
4977 meta_left, meta_needed);
4978 return -EINVAL;
4979 }
4980
4981 value = btf_name_by_offset(env->btf, t->name_off);
4982 if (!value || !value[0]) {
4983 btf_verifier_log_type(env, t, "Invalid value");
4984 return -EINVAL;
4985 }
4986
4987 if (btf_type_vlen(t)) {
4988 btf_verifier_log_type(env, t, "vlen != 0");
4989 return -EINVAL;
4990 }
4991
4992 component_idx = btf_type_decl_tag(t)->component_idx;
4993 if (component_idx < -1) {
4994 btf_verifier_log_type(env, t, "Invalid component_idx");
4995 return -EINVAL;
4996 }
4997
4998 btf_verifier_log_type(env, t, NULL);
4999
5000 return meta_needed;
5001 }
5002
btf_decl_tag_resolve(struct btf_verifier_env * env,const struct resolve_vertex * v)5003 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
5004 const struct resolve_vertex *v)
5005 {
5006 const struct btf_type *next_type;
5007 const struct btf_type *t = v->t;
5008 u32 next_type_id = t->type;
5009 struct btf *btf = env->btf;
5010 s32 component_idx;
5011 u32 vlen;
5012
5013 next_type = btf_type_by_id(btf, next_type_id);
5014 if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
5015 btf_verifier_log_type(env, v->t, "Invalid type_id");
5016 return -EINVAL;
5017 }
5018
5019 if (!env_type_is_resolve_sink(env, next_type) &&
5020 !env_type_is_resolved(env, next_type_id))
5021 return env_stack_push(env, next_type, next_type_id);
5022
5023 component_idx = btf_type_decl_tag(t)->component_idx;
5024 if (component_idx != -1) {
5025 if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
5026 btf_verifier_log_type(env, v->t, "Invalid component_idx");
5027 return -EINVAL;
5028 }
5029
5030 if (btf_type_is_struct(next_type)) {
5031 vlen = btf_type_vlen(next_type);
5032 } else {
5033 /* next_type should be a function */
5034 next_type = btf_type_by_id(btf, next_type->type);
5035 vlen = btf_type_vlen(next_type);
5036 }
5037
5038 if ((u32)component_idx >= vlen) {
5039 btf_verifier_log_type(env, v->t, "Invalid component_idx");
5040 return -EINVAL;
5041 }
5042 }
5043
5044 env_stack_pop_resolved(env, next_type_id, 0);
5045
5046 return 0;
5047 }
5048
btf_decl_tag_log(struct btf_verifier_env * env,const struct btf_type * t)5049 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
5050 {
5051 btf_verifier_log(env, "type=%u component_idx=%d", t->type,
5052 btf_type_decl_tag(t)->component_idx);
5053 }
5054
5055 static const struct btf_kind_operations decl_tag_ops = {
5056 .check_meta = btf_decl_tag_check_meta,
5057 .resolve = btf_decl_tag_resolve,
5058 .check_member = btf_df_check_member,
5059 .check_kflag_member = btf_df_check_kflag_member,
5060 .log_details = btf_decl_tag_log,
5061 .show = btf_df_show,
5062 };
5063
btf_func_proto_check(struct btf_verifier_env * env,const struct btf_type * t)5064 static int btf_func_proto_check(struct btf_verifier_env *env,
5065 const struct btf_type *t)
5066 {
5067 const struct btf_type *ret_type;
5068 const struct btf_param *args;
5069 const struct btf *btf;
5070 u16 nr_args, i;
5071 int err;
5072
5073 btf = env->btf;
5074 args = (const struct btf_param *)(t + 1);
5075 nr_args = btf_type_vlen(t);
5076
5077 /* Check func return type which could be "void" (t->type == 0) */
5078 if (t->type) {
5079 u32 ret_type_id = t->type;
5080
5081 ret_type = btf_type_by_id(btf, ret_type_id);
5082 if (!ret_type) {
5083 btf_verifier_log_type(env, t, "Invalid return type");
5084 return -EINVAL;
5085 }
5086
5087 if (btf_type_is_resolve_source_only(ret_type)) {
5088 btf_verifier_log_type(env, t, "Invalid return type");
5089 return -EINVAL;
5090 }
5091
5092 if (btf_type_needs_resolve(ret_type) &&
5093 !env_type_is_resolved(env, ret_type_id)) {
5094 err = btf_resolve(env, ret_type, ret_type_id);
5095 if (err)
5096 return err;
5097 }
5098
5099 /* Ensure the return type is a type that has a size */
5100 if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
5101 btf_verifier_log_type(env, t, "Invalid return type");
5102 return -EINVAL;
5103 }
5104 }
5105
5106 if (!nr_args)
5107 return 0;
5108
5109 /* Last func arg type_id could be 0 if it is a vararg */
5110 if (!args[nr_args - 1].type) {
5111 if (args[nr_args - 1].name_off) {
5112 btf_verifier_log_type(env, t, "Invalid arg#%u",
5113 nr_args);
5114 return -EINVAL;
5115 }
5116 nr_args--;
5117 }
5118
5119 for (i = 0; i < nr_args; i++) {
5120 const struct btf_type *arg_type;
5121 u32 arg_type_id;
5122
5123 arg_type_id = args[i].type;
5124 arg_type = btf_type_by_id(btf, arg_type_id);
5125 if (!arg_type) {
5126 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5127 return -EINVAL;
5128 }
5129
5130 if (btf_type_is_resolve_source_only(arg_type)) {
5131 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5132 return -EINVAL;
5133 }
5134
5135 if (args[i].name_off &&
5136 (!btf_name_offset_valid(btf, args[i].name_off) ||
5137 !btf_name_valid_identifier(btf, args[i].name_off))) {
5138 btf_verifier_log_type(env, t,
5139 "Invalid arg#%u", i + 1);
5140 return -EINVAL;
5141 }
5142
5143 if (btf_type_needs_resolve(arg_type) &&
5144 !env_type_is_resolved(env, arg_type_id)) {
5145 err = btf_resolve(env, arg_type, arg_type_id);
5146 if (err)
5147 return err;
5148 }
5149
5150 if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
5151 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5152 return -EINVAL;
5153 }
5154 }
5155
5156 return 0;
5157 }
5158
btf_func_check(struct btf_verifier_env * env,const struct btf_type * t)5159 static int btf_func_check(struct btf_verifier_env *env,
5160 const struct btf_type *t)
5161 {
5162 const struct btf_type *proto_type;
5163 const struct btf_param *args;
5164 const struct btf *btf;
5165 u16 nr_args, i;
5166
5167 btf = env->btf;
5168 proto_type = btf_type_by_id(btf, t->type);
5169
5170 if (!proto_type || !btf_type_is_func_proto(proto_type)) {
5171 btf_verifier_log_type(env, t, "Invalid type_id");
5172 return -EINVAL;
5173 }
5174
5175 args = (const struct btf_param *)(proto_type + 1);
5176 nr_args = btf_type_vlen(proto_type);
5177 for (i = 0; i < nr_args; i++) {
5178 if (!args[i].name_off && args[i].type) {
5179 btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5180 return -EINVAL;
5181 }
5182 }
5183
5184 return 0;
5185 }
5186
5187 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5188 [BTF_KIND_INT] = &int_ops,
5189 [BTF_KIND_PTR] = &ptr_ops,
5190 [BTF_KIND_ARRAY] = &array_ops,
5191 [BTF_KIND_STRUCT] = &struct_ops,
5192 [BTF_KIND_UNION] = &struct_ops,
5193 [BTF_KIND_ENUM] = &enum_ops,
5194 [BTF_KIND_FWD] = &fwd_ops,
5195 [BTF_KIND_TYPEDEF] = &modifier_ops,
5196 [BTF_KIND_VOLATILE] = &modifier_ops,
5197 [BTF_KIND_CONST] = &modifier_ops,
5198 [BTF_KIND_RESTRICT] = &modifier_ops,
5199 [BTF_KIND_FUNC] = &func_ops,
5200 [BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5201 [BTF_KIND_VAR] = &var_ops,
5202 [BTF_KIND_DATASEC] = &datasec_ops,
5203 [BTF_KIND_FLOAT] = &float_ops,
5204 [BTF_KIND_DECL_TAG] = &decl_tag_ops,
5205 [BTF_KIND_TYPE_TAG] = &modifier_ops,
5206 [BTF_KIND_ENUM64] = &enum64_ops,
5207 };
5208
btf_check_meta(struct btf_verifier_env * env,const struct btf_type * t,u32 meta_left)5209 static s32 btf_check_meta(struct btf_verifier_env *env,
5210 const struct btf_type *t,
5211 u32 meta_left)
5212 {
5213 u32 saved_meta_left = meta_left;
5214 s32 var_meta_size;
5215
5216 if (meta_left < sizeof(*t)) {
5217 btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5218 env->log_type_id, meta_left, sizeof(*t));
5219 return -EINVAL;
5220 }
5221 meta_left -= sizeof(*t);
5222
5223 if (t->info & ~BTF_INFO_MASK) {
5224 btf_verifier_log(env, "[%u] Invalid btf_info:%x",
5225 env->log_type_id, t->info);
5226 return -EINVAL;
5227 }
5228
5229 if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5230 BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5231 btf_verifier_log(env, "[%u] Invalid kind:%u",
5232 env->log_type_id, BTF_INFO_KIND(t->info));
5233 return -EINVAL;
5234 }
5235
5236 if (!btf_name_offset_valid(env->btf, t->name_off)) {
5237 btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5238 env->log_type_id, t->name_off);
5239 return -EINVAL;
5240 }
5241
5242 var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5243 if (var_meta_size < 0)
5244 return var_meta_size;
5245
5246 meta_left -= var_meta_size;
5247
5248 return saved_meta_left - meta_left;
5249 }
5250
btf_check_all_metas(struct btf_verifier_env * env)5251 static int btf_check_all_metas(struct btf_verifier_env *env)
5252 {
5253 struct btf *btf = env->btf;
5254 struct btf_header *hdr;
5255 void *cur, *end;
5256
5257 hdr = &btf->hdr;
5258 cur = btf->nohdr_data + hdr->type_off;
5259 end = cur + hdr->type_len;
5260
5261 env->log_type_id = btf->base_btf ? btf->start_id : 1;
5262 while (cur < end) {
5263 struct btf_type *t = cur;
5264 s32 meta_size;
5265
5266 meta_size = btf_check_meta(env, t, end - cur);
5267 if (meta_size < 0)
5268 return meta_size;
5269
5270 btf_add_type(env, t);
5271 cur += meta_size;
5272 env->log_type_id++;
5273 }
5274
5275 return 0;
5276 }
5277
btf_resolve_valid(struct btf_verifier_env * env,const struct btf_type * t,u32 type_id)5278 static bool btf_resolve_valid(struct btf_verifier_env *env,
5279 const struct btf_type *t,
5280 u32 type_id)
5281 {
5282 struct btf *btf = env->btf;
5283
5284 if (!env_type_is_resolved(env, type_id))
5285 return false;
5286
5287 if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5288 return !btf_resolved_type_id(btf, type_id) &&
5289 !btf_resolved_type_size(btf, type_id);
5290
5291 if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5292 return btf_resolved_type_id(btf, type_id) &&
5293 !btf_resolved_type_size(btf, type_id);
5294
5295 if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5296 btf_type_is_var(t)) {
5297 t = btf_type_id_resolve(btf, &type_id);
5298 return t &&
5299 !btf_type_is_modifier(t) &&
5300 !btf_type_is_var(t) &&
5301 !btf_type_is_datasec(t);
5302 }
5303
5304 if (btf_type_is_array(t)) {
5305 const struct btf_array *array = btf_type_array(t);
5306 const struct btf_type *elem_type;
5307 u32 elem_type_id = array->type;
5308 u32 elem_size;
5309
5310 elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5311 return elem_type && !btf_type_is_modifier(elem_type) &&
5312 (array->nelems * elem_size ==
5313 btf_resolved_type_size(btf, type_id));
5314 }
5315
5316 return false;
5317 }
5318
btf_resolve(struct btf_verifier_env * env,const struct btf_type * t,u32 type_id)5319 static int btf_resolve(struct btf_verifier_env *env,
5320 const struct btf_type *t, u32 type_id)
5321 {
5322 u32 save_log_type_id = env->log_type_id;
5323 const struct resolve_vertex *v;
5324 int err = 0;
5325
5326 env->resolve_mode = RESOLVE_TBD;
5327 env_stack_push(env, t, type_id);
5328 while (!err && (v = env_stack_peak(env))) {
5329 env->log_type_id = v->type_id;
5330 err = btf_type_ops(v->t)->resolve(env, v);
5331 }
5332
5333 env->log_type_id = type_id;
5334 if (err == -E2BIG) {
5335 btf_verifier_log_type(env, t,
5336 "Exceeded max resolving depth:%u",
5337 MAX_RESOLVE_DEPTH);
5338 } else if (err == -EEXIST) {
5339 btf_verifier_log_type(env, t, "Loop detected");
5340 }
5341
5342 /* Final sanity check */
5343 if (!err && !btf_resolve_valid(env, t, type_id)) {
5344 btf_verifier_log_type(env, t, "Invalid resolve state");
5345 err = -EINVAL;
5346 }
5347
5348 env->log_type_id = save_log_type_id;
5349 return err;
5350 }
5351
btf_check_all_types(struct btf_verifier_env * env)5352 static int btf_check_all_types(struct btf_verifier_env *env)
5353 {
5354 struct btf *btf = env->btf;
5355 const struct btf_type *t;
5356 u32 type_id, i;
5357 int err;
5358
5359 err = env_resolve_init(env);
5360 if (err)
5361 return err;
5362
5363 env->phase++;
5364 for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5365 type_id = btf->start_id + i;
5366 t = btf_type_by_id(btf, type_id);
5367
5368 env->log_type_id = type_id;
5369 if (btf_type_needs_resolve(t) &&
5370 !env_type_is_resolved(env, type_id)) {
5371 err = btf_resolve(env, t, type_id);
5372 if (err)
5373 return err;
5374 }
5375
5376 if (btf_type_is_func_proto(t)) {
5377 err = btf_func_proto_check(env, t);
5378 if (err)
5379 return err;
5380 }
5381 }
5382
5383 return 0;
5384 }
5385
btf_parse_type_sec(struct btf_verifier_env * env)5386 static int btf_parse_type_sec(struct btf_verifier_env *env)
5387 {
5388 const struct btf_header *hdr = &env->btf->hdr;
5389 int err;
5390
5391 /* Type section must align to 4 bytes */
5392 if (hdr->type_off & (sizeof(u32) - 1)) {
5393 btf_verifier_log(env, "Unaligned type_off");
5394 return -EINVAL;
5395 }
5396
5397 if (!env->btf->base_btf && !hdr->type_len) {
5398 btf_verifier_log(env, "No type found");
5399 return -EINVAL;
5400 }
5401
5402 err = btf_check_all_metas(env);
5403 if (err)
5404 return err;
5405
5406 return btf_check_all_types(env);
5407 }
5408
btf_parse_str_sec(struct btf_verifier_env * env)5409 static int btf_parse_str_sec(struct btf_verifier_env *env)
5410 {
5411 const struct btf_header *hdr;
5412 struct btf *btf = env->btf;
5413 const char *start, *end;
5414
5415 hdr = &btf->hdr;
5416 start = btf->nohdr_data + hdr->str_off;
5417 end = start + hdr->str_len;
5418
5419 if (end != btf->data + btf->data_size) {
5420 btf_verifier_log(env, "String section is not at the end");
5421 return -EINVAL;
5422 }
5423
5424 btf->strings = start;
5425
5426 if (btf->base_btf && !hdr->str_len)
5427 return 0;
5428 if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5429 btf_verifier_log(env, "Invalid string section");
5430 return -EINVAL;
5431 }
5432 if (!btf->base_btf && start[0]) {
5433 btf_verifier_log(env, "Invalid string section");
5434 return -EINVAL;
5435 }
5436
5437 return 0;
5438 }
5439
5440 static const size_t btf_sec_info_offset[] = {
5441 offsetof(struct btf_header, type_off),
5442 offsetof(struct btf_header, str_off),
5443 };
5444
btf_sec_info_cmp(const void * a,const void * b)5445 static int btf_sec_info_cmp(const void *a, const void *b)
5446 {
5447 const struct btf_sec_info *x = a;
5448 const struct btf_sec_info *y = b;
5449
5450 return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5451 }
5452
btf_check_sec_info(struct btf_verifier_env * env,u32 btf_data_size)5453 static int btf_check_sec_info(struct btf_verifier_env *env,
5454 u32 btf_data_size)
5455 {
5456 struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5457 u32 total, expected_total, i;
5458 const struct btf_header *hdr;
5459 const struct btf *btf;
5460
5461 btf = env->btf;
5462 hdr = &btf->hdr;
5463
5464 /* Populate the secs from hdr */
5465 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5466 secs[i] = *(struct btf_sec_info *)((void *)hdr +
5467 btf_sec_info_offset[i]);
5468
5469 sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5470 sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5471
5472 /* Check for gaps and overlap among sections */
5473 total = 0;
5474 expected_total = btf_data_size - hdr->hdr_len;
5475 for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5476 if (expected_total < secs[i].off) {
5477 btf_verifier_log(env, "Invalid section offset");
5478 return -EINVAL;
5479 }
5480 if (total < secs[i].off) {
5481 /* gap */
5482 btf_verifier_log(env, "Unsupported section found");
5483 return -EINVAL;
5484 }
5485 if (total > secs[i].off) {
5486 btf_verifier_log(env, "Section overlap found");
5487 return -EINVAL;
5488 }
5489 if (expected_total - total < secs[i].len) {
5490 btf_verifier_log(env,
5491 "Total section length too long");
5492 return -EINVAL;
5493 }
5494 total += secs[i].len;
5495 }
5496
5497 /* There is data other than hdr and known sections */
5498 if (expected_total != total) {
5499 btf_verifier_log(env, "Unsupported section found");
5500 return -EINVAL;
5501 }
5502
5503 return 0;
5504 }
5505
btf_parse_hdr(struct btf_verifier_env * env)5506 static int btf_parse_hdr(struct btf_verifier_env *env)
5507 {
5508 u32 hdr_len, hdr_copy, btf_data_size;
5509 const struct btf_header *hdr;
5510 struct btf *btf;
5511
5512 btf = env->btf;
5513 btf_data_size = btf->data_size;
5514
5515 if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5516 btf_verifier_log(env, "hdr_len not found");
5517 return -EINVAL;
5518 }
5519
5520 hdr = btf->data;
5521 hdr_len = hdr->hdr_len;
5522 if (btf_data_size < hdr_len) {
5523 btf_verifier_log(env, "btf_header not found");
5524 return -EINVAL;
5525 }
5526
5527 /* Ensure the unsupported header fields are zero */
5528 if (hdr_len > sizeof(btf->hdr)) {
5529 u8 *expected_zero = btf->data + sizeof(btf->hdr);
5530 u8 *end = btf->data + hdr_len;
5531
5532 for (; expected_zero < end; expected_zero++) {
5533 if (*expected_zero) {
5534 btf_verifier_log(env, "Unsupported btf_header");
5535 return -E2BIG;
5536 }
5537 }
5538 }
5539
5540 hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5541 memcpy(&btf->hdr, btf->data, hdr_copy);
5542
5543 hdr = &btf->hdr;
5544
5545 btf_verifier_log_hdr(env, btf_data_size);
5546
5547 if (hdr->magic != BTF_MAGIC) {
5548 btf_verifier_log(env, "Invalid magic");
5549 return -EINVAL;
5550 }
5551
5552 if (hdr->version != BTF_VERSION) {
5553 btf_verifier_log(env, "Unsupported version");
5554 return -ENOTSUPP;
5555 }
5556
5557 if (hdr->flags) {
5558 btf_verifier_log(env, "Unsupported flags");
5559 return -ENOTSUPP;
5560 }
5561
5562 if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5563 btf_verifier_log(env, "No data");
5564 return -EINVAL;
5565 }
5566
5567 return btf_check_sec_info(env, btf_data_size);
5568 }
5569
5570 static const char *alloc_obj_fields[] = {
5571 "bpf_spin_lock",
5572 "bpf_list_head",
5573 "bpf_list_node",
5574 "bpf_rb_root",
5575 "bpf_rb_node",
5576 "bpf_refcount",
5577 };
5578
5579 static struct btf_struct_metas *
btf_parse_struct_metas(struct bpf_verifier_log * log,struct btf * btf)5580 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5581 {
5582 struct btf_struct_metas *tab = NULL;
5583 struct btf_id_set *aof;
5584 int i, n, id, ret;
5585
5586 BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5587 BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5588
5589 aof = kmalloc(sizeof(*aof), GFP_KERNEL | __GFP_NOWARN);
5590 if (!aof)
5591 return ERR_PTR(-ENOMEM);
5592 aof->cnt = 0;
5593
5594 for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5595 /* Try to find whether this special type exists in user BTF, and
5596 * if so remember its ID so we can easily find it among members
5597 * of structs that we iterate in the next loop.
5598 */
5599 struct btf_id_set *new_aof;
5600
5601 id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5602 if (id < 0)
5603 continue;
5604
5605 new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
5606 GFP_KERNEL | __GFP_NOWARN);
5607 if (!new_aof) {
5608 ret = -ENOMEM;
5609 goto free_aof;
5610 }
5611 aof = new_aof;
5612 aof->ids[aof->cnt++] = id;
5613 }
5614
5615 n = btf_nr_types(btf);
5616 for (i = 1; i < n; i++) {
5617 /* Try to find if there are kptrs in user BTF and remember their ID */
5618 struct btf_id_set *new_aof;
5619 struct btf_field_info tmp;
5620 const struct btf_type *t;
5621
5622 t = btf_type_by_id(btf, i);
5623 if (!t) {
5624 ret = -EINVAL;
5625 goto free_aof;
5626 }
5627
5628 ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
5629 if (ret != BTF_FIELD_FOUND)
5630 continue;
5631
5632 new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
5633 GFP_KERNEL | __GFP_NOWARN);
5634 if (!new_aof) {
5635 ret = -ENOMEM;
5636 goto free_aof;
5637 }
5638 aof = new_aof;
5639 aof->ids[aof->cnt++] = i;
5640 }
5641
5642 if (!aof->cnt) {
5643 kfree(aof);
5644 return NULL;
5645 }
5646 sort(&aof->ids, aof->cnt, sizeof(aof->ids[0]), btf_id_cmp_func, NULL);
5647
5648 for (i = 1; i < n; i++) {
5649 struct btf_struct_metas *new_tab;
5650 const struct btf_member *member;
5651 struct btf_struct_meta *type;
5652 struct btf_record *record;
5653 const struct btf_type *t;
5654 int j, tab_cnt;
5655
5656 t = btf_type_by_id(btf, i);
5657 if (!__btf_type_is_struct(t))
5658 continue;
5659
5660 cond_resched();
5661
5662 for_each_member(j, t, member) {
5663 if (btf_id_set_contains(aof, member->type))
5664 goto parse;
5665 }
5666 continue;
5667 parse:
5668 tab_cnt = tab ? tab->cnt : 0;
5669 new_tab = krealloc(tab, struct_size(new_tab, types, tab_cnt + 1),
5670 GFP_KERNEL | __GFP_NOWARN);
5671 if (!new_tab) {
5672 ret = -ENOMEM;
5673 goto free;
5674 }
5675 if (!tab)
5676 new_tab->cnt = 0;
5677 tab = new_tab;
5678
5679 type = &tab->types[tab->cnt];
5680 type->btf_id = i;
5681 record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5682 BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
5683 BPF_KPTR, t->size);
5684 /* The record cannot be unset, treat it as an error if so */
5685 if (IS_ERR_OR_NULL(record)) {
5686 ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5687 goto free;
5688 }
5689 type->record = record;
5690 tab->cnt++;
5691 }
5692 kfree(aof);
5693 return tab;
5694 free:
5695 btf_struct_metas_free(tab);
5696 free_aof:
5697 kfree(aof);
5698 return ERR_PTR(ret);
5699 }
5700
btf_find_struct_meta(const struct btf * btf,u32 btf_id)5701 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5702 {
5703 struct btf_struct_metas *tab;
5704
5705 BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5706 tab = btf->struct_meta_tab;
5707 if (!tab)
5708 return NULL;
5709 return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5710 }
5711
btf_check_type_tags(struct btf_verifier_env * env,struct btf * btf,int start_id)5712 static int btf_check_type_tags(struct btf_verifier_env *env,
5713 struct btf *btf, int start_id)
5714 {
5715 int i, n, good_id = start_id - 1;
5716 bool in_tags;
5717
5718 n = btf_nr_types(btf);
5719 for (i = start_id; i < n; i++) {
5720 const struct btf_type *t;
5721 int chain_limit = 32;
5722 u32 cur_id = i;
5723
5724 t = btf_type_by_id(btf, i);
5725 if (!t)
5726 return -EINVAL;
5727 if (!btf_type_is_modifier(t))
5728 continue;
5729
5730 cond_resched();
5731
5732 in_tags = btf_type_is_type_tag(t);
5733 while (btf_type_is_modifier(t)) {
5734 if (!chain_limit--) {
5735 btf_verifier_log(env, "Max chain length or cycle detected");
5736 return -ELOOP;
5737 }
5738 if (btf_type_is_type_tag(t)) {
5739 if (!in_tags) {
5740 btf_verifier_log(env, "Type tags don't precede modifiers");
5741 return -EINVAL;
5742 }
5743 } else if (in_tags) {
5744 in_tags = false;
5745 }
5746 if (cur_id <= good_id)
5747 break;
5748 /* Move to next type */
5749 cur_id = t->type;
5750 t = btf_type_by_id(btf, cur_id);
5751 if (!t)
5752 return -EINVAL;
5753 }
5754 good_id = i;
5755 }
5756 return 0;
5757 }
5758
finalize_log(struct bpf_verifier_log * log,bpfptr_t uattr,u32 uattr_size)5759 static int finalize_log(struct bpf_verifier_log *log, bpfptr_t uattr, u32 uattr_size)
5760 {
5761 u32 log_true_size;
5762 int err;
5763
5764 err = bpf_vlog_finalize(log, &log_true_size);
5765
5766 if (uattr_size >= offsetofend(union bpf_attr, btf_log_true_size) &&
5767 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, btf_log_true_size),
5768 &log_true_size, sizeof(log_true_size)))
5769 err = -EFAULT;
5770
5771 return err;
5772 }
5773
btf_parse(const union bpf_attr * attr,bpfptr_t uattr,u32 uattr_size)5774 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
5775 {
5776 bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
5777 char __user *log_ubuf = u64_to_user_ptr(attr->btf_log_buf);
5778 struct btf_struct_metas *struct_meta_tab;
5779 struct btf_verifier_env *env = NULL;
5780 struct btf *btf = NULL;
5781 u8 *data;
5782 int err, ret;
5783
5784 if (attr->btf_size > BTF_MAX_SIZE)
5785 return ERR_PTR(-E2BIG);
5786
5787 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5788 if (!env)
5789 return ERR_PTR(-ENOMEM);
5790
5791 /* user could have requested verbose verifier output
5792 * and supplied buffer to store the verification trace
5793 */
5794 err = bpf_vlog_init(&env->log, attr->btf_log_level,
5795 log_ubuf, attr->btf_log_size);
5796 if (err)
5797 goto errout_free;
5798
5799 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5800 if (!btf) {
5801 err = -ENOMEM;
5802 goto errout;
5803 }
5804 env->btf = btf;
5805
5806 data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
5807 if (!data) {
5808 err = -ENOMEM;
5809 goto errout;
5810 }
5811
5812 btf->data = data;
5813 btf->data_size = attr->btf_size;
5814
5815 if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
5816 err = -EFAULT;
5817 goto errout;
5818 }
5819
5820 err = btf_parse_hdr(env);
5821 if (err)
5822 goto errout;
5823
5824 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5825
5826 err = btf_parse_str_sec(env);
5827 if (err)
5828 goto errout;
5829
5830 err = btf_parse_type_sec(env);
5831 if (err)
5832 goto errout;
5833
5834 err = btf_check_type_tags(env, btf, 1);
5835 if (err)
5836 goto errout;
5837
5838 struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
5839 if (IS_ERR(struct_meta_tab)) {
5840 err = PTR_ERR(struct_meta_tab);
5841 goto errout;
5842 }
5843 btf->struct_meta_tab = struct_meta_tab;
5844
5845 if (struct_meta_tab) {
5846 int i;
5847
5848 for (i = 0; i < struct_meta_tab->cnt; i++) {
5849 err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5850 if (err < 0)
5851 goto errout_meta;
5852 }
5853 }
5854
5855 err = finalize_log(&env->log, uattr, uattr_size);
5856 if (err)
5857 goto errout_free;
5858
5859 btf_verifier_env_free(env);
5860 refcount_set(&btf->refcnt, 1);
5861 return btf;
5862
5863 errout_meta:
5864 btf_free_struct_meta_tab(btf);
5865 errout:
5866 /* overwrite err with -ENOSPC or -EFAULT */
5867 ret = finalize_log(&env->log, uattr, uattr_size);
5868 if (ret)
5869 err = ret;
5870 errout_free:
5871 btf_verifier_env_free(env);
5872 if (btf)
5873 btf_free(btf);
5874 return ERR_PTR(err);
5875 }
5876
5877 extern char __start_BTF[];
5878 extern char __stop_BTF[];
5879 extern struct btf *btf_vmlinux;
5880
5881 #define BPF_MAP_TYPE(_id, _ops)
5882 #define BPF_LINK_TYPE(_id, _name)
5883 static union {
5884 struct bpf_ctx_convert {
5885 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5886 prog_ctx_type _id##_prog; \
5887 kern_ctx_type _id##_kern;
5888 #include <linux/bpf_types.h>
5889 #undef BPF_PROG_TYPE
5890 } *__t;
5891 /* 't' is written once under lock. Read many times. */
5892 const struct btf_type *t;
5893 } bpf_ctx_convert;
5894 enum {
5895 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5896 __ctx_convert##_id,
5897 #include <linux/bpf_types.h>
5898 #undef BPF_PROG_TYPE
5899 __ctx_convert_unused, /* to avoid empty enum in extreme .config */
5900 };
5901 static u8 bpf_ctx_convert_map[] = {
5902 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5903 [_id] = __ctx_convert##_id,
5904 #include <linux/bpf_types.h>
5905 #undef BPF_PROG_TYPE
5906 0, /* avoid empty array */
5907 };
5908 #undef BPF_MAP_TYPE
5909 #undef BPF_LINK_TYPE
5910
find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)5911 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
5912 {
5913 const struct btf_type *conv_struct;
5914 const struct btf_member *ctx_type;
5915
5916 conv_struct = bpf_ctx_convert.t;
5917 if (!conv_struct)
5918 return NULL;
5919 /* prog_type is valid bpf program type. No need for bounds check. */
5920 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5921 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5922 * Like 'struct __sk_buff'
5923 */
5924 return btf_type_by_id(btf_vmlinux, ctx_type->type);
5925 }
5926
find_kern_ctx_type_id(enum bpf_prog_type prog_type)5927 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
5928 {
5929 const struct btf_type *conv_struct;
5930 const struct btf_member *ctx_type;
5931
5932 conv_struct = bpf_ctx_convert.t;
5933 if (!conv_struct)
5934 return -EFAULT;
5935 /* prog_type is valid bpf program type. No need for bounds check. */
5936 ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5937 /* ctx_type is a pointer to prog_ctx_type in vmlinux.
5938 * Like 'struct sk_buff'
5939 */
5940 return ctx_type->type;
5941 }
5942
btf_is_projection_of(const char * pname,const char * tname)5943 bool btf_is_projection_of(const char *pname, const char *tname)
5944 {
5945 if (strcmp(pname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5946 return true;
5947 if (strcmp(pname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5948 return true;
5949 return false;
5950 }
5951
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)5952 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5953 const struct btf_type *t, enum bpf_prog_type prog_type,
5954 int arg)
5955 {
5956 const struct btf_type *ctx_type;
5957 const char *tname, *ctx_tname;
5958
5959 t = btf_type_by_id(btf, t->type);
5960
5961 /* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
5962 * check before we skip all the typedef below.
5963 */
5964 if (prog_type == BPF_PROG_TYPE_KPROBE) {
5965 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5966 t = btf_type_by_id(btf, t->type);
5967
5968 if (btf_type_is_typedef(t)) {
5969 tname = btf_name_by_offset(btf, t->name_off);
5970 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5971 return true;
5972 }
5973 }
5974
5975 while (btf_type_is_modifier(t))
5976 t = btf_type_by_id(btf, t->type);
5977 if (!btf_type_is_struct(t)) {
5978 /* Only pointer to struct is supported for now.
5979 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5980 * is not supported yet.
5981 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5982 */
5983 return false;
5984 }
5985 tname = btf_name_by_offset(btf, t->name_off);
5986 if (!tname) {
5987 bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5988 return false;
5989 }
5990
5991 ctx_type = find_canonical_prog_ctx_type(prog_type);
5992 if (!ctx_type) {
5993 bpf_log(log, "btf_vmlinux is malformed\n");
5994 /* should not happen */
5995 return false;
5996 }
5997 again:
5998 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5999 if (!ctx_tname) {
6000 /* should not happen */
6001 bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
6002 return false;
6003 }
6004 /* program types without named context types work only with arg:ctx tag */
6005 if (ctx_tname[0] == '\0')
6006 return false;
6007 /* only compare that prog's ctx type name is the same as
6008 * kernel expects. No need to compare field by field.
6009 * It's ok for bpf prog to do:
6010 * struct __sk_buff {};
6011 * int socket_filter_bpf_prog(struct __sk_buff *skb)
6012 * { // no fields of skb are ever used }
6013 */
6014 if (btf_is_projection_of(ctx_tname, tname))
6015 return true;
6016 if (strcmp(ctx_tname, tname)) {
6017 /* bpf_user_pt_regs_t is a typedef, so resolve it to
6018 * underlying struct and check name again
6019 */
6020 if (!btf_type_is_modifier(ctx_type))
6021 return false;
6022 while (btf_type_is_modifier(ctx_type))
6023 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6024 goto again;
6025 }
6026 return true;
6027 }
6028
6029 /* forward declarations for arch-specific underlying types of
6030 * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
6031 * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
6032 * works correctly with __builtin_types_compatible_p() on respective
6033 * architectures
6034 */
6035 struct user_regs_struct;
6036 struct user_pt_regs;
6037
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)6038 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6039 const struct btf_type *t, int arg,
6040 enum bpf_prog_type prog_type,
6041 enum bpf_attach_type attach_type)
6042 {
6043 const struct btf_type *ctx_type;
6044 const char *tname, *ctx_tname;
6045
6046 if (!btf_is_ptr(t)) {
6047 bpf_log(log, "arg#%d type isn't a pointer\n", arg);
6048 return -EINVAL;
6049 }
6050 t = btf_type_by_id(btf, t->type);
6051
6052 /* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
6053 if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
6054 while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6055 t = btf_type_by_id(btf, t->type);
6056
6057 if (btf_type_is_typedef(t)) {
6058 tname = btf_name_by_offset(btf, t->name_off);
6059 if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6060 return 0;
6061 }
6062 }
6063
6064 /* all other program types don't use typedefs for context type */
6065 while (btf_type_is_modifier(t))
6066 t = btf_type_by_id(btf, t->type);
6067
6068 /* `void *ctx __arg_ctx` is always valid */
6069 if (btf_type_is_void(t))
6070 return 0;
6071
6072 tname = btf_name_by_offset(btf, t->name_off);
6073 if (str_is_empty(tname)) {
6074 bpf_log(log, "arg#%d type doesn't have a name\n", arg);
6075 return -EINVAL;
6076 }
6077
6078 /* special cases */
6079 switch (prog_type) {
6080 case BPF_PROG_TYPE_KPROBE:
6081 if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6082 return 0;
6083 break;
6084 case BPF_PROG_TYPE_PERF_EVENT:
6085 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6086 __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6087 return 0;
6088 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6089 __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6090 return 0;
6091 if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6092 __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6093 return 0;
6094 break;
6095 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6096 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6097 /* allow u64* as ctx */
6098 if (btf_is_int(t) && t->size == 8)
6099 return 0;
6100 break;
6101 case BPF_PROG_TYPE_TRACING:
6102 switch (attach_type) {
6103 case BPF_TRACE_RAW_TP:
6104 /* tp_btf program is TRACING, so need special case here */
6105 if (__btf_type_is_struct(t) &&
6106 strcmp(tname, "bpf_raw_tracepoint_args") == 0)
6107 return 0;
6108 /* allow u64* as ctx */
6109 if (btf_is_int(t) && t->size == 8)
6110 return 0;
6111 break;
6112 case BPF_TRACE_ITER:
6113 /* allow struct bpf_iter__xxx types only */
6114 if (__btf_type_is_struct(t) &&
6115 strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
6116 return 0;
6117 break;
6118 case BPF_TRACE_FENTRY:
6119 case BPF_TRACE_FEXIT:
6120 case BPF_MODIFY_RETURN:
6121 /* allow u64* as ctx */
6122 if (btf_is_int(t) && t->size == 8)
6123 return 0;
6124 break;
6125 default:
6126 break;
6127 }
6128 break;
6129 case BPF_PROG_TYPE_LSM:
6130 case BPF_PROG_TYPE_STRUCT_OPS:
6131 /* allow u64* as ctx */
6132 if (btf_is_int(t) && t->size == 8)
6133 return 0;
6134 break;
6135 case BPF_PROG_TYPE_TRACEPOINT:
6136 case BPF_PROG_TYPE_SYSCALL:
6137 case BPF_PROG_TYPE_EXT:
6138 return 0; /* anything goes */
6139 default:
6140 break;
6141 }
6142
6143 ctx_type = find_canonical_prog_ctx_type(prog_type);
6144 if (!ctx_type) {
6145 /* should not happen */
6146 bpf_log(log, "btf_vmlinux is malformed\n");
6147 return -EINVAL;
6148 }
6149
6150 /* resolve typedefs and check that underlying structs are matching as well */
6151 while (btf_type_is_modifier(ctx_type))
6152 ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6153
6154 /* if program type doesn't have distinctly named struct type for
6155 * context, then __arg_ctx argument can only be `void *`, which we
6156 * already checked above
6157 */
6158 if (!__btf_type_is_struct(ctx_type)) {
6159 bpf_log(log, "arg#%d should be void pointer\n", arg);
6160 return -EINVAL;
6161 }
6162
6163 ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6164 if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6165 bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6166 return -EINVAL;
6167 }
6168
6169 return 0;
6170 }
6171
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)6172 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6173 struct btf *btf,
6174 const struct btf_type *t,
6175 enum bpf_prog_type prog_type,
6176 int arg)
6177 {
6178 if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6179 return -ENOENT;
6180 return find_kern_ctx_type_id(prog_type);
6181 }
6182
get_kern_ctx_btf_id(struct bpf_verifier_log * log,enum bpf_prog_type prog_type)6183 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6184 {
6185 const struct btf_member *kctx_member;
6186 const struct btf_type *conv_struct;
6187 const struct btf_type *kctx_type;
6188 u32 kctx_type_id;
6189
6190 conv_struct = bpf_ctx_convert.t;
6191 /* get member for kernel ctx type */
6192 kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6193 kctx_type_id = kctx_member->type;
6194 kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6195 if (!btf_type_is_struct(kctx_type)) {
6196 bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6197 return -EINVAL;
6198 }
6199
6200 return kctx_type_id;
6201 }
6202
BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id,struct,bpf_ctx_convert)6203 BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id, struct, bpf_ctx_convert)
6204
6205 static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,
6206 void *data, unsigned int data_size)
6207 {
6208 struct btf *btf = NULL;
6209 int err;
6210
6211 if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6212 return ERR_PTR(-ENOENT);
6213
6214 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6215 if (!btf) {
6216 err = -ENOMEM;
6217 goto errout;
6218 }
6219 env->btf = btf;
6220
6221 btf->data = data;
6222 btf->data_size = data_size;
6223 btf->kernel_btf = true;
6224 snprintf(btf->name, sizeof(btf->name), "%s", name);
6225
6226 err = btf_parse_hdr(env);
6227 if (err)
6228 goto errout;
6229
6230 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6231
6232 err = btf_parse_str_sec(env);
6233 if (err)
6234 goto errout;
6235
6236 err = btf_check_all_metas(env);
6237 if (err)
6238 goto errout;
6239
6240 err = btf_check_type_tags(env, btf, 1);
6241 if (err)
6242 goto errout;
6243
6244 refcount_set(&btf->refcnt, 1);
6245
6246 return btf;
6247
6248 errout:
6249 if (btf) {
6250 kvfree(btf->types);
6251 kfree(btf);
6252 }
6253 return ERR_PTR(err);
6254 }
6255
btf_parse_vmlinux(void)6256 struct btf *btf_parse_vmlinux(void)
6257 {
6258 struct btf_verifier_env *env = NULL;
6259 struct bpf_verifier_log *log;
6260 struct btf *btf;
6261 int err;
6262
6263 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6264 if (!env)
6265 return ERR_PTR(-ENOMEM);
6266
6267 log = &env->log;
6268 log->level = BPF_LOG_KERNEL;
6269 btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
6270 if (IS_ERR(btf))
6271 goto err_out;
6272
6273 /* btf_parse_vmlinux() runs under bpf_verifier_lock */
6274 bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6275 err = btf_alloc_id(btf);
6276 if (err) {
6277 btf_free(btf);
6278 btf = ERR_PTR(err);
6279 }
6280 err_out:
6281 btf_verifier_env_free(env);
6282 return btf;
6283 }
6284
6285 /* If .BTF_ids section was created with distilled base BTF, both base and
6286 * split BTF ids will need to be mapped to actual base/split ids for
6287 * BTF now that it has been relocated.
6288 */
btf_relocate_id(const struct btf * btf,__u32 id)6289 static __u32 btf_relocate_id(const struct btf *btf, __u32 id)
6290 {
6291 if (!btf->base_btf || !btf->base_id_map)
6292 return id;
6293 return btf->base_id_map[id];
6294 }
6295
6296 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6297
btf_parse_module(const char * module_name,const void * data,unsigned int data_size,void * base_data,unsigned int base_data_size)6298 static struct btf *btf_parse_module(const char *module_name, const void *data,
6299 unsigned int data_size, void *base_data,
6300 unsigned int base_data_size)
6301 {
6302 struct btf *btf = NULL, *vmlinux_btf, *base_btf = NULL;
6303 struct btf_verifier_env *env = NULL;
6304 struct bpf_verifier_log *log;
6305 int err = 0;
6306
6307 vmlinux_btf = bpf_get_btf_vmlinux();
6308 if (IS_ERR(vmlinux_btf))
6309 return vmlinux_btf;
6310 if (!vmlinux_btf)
6311 return ERR_PTR(-EINVAL);
6312
6313 env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6314 if (!env)
6315 return ERR_PTR(-ENOMEM);
6316
6317 log = &env->log;
6318 log->level = BPF_LOG_KERNEL;
6319
6320 if (base_data) {
6321 base_btf = btf_parse_base(env, ".BTF.base", base_data, base_data_size);
6322 if (IS_ERR(base_btf)) {
6323 err = PTR_ERR(base_btf);
6324 goto errout;
6325 }
6326 } else {
6327 base_btf = vmlinux_btf;
6328 }
6329
6330 btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6331 if (!btf) {
6332 err = -ENOMEM;
6333 goto errout;
6334 }
6335 env->btf = btf;
6336
6337 btf->base_btf = base_btf;
6338 btf->start_id = base_btf->nr_types;
6339 btf->start_str_off = base_btf->hdr.str_len;
6340 btf->kernel_btf = true;
6341 snprintf(btf->name, sizeof(btf->name), "%s", module_name);
6342
6343 btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
6344 if (!btf->data) {
6345 err = -ENOMEM;
6346 goto errout;
6347 }
6348 btf->data_size = data_size;
6349
6350 err = btf_parse_hdr(env);
6351 if (err)
6352 goto errout;
6353
6354 btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6355
6356 err = btf_parse_str_sec(env);
6357 if (err)
6358 goto errout;
6359
6360 err = btf_check_all_metas(env);
6361 if (err)
6362 goto errout;
6363
6364 err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6365 if (err)
6366 goto errout;
6367
6368 if (base_btf != vmlinux_btf) {
6369 err = btf_relocate(btf, vmlinux_btf, &btf->base_id_map);
6370 if (err)
6371 goto errout;
6372 btf_free(base_btf);
6373 base_btf = vmlinux_btf;
6374 }
6375
6376 btf_verifier_env_free(env);
6377 refcount_set(&btf->refcnt, 1);
6378 return btf;
6379
6380 errout:
6381 btf_verifier_env_free(env);
6382 if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
6383 btf_free(base_btf);
6384 if (btf) {
6385 kvfree(btf->data);
6386 kvfree(btf->types);
6387 kfree(btf);
6388 }
6389 return ERR_PTR(err);
6390 }
6391
6392 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6393
bpf_prog_get_target_btf(const struct bpf_prog * prog)6394 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6395 {
6396 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6397
6398 if (tgt_prog)
6399 return tgt_prog->aux->btf;
6400 else
6401 return prog->aux->attach_btf;
6402 }
6403
is_void_or_int_ptr(struct btf * btf,const struct btf_type * t)6404 static bool is_void_or_int_ptr(struct btf *btf, const struct btf_type *t)
6405 {
6406 /* skip modifiers */
6407 t = btf_type_skip_modifiers(btf, t->type, NULL);
6408 return btf_type_is_void(t) || btf_type_is_int(t);
6409 }
6410
btf_ctx_arg_idx(struct btf * btf,const struct btf_type * func_proto,int off)6411 u32 btf_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6412 int off)
6413 {
6414 const struct btf_param *args;
6415 const struct btf_type *t;
6416 u32 offset = 0, nr_args;
6417 int i;
6418
6419 if (!func_proto)
6420 return off / 8;
6421
6422 nr_args = btf_type_vlen(func_proto);
6423 args = (const struct btf_param *)(func_proto + 1);
6424 for (i = 0; i < nr_args; i++) {
6425 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6426 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6427 if (off < offset)
6428 return i;
6429 }
6430
6431 t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6432 offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6433 if (off < offset)
6434 return nr_args;
6435
6436 return nr_args + 1;
6437 }
6438
prog_args_trusted(const struct bpf_prog * prog)6439 static bool prog_args_trusted(const struct bpf_prog *prog)
6440 {
6441 enum bpf_attach_type atype = prog->expected_attach_type;
6442
6443 switch (prog->type) {
6444 case BPF_PROG_TYPE_TRACING:
6445 return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
6446 case BPF_PROG_TYPE_LSM:
6447 return bpf_lsm_is_trusted(prog);
6448 case BPF_PROG_TYPE_STRUCT_OPS:
6449 return true;
6450 default:
6451 return false;
6452 }
6453 }
6454
btf_ctx_arg_offset(const struct btf * btf,const struct btf_type * func_proto,u32 arg_no)6455 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6456 u32 arg_no)
6457 {
6458 const struct btf_param *args;
6459 const struct btf_type *t;
6460 int off = 0, i;
6461 u32 sz;
6462
6463 args = btf_params(func_proto);
6464 for (i = 0; i < arg_no; i++) {
6465 t = btf_type_by_id(btf, args[i].type);
6466 t = btf_resolve_size(btf, t, &sz);
6467 if (IS_ERR(t))
6468 return PTR_ERR(t);
6469 off += roundup(sz, 8);
6470 }
6471
6472 return off;
6473 }
6474
6475 struct bpf_raw_tp_null_args {
6476 const char *func;
6477 u64 mask;
6478 };
6479
6480 static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {
6481 /* sched */
6482 { "sched_pi_setprio", 0x10 },
6483 /* ... from sched_numa_pair_template event class */
6484 { "sched_stick_numa", 0x100 },
6485 { "sched_swap_numa", 0x100 },
6486 /* afs */
6487 { "afs_make_fs_call", 0x10 },
6488 { "afs_make_fs_calli", 0x10 },
6489 { "afs_make_fs_call1", 0x10 },
6490 { "afs_make_fs_call2", 0x10 },
6491 { "afs_protocol_error", 0x1 },
6492 { "afs_flock_ev", 0x10 },
6493 /* cachefiles */
6494 { "cachefiles_lookup", 0x1 | 0x200 },
6495 { "cachefiles_unlink", 0x1 },
6496 { "cachefiles_rename", 0x1 },
6497 { "cachefiles_prep_read", 0x1 },
6498 { "cachefiles_mark_active", 0x1 },
6499 { "cachefiles_mark_failed", 0x1 },
6500 { "cachefiles_mark_inactive", 0x1 },
6501 { "cachefiles_vfs_error", 0x1 },
6502 { "cachefiles_io_error", 0x1 },
6503 { "cachefiles_ondemand_open", 0x1 },
6504 { "cachefiles_ondemand_copen", 0x1 },
6505 { "cachefiles_ondemand_close", 0x1 },
6506 { "cachefiles_ondemand_read", 0x1 },
6507 { "cachefiles_ondemand_cread", 0x1 },
6508 { "cachefiles_ondemand_fd_write", 0x1 },
6509 { "cachefiles_ondemand_fd_release", 0x1 },
6510 /* ext4, from ext4__mballoc event class */
6511 { "ext4_mballoc_discard", 0x10 },
6512 { "ext4_mballoc_free", 0x10 },
6513 /* fib */
6514 { "fib_table_lookup", 0x100 },
6515 /* filelock */
6516 /* ... from filelock_lock event class */
6517 { "posix_lock_inode", 0x10 },
6518 { "fcntl_setlk", 0x10 },
6519 { "locks_remove_posix", 0x10 },
6520 { "flock_lock_inode", 0x10 },
6521 /* ... from filelock_lease event class */
6522 { "break_lease_noblock", 0x10 },
6523 { "break_lease_block", 0x10 },
6524 { "break_lease_unblock", 0x10 },
6525 { "generic_delete_lease", 0x10 },
6526 { "time_out_leases", 0x10 },
6527 /* host1x */
6528 { "host1x_cdma_push_gather", 0x10000 },
6529 /* huge_memory */
6530 { "mm_khugepaged_scan_pmd", 0x10 },
6531 { "mm_collapse_huge_page_isolate", 0x1 },
6532 { "mm_khugepaged_scan_file", 0x10 },
6533 { "mm_khugepaged_collapse_file", 0x10 },
6534 /* kmem */
6535 { "mm_page_alloc", 0x1 },
6536 { "mm_page_pcpu_drain", 0x1 },
6537 /* .. from mm_page event class */
6538 { "mm_page_alloc_zone_locked", 0x1 },
6539 /* netfs */
6540 { "netfs_failure", 0x10 },
6541 /* power */
6542 { "device_pm_callback_start", 0x10 },
6543 /* qdisc */
6544 { "qdisc_dequeue", 0x1000 },
6545 /* rxrpc */
6546 { "rxrpc_recvdata", 0x1 },
6547 { "rxrpc_resend", 0x10 },
6548 { "rxrpc_tq", 0x10 },
6549 { "rxrpc_client", 0x1 },
6550 /* skb */
6551 {"kfree_skb", 0x1000},
6552 /* sunrpc */
6553 { "xs_stream_read_data", 0x1 },
6554 /* ... from xprt_cong_event event class */
6555 { "xprt_reserve_cong", 0x10 },
6556 { "xprt_release_cong", 0x10 },
6557 { "xprt_get_cong", 0x10 },
6558 { "xprt_put_cong", 0x10 },
6559 /* tcp */
6560 { "tcp_send_reset", 0x11 },
6561 { "tcp_sendmsg_locked", 0x100 },
6562 /* tegra_apb_dma */
6563 { "tegra_dma_tx_status", 0x100 },
6564 /* timer_migration */
6565 { "tmigr_update_events", 0x1 },
6566 /* writeback, from writeback_folio_template event class */
6567 { "writeback_dirty_folio", 0x10 },
6568 { "folio_wait_writeback", 0x10 },
6569 /* rdma */
6570 { "mr_integ_alloc", 0x2000 },
6571 /* bpf_testmod */
6572 { "bpf_testmod_test_read", 0x0 },
6573 /* amdgpu */
6574 { "amdgpu_vm_bo_map", 0x1 },
6575 { "amdgpu_vm_bo_unmap", 0x1 },
6576 /* netfs */
6577 { "netfs_folioq", 0x1 },
6578 /* xfs from xfs_defer_pending_class */
6579 { "xfs_defer_create_intent", 0x1 },
6580 { "xfs_defer_cancel_list", 0x1 },
6581 { "xfs_defer_pending_finish", 0x1 },
6582 { "xfs_defer_pending_abort", 0x1 },
6583 { "xfs_defer_relog_intent", 0x1 },
6584 { "xfs_defer_isolate_paused", 0x1 },
6585 { "xfs_defer_item_pause", 0x1 },
6586 { "xfs_defer_item_unpause", 0x1 },
6587 /* xfs from xfs_defer_pending_item_class */
6588 { "xfs_defer_add_item", 0x1 },
6589 { "xfs_defer_cancel_item", 0x1 },
6590 { "xfs_defer_finish_item", 0x1 },
6591 /* xfs from xfs_icwalk_class */
6592 { "xfs_ioc_free_eofblocks", 0x10 },
6593 { "xfs_blockgc_free_space", 0x10 },
6594 /* xfs from xfs_btree_cur_class */
6595 { "xfs_btree_updkeys", 0x100 },
6596 { "xfs_btree_overlapped_query_range", 0x100 },
6597 /* xfs from xfs_imap_class*/
6598 { "xfs_map_blocks_found", 0x10000 },
6599 { "xfs_map_blocks_alloc", 0x10000 },
6600 { "xfs_iomap_alloc", 0x1000 },
6601 { "xfs_iomap_found", 0x1000 },
6602 /* xfs from xfs_fs_class */
6603 { "xfs_inodegc_flush", 0x1 },
6604 { "xfs_inodegc_push", 0x1 },
6605 { "xfs_inodegc_start", 0x1 },
6606 { "xfs_inodegc_stop", 0x1 },
6607 { "xfs_inodegc_queue", 0x1 },
6608 { "xfs_inodegc_throttle", 0x1 },
6609 { "xfs_fs_sync_fs", 0x1 },
6610 { "xfs_blockgc_start", 0x1 },
6611 { "xfs_blockgc_stop", 0x1 },
6612 { "xfs_blockgc_worker", 0x1 },
6613 { "xfs_blockgc_flush_all", 0x1 },
6614 /* xfs_scrub */
6615 { "xchk_nlinks_live_update", 0x10 },
6616 /* xfs_scrub from xchk_metapath_class */
6617 { "xchk_metapath_lookup", 0x100 },
6618 /* nfsd */
6619 { "nfsd_dirent", 0x1 },
6620 { "nfsd_file_acquire", 0x1001 },
6621 { "nfsd_file_insert_err", 0x1 },
6622 { "nfsd_file_cons_err", 0x1 },
6623 /* nfs4 */
6624 { "nfs4_setup_sequence", 0x1 },
6625 { "pnfs_update_layout", 0x10000 },
6626 { "nfs4_inode_callback_event", 0x200 },
6627 { "nfs4_inode_stateid_callback_event", 0x200 },
6628 /* nfs from pnfs_layout_event */
6629 { "pnfs_mds_fallback_pg_init_read", 0x10000 },
6630 { "pnfs_mds_fallback_pg_init_write", 0x10000 },
6631 { "pnfs_mds_fallback_pg_get_mirror_count", 0x10000 },
6632 { "pnfs_mds_fallback_read_done", 0x10000 },
6633 { "pnfs_mds_fallback_write_done", 0x10000 },
6634 { "pnfs_mds_fallback_read_pagelist", 0x10000 },
6635 { "pnfs_mds_fallback_write_pagelist", 0x10000 },
6636 /* coda */
6637 { "coda_dec_pic_run", 0x10 },
6638 { "coda_dec_pic_done", 0x10 },
6639 /* cfg80211 */
6640 { "cfg80211_scan_done", 0x11 },
6641 { "rdev_set_coalesce", 0x10 },
6642 { "cfg80211_report_wowlan_wakeup", 0x100 },
6643 { "cfg80211_inform_bss_frame", 0x100 },
6644 { "cfg80211_michael_mic_failure", 0x10000 },
6645 /* cfg80211 from wiphy_work_event */
6646 { "wiphy_work_queue", 0x10 },
6647 { "wiphy_work_run", 0x10 },
6648 { "wiphy_work_cancel", 0x10 },
6649 { "wiphy_work_flush", 0x10 },
6650 /* hugetlbfs */
6651 { "hugetlbfs_alloc_inode", 0x10 },
6652 /* spufs */
6653 { "spufs_context", 0x10 },
6654 /* kvm_hv */
6655 { "kvm_page_fault_enter", 0x100 },
6656 /* dpu */
6657 { "dpu_crtc_setup_mixer", 0x100 },
6658 /* binder */
6659 { "binder_transaction", 0x100 },
6660 /* bcachefs */
6661 { "btree_path_free", 0x100 },
6662 /* hfi1_tx */
6663 { "hfi1_sdma_progress", 0x1000 },
6664 /* iptfs */
6665 { "iptfs_ingress_postq_event", 0x1000 },
6666 /* neigh */
6667 { "neigh_update", 0x10 },
6668 /* snd_firewire_lib */
6669 { "amdtp_packet", 0x100 },
6670 };
6671
btf_ctx_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)6672 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
6673 const struct bpf_prog *prog,
6674 struct bpf_insn_access_aux *info)
6675 {
6676 const struct btf_type *t = prog->aux->attach_func_proto;
6677 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6678 struct btf *btf = bpf_prog_get_target_btf(prog);
6679 const char *tname = prog->aux->attach_func_name;
6680 struct bpf_verifier_log *log = info->log;
6681 const struct btf_param *args;
6682 bool ptr_err_raw_tp = false;
6683 const char *tag_value;
6684 u32 nr_args, arg;
6685 int i, ret;
6686
6687 if (off % 8) {
6688 bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6689 tname, off);
6690 return false;
6691 }
6692 arg = btf_ctx_arg_idx(btf, t, off);
6693 args = (const struct btf_param *)(t + 1);
6694 /* if (t == NULL) Fall back to default BPF prog with
6695 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
6696 */
6697 nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
6698 if (prog->aux->attach_btf_trace) {
6699 /* skip first 'void *__data' argument in btf_trace_##name typedef */
6700 args++;
6701 nr_args--;
6702 }
6703
6704 if (arg > nr_args) {
6705 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6706 tname, arg + 1);
6707 return false;
6708 }
6709
6710 if (arg == nr_args) {
6711 switch (prog->expected_attach_type) {
6712 case BPF_LSM_MAC:
6713 /* mark we are accessing the return value */
6714 info->is_retval = true;
6715 fallthrough;
6716 case BPF_LSM_CGROUP:
6717 case BPF_TRACE_FEXIT:
6718 /* When LSM programs are attached to void LSM hooks
6719 * they use FEXIT trampolines and when attached to
6720 * int LSM hooks, they use MODIFY_RETURN trampolines.
6721 *
6722 * While the LSM programs are BPF_MODIFY_RETURN-like
6723 * the check:
6724 *
6725 * if (ret_type != 'int')
6726 * return -EINVAL;
6727 *
6728 * is _not_ done here. This is still safe as LSM hooks
6729 * have only void and int return types.
6730 */
6731 if (!t)
6732 return true;
6733 t = btf_type_by_id(btf, t->type);
6734 break;
6735 case BPF_MODIFY_RETURN:
6736 /* For now the BPF_MODIFY_RETURN can only be attached to
6737 * functions that return an int.
6738 */
6739 if (!t)
6740 return false;
6741
6742 t = btf_type_skip_modifiers(btf, t->type, NULL);
6743 if (!btf_type_is_small_int(t)) {
6744 bpf_log(log,
6745 "ret type %s not allowed for fmod_ret\n",
6746 btf_type_str(t));
6747 return false;
6748 }
6749 break;
6750 default:
6751 bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6752 tname, arg + 1);
6753 return false;
6754 }
6755 } else {
6756 if (!t)
6757 /* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6758 return true;
6759 t = btf_type_by_id(btf, args[arg].type);
6760 }
6761
6762 /* skip modifiers */
6763 while (btf_type_is_modifier(t))
6764 t = btf_type_by_id(btf, t->type);
6765 if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6766 /* accessing a scalar */
6767 return true;
6768 if (!btf_type_is_ptr(t)) {
6769 bpf_log(log,
6770 "func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6771 tname, arg,
6772 __btf_name_by_offset(btf, t->name_off),
6773 btf_type_str(t));
6774 return false;
6775 }
6776
6777 if (size != sizeof(u64)) {
6778 bpf_log(log, "func '%s' size %d must be 8\n",
6779 tname, size);
6780 return false;
6781 }
6782
6783 /* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6784 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6785 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6786 u32 type, flag;
6787
6788 type = base_type(ctx_arg_info->reg_type);
6789 flag = type_flag(ctx_arg_info->reg_type);
6790 if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6791 (flag & PTR_MAYBE_NULL)) {
6792 info->reg_type = ctx_arg_info->reg_type;
6793 return true;
6794 }
6795 }
6796
6797 /*
6798 * If it's a pointer to void, it's the same as scalar from the verifier
6799 * safety POV. Either way, no futher pointer walking is allowed.
6800 */
6801 if (is_void_or_int_ptr(btf, t))
6802 return true;
6803
6804 /* this is a pointer to another type */
6805 for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6806 const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6807
6808 if (ctx_arg_info->offset == off) {
6809 if (!ctx_arg_info->btf_id) {
6810 bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6811 return false;
6812 }
6813
6814 info->reg_type = ctx_arg_info->reg_type;
6815 info->btf = ctx_arg_info->btf ? : btf_vmlinux;
6816 info->btf_id = ctx_arg_info->btf_id;
6817 info->ref_obj_id = ctx_arg_info->ref_obj_id;
6818 return true;
6819 }
6820 }
6821
6822 info->reg_type = PTR_TO_BTF_ID;
6823 if (prog_args_trusted(prog))
6824 info->reg_type |= PTR_TRUSTED;
6825
6826 if (btf_param_match_suffix(btf, &args[arg], "__nullable"))
6827 info->reg_type |= PTR_MAYBE_NULL;
6828
6829 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
6830 struct btf *btf = prog->aux->attach_btf;
6831 const struct btf_type *t;
6832 const char *tname;
6833
6834 /* BTF lookups cannot fail, return false on error */
6835 t = btf_type_by_id(btf, prog->aux->attach_btf_id);
6836 if (!t)
6837 return false;
6838 tname = btf_name_by_offset(btf, t->name_off);
6839 if (!tname)
6840 return false;
6841 /* Checked by bpf_check_attach_target */
6842 tname += sizeof("btf_trace_") - 1;
6843 for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) {
6844 /* Is this a func with potential NULL args? */
6845 if (strcmp(tname, raw_tp_null_args[i].func))
6846 continue;
6847 if (raw_tp_null_args[i].mask & (0x1ULL << (arg * 4)))
6848 info->reg_type |= PTR_MAYBE_NULL;
6849 /* Is the current arg IS_ERR? */
6850 if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4)))
6851 ptr_err_raw_tp = true;
6852 break;
6853 }
6854 /* If we don't know NULL-ness specification and the tracepoint
6855 * is coming from a loadable module, be conservative and mark
6856 * argument as PTR_MAYBE_NULL.
6857 */
6858 if (i == ARRAY_SIZE(raw_tp_null_args) && btf_is_module(btf))
6859 info->reg_type |= PTR_MAYBE_NULL;
6860 }
6861
6862 if (tgt_prog) {
6863 enum bpf_prog_type tgt_type;
6864
6865 if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6866 tgt_type = tgt_prog->aux->saved_dst_prog_type;
6867 else
6868 tgt_type = tgt_prog->type;
6869
6870 ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6871 if (ret > 0) {
6872 info->btf = btf_vmlinux;
6873 info->btf_id = ret;
6874 return true;
6875 } else {
6876 return false;
6877 }
6878 }
6879
6880 info->btf = btf;
6881 info->btf_id = t->type;
6882 t = btf_type_by_id(btf, t->type);
6883
6884 if (btf_type_is_type_tag(t) && !btf_type_kflag(t)) {
6885 tag_value = __btf_name_by_offset(btf, t->name_off);
6886 if (strcmp(tag_value, "user") == 0)
6887 info->reg_type |= MEM_USER;
6888 if (strcmp(tag_value, "percpu") == 0)
6889 info->reg_type |= MEM_PERCPU;
6890 }
6891
6892 /* skip modifiers */
6893 while (btf_type_is_modifier(t)) {
6894 info->btf_id = t->type;
6895 t = btf_type_by_id(btf, t->type);
6896 }
6897 if (!btf_type_is_struct(t)) {
6898 bpf_log(log,
6899 "func '%s' arg%d type %s is not a struct\n",
6900 tname, arg, btf_type_str(t));
6901 return false;
6902 }
6903 bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6904 tname, arg, info->btf_id, btf_type_str(t),
6905 __btf_name_by_offset(btf, t->name_off));
6906
6907 /* Perform all checks on the validity of type for this argument, but if
6908 * we know it can be IS_ERR at runtime, scrub pointer type and mark as
6909 * scalar.
6910 */
6911 if (ptr_err_raw_tp) {
6912 bpf_log(log, "marking pointer arg%d as scalar as it may encode error", arg);
6913 info->reg_type = SCALAR_VALUE;
6914 }
6915 return true;
6916 }
6917 EXPORT_SYMBOL_GPL(btf_ctx_access);
6918
6919 enum bpf_struct_walk_result {
6920 /* < 0 error */
6921 WALK_SCALAR = 0,
6922 WALK_PTR,
6923 WALK_PTR_UNTRUSTED,
6924 WALK_STRUCT,
6925 };
6926
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)6927 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6928 const struct btf_type *t, int off, int size,
6929 u32 *next_btf_id, enum bpf_type_flag *flag,
6930 const char **field_name)
6931 {
6932 u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6933 const struct btf_type *mtype, *elem_type = NULL;
6934 const struct btf_member *member;
6935 const char *tname, *mname, *tag_value;
6936 u32 vlen, elem_id, mid;
6937
6938 again:
6939 if (btf_type_is_modifier(t))
6940 t = btf_type_skip_modifiers(btf, t->type, NULL);
6941 tname = __btf_name_by_offset(btf, t->name_off);
6942 if (!btf_type_is_struct(t)) {
6943 bpf_log(log, "Type '%s' is not a struct\n", tname);
6944 return -EINVAL;
6945 }
6946
6947 vlen = btf_type_vlen(t);
6948 if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
6949 /*
6950 * walking unions yields untrusted pointers
6951 * with exception of __bpf_md_ptr and other
6952 * unions with a single member
6953 */
6954 *flag |= PTR_UNTRUSTED;
6955
6956 if (off + size > t->size) {
6957 /* If the last element is a variable size array, we may
6958 * need to relax the rule.
6959 */
6960 struct btf_array *array_elem;
6961
6962 if (vlen == 0)
6963 goto error;
6964
6965 member = btf_type_member(t) + vlen - 1;
6966 mtype = btf_type_skip_modifiers(btf, member->type,
6967 NULL);
6968 if (!btf_type_is_array(mtype))
6969 goto error;
6970
6971 array_elem = (struct btf_array *)(mtype + 1);
6972 if (array_elem->nelems != 0)
6973 goto error;
6974
6975 moff = __btf_member_bit_offset(t, member) / 8;
6976 if (off < moff)
6977 goto error;
6978
6979 /* allow structure and integer */
6980 t = btf_type_skip_modifiers(btf, array_elem->type,
6981 NULL);
6982
6983 if (btf_type_is_int(t))
6984 return WALK_SCALAR;
6985
6986 if (!btf_type_is_struct(t))
6987 goto error;
6988
6989 off = (off - moff) % t->size;
6990 goto again;
6991
6992 error:
6993 bpf_log(log, "access beyond struct %s at off %u size %u\n",
6994 tname, off, size);
6995 return -EACCES;
6996 }
6997
6998 for_each_member(i, t, member) {
6999 /* offset of the field in bytes */
7000 moff = __btf_member_bit_offset(t, member) / 8;
7001 if (off + size <= moff)
7002 /* won't find anything, field is already too far */
7003 break;
7004
7005 if (__btf_member_bitfield_size(t, member)) {
7006 u32 end_bit = __btf_member_bit_offset(t, member) +
7007 __btf_member_bitfield_size(t, member);
7008
7009 /* off <= moff instead of off == moff because clang
7010 * does not generate a BTF member for anonymous
7011 * bitfield like the ":16" here:
7012 * struct {
7013 * int :16;
7014 * int x:8;
7015 * };
7016 */
7017 if (off <= moff &&
7018 BITS_ROUNDUP_BYTES(end_bit) <= off + size)
7019 return WALK_SCALAR;
7020
7021 /* off may be accessing a following member
7022 *
7023 * or
7024 *
7025 * Doing partial access at either end of this
7026 * bitfield. Continue on this case also to
7027 * treat it as not accessing this bitfield
7028 * and eventually error out as field not
7029 * found to keep it simple.
7030 * It could be relaxed if there was a legit
7031 * partial access case later.
7032 */
7033 continue;
7034 }
7035
7036 /* In case of "off" is pointing to holes of a struct */
7037 if (off < moff)
7038 break;
7039
7040 /* type of the field */
7041 mid = member->type;
7042 mtype = btf_type_by_id(btf, member->type);
7043 mname = __btf_name_by_offset(btf, member->name_off);
7044
7045 mtype = __btf_resolve_size(btf, mtype, &msize,
7046 &elem_type, &elem_id, &total_nelems,
7047 &mid);
7048 if (IS_ERR(mtype)) {
7049 bpf_log(log, "field %s doesn't have size\n", mname);
7050 return -EFAULT;
7051 }
7052
7053 mtrue_end = moff + msize;
7054 if (off >= mtrue_end)
7055 /* no overlap with member, keep iterating */
7056 continue;
7057
7058 if (btf_type_is_array(mtype)) {
7059 u32 elem_idx;
7060
7061 /* __btf_resolve_size() above helps to
7062 * linearize a multi-dimensional array.
7063 *
7064 * The logic here is treating an array
7065 * in a struct as the following way:
7066 *
7067 * struct outer {
7068 * struct inner array[2][2];
7069 * };
7070 *
7071 * looks like:
7072 *
7073 * struct outer {
7074 * struct inner array_elem0;
7075 * struct inner array_elem1;
7076 * struct inner array_elem2;
7077 * struct inner array_elem3;
7078 * };
7079 *
7080 * When accessing outer->array[1][0], it moves
7081 * moff to "array_elem2", set mtype to
7082 * "struct inner", and msize also becomes
7083 * sizeof(struct inner). Then most of the
7084 * remaining logic will fall through without
7085 * caring the current member is an array or
7086 * not.
7087 *
7088 * Unlike mtype/msize/moff, mtrue_end does not
7089 * change. The naming difference ("_true") tells
7090 * that it is not always corresponding to
7091 * the current mtype/msize/moff.
7092 * It is the true end of the current
7093 * member (i.e. array in this case). That
7094 * will allow an int array to be accessed like
7095 * a scratch space,
7096 * i.e. allow access beyond the size of
7097 * the array's element as long as it is
7098 * within the mtrue_end boundary.
7099 */
7100
7101 /* skip empty array */
7102 if (moff == mtrue_end)
7103 continue;
7104
7105 msize /= total_nelems;
7106 elem_idx = (off - moff) / msize;
7107 moff += elem_idx * msize;
7108 mtype = elem_type;
7109 mid = elem_id;
7110 }
7111
7112 /* the 'off' we're looking for is either equal to start
7113 * of this field or inside of this struct
7114 */
7115 if (btf_type_is_struct(mtype)) {
7116 /* our field must be inside that union or struct */
7117 t = mtype;
7118
7119 /* return if the offset matches the member offset */
7120 if (off == moff) {
7121 *next_btf_id = mid;
7122 return WALK_STRUCT;
7123 }
7124
7125 /* adjust offset we're looking for */
7126 off -= moff;
7127 goto again;
7128 }
7129
7130 if (btf_type_is_ptr(mtype)) {
7131 const struct btf_type *stype, *t;
7132 enum bpf_type_flag tmp_flag = 0;
7133 u32 id;
7134
7135 if (msize != size || off != moff) {
7136 bpf_log(log,
7137 "cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
7138 mname, moff, tname, off, size);
7139 return -EACCES;
7140 }
7141
7142 /* check type tag */
7143 t = btf_type_by_id(btf, mtype->type);
7144 if (btf_type_is_type_tag(t) && !btf_type_kflag(t)) {
7145 tag_value = __btf_name_by_offset(btf, t->name_off);
7146 /* check __user tag */
7147 if (strcmp(tag_value, "user") == 0)
7148 tmp_flag = MEM_USER;
7149 /* check __percpu tag */
7150 if (strcmp(tag_value, "percpu") == 0)
7151 tmp_flag = MEM_PERCPU;
7152 /* check __rcu tag */
7153 if (strcmp(tag_value, "rcu") == 0)
7154 tmp_flag = MEM_RCU;
7155 }
7156
7157 stype = btf_type_skip_modifiers(btf, mtype->type, &id);
7158 if (btf_type_is_struct(stype)) {
7159 *next_btf_id = id;
7160 *flag |= tmp_flag;
7161 if (field_name)
7162 *field_name = mname;
7163 return WALK_PTR;
7164 }
7165
7166 return WALK_PTR_UNTRUSTED;
7167 }
7168
7169 /* Allow more flexible access within an int as long as
7170 * it is within mtrue_end.
7171 * Since mtrue_end could be the end of an array,
7172 * that also allows using an array of int as a scratch
7173 * space. e.g. skb->cb[].
7174 */
7175 if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
7176 bpf_log(log,
7177 "access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
7178 mname, mtrue_end, tname, off, size);
7179 return -EACCES;
7180 }
7181
7182 return WALK_SCALAR;
7183 }
7184 bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
7185 return -EINVAL;
7186 }
7187
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)7188 int btf_struct_access(struct bpf_verifier_log *log,
7189 const struct bpf_reg_state *reg,
7190 int off, int size, enum bpf_access_type atype __maybe_unused,
7191 u32 *next_btf_id, enum bpf_type_flag *flag,
7192 const char **field_name)
7193 {
7194 const struct btf *btf = reg->btf;
7195 enum bpf_type_flag tmp_flag = 0;
7196 const struct btf_type *t;
7197 u32 id = reg->btf_id;
7198 int err;
7199
7200 while (type_is_alloc(reg->type)) {
7201 struct btf_struct_meta *meta;
7202 struct btf_record *rec;
7203 int i;
7204
7205 meta = btf_find_struct_meta(btf, id);
7206 if (!meta)
7207 break;
7208 rec = meta->record;
7209 for (i = 0; i < rec->cnt; i++) {
7210 struct btf_field *field = &rec->fields[i];
7211 u32 offset = field->offset;
7212 if (off < offset + field->size && offset < off + size) {
7213 bpf_log(log,
7214 "direct access to %s is disallowed\n",
7215 btf_field_type_name(field->type));
7216 return -EACCES;
7217 }
7218 }
7219 break;
7220 }
7221
7222 t = btf_type_by_id(btf, id);
7223 do {
7224 err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
7225
7226 switch (err) {
7227 case WALK_PTR:
7228 /* For local types, the destination register cannot
7229 * become a pointer again.
7230 */
7231 if (type_is_alloc(reg->type))
7232 return SCALAR_VALUE;
7233 /* If we found the pointer or scalar on t+off,
7234 * we're done.
7235 */
7236 *next_btf_id = id;
7237 *flag = tmp_flag;
7238 return PTR_TO_BTF_ID;
7239 case WALK_PTR_UNTRUSTED:
7240 *flag = MEM_RDONLY | PTR_UNTRUSTED;
7241 return PTR_TO_MEM;
7242 case WALK_SCALAR:
7243 return SCALAR_VALUE;
7244 case WALK_STRUCT:
7245 /* We found nested struct, so continue the search
7246 * by diving in it. At this point the offset is
7247 * aligned with the new type, so set it to 0.
7248 */
7249 t = btf_type_by_id(btf, id);
7250 off = 0;
7251 break;
7252 default:
7253 /* It's either error or unknown return value..
7254 * scream and leave.
7255 */
7256 if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
7257 return -EINVAL;
7258 return err;
7259 }
7260 } while (t);
7261
7262 return -EINVAL;
7263 }
7264
7265 /* Check that two BTF types, each specified as an BTF object + id, are exactly
7266 * the same. Trivial ID check is not enough due to module BTFs, because we can
7267 * end up with two different module BTFs, but IDs point to the common type in
7268 * vmlinux BTF.
7269 */
btf_types_are_same(const struct btf * btf1,u32 id1,const struct btf * btf2,u32 id2)7270 bool btf_types_are_same(const struct btf *btf1, u32 id1,
7271 const struct btf *btf2, u32 id2)
7272 {
7273 if (id1 != id2)
7274 return false;
7275 if (btf1 == btf2)
7276 return true;
7277 return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
7278 }
7279
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)7280 bool btf_struct_ids_match(struct bpf_verifier_log *log,
7281 const struct btf *btf, u32 id, int off,
7282 const struct btf *need_btf, u32 need_type_id,
7283 bool strict)
7284 {
7285 const struct btf_type *type;
7286 enum bpf_type_flag flag = 0;
7287 int err;
7288
7289 /* Are we already done? */
7290 if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
7291 return true;
7292 /* In case of strict type match, we do not walk struct, the top level
7293 * type match must succeed. When strict is true, off should have already
7294 * been 0.
7295 */
7296 if (strict)
7297 return false;
7298 again:
7299 type = btf_type_by_id(btf, id);
7300 if (!type)
7301 return false;
7302 err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
7303 if (err != WALK_STRUCT)
7304 return false;
7305
7306 /* We found nested struct object. If it matches
7307 * the requested ID, we're done. Otherwise let's
7308 * continue the search with offset 0 in the new
7309 * type.
7310 */
7311 if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
7312 off = 0;
7313 goto again;
7314 }
7315
7316 return true;
7317 }
7318
__get_type_size(struct btf * btf,u32 btf_id,const struct btf_type ** ret_type)7319 static int __get_type_size(struct btf *btf, u32 btf_id,
7320 const struct btf_type **ret_type)
7321 {
7322 const struct btf_type *t;
7323
7324 *ret_type = btf_type_by_id(btf, 0);
7325 if (!btf_id)
7326 /* void */
7327 return 0;
7328 t = btf_type_by_id(btf, btf_id);
7329 while (t && btf_type_is_modifier(t))
7330 t = btf_type_by_id(btf, t->type);
7331 if (!t)
7332 return -EINVAL;
7333 *ret_type = t;
7334 if (btf_type_is_ptr(t))
7335 /* kernel size of pointer. Not BPF's size of pointer*/
7336 return sizeof(void *);
7337 if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
7338 return t->size;
7339 return -EINVAL;
7340 }
7341
__get_type_fmodel_flags(const struct btf_type * t)7342 static u8 __get_type_fmodel_flags(const struct btf_type *t)
7343 {
7344 u8 flags = 0;
7345
7346 if (__btf_type_is_struct(t))
7347 flags |= BTF_FMODEL_STRUCT_ARG;
7348 if (btf_type_is_signed_int(t))
7349 flags |= BTF_FMODEL_SIGNED_ARG;
7350
7351 return flags;
7352 }
7353
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)7354 int btf_distill_func_proto(struct bpf_verifier_log *log,
7355 struct btf *btf,
7356 const struct btf_type *func,
7357 const char *tname,
7358 struct btf_func_model *m)
7359 {
7360 const struct btf_param *args;
7361 const struct btf_type *t;
7362 u32 i, nargs;
7363 int ret;
7364
7365 if (!func) {
7366 /* BTF function prototype doesn't match the verifier types.
7367 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
7368 */
7369 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7370 m->arg_size[i] = 8;
7371 m->arg_flags[i] = 0;
7372 }
7373 m->ret_size = 8;
7374 m->ret_flags = 0;
7375 m->nr_args = MAX_BPF_FUNC_REG_ARGS;
7376 return 0;
7377 }
7378 args = (const struct btf_param *)(func + 1);
7379 nargs = btf_type_vlen(func);
7380 if (nargs > MAX_BPF_FUNC_ARGS) {
7381 bpf_log(log,
7382 "The function %s has %d arguments. Too many.\n",
7383 tname, nargs);
7384 return -EINVAL;
7385 }
7386 ret = __get_type_size(btf, func->type, &t);
7387 if (ret < 0 || __btf_type_is_struct(t)) {
7388 bpf_log(log,
7389 "The function %s return type %s is unsupported.\n",
7390 tname, btf_type_str(t));
7391 return -EINVAL;
7392 }
7393 m->ret_size = ret;
7394 m->ret_flags = __get_type_fmodel_flags(t);
7395
7396 for (i = 0; i < nargs; i++) {
7397 if (i == nargs - 1 && args[i].type == 0) {
7398 bpf_log(log,
7399 "The function %s with variable args is unsupported.\n",
7400 tname);
7401 return -EINVAL;
7402 }
7403 ret = __get_type_size(btf, args[i].type, &t);
7404
7405 /* No support of struct argument size greater than 16 bytes */
7406 if (ret < 0 || ret > 16) {
7407 bpf_log(log,
7408 "The function %s arg%d type %s is unsupported.\n",
7409 tname, i, btf_type_str(t));
7410 return -EINVAL;
7411 }
7412 if (ret == 0) {
7413 bpf_log(log,
7414 "The function %s has malformed void argument.\n",
7415 tname);
7416 return -EINVAL;
7417 }
7418 m->arg_size[i] = ret;
7419 m->arg_flags[i] = __get_type_fmodel_flags(t);
7420 }
7421 m->nr_args = nargs;
7422 return 0;
7423 }
7424
7425 /* Compare BTFs of two functions assuming only scalars and pointers to context.
7426 * t1 points to BTF_KIND_FUNC in btf1
7427 * t2 points to BTF_KIND_FUNC in btf2
7428 * Returns:
7429 * EINVAL - function prototype mismatch
7430 * EFAULT - verifier bug
7431 * 0 - 99% match. The last 1% is validated by the verifier.
7432 */
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)7433 static int btf_check_func_type_match(struct bpf_verifier_log *log,
7434 struct btf *btf1, const struct btf_type *t1,
7435 struct btf *btf2, const struct btf_type *t2)
7436 {
7437 const struct btf_param *args1, *args2;
7438 const char *fn1, *fn2, *s1, *s2;
7439 u32 nargs1, nargs2, i;
7440
7441 fn1 = btf_name_by_offset(btf1, t1->name_off);
7442 fn2 = btf_name_by_offset(btf2, t2->name_off);
7443
7444 if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
7445 bpf_log(log, "%s() is not a global function\n", fn1);
7446 return -EINVAL;
7447 }
7448 if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
7449 bpf_log(log, "%s() is not a global function\n", fn2);
7450 return -EINVAL;
7451 }
7452
7453 t1 = btf_type_by_id(btf1, t1->type);
7454 if (!t1 || !btf_type_is_func_proto(t1))
7455 return -EFAULT;
7456 t2 = btf_type_by_id(btf2, t2->type);
7457 if (!t2 || !btf_type_is_func_proto(t2))
7458 return -EFAULT;
7459
7460 args1 = (const struct btf_param *)(t1 + 1);
7461 nargs1 = btf_type_vlen(t1);
7462 args2 = (const struct btf_param *)(t2 + 1);
7463 nargs2 = btf_type_vlen(t2);
7464
7465 if (nargs1 != nargs2) {
7466 bpf_log(log, "%s() has %d args while %s() has %d args\n",
7467 fn1, nargs1, fn2, nargs2);
7468 return -EINVAL;
7469 }
7470
7471 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7472 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7473 if (t1->info != t2->info) {
7474 bpf_log(log,
7475 "Return type %s of %s() doesn't match type %s of %s()\n",
7476 btf_type_str(t1), fn1,
7477 btf_type_str(t2), fn2);
7478 return -EINVAL;
7479 }
7480
7481 for (i = 0; i < nargs1; i++) {
7482 t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
7483 t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
7484
7485 if (t1->info != t2->info) {
7486 bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
7487 i, fn1, btf_type_str(t1),
7488 fn2, btf_type_str(t2));
7489 return -EINVAL;
7490 }
7491 if (btf_type_has_size(t1) && t1->size != t2->size) {
7492 bpf_log(log,
7493 "arg%d in %s() has size %d while %s() has %d\n",
7494 i, fn1, t1->size,
7495 fn2, t2->size);
7496 return -EINVAL;
7497 }
7498
7499 /* global functions are validated with scalars and pointers
7500 * to context only. And only global functions can be replaced.
7501 * Hence type check only those types.
7502 */
7503 if (btf_type_is_int(t1) || btf_is_any_enum(t1))
7504 continue;
7505 if (!btf_type_is_ptr(t1)) {
7506 bpf_log(log,
7507 "arg%d in %s() has unrecognized type\n",
7508 i, fn1);
7509 return -EINVAL;
7510 }
7511 t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7512 t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7513 if (!btf_type_is_struct(t1)) {
7514 bpf_log(log,
7515 "arg%d in %s() is not a pointer to context\n",
7516 i, fn1);
7517 return -EINVAL;
7518 }
7519 if (!btf_type_is_struct(t2)) {
7520 bpf_log(log,
7521 "arg%d in %s() is not a pointer to context\n",
7522 i, fn2);
7523 return -EINVAL;
7524 }
7525 /* This is an optional check to make program writing easier.
7526 * Compare names of structs and report an error to the user.
7527 * btf_prepare_func_args() already checked that t2 struct
7528 * is a context type. btf_prepare_func_args() will check
7529 * later that t1 struct is a context type as well.
7530 */
7531 s1 = btf_name_by_offset(btf1, t1->name_off);
7532 s2 = btf_name_by_offset(btf2, t2->name_off);
7533 if (strcmp(s1, s2)) {
7534 bpf_log(log,
7535 "arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7536 i, fn1, s1, fn2, s2);
7537 return -EINVAL;
7538 }
7539 }
7540 return 0;
7541 }
7542
7543 /* 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)7544 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
7545 struct btf *btf2, const struct btf_type *t2)
7546 {
7547 struct btf *btf1 = prog->aux->btf;
7548 const struct btf_type *t1;
7549 u32 btf_id = 0;
7550
7551 if (!prog->aux->func_info) {
7552 bpf_log(log, "Program extension requires BTF\n");
7553 return -EINVAL;
7554 }
7555
7556 btf_id = prog->aux->func_info[0].type_id;
7557 if (!btf_id)
7558 return -EFAULT;
7559
7560 t1 = btf_type_by_id(btf1, btf_id);
7561 if (!t1 || !btf_type_is_func(t1))
7562 return -EFAULT;
7563
7564 return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7565 }
7566
btf_is_dynptr_ptr(const struct btf * btf,const struct btf_type * t)7567 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7568 {
7569 const char *name;
7570
7571 t = btf_type_by_id(btf, t->type); /* skip PTR */
7572
7573 while (btf_type_is_modifier(t))
7574 t = btf_type_by_id(btf, t->type);
7575
7576 /* allow either struct or struct forward declaration */
7577 if (btf_type_is_struct(t) ||
7578 (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
7579 name = btf_str_by_offset(btf, t->name_off);
7580 return name && strcmp(name, "bpf_dynptr") == 0;
7581 }
7582
7583 return false;
7584 }
7585
7586 struct bpf_cand_cache {
7587 const char *name;
7588 u32 name_len;
7589 u16 kind;
7590 u16 cnt;
7591 struct {
7592 const struct btf *btf;
7593 u32 id;
7594 } cands[];
7595 };
7596
7597 static DEFINE_MUTEX(cand_cache_mutex);
7598
7599 static struct bpf_cand_cache *
7600 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7601
btf_get_ptr_to_btf_id(struct bpf_verifier_log * log,int arg_idx,const struct btf * btf,const struct btf_type * t)7602 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
7603 const struct btf *btf, const struct btf_type *t)
7604 {
7605 struct bpf_cand_cache *cc;
7606 struct bpf_core_ctx ctx = {
7607 .btf = btf,
7608 .log = log,
7609 };
7610 u32 kern_type_id, type_id;
7611 int err = 0;
7612
7613 /* skip PTR and modifiers */
7614 type_id = t->type;
7615 t = btf_type_by_id(btf, t->type);
7616 while (btf_type_is_modifier(t)) {
7617 type_id = t->type;
7618 t = btf_type_by_id(btf, t->type);
7619 }
7620
7621 mutex_lock(&cand_cache_mutex);
7622 cc = bpf_core_find_cands(&ctx, type_id);
7623 if (IS_ERR(cc)) {
7624 err = PTR_ERR(cc);
7625 bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
7626 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7627 err);
7628 goto cand_cache_unlock;
7629 }
7630 if (cc->cnt != 1) {
7631 bpf_log(log, "arg#%d reference type('%s %s') %s\n",
7632 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7633 cc->cnt == 0 ? "has no matches" : "is ambiguous");
7634 err = cc->cnt == 0 ? -ENOENT : -ESRCH;
7635 goto cand_cache_unlock;
7636 }
7637 if (btf_is_module(cc->cands[0].btf)) {
7638 bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
7639 arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
7640 err = -EOPNOTSUPP;
7641 goto cand_cache_unlock;
7642 }
7643 kern_type_id = cc->cands[0].id;
7644
7645 cand_cache_unlock:
7646 mutex_unlock(&cand_cache_mutex);
7647 if (err)
7648 return err;
7649
7650 return kern_type_id;
7651 }
7652
7653 enum btf_arg_tag {
7654 ARG_TAG_CTX = BIT_ULL(0),
7655 ARG_TAG_NONNULL = BIT_ULL(1),
7656 ARG_TAG_TRUSTED = BIT_ULL(2),
7657 ARG_TAG_UNTRUSTED = BIT_ULL(3),
7658 ARG_TAG_NULLABLE = BIT_ULL(4),
7659 ARG_TAG_ARENA = BIT_ULL(5),
7660 };
7661
7662 /* Process BTF of a function to produce high-level expectation of function
7663 * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
7664 * is cached in subprog info for reuse.
7665 * Returns:
7666 * EFAULT - there is a verifier bug. Abort verification.
7667 * EINVAL - cannot convert BTF.
7668 * 0 - Successfully processed BTF and constructed argument expectations.
7669 */
btf_prepare_func_args(struct bpf_verifier_env * env,int subprog)7670 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7671 {
7672 bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
7673 struct bpf_subprog_info *sub = subprog_info(env, subprog);
7674 struct bpf_verifier_log *log = &env->log;
7675 struct bpf_prog *prog = env->prog;
7676 enum bpf_prog_type prog_type = prog->type;
7677 struct btf *btf = prog->aux->btf;
7678 const struct btf_param *args;
7679 const struct btf_type *t, *ref_t, *fn_t;
7680 u32 i, nargs, btf_id;
7681 const char *tname;
7682
7683 if (sub->args_cached)
7684 return 0;
7685
7686 if (!prog->aux->func_info) {
7687 verifier_bug(env, "func_info undefined");
7688 return -EFAULT;
7689 }
7690
7691 btf_id = prog->aux->func_info[subprog].type_id;
7692 if (!btf_id) {
7693 if (!is_global) /* not fatal for static funcs */
7694 return -EINVAL;
7695 bpf_log(log, "Global functions need valid BTF\n");
7696 return -EFAULT;
7697 }
7698
7699 fn_t = btf_type_by_id(btf, btf_id);
7700 if (!fn_t || !btf_type_is_func(fn_t)) {
7701 /* These checks were already done by the verifier while loading
7702 * struct bpf_func_info
7703 */
7704 bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7705 subprog);
7706 return -EFAULT;
7707 }
7708 tname = btf_name_by_offset(btf, fn_t->name_off);
7709
7710 if (prog->aux->func_info_aux[subprog].unreliable) {
7711 verifier_bug(env, "unreliable BTF for function %s()", tname);
7712 return -EFAULT;
7713 }
7714 if (prog_type == BPF_PROG_TYPE_EXT)
7715 prog_type = prog->aux->dst_prog->type;
7716
7717 t = btf_type_by_id(btf, fn_t->type);
7718 if (!t || !btf_type_is_func_proto(t)) {
7719 bpf_log(log, "Invalid type of function %s()\n", tname);
7720 return -EFAULT;
7721 }
7722 args = (const struct btf_param *)(t + 1);
7723 nargs = btf_type_vlen(t);
7724 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7725 if (!is_global)
7726 return -EINVAL;
7727 bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7728 tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7729 return -EINVAL;
7730 }
7731 /* check that function returns int, exception cb also requires this */
7732 t = btf_type_by_id(btf, t->type);
7733 while (btf_type_is_modifier(t))
7734 t = btf_type_by_id(btf, t->type);
7735 if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7736 if (!is_global)
7737 return -EINVAL;
7738 bpf_log(log,
7739 "Global function %s() doesn't return scalar. Only those are supported.\n",
7740 tname);
7741 return -EINVAL;
7742 }
7743 /* Convert BTF function arguments into verifier types.
7744 * Only PTR_TO_CTX and SCALAR are supported atm.
7745 */
7746 for (i = 0; i < nargs; i++) {
7747 u32 tags = 0;
7748 int id = 0;
7749
7750 /* 'arg:<tag>' decl_tag takes precedence over derivation of
7751 * register type from BTF type itself
7752 */
7753 while ((id = btf_find_next_decl_tag(btf, fn_t, i, "arg:", id)) > 0) {
7754 const struct btf_type *tag_t = btf_type_by_id(btf, id);
7755 const char *tag = __btf_name_by_offset(btf, tag_t->name_off) + 4;
7756
7757 /* disallow arg tags in static subprogs */
7758 if (!is_global) {
7759 bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7760 return -EOPNOTSUPP;
7761 }
7762
7763 if (strcmp(tag, "ctx") == 0) {
7764 tags |= ARG_TAG_CTX;
7765 } else if (strcmp(tag, "trusted") == 0) {
7766 tags |= ARG_TAG_TRUSTED;
7767 } else if (strcmp(tag, "untrusted") == 0) {
7768 tags |= ARG_TAG_UNTRUSTED;
7769 } else if (strcmp(tag, "nonnull") == 0) {
7770 tags |= ARG_TAG_NONNULL;
7771 } else if (strcmp(tag, "nullable") == 0) {
7772 tags |= ARG_TAG_NULLABLE;
7773 } else if (strcmp(tag, "arena") == 0) {
7774 tags |= ARG_TAG_ARENA;
7775 } else {
7776 bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7777 return -EOPNOTSUPP;
7778 }
7779 }
7780 if (id != -ENOENT) {
7781 bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7782 return id;
7783 }
7784
7785 t = btf_type_by_id(btf, args[i].type);
7786 while (btf_type_is_modifier(t))
7787 t = btf_type_by_id(btf, t->type);
7788 if (!btf_type_is_ptr(t))
7789 goto skip_pointer;
7790
7791 if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
7792 if (tags & ~ARG_TAG_CTX) {
7793 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7794 return -EINVAL;
7795 }
7796 if ((tags & ARG_TAG_CTX) &&
7797 btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7798 prog->expected_attach_type))
7799 return -EINVAL;
7800 sub->args[i].arg_type = ARG_PTR_TO_CTX;
7801 continue;
7802 }
7803 if (btf_is_dynptr_ptr(btf, t)) {
7804 if (tags) {
7805 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7806 return -EINVAL;
7807 }
7808 sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7809 continue;
7810 }
7811 if (tags & ARG_TAG_TRUSTED) {
7812 int kern_type_id;
7813
7814 if (tags & ARG_TAG_NONNULL) {
7815 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7816 return -EINVAL;
7817 }
7818
7819 kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7820 if (kern_type_id < 0)
7821 return kern_type_id;
7822
7823 sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
7824 if (tags & ARG_TAG_NULLABLE)
7825 sub->args[i].arg_type |= PTR_MAYBE_NULL;
7826 sub->args[i].btf_id = kern_type_id;
7827 continue;
7828 }
7829 if (tags & ARG_TAG_UNTRUSTED) {
7830 struct btf *vmlinux_btf;
7831 int kern_type_id;
7832
7833 if (tags & ~ARG_TAG_UNTRUSTED) {
7834 bpf_log(log, "arg#%d untrusted cannot be combined with any other tags\n", i);
7835 return -EINVAL;
7836 }
7837
7838 ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
7839 if (btf_type_is_void(ref_t) || btf_type_is_primitive(ref_t)) {
7840 sub->args[i].arg_type = ARG_PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
7841 sub->args[i].mem_size = 0;
7842 continue;
7843 }
7844
7845 kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7846 if (kern_type_id < 0)
7847 return kern_type_id;
7848
7849 vmlinux_btf = bpf_get_btf_vmlinux();
7850 ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
7851 if (!btf_type_is_struct(ref_t)) {
7852 tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
7853 bpf_log(log, "arg#%d has type %s '%s', but only struct or primitive types are allowed\n",
7854 i, btf_type_str(ref_t), tname);
7855 return -EINVAL;
7856 }
7857 sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_UNTRUSTED;
7858 sub->args[i].btf_id = kern_type_id;
7859 continue;
7860 }
7861 if (tags & ARG_TAG_ARENA) {
7862 if (tags & ~ARG_TAG_ARENA) {
7863 bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
7864 return -EINVAL;
7865 }
7866 sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7867 continue;
7868 }
7869 if (is_global) { /* generic user data pointer */
7870 u32 mem_size;
7871
7872 if (tags & ARG_TAG_NULLABLE) {
7873 bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7874 return -EINVAL;
7875 }
7876
7877 t = btf_type_skip_modifiers(btf, t->type, NULL);
7878 ref_t = btf_resolve_size(btf, t, &mem_size);
7879 if (IS_ERR(ref_t)) {
7880 bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7881 i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7882 PTR_ERR(ref_t));
7883 return -EINVAL;
7884 }
7885
7886 sub->args[i].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
7887 if (tags & ARG_TAG_NONNULL)
7888 sub->args[i].arg_type &= ~PTR_MAYBE_NULL;
7889 sub->args[i].mem_size = mem_size;
7890 continue;
7891 }
7892
7893 skip_pointer:
7894 if (tags) {
7895 bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
7896 return -EINVAL;
7897 }
7898 if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7899 sub->args[i].arg_type = ARG_ANYTHING;
7900 continue;
7901 }
7902 if (!is_global)
7903 return -EINVAL;
7904 bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7905 i, btf_type_str(t), tname);
7906 return -EINVAL;
7907 }
7908
7909 sub->arg_cnt = nargs;
7910 sub->args_cached = true;
7911
7912 return 0;
7913 }
7914
btf_type_show(const struct btf * btf,u32 type_id,void * obj,struct btf_show * show)7915 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7916 struct btf_show *show)
7917 {
7918 const struct btf_type *t = btf_type_by_id(btf, type_id);
7919
7920 show->btf = btf;
7921 memset(&show->state, 0, sizeof(show->state));
7922 memset(&show->obj, 0, sizeof(show->obj));
7923
7924 btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7925 }
7926
btf_seq_show(struct btf_show * show,const char * fmt,va_list args)7927 __printf(2, 0) static void btf_seq_show(struct btf_show *show, const char *fmt,
7928 va_list args)
7929 {
7930 seq_vprintf((struct seq_file *)show->target, fmt, args);
7931 }
7932
btf_type_seq_show_flags(const struct btf * btf,u32 type_id,void * obj,struct seq_file * m,u64 flags)7933 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7934 void *obj, struct seq_file *m, u64 flags)
7935 {
7936 struct btf_show sseq;
7937
7938 sseq.target = m;
7939 sseq.showfn = btf_seq_show;
7940 sseq.flags = flags;
7941
7942 btf_type_show(btf, type_id, obj, &sseq);
7943
7944 return sseq.state.status;
7945 }
7946
btf_type_seq_show(const struct btf * btf,u32 type_id,void * obj,struct seq_file * m)7947 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7948 struct seq_file *m)
7949 {
7950 (void) btf_type_seq_show_flags(btf, type_id, obj, m,
7951 BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7952 BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7953 }
7954
7955 struct btf_show_snprintf {
7956 struct btf_show show;
7957 int len_left; /* space left in string */
7958 int len; /* length we would have written */
7959 };
7960
btf_snprintf_show(struct btf_show * show,const char * fmt,va_list args)7961 __printf(2, 0) static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7962 va_list args)
7963 {
7964 struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7965 int len;
7966
7967 len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7968
7969 if (len < 0) {
7970 ssnprintf->len_left = 0;
7971 ssnprintf->len = len;
7972 } else if (len >= ssnprintf->len_left) {
7973 /* no space, drive on to get length we would have written */
7974 ssnprintf->len_left = 0;
7975 ssnprintf->len += len;
7976 } else {
7977 ssnprintf->len_left -= len;
7978 ssnprintf->len += len;
7979 show->target += len;
7980 }
7981 }
7982
btf_type_snprintf_show(const struct btf * btf,u32 type_id,void * obj,char * buf,int len,u64 flags)7983 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7984 char *buf, int len, u64 flags)
7985 {
7986 struct btf_show_snprintf ssnprintf;
7987
7988 ssnprintf.show.target = buf;
7989 ssnprintf.show.flags = flags;
7990 ssnprintf.show.showfn = btf_snprintf_show;
7991 ssnprintf.len_left = len;
7992 ssnprintf.len = 0;
7993
7994 btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7995
7996 /* If we encountered an error, return it. */
7997 if (ssnprintf.show.state.status)
7998 return ssnprintf.show.state.status;
7999
8000 /* Otherwise return length we would have written */
8001 return ssnprintf.len;
8002 }
8003
8004 #ifdef CONFIG_PROC_FS
bpf_btf_show_fdinfo(struct seq_file * m,struct file * filp)8005 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
8006 {
8007 const struct btf *btf = filp->private_data;
8008
8009 seq_printf(m, "btf_id:\t%u\n", btf->id);
8010 }
8011 #endif
8012
btf_release(struct inode * inode,struct file * filp)8013 static int btf_release(struct inode *inode, struct file *filp)
8014 {
8015 btf_put(filp->private_data);
8016 return 0;
8017 }
8018
8019 const struct file_operations btf_fops = {
8020 #ifdef CONFIG_PROC_FS
8021 .show_fdinfo = bpf_btf_show_fdinfo,
8022 #endif
8023 .release = btf_release,
8024 };
8025
__btf_new_fd(struct btf * btf)8026 static int __btf_new_fd(struct btf *btf)
8027 {
8028 return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
8029 }
8030
btf_new_fd(const union bpf_attr * attr,bpfptr_t uattr,u32 uattr_size)8031 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
8032 {
8033 struct btf *btf;
8034 int ret;
8035
8036 btf = btf_parse(attr, uattr, uattr_size);
8037 if (IS_ERR(btf))
8038 return PTR_ERR(btf);
8039
8040 ret = btf_alloc_id(btf);
8041 if (ret) {
8042 btf_free(btf);
8043 return ret;
8044 }
8045
8046 /*
8047 * The BTF ID is published to the userspace.
8048 * All BTF free must go through call_rcu() from
8049 * now on (i.e. free by calling btf_put()).
8050 */
8051
8052 ret = __btf_new_fd(btf);
8053 if (ret < 0)
8054 btf_put(btf);
8055
8056 return ret;
8057 }
8058
btf_get_by_fd(int fd)8059 struct btf *btf_get_by_fd(int fd)
8060 {
8061 struct btf *btf;
8062 CLASS(fd, f)(fd);
8063
8064 btf = __btf_get_by_fd(f);
8065 if (!IS_ERR(btf))
8066 refcount_inc(&btf->refcnt);
8067
8068 return btf;
8069 }
8070
btf_get_info_by_fd(const struct btf * btf,const union bpf_attr * attr,union bpf_attr __user * uattr)8071 int btf_get_info_by_fd(const struct btf *btf,
8072 const union bpf_attr *attr,
8073 union bpf_attr __user *uattr)
8074 {
8075 struct bpf_btf_info __user *uinfo;
8076 struct bpf_btf_info info;
8077 u32 info_copy, btf_copy;
8078 void __user *ubtf;
8079 char __user *uname;
8080 u32 uinfo_len, uname_len, name_len;
8081 int ret = 0;
8082
8083 uinfo = u64_to_user_ptr(attr->info.info);
8084 uinfo_len = attr->info.info_len;
8085
8086 info_copy = min_t(u32, uinfo_len, sizeof(info));
8087 memset(&info, 0, sizeof(info));
8088 if (copy_from_user(&info, uinfo, info_copy))
8089 return -EFAULT;
8090
8091 info.id = btf->id;
8092 ubtf = u64_to_user_ptr(info.btf);
8093 btf_copy = min_t(u32, btf->data_size, info.btf_size);
8094 if (copy_to_user(ubtf, btf->data, btf_copy))
8095 return -EFAULT;
8096 info.btf_size = btf->data_size;
8097
8098 info.kernel_btf = btf->kernel_btf;
8099
8100 uname = u64_to_user_ptr(info.name);
8101 uname_len = info.name_len;
8102 if (!uname ^ !uname_len)
8103 return -EINVAL;
8104
8105 name_len = strlen(btf->name);
8106 info.name_len = name_len;
8107
8108 if (uname) {
8109 if (uname_len >= name_len + 1) {
8110 if (copy_to_user(uname, btf->name, name_len + 1))
8111 return -EFAULT;
8112 } else {
8113 char zero = '\0';
8114
8115 if (copy_to_user(uname, btf->name, uname_len - 1))
8116 return -EFAULT;
8117 if (put_user(zero, uname + uname_len - 1))
8118 return -EFAULT;
8119 /* let user-space know about too short buffer */
8120 ret = -ENOSPC;
8121 }
8122 }
8123
8124 if (copy_to_user(uinfo, &info, info_copy) ||
8125 put_user(info_copy, &uattr->info.info_len))
8126 return -EFAULT;
8127
8128 return ret;
8129 }
8130
btf_get_fd_by_id(u32 id)8131 int btf_get_fd_by_id(u32 id)
8132 {
8133 struct btf *btf;
8134 int fd;
8135
8136 rcu_read_lock();
8137 btf = idr_find(&btf_idr, id);
8138 if (!btf || !refcount_inc_not_zero(&btf->refcnt))
8139 btf = ERR_PTR(-ENOENT);
8140 rcu_read_unlock();
8141
8142 if (IS_ERR(btf))
8143 return PTR_ERR(btf);
8144
8145 fd = __btf_new_fd(btf);
8146 if (fd < 0)
8147 btf_put(btf);
8148
8149 return fd;
8150 }
8151
btf_obj_id(const struct btf * btf)8152 u32 btf_obj_id(const struct btf *btf)
8153 {
8154 return btf->id;
8155 }
8156
btf_is_kernel(const struct btf * btf)8157 bool btf_is_kernel(const struct btf *btf)
8158 {
8159 return btf->kernel_btf;
8160 }
8161
btf_is_module(const struct btf * btf)8162 bool btf_is_module(const struct btf *btf)
8163 {
8164 return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
8165 }
8166
8167 enum {
8168 BTF_MODULE_F_LIVE = (1 << 0),
8169 };
8170
8171 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8172 struct btf_module {
8173 struct list_head list;
8174 struct module *module;
8175 struct btf *btf;
8176 struct bin_attribute *sysfs_attr;
8177 int flags;
8178 };
8179
8180 static LIST_HEAD(btf_modules);
8181 static DEFINE_MUTEX(btf_module_mutex);
8182
8183 static void purge_cand_cache(struct btf *btf);
8184
btf_module_notify(struct notifier_block * nb,unsigned long op,void * module)8185 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
8186 void *module)
8187 {
8188 struct btf_module *btf_mod, *tmp;
8189 struct module *mod = module;
8190 struct btf *btf;
8191 int err = 0;
8192
8193 if (mod->btf_data_size == 0 ||
8194 (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
8195 op != MODULE_STATE_GOING))
8196 goto out;
8197
8198 switch (op) {
8199 case MODULE_STATE_COMING:
8200 btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
8201 if (!btf_mod) {
8202 err = -ENOMEM;
8203 goto out;
8204 }
8205 btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size,
8206 mod->btf_base_data, mod->btf_base_data_size);
8207 if (IS_ERR(btf)) {
8208 kfree(btf_mod);
8209 if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
8210 pr_warn("failed to validate module [%s] BTF: %ld\n",
8211 mod->name, PTR_ERR(btf));
8212 err = PTR_ERR(btf);
8213 } else {
8214 pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
8215 }
8216 goto out;
8217 }
8218 err = btf_alloc_id(btf);
8219 if (err) {
8220 btf_free(btf);
8221 kfree(btf_mod);
8222 goto out;
8223 }
8224
8225 purge_cand_cache(NULL);
8226 mutex_lock(&btf_module_mutex);
8227 btf_mod->module = module;
8228 btf_mod->btf = btf;
8229 list_add(&btf_mod->list, &btf_modules);
8230 mutex_unlock(&btf_module_mutex);
8231
8232 if (IS_ENABLED(CONFIG_SYSFS)) {
8233 struct bin_attribute *attr;
8234
8235 attr = kzalloc(sizeof(*attr), GFP_KERNEL);
8236 if (!attr)
8237 goto out;
8238
8239 sysfs_bin_attr_init(attr);
8240 attr->attr.name = btf->name;
8241 attr->attr.mode = 0444;
8242 attr->size = btf->data_size;
8243 attr->private = btf->data;
8244 attr->read = sysfs_bin_attr_simple_read;
8245
8246 err = sysfs_create_bin_file(btf_kobj, attr);
8247 if (err) {
8248 pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
8249 mod->name, err);
8250 kfree(attr);
8251 err = 0;
8252 goto out;
8253 }
8254
8255 btf_mod->sysfs_attr = attr;
8256 }
8257
8258 break;
8259 case MODULE_STATE_LIVE:
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 btf_mod->flags |= BTF_MODULE_F_LIVE;
8266 break;
8267 }
8268 mutex_unlock(&btf_module_mutex);
8269 break;
8270 case MODULE_STATE_GOING:
8271 mutex_lock(&btf_module_mutex);
8272 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8273 if (btf_mod->module != module)
8274 continue;
8275
8276 list_del(&btf_mod->list);
8277 if (btf_mod->sysfs_attr)
8278 sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
8279 purge_cand_cache(btf_mod->btf);
8280 btf_put(btf_mod->btf);
8281 kfree(btf_mod->sysfs_attr);
8282 kfree(btf_mod);
8283 break;
8284 }
8285 mutex_unlock(&btf_module_mutex);
8286 break;
8287 }
8288 out:
8289 return notifier_from_errno(err);
8290 }
8291
8292 static struct notifier_block btf_module_nb = {
8293 .notifier_call = btf_module_notify,
8294 };
8295
btf_module_init(void)8296 static int __init btf_module_init(void)
8297 {
8298 register_module_notifier(&btf_module_nb);
8299 return 0;
8300 }
8301
8302 fs_initcall(btf_module_init);
8303 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
8304
btf_try_get_module(const struct btf * btf)8305 struct module *btf_try_get_module(const struct btf *btf)
8306 {
8307 struct module *res = NULL;
8308 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8309 struct btf_module *btf_mod, *tmp;
8310
8311 mutex_lock(&btf_module_mutex);
8312 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8313 if (btf_mod->btf != btf)
8314 continue;
8315
8316 /* We must only consider module whose __init routine has
8317 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
8318 * which is set from the notifier callback for
8319 * MODULE_STATE_LIVE.
8320 */
8321 if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
8322 res = btf_mod->module;
8323
8324 break;
8325 }
8326 mutex_unlock(&btf_module_mutex);
8327 #endif
8328
8329 return res;
8330 }
8331
8332 /* Returns struct btf corresponding to the struct module.
8333 * This function can return NULL or ERR_PTR.
8334 */
btf_get_module_btf(const struct module * module)8335 static struct btf *btf_get_module_btf(const struct module *module)
8336 {
8337 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8338 struct btf_module *btf_mod, *tmp;
8339 #endif
8340 struct btf *btf = NULL;
8341
8342 if (!module) {
8343 btf = bpf_get_btf_vmlinux();
8344 if (!IS_ERR_OR_NULL(btf))
8345 btf_get(btf);
8346 return btf;
8347 }
8348
8349 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8350 mutex_lock(&btf_module_mutex);
8351 list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
8352 if (btf_mod->module != module)
8353 continue;
8354
8355 btf_get(btf_mod->btf);
8356 btf = btf_mod->btf;
8357 break;
8358 }
8359 mutex_unlock(&btf_module_mutex);
8360 #endif
8361
8362 return btf;
8363 }
8364
check_btf_kconfigs(const struct module * module,const char * feature)8365 static int check_btf_kconfigs(const struct module *module, const char *feature)
8366 {
8367 if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
8368 pr_err("missing vmlinux BTF, cannot register %s\n", feature);
8369 return -ENOENT;
8370 }
8371 if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
8372 pr_warn("missing module BTF, cannot register %s\n", feature);
8373 return 0;
8374 }
8375
BPF_CALL_4(bpf_btf_find_by_name_kind,char *,name,int,name_sz,u32,kind,int,flags)8376 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
8377 {
8378 struct btf *btf = NULL;
8379 int btf_obj_fd = 0;
8380 long ret;
8381
8382 if (flags)
8383 return -EINVAL;
8384
8385 if (name_sz <= 1 || name[name_sz - 1])
8386 return -EINVAL;
8387
8388 ret = bpf_find_btf_id(name, kind, &btf);
8389 if (ret > 0 && btf_is_module(btf)) {
8390 btf_obj_fd = __btf_new_fd(btf);
8391 if (btf_obj_fd < 0) {
8392 btf_put(btf);
8393 return btf_obj_fd;
8394 }
8395 return ret | (((u64)btf_obj_fd) << 32);
8396 }
8397 if (ret > 0)
8398 btf_put(btf);
8399 return ret;
8400 }
8401
8402 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
8403 .func = bpf_btf_find_by_name_kind,
8404 .gpl_only = false,
8405 .ret_type = RET_INTEGER,
8406 .arg1_type = ARG_PTR_TO_MEM | MEM_RDONLY,
8407 .arg2_type = ARG_CONST_SIZE,
8408 .arg3_type = ARG_ANYTHING,
8409 .arg4_type = ARG_ANYTHING,
8410 };
8411
BTF_ID_LIST_GLOBAL(btf_tracing_ids,MAX_BTF_TRACING_TYPE)8412 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
8413 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
8414 BTF_TRACING_TYPE_xxx
8415 #undef BTF_TRACING_TYPE
8416
8417 /* Validate well-formedness of iter argument type.
8418 * On success, return positive BTF ID of iter state's STRUCT type.
8419 * On error, negative error is returned.
8420 */
8421 int btf_check_iter_arg(struct btf *btf, const struct btf_type *func, int arg_idx)
8422 {
8423 const struct btf_param *arg;
8424 const struct btf_type *t;
8425 const char *name;
8426 int btf_id;
8427
8428 if (btf_type_vlen(func) <= arg_idx)
8429 return -EINVAL;
8430
8431 arg = &btf_params(func)[arg_idx];
8432 t = btf_type_skip_modifiers(btf, arg->type, NULL);
8433 if (!t || !btf_type_is_ptr(t))
8434 return -EINVAL;
8435 t = btf_type_skip_modifiers(btf, t->type, &btf_id);
8436 if (!t || !__btf_type_is_struct(t))
8437 return -EINVAL;
8438
8439 name = btf_name_by_offset(btf, t->name_off);
8440 if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
8441 return -EINVAL;
8442
8443 return btf_id;
8444 }
8445
btf_check_iter_kfuncs(struct btf * btf,const char * func_name,const struct btf_type * func,u32 func_flags)8446 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
8447 const struct btf_type *func, u32 func_flags)
8448 {
8449 u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8450 const char *sfx, *iter_name;
8451 const struct btf_type *t;
8452 char exp_name[128];
8453 u32 nr_args;
8454 int btf_id;
8455
8456 /* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
8457 if (!flags || (flags & (flags - 1)))
8458 return -EINVAL;
8459
8460 /* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
8461 nr_args = btf_type_vlen(func);
8462 if (nr_args < 1)
8463 return -EINVAL;
8464
8465 btf_id = btf_check_iter_arg(btf, func, 0);
8466 if (btf_id < 0)
8467 return btf_id;
8468
8469 /* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
8470 * fit nicely in stack slots
8471 */
8472 t = btf_type_by_id(btf, btf_id);
8473 if (t->size == 0 || (t->size % 8))
8474 return -EINVAL;
8475
8476 /* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
8477 * naming pattern
8478 */
8479 iter_name = btf_name_by_offset(btf, t->name_off) + sizeof(ITER_PREFIX) - 1;
8480 if (flags & KF_ITER_NEW)
8481 sfx = "new";
8482 else if (flags & KF_ITER_NEXT)
8483 sfx = "next";
8484 else /* (flags & KF_ITER_DESTROY) */
8485 sfx = "destroy";
8486
8487 snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
8488 if (strcmp(func_name, exp_name))
8489 return -EINVAL;
8490
8491 /* only iter constructor should have extra arguments */
8492 if (!(flags & KF_ITER_NEW) && nr_args != 1)
8493 return -EINVAL;
8494
8495 if (flags & KF_ITER_NEXT) {
8496 /* bpf_iter_<type>_next() should return pointer */
8497 t = btf_type_skip_modifiers(btf, func->type, NULL);
8498 if (!t || !btf_type_is_ptr(t))
8499 return -EINVAL;
8500 }
8501
8502 if (flags & KF_ITER_DESTROY) {
8503 /* bpf_iter_<type>_destroy() should return void */
8504 t = btf_type_by_id(btf, func->type);
8505 if (!t || !btf_type_is_void(t))
8506 return -EINVAL;
8507 }
8508
8509 return 0;
8510 }
8511
btf_check_kfunc_protos(struct btf * btf,u32 func_id,u32 func_flags)8512 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
8513 {
8514 const struct btf_type *func;
8515 const char *func_name;
8516 int err;
8517
8518 /* any kfunc should be FUNC -> FUNC_PROTO */
8519 func = btf_type_by_id(btf, func_id);
8520 if (!func || !btf_type_is_func(func))
8521 return -EINVAL;
8522
8523 /* sanity check kfunc name */
8524 func_name = btf_name_by_offset(btf, func->name_off);
8525 if (!func_name || !func_name[0])
8526 return -EINVAL;
8527
8528 func = btf_type_by_id(btf, func->type);
8529 if (!func || !btf_type_is_func_proto(func))
8530 return -EINVAL;
8531
8532 if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
8533 err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
8534 if (err)
8535 return err;
8536 }
8537
8538 return 0;
8539 }
8540
8541 /* Kernel Function (kfunc) BTF ID set registration API */
8542
btf_populate_kfunc_set(struct btf * btf,enum btf_kfunc_hook hook,const struct btf_kfunc_id_set * kset)8543 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
8544 const struct btf_kfunc_id_set *kset)
8545 {
8546 struct btf_kfunc_hook_filter *hook_filter;
8547 struct btf_id_set8 *add_set = kset->set;
8548 bool vmlinux_set = !btf_is_module(btf);
8549 bool add_filter = !!kset->filter;
8550 struct btf_kfunc_set_tab *tab;
8551 struct btf_id_set8 *set;
8552 u32 set_cnt, i;
8553 int ret;
8554
8555 if (hook >= BTF_KFUNC_HOOK_MAX) {
8556 ret = -EINVAL;
8557 goto end;
8558 }
8559
8560 if (!add_set->cnt)
8561 return 0;
8562
8563 tab = btf->kfunc_set_tab;
8564
8565 if (tab && add_filter) {
8566 u32 i;
8567
8568 hook_filter = &tab->hook_filters[hook];
8569 for (i = 0; i < hook_filter->nr_filters; i++) {
8570 if (hook_filter->filters[i] == kset->filter) {
8571 add_filter = false;
8572 break;
8573 }
8574 }
8575
8576 if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8577 ret = -E2BIG;
8578 goto end;
8579 }
8580 }
8581
8582 if (!tab) {
8583 tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
8584 if (!tab)
8585 return -ENOMEM;
8586 btf->kfunc_set_tab = tab;
8587 }
8588
8589 set = tab->sets[hook];
8590 /* Warn when register_btf_kfunc_id_set is called twice for the same hook
8591 * for module sets.
8592 */
8593 if (WARN_ON_ONCE(set && !vmlinux_set)) {
8594 ret = -EINVAL;
8595 goto end;
8596 }
8597
8598 /* In case of vmlinux sets, there may be more than one set being
8599 * registered per hook. To create a unified set, we allocate a new set
8600 * and concatenate all individual sets being registered. While each set
8601 * is individually sorted, they may become unsorted when concatenated,
8602 * hence re-sorting the final set again is required to make binary
8603 * searching the set using btf_id_set8_contains function work.
8604 *
8605 * For module sets, we need to allocate as we may need to relocate
8606 * BTF ids.
8607 */
8608 set_cnt = set ? set->cnt : 0;
8609
8610 if (set_cnt > U32_MAX - add_set->cnt) {
8611 ret = -EOVERFLOW;
8612 goto end;
8613 }
8614
8615 if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8616 ret = -E2BIG;
8617 goto end;
8618 }
8619
8620 /* Grow set */
8621 set = krealloc(tab->sets[hook],
8622 struct_size(set, pairs, set_cnt + add_set->cnt),
8623 GFP_KERNEL | __GFP_NOWARN);
8624 if (!set) {
8625 ret = -ENOMEM;
8626 goto end;
8627 }
8628
8629 /* For newly allocated set, initialize set->cnt to 0 */
8630 if (!tab->sets[hook])
8631 set->cnt = 0;
8632 tab->sets[hook] = set;
8633
8634 /* Concatenate the two sets */
8635 memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
8636 /* Now that the set is copied, update with relocated BTF ids */
8637 for (i = set->cnt; i < set->cnt + add_set->cnt; i++)
8638 set->pairs[i].id = btf_relocate_id(btf, set->pairs[i].id);
8639
8640 set->cnt += add_set->cnt;
8641
8642 sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8643
8644 if (add_filter) {
8645 hook_filter = &tab->hook_filters[hook];
8646 hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8647 }
8648 return 0;
8649 end:
8650 btf_free_kfunc_set_tab(btf);
8651 return ret;
8652 }
8653
__btf_kfunc_id_set_contains(const struct btf * btf,enum btf_kfunc_hook hook,u32 kfunc_btf_id,const struct bpf_prog * prog)8654 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
8655 enum btf_kfunc_hook hook,
8656 u32 kfunc_btf_id,
8657 const struct bpf_prog *prog)
8658 {
8659 struct btf_kfunc_hook_filter *hook_filter;
8660 struct btf_id_set8 *set;
8661 u32 *id, i;
8662
8663 if (hook >= BTF_KFUNC_HOOK_MAX)
8664 return NULL;
8665 if (!btf->kfunc_set_tab)
8666 return NULL;
8667 hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
8668 for (i = 0; i < hook_filter->nr_filters; i++) {
8669 if (hook_filter->filters[i](prog, kfunc_btf_id))
8670 return NULL;
8671 }
8672 set = btf->kfunc_set_tab->sets[hook];
8673 if (!set)
8674 return NULL;
8675 id = btf_id_set8_contains(set, kfunc_btf_id);
8676 if (!id)
8677 return NULL;
8678 /* The flags for BTF ID are located next to it */
8679 return id + 1;
8680 }
8681
bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)8682 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8683 {
8684 switch (prog_type) {
8685 case BPF_PROG_TYPE_UNSPEC:
8686 return BTF_KFUNC_HOOK_COMMON;
8687 case BPF_PROG_TYPE_XDP:
8688 return BTF_KFUNC_HOOK_XDP;
8689 case BPF_PROG_TYPE_SCHED_CLS:
8690 return BTF_KFUNC_HOOK_TC;
8691 case BPF_PROG_TYPE_STRUCT_OPS:
8692 return BTF_KFUNC_HOOK_STRUCT_OPS;
8693 case BPF_PROG_TYPE_TRACING:
8694 case BPF_PROG_TYPE_TRACEPOINT:
8695 case BPF_PROG_TYPE_PERF_EVENT:
8696 case BPF_PROG_TYPE_LSM:
8697 return BTF_KFUNC_HOOK_TRACING;
8698 case BPF_PROG_TYPE_SYSCALL:
8699 return BTF_KFUNC_HOOK_SYSCALL;
8700 case BPF_PROG_TYPE_CGROUP_SKB:
8701 case BPF_PROG_TYPE_CGROUP_SOCK:
8702 case BPF_PROG_TYPE_CGROUP_DEVICE:
8703 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8704 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8705 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8706 case BPF_PROG_TYPE_SOCK_OPS:
8707 return BTF_KFUNC_HOOK_CGROUP;
8708 case BPF_PROG_TYPE_SCHED_ACT:
8709 return BTF_KFUNC_HOOK_SCHED_ACT;
8710 case BPF_PROG_TYPE_SK_SKB:
8711 return BTF_KFUNC_HOOK_SK_SKB;
8712 case BPF_PROG_TYPE_SOCKET_FILTER:
8713 return BTF_KFUNC_HOOK_SOCKET_FILTER;
8714 case BPF_PROG_TYPE_LWT_OUT:
8715 case BPF_PROG_TYPE_LWT_IN:
8716 case BPF_PROG_TYPE_LWT_XMIT:
8717 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
8718 return BTF_KFUNC_HOOK_LWT;
8719 case BPF_PROG_TYPE_NETFILTER:
8720 return BTF_KFUNC_HOOK_NETFILTER;
8721 case BPF_PROG_TYPE_KPROBE:
8722 return BTF_KFUNC_HOOK_KPROBE;
8723 default:
8724 return BTF_KFUNC_HOOK_MAX;
8725 }
8726 }
8727
8728 /* Caution:
8729 * Reference to the module (obtained using btf_try_get_module) corresponding to
8730 * the struct btf *MUST* be held when calling this function from verifier
8731 * context. This is usually true as we stash references in prog's kfunc_btf_tab;
8732 * keeping the reference for the duration of the call provides the necessary
8733 * protection for looking up a well-formed btf->kfunc_set_tab.
8734 */
btf_kfunc_id_set_contains(const struct btf * btf,u32 kfunc_btf_id,const struct bpf_prog * prog)8735 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8736 u32 kfunc_btf_id,
8737 const struct bpf_prog *prog)
8738 {
8739 enum bpf_prog_type prog_type = resolve_prog_type(prog);
8740 enum btf_kfunc_hook hook;
8741 u32 *kfunc_flags;
8742
8743 kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
8744 if (kfunc_flags)
8745 return kfunc_flags;
8746
8747 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8748 return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
8749 }
8750
btf_kfunc_is_modify_return(const struct btf * btf,u32 kfunc_btf_id,const struct bpf_prog * prog)8751 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8752 const struct bpf_prog *prog)
8753 {
8754 return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
8755 }
8756
__register_btf_kfunc_id_set(enum btf_kfunc_hook hook,const struct btf_kfunc_id_set * kset)8757 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8758 const struct btf_kfunc_id_set *kset)
8759 {
8760 struct btf *btf;
8761 int ret, i;
8762
8763 btf = btf_get_module_btf(kset->owner);
8764 if (!btf)
8765 return check_btf_kconfigs(kset->owner, "kfunc");
8766 if (IS_ERR(btf))
8767 return PTR_ERR(btf);
8768
8769 for (i = 0; i < kset->set->cnt; i++) {
8770 ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
8771 kset->set->pairs[i].flags);
8772 if (ret)
8773 goto err_out;
8774 }
8775
8776 ret = btf_populate_kfunc_set(btf, hook, kset);
8777
8778 err_out:
8779 btf_put(btf);
8780 return ret;
8781 }
8782
8783 /* 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)8784 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
8785 const struct btf_kfunc_id_set *kset)
8786 {
8787 enum btf_kfunc_hook hook;
8788
8789 /* All kfuncs need to be tagged as such in BTF.
8790 * WARN() for initcall registrations that do not check errors.
8791 */
8792 if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8793 WARN_ON(!kset->owner);
8794 return -EINVAL;
8795 }
8796
8797 hook = bpf_prog_type_to_kfunc_hook(prog_type);
8798 return __register_btf_kfunc_id_set(hook, kset);
8799 }
8800 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8801
8802 /* This function must be invoked only from initcalls/module init functions */
register_btf_fmodret_id_set(const struct btf_kfunc_id_set * kset)8803 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
8804 {
8805 return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8806 }
8807 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8808
btf_find_dtor_kfunc(struct btf * btf,u32 btf_id)8809 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8810 {
8811 struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8812 struct btf_id_dtor_kfunc *dtor;
8813
8814 if (!tab)
8815 return -ENOENT;
8816 /* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
8817 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
8818 */
8819 BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
8820 dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
8821 if (!dtor)
8822 return -ENOENT;
8823 return dtor->kfunc_btf_id;
8824 }
8825
btf_check_dtor_kfuncs(struct btf * btf,const struct btf_id_dtor_kfunc * dtors,u32 cnt)8826 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8827 {
8828 const struct btf_type *dtor_func, *dtor_func_proto, *t;
8829 const struct btf_param *args;
8830 s32 dtor_btf_id;
8831 u32 nr_args, i;
8832
8833 for (i = 0; i < cnt; i++) {
8834 dtor_btf_id = btf_relocate_id(btf, dtors[i].kfunc_btf_id);
8835
8836 dtor_func = btf_type_by_id(btf, dtor_btf_id);
8837 if (!dtor_func || !btf_type_is_func(dtor_func))
8838 return -EINVAL;
8839
8840 dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
8841 if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
8842 return -EINVAL;
8843
8844 /* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
8845 t = btf_type_by_id(btf, dtor_func_proto->type);
8846 if (!t || !btf_type_is_void(t))
8847 return -EINVAL;
8848
8849 nr_args = btf_type_vlen(dtor_func_proto);
8850 if (nr_args != 1)
8851 return -EINVAL;
8852 args = btf_params(dtor_func_proto);
8853 t = btf_type_by_id(btf, args[0].type);
8854 /* Allow any pointer type, as width on targets Linux supports
8855 * will be same for all pointer types (i.e. sizeof(void *))
8856 */
8857 if (!t || !btf_type_is_ptr(t))
8858 return -EINVAL;
8859 }
8860 return 0;
8861 }
8862
8863 /* 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)8864 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
8865 struct module *owner)
8866 {
8867 struct btf_id_dtor_kfunc_tab *tab;
8868 struct btf *btf;
8869 u32 tab_cnt, i;
8870 int ret;
8871
8872 btf = btf_get_module_btf(owner);
8873 if (!btf)
8874 return check_btf_kconfigs(owner, "dtor kfuncs");
8875 if (IS_ERR(btf))
8876 return PTR_ERR(btf);
8877
8878 if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8879 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8880 ret = -E2BIG;
8881 goto end;
8882 }
8883
8884 /* Ensure that the prototype of dtor kfuncs being registered is sane */
8885 ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8886 if (ret < 0)
8887 goto end;
8888
8889 tab = btf->dtor_kfunc_tab;
8890 /* Only one call allowed for modules */
8891 if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8892 ret = -EINVAL;
8893 goto end;
8894 }
8895
8896 tab_cnt = tab ? tab->cnt : 0;
8897 if (tab_cnt > U32_MAX - add_cnt) {
8898 ret = -EOVERFLOW;
8899 goto end;
8900 }
8901 if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8902 pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8903 ret = -E2BIG;
8904 goto end;
8905 }
8906
8907 tab = krealloc(btf->dtor_kfunc_tab,
8908 struct_size(tab, dtors, tab_cnt + add_cnt),
8909 GFP_KERNEL | __GFP_NOWARN);
8910 if (!tab) {
8911 ret = -ENOMEM;
8912 goto end;
8913 }
8914
8915 if (!btf->dtor_kfunc_tab)
8916 tab->cnt = 0;
8917 btf->dtor_kfunc_tab = tab;
8918
8919 memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8920
8921 /* remap BTF ids based on BTF relocation (if any) */
8922 for (i = tab_cnt; i < tab_cnt + add_cnt; i++) {
8923 tab->dtors[i].btf_id = btf_relocate_id(btf, tab->dtors[i].btf_id);
8924 tab->dtors[i].kfunc_btf_id = btf_relocate_id(btf, tab->dtors[i].kfunc_btf_id);
8925 }
8926
8927 tab->cnt += add_cnt;
8928
8929 sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8930
8931 end:
8932 if (ret)
8933 btf_free_dtor_kfunc_tab(btf);
8934 btf_put(btf);
8935 return ret;
8936 }
8937 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8938
8939 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8940
8941 /* Check local and target types for compatibility. This check is used for
8942 * type-based CO-RE relocations and follow slightly different rules than
8943 * field-based relocations. This function assumes that root types were already
8944 * checked for name match. Beyond that initial root-level name check, names
8945 * are completely ignored. Compatibility rules are as follows:
8946 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8947 * kind should match for local and target types (i.e., STRUCT is not
8948 * compatible with UNION);
8949 * - for ENUMs/ENUM64s, the size is ignored;
8950 * - for INT, size and signedness are ignored;
8951 * - for ARRAY, dimensionality is ignored, element types are checked for
8952 * compatibility recursively;
8953 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
8954 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8955 * - FUNC_PROTOs are compatible if they have compatible signature: same
8956 * number of input args and compatible return and argument types.
8957 * These rules are not set in stone and probably will be adjusted as we get
8958 * more experience with using BPF CO-RE relocations.
8959 */
bpf_core_types_are_compat(const struct btf * local_btf,__u32 local_id,const struct btf * targ_btf,__u32 targ_id)8960 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8961 const struct btf *targ_btf, __u32 targ_id)
8962 {
8963 return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8964 MAX_TYPES_ARE_COMPAT_DEPTH);
8965 }
8966
8967 #define MAX_TYPES_MATCH_DEPTH 2
8968
bpf_core_types_match(const struct btf * local_btf,u32 local_id,const struct btf * targ_btf,u32 targ_id)8969 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8970 const struct btf *targ_btf, u32 targ_id)
8971 {
8972 return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8973 MAX_TYPES_MATCH_DEPTH);
8974 }
8975
bpf_core_is_flavor_sep(const char * s)8976 static bool bpf_core_is_flavor_sep(const char *s)
8977 {
8978 /* check X___Y name pattern, where X and Y are not underscores */
8979 return s[0] != '_' && /* X */
8980 s[1] == '_' && s[2] == '_' && s[3] == '_' && /* ___ */
8981 s[4] != '_'; /* Y */
8982 }
8983
bpf_core_essential_name_len(const char * name)8984 size_t bpf_core_essential_name_len(const char *name)
8985 {
8986 size_t n = strlen(name);
8987 int i;
8988
8989 for (i = n - 5; i >= 0; i--) {
8990 if (bpf_core_is_flavor_sep(name + i))
8991 return i + 1;
8992 }
8993 return n;
8994 }
8995
bpf_free_cands(struct bpf_cand_cache * cands)8996 static void bpf_free_cands(struct bpf_cand_cache *cands)
8997 {
8998 if (!cands->cnt)
8999 /* empty candidate array was allocated on stack */
9000 return;
9001 kfree(cands);
9002 }
9003
bpf_free_cands_from_cache(struct bpf_cand_cache * cands)9004 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
9005 {
9006 kfree(cands->name);
9007 kfree(cands);
9008 }
9009
9010 #define VMLINUX_CAND_CACHE_SIZE 31
9011 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
9012
9013 #define MODULE_CAND_CACHE_SIZE 31
9014 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
9015
__print_cand_cache(struct bpf_verifier_log * log,struct bpf_cand_cache ** cache,int cache_size)9016 static void __print_cand_cache(struct bpf_verifier_log *log,
9017 struct bpf_cand_cache **cache,
9018 int cache_size)
9019 {
9020 struct bpf_cand_cache *cc;
9021 int i, j;
9022
9023 for (i = 0; i < cache_size; i++) {
9024 cc = cache[i];
9025 if (!cc)
9026 continue;
9027 bpf_log(log, "[%d]%s(", i, cc->name);
9028 for (j = 0; j < cc->cnt; j++) {
9029 bpf_log(log, "%d", cc->cands[j].id);
9030 if (j < cc->cnt - 1)
9031 bpf_log(log, " ");
9032 }
9033 bpf_log(log, "), ");
9034 }
9035 }
9036
print_cand_cache(struct bpf_verifier_log * log)9037 static void print_cand_cache(struct bpf_verifier_log *log)
9038 {
9039 mutex_lock(&cand_cache_mutex);
9040 bpf_log(log, "vmlinux_cand_cache:");
9041 __print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9042 bpf_log(log, "\nmodule_cand_cache:");
9043 __print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9044 bpf_log(log, "\n");
9045 mutex_unlock(&cand_cache_mutex);
9046 }
9047
hash_cands(struct bpf_cand_cache * cands)9048 static u32 hash_cands(struct bpf_cand_cache *cands)
9049 {
9050 return jhash(cands->name, cands->name_len, 0);
9051 }
9052
check_cand_cache(struct bpf_cand_cache * cands,struct bpf_cand_cache ** cache,int cache_size)9053 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
9054 struct bpf_cand_cache **cache,
9055 int cache_size)
9056 {
9057 struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
9058
9059 if (cc && cc->name_len == cands->name_len &&
9060 !strncmp(cc->name, cands->name, cands->name_len))
9061 return cc;
9062 return NULL;
9063 }
9064
sizeof_cands(int cnt)9065 static size_t sizeof_cands(int cnt)
9066 {
9067 return offsetof(struct bpf_cand_cache, cands[cnt]);
9068 }
9069
populate_cand_cache(struct bpf_cand_cache * cands,struct bpf_cand_cache ** cache,int cache_size)9070 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
9071 struct bpf_cand_cache **cache,
9072 int cache_size)
9073 {
9074 struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
9075
9076 if (*cc) {
9077 bpf_free_cands_from_cache(*cc);
9078 *cc = NULL;
9079 }
9080 new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL_ACCOUNT);
9081 if (!new_cands) {
9082 bpf_free_cands(cands);
9083 return ERR_PTR(-ENOMEM);
9084 }
9085 /* strdup the name, since it will stay in cache.
9086 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
9087 */
9088 new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL_ACCOUNT);
9089 bpf_free_cands(cands);
9090 if (!new_cands->name) {
9091 kfree(new_cands);
9092 return ERR_PTR(-ENOMEM);
9093 }
9094 *cc = new_cands;
9095 return new_cands;
9096 }
9097
9098 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
__purge_cand_cache(struct btf * btf,struct bpf_cand_cache ** cache,int cache_size)9099 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
9100 int cache_size)
9101 {
9102 struct bpf_cand_cache *cc;
9103 int i, j;
9104
9105 for (i = 0; i < cache_size; i++) {
9106 cc = cache[i];
9107 if (!cc)
9108 continue;
9109 if (!btf) {
9110 /* when new module is loaded purge all of module_cand_cache,
9111 * since new module might have candidates with the name
9112 * that matches cached cands.
9113 */
9114 bpf_free_cands_from_cache(cc);
9115 cache[i] = NULL;
9116 continue;
9117 }
9118 /* when module is unloaded purge cache entries
9119 * that match module's btf
9120 */
9121 for (j = 0; j < cc->cnt; j++)
9122 if (cc->cands[j].btf == btf) {
9123 bpf_free_cands_from_cache(cc);
9124 cache[i] = NULL;
9125 break;
9126 }
9127 }
9128
9129 }
9130
purge_cand_cache(struct btf * btf)9131 static void purge_cand_cache(struct btf *btf)
9132 {
9133 mutex_lock(&cand_cache_mutex);
9134 __purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9135 mutex_unlock(&cand_cache_mutex);
9136 }
9137 #endif
9138
9139 static struct bpf_cand_cache *
bpf_core_add_cands(struct bpf_cand_cache * cands,const struct btf * targ_btf,int targ_start_id)9140 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
9141 int targ_start_id)
9142 {
9143 struct bpf_cand_cache *new_cands;
9144 const struct btf_type *t;
9145 const char *targ_name;
9146 size_t targ_essent_len;
9147 int n, i;
9148
9149 n = btf_nr_types(targ_btf);
9150 for (i = targ_start_id; i < n; i++) {
9151 t = btf_type_by_id(targ_btf, i);
9152 if (btf_kind(t) != cands->kind)
9153 continue;
9154
9155 targ_name = btf_name_by_offset(targ_btf, t->name_off);
9156 if (!targ_name)
9157 continue;
9158
9159 /* the resched point is before strncmp to make sure that search
9160 * for non-existing name will have a chance to schedule().
9161 */
9162 cond_resched();
9163
9164 if (strncmp(cands->name, targ_name, cands->name_len) != 0)
9165 continue;
9166
9167 targ_essent_len = bpf_core_essential_name_len(targ_name);
9168 if (targ_essent_len != cands->name_len)
9169 continue;
9170
9171 /* most of the time there is only one candidate for a given kind+name pair */
9172 new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL_ACCOUNT);
9173 if (!new_cands) {
9174 bpf_free_cands(cands);
9175 return ERR_PTR(-ENOMEM);
9176 }
9177
9178 memcpy(new_cands, cands, sizeof_cands(cands->cnt));
9179 bpf_free_cands(cands);
9180 cands = new_cands;
9181 cands->cands[cands->cnt].btf = targ_btf;
9182 cands->cands[cands->cnt].id = i;
9183 cands->cnt++;
9184 }
9185 return cands;
9186 }
9187
9188 static struct bpf_cand_cache *
bpf_core_find_cands(struct bpf_core_ctx * ctx,u32 local_type_id)9189 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
9190 {
9191 struct bpf_cand_cache *cands, *cc, local_cand = {};
9192 const struct btf *local_btf = ctx->btf;
9193 const struct btf_type *local_type;
9194 const struct btf *main_btf;
9195 size_t local_essent_len;
9196 struct btf *mod_btf;
9197 const char *name;
9198 int id;
9199
9200 main_btf = bpf_get_btf_vmlinux();
9201 if (IS_ERR(main_btf))
9202 return ERR_CAST(main_btf);
9203 if (!main_btf)
9204 return ERR_PTR(-EINVAL);
9205
9206 local_type = btf_type_by_id(local_btf, local_type_id);
9207 if (!local_type)
9208 return ERR_PTR(-EINVAL);
9209
9210 name = btf_name_by_offset(local_btf, local_type->name_off);
9211 if (str_is_empty(name))
9212 return ERR_PTR(-EINVAL);
9213 local_essent_len = bpf_core_essential_name_len(name);
9214
9215 cands = &local_cand;
9216 cands->name = name;
9217 cands->kind = btf_kind(local_type);
9218 cands->name_len = local_essent_len;
9219
9220 cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9221 /* cands is a pointer to stack here */
9222 if (cc) {
9223 if (cc->cnt)
9224 return cc;
9225 goto check_modules;
9226 }
9227
9228 /* Attempt to find target candidates in vmlinux BTF first */
9229 cands = bpf_core_add_cands(cands, main_btf, 1);
9230 if (IS_ERR(cands))
9231 return ERR_CAST(cands);
9232
9233 /* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
9234
9235 /* populate cache even when cands->cnt == 0 */
9236 cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9237 if (IS_ERR(cc))
9238 return ERR_CAST(cc);
9239
9240 /* if vmlinux BTF has any candidate, don't go for module BTFs */
9241 if (cc->cnt)
9242 return cc;
9243
9244 check_modules:
9245 /* cands is a pointer to stack here and cands->cnt == 0 */
9246 cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9247 if (cc)
9248 /* if cache has it return it even if cc->cnt == 0 */
9249 return cc;
9250
9251 /* If candidate is not found in vmlinux's BTF then search in module's BTFs */
9252 spin_lock_bh(&btf_idr_lock);
9253 idr_for_each_entry(&btf_idr, mod_btf, id) {
9254 if (!btf_is_module(mod_btf))
9255 continue;
9256 /* linear search could be slow hence unlock/lock
9257 * the IDR to avoiding holding it for too long
9258 */
9259 btf_get(mod_btf);
9260 spin_unlock_bh(&btf_idr_lock);
9261 cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
9262 btf_put(mod_btf);
9263 if (IS_ERR(cands))
9264 return ERR_CAST(cands);
9265 spin_lock_bh(&btf_idr_lock);
9266 }
9267 spin_unlock_bh(&btf_idr_lock);
9268 /* cands is a pointer to kmalloced memory here if cands->cnt > 0
9269 * or pointer to stack if cands->cnd == 0.
9270 * Copy it into the cache even when cands->cnt == 0 and
9271 * return the result.
9272 */
9273 return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9274 }
9275
bpf_core_apply(struct bpf_core_ctx * ctx,const struct bpf_core_relo * relo,int relo_idx,void * insn)9276 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
9277 int relo_idx, void *insn)
9278 {
9279 bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
9280 struct bpf_core_cand_list cands = {};
9281 struct bpf_core_relo_res targ_res;
9282 struct bpf_core_spec *specs;
9283 const struct btf_type *type;
9284 int err;
9285
9286 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
9287 * into arrays of btf_ids of struct fields and array indices.
9288 */
9289 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL_ACCOUNT);
9290 if (!specs)
9291 return -ENOMEM;
9292
9293 type = btf_type_by_id(ctx->btf, relo->type_id);
9294 if (!type) {
9295 bpf_log(ctx->log, "relo #%u: bad type id %u\n",
9296 relo_idx, relo->type_id);
9297 kfree(specs);
9298 return -EINVAL;
9299 }
9300
9301 if (need_cands) {
9302 struct bpf_cand_cache *cc;
9303 int i;
9304
9305 mutex_lock(&cand_cache_mutex);
9306 cc = bpf_core_find_cands(ctx, relo->type_id);
9307 if (IS_ERR(cc)) {
9308 bpf_log(ctx->log, "target candidate search failed for %d\n",
9309 relo->type_id);
9310 err = PTR_ERR(cc);
9311 goto out;
9312 }
9313 if (cc->cnt) {
9314 cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL_ACCOUNT);
9315 if (!cands.cands) {
9316 err = -ENOMEM;
9317 goto out;
9318 }
9319 }
9320 for (i = 0; i < cc->cnt; i++) {
9321 bpf_log(ctx->log,
9322 "CO-RE relocating %s %s: found target candidate [%d]\n",
9323 btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
9324 cands.cands[i].btf = cc->cands[i].btf;
9325 cands.cands[i].id = cc->cands[i].id;
9326 }
9327 cands.len = cc->cnt;
9328 /* cand_cache_mutex needs to span the cache lookup and
9329 * copy of btf pointer into bpf_core_cand_list,
9330 * since module can be unloaded while bpf_core_calc_relo_insn
9331 * is working with module's btf.
9332 */
9333 }
9334
9335 err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
9336 &targ_res);
9337 if (err)
9338 goto out;
9339
9340 err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
9341 &targ_res);
9342
9343 out:
9344 kfree(specs);
9345 if (need_cands) {
9346 kfree(cands.cands);
9347 mutex_unlock(&cand_cache_mutex);
9348 if (ctx->log->level & BPF_LOG_LEVEL2)
9349 print_cand_cache(ctx->log);
9350 }
9351 return err;
9352 }
9353
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)9354 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
9355 const struct bpf_reg_state *reg,
9356 const char *field_name, u32 btf_id, const char *suffix)
9357 {
9358 struct btf *btf = reg->btf;
9359 const struct btf_type *walk_type, *safe_type;
9360 const char *tname;
9361 char safe_tname[64];
9362 long ret, safe_id;
9363 const struct btf_member *member;
9364 u32 i;
9365
9366 walk_type = btf_type_by_id(btf, reg->btf_id);
9367 if (!walk_type)
9368 return false;
9369
9370 tname = btf_name_by_offset(btf, walk_type->name_off);
9371
9372 ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
9373 if (ret >= sizeof(safe_tname))
9374 return false;
9375
9376 safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
9377 if (safe_id < 0)
9378 return false;
9379
9380 safe_type = btf_type_by_id(btf, safe_id);
9381 if (!safe_type)
9382 return false;
9383
9384 for_each_member(i, safe_type, member) {
9385 const char *m_name = __btf_name_by_offset(btf, member->name_off);
9386 const struct btf_type *mtype = btf_type_by_id(btf, member->type);
9387 u32 id;
9388
9389 if (!btf_type_is_ptr(mtype))
9390 continue;
9391
9392 btf_type_skip_modifiers(btf, mtype->type, &id);
9393 /* If we match on both type and name, the field is considered trusted. */
9394 if (btf_id == id && !strcmp(field_name, m_name))
9395 return true;
9396 }
9397
9398 return false;
9399 }
9400
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)9401 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
9402 const struct btf *reg_btf, u32 reg_id,
9403 const struct btf *arg_btf, u32 arg_id)
9404 {
9405 const char *reg_name, *arg_name, *search_needle;
9406 const struct btf_type *reg_type, *arg_type;
9407 int reg_len, arg_len, cmp_len;
9408 size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
9409
9410 reg_type = btf_type_by_id(reg_btf, reg_id);
9411 if (!reg_type)
9412 return false;
9413
9414 arg_type = btf_type_by_id(arg_btf, arg_id);
9415 if (!arg_type)
9416 return false;
9417
9418 reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
9419 arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
9420
9421 reg_len = strlen(reg_name);
9422 arg_len = strlen(arg_name);
9423
9424 /* Exactly one of the two type names may be suffixed with ___init, so
9425 * if the strings are the same size, they can't possibly be no-cast
9426 * aliases of one another. If you have two of the same type names, e.g.
9427 * they're both nf_conn___init, it would be improper to return true
9428 * because they are _not_ no-cast aliases, they are the same type.
9429 */
9430 if (reg_len == arg_len)
9431 return false;
9432
9433 /* Either of the two names must be the other name, suffixed with ___init. */
9434 if ((reg_len != arg_len + pattern_len) &&
9435 (arg_len != reg_len + pattern_len))
9436 return false;
9437
9438 if (reg_len < arg_len) {
9439 search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
9440 cmp_len = reg_len;
9441 } else {
9442 search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
9443 cmp_len = arg_len;
9444 }
9445
9446 if (!search_needle)
9447 return false;
9448
9449 /* ___init suffix must come at the end of the name */
9450 if (*(search_needle + pattern_len) != '\0')
9451 return false;
9452
9453 return !strncmp(reg_name, arg_name, cmp_len);
9454 }
9455
9456 #ifdef CONFIG_BPF_JIT
9457 static int
btf_add_struct_ops(struct btf * btf,struct bpf_struct_ops * st_ops,struct bpf_verifier_log * log)9458 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
9459 struct bpf_verifier_log *log)
9460 {
9461 struct btf_struct_ops_tab *tab, *new_tab;
9462 int i, err;
9463
9464 tab = btf->struct_ops_tab;
9465 if (!tab) {
9466 tab = kzalloc(struct_size(tab, ops, 4), GFP_KERNEL);
9467 if (!tab)
9468 return -ENOMEM;
9469 tab->capacity = 4;
9470 btf->struct_ops_tab = tab;
9471 }
9472
9473 for (i = 0; i < tab->cnt; i++)
9474 if (tab->ops[i].st_ops == st_ops)
9475 return -EEXIST;
9476
9477 if (tab->cnt == tab->capacity) {
9478 new_tab = krealloc(tab,
9479 struct_size(tab, ops, tab->capacity * 2),
9480 GFP_KERNEL);
9481 if (!new_tab)
9482 return -ENOMEM;
9483 tab = new_tab;
9484 tab->capacity *= 2;
9485 btf->struct_ops_tab = tab;
9486 }
9487
9488 tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
9489
9490 err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
9491 if (err)
9492 return err;
9493
9494 btf->struct_ops_tab->cnt++;
9495
9496 return 0;
9497 }
9498
9499 const struct bpf_struct_ops_desc *
bpf_struct_ops_find_value(struct btf * btf,u32 value_id)9500 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
9501 {
9502 const struct bpf_struct_ops_desc *st_ops_list;
9503 unsigned int i;
9504 u32 cnt;
9505
9506 if (!value_id)
9507 return NULL;
9508 if (!btf->struct_ops_tab)
9509 return NULL;
9510
9511 cnt = btf->struct_ops_tab->cnt;
9512 st_ops_list = btf->struct_ops_tab->ops;
9513 for (i = 0; i < cnt; i++) {
9514 if (st_ops_list[i].value_id == value_id)
9515 return &st_ops_list[i];
9516 }
9517
9518 return NULL;
9519 }
9520
9521 const struct bpf_struct_ops_desc *
bpf_struct_ops_find(struct btf * btf,u32 type_id)9522 bpf_struct_ops_find(struct btf *btf, u32 type_id)
9523 {
9524 const struct bpf_struct_ops_desc *st_ops_list;
9525 unsigned int i;
9526 u32 cnt;
9527
9528 if (!type_id)
9529 return NULL;
9530 if (!btf->struct_ops_tab)
9531 return NULL;
9532
9533 cnt = btf->struct_ops_tab->cnt;
9534 st_ops_list = btf->struct_ops_tab->ops;
9535 for (i = 0; i < cnt; i++) {
9536 if (st_ops_list[i].type_id == type_id)
9537 return &st_ops_list[i];
9538 }
9539
9540 return NULL;
9541 }
9542
__register_bpf_struct_ops(struct bpf_struct_ops * st_ops)9543 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
9544 {
9545 struct bpf_verifier_log *log;
9546 struct btf *btf;
9547 int err = 0;
9548
9549 btf = btf_get_module_btf(st_ops->owner);
9550 if (!btf)
9551 return check_btf_kconfigs(st_ops->owner, "struct_ops");
9552 if (IS_ERR(btf))
9553 return PTR_ERR(btf);
9554
9555 log = kzalloc(sizeof(*log), GFP_KERNEL | __GFP_NOWARN);
9556 if (!log) {
9557 err = -ENOMEM;
9558 goto errout;
9559 }
9560
9561 log->level = BPF_LOG_KERNEL;
9562
9563 err = btf_add_struct_ops(btf, st_ops, log);
9564
9565 errout:
9566 kfree(log);
9567 btf_put(btf);
9568
9569 return err;
9570 }
9571 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
9572 #endif
9573
btf_param_match_suffix(const struct btf * btf,const struct btf_param * arg,const char * suffix)9574 bool btf_param_match_suffix(const struct btf *btf,
9575 const struct btf_param *arg,
9576 const char *suffix)
9577 {
9578 int suffix_len = strlen(suffix), len;
9579 const char *param_name;
9580
9581 /* In the future, this can be ported to use BTF tagging */
9582 param_name = btf_name_by_offset(btf, arg->name_off);
9583 if (str_is_empty(param_name))
9584 return false;
9585 len = strlen(param_name);
9586 if (len <= suffix_len)
9587 return false;
9588 param_name += len - suffix_len;
9589 return !strncmp(param_name, suffix, suffix_len);
9590 }
9591