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