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