1 /* SPDX-License-Identifier: GPL-2.0-only */ 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 */ 4 #ifndef _LINUX_BPF_VERIFIER_H 5 #define _LINUX_BPF_VERIFIER_H 1 6 7 #include <linux/bpf.h> /* for enum bpf_reg_type */ 8 #include <linux/btf.h> /* for struct btf and btf_id() */ 9 #include <linux/filter.h> /* for MAX_BPF_STACK */ 10 #include <linux/tnum.h> 11 #include <linux/cnum.h> 12 13 /* Maximum variable offset umax_value permitted when resolving memory accesses. 14 * In practice this is far bigger than any realistic pointer offset; this limit 15 * ensures that umax_value + (int)off + (int)size cannot overflow a u64. 16 */ 17 #define BPF_MAX_VAR_OFF (1 << 29) 18 /* Maximum variable size permitted for ARG_CONST_SIZE[_OR_ZERO]. This ensures 19 * that converting umax_value to int cannot overflow. 20 */ 21 #define BPF_MAX_VAR_SIZ (1 << 29) 22 /* size of tmp_str_buf in bpf_verifier. 23 * we need at least 306 bytes to fit full stack mask representation 24 * (in the "-8,-16,...,-512" form) 25 */ 26 #define TMP_STR_BUF_LEN 320 27 /* Patch buffer size */ 28 #define INSN_BUF_SIZE 32 29 30 #define ITER_PREFIX "bpf_iter_" 31 32 enum bpf_iter_state { 33 BPF_ITER_STATE_INVALID, /* for non-first slot */ 34 BPF_ITER_STATE_ACTIVE, 35 BPF_ITER_STATE_DRAINED, 36 }; 37 38 struct bpf_reg_state { 39 /* Ordering of fields matters. See states_equal() */ 40 enum bpf_reg_type type; 41 /* 42 * Constant delta between "linked" scalars with the same ID. 43 */ 44 s32 delta; 45 union { 46 /* valid when type == PTR_TO_PACKET */ 47 int range; 48 49 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE | 50 * PTR_TO_MAP_VALUE_OR_NULL 51 */ 52 struct { 53 struct bpf_map *map_ptr; 54 /* To distinguish map lookups from outer map 55 * the map_uid is non-zero for registers 56 * pointing to inner maps. 57 */ 58 u32 map_uid; 59 }; 60 61 /* for PTR_TO_BTF_ID */ 62 struct { 63 struct btf *btf; 64 u32 btf_id; 65 }; 66 67 struct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */ 68 u32 mem_size; 69 }; 70 71 /* For dynptr stack slots */ 72 struct { 73 enum bpf_dynptr_type type; 74 /* A dynptr is 16 bytes so it takes up 2 stack slots. 75 * We need to track which slot is the first slot 76 * to protect against cases where the user may try to 77 * pass in an address starting at the second slot of the 78 * dynptr. 79 */ 80 bool first_slot; 81 } dynptr; 82 83 /* For bpf_iter stack slots */ 84 struct { 85 /* BTF container and BTF type ID describing 86 * struct bpf_iter_<type> of an iterator state 87 */ 88 struct btf *btf; 89 u32 btf_id; 90 /* packing following two fields to fit iter state into 16 bytes */ 91 enum bpf_iter_state state:2; 92 int depth:30; 93 } iter; 94 95 /* For irq stack slots */ 96 struct { 97 enum { 98 IRQ_NATIVE_KFUNC, 99 IRQ_LOCK_KFUNC, 100 } kfunc_class; 101 } irq; 102 103 /* Max size from any of the above. */ 104 struct { 105 unsigned long raw1; 106 unsigned long raw2; 107 } raw; 108 109 u32 subprogno; /* for PTR_TO_FUNC */ 110 }; 111 /* For scalar types (SCALAR_VALUE), this represents our knowledge of 112 * the actual value. 113 * For pointer types, this represents the variable part of the offset 114 * from the pointed-to object, and is shared with all bpf_reg_states 115 * with the same id as us. 116 */ 117 struct tnum var_off; 118 /* Used to determine if any memory access using this register will 119 * result in a bad access. 120 * These refer to the same value as var_off, not necessarily the actual 121 * contents of the register. 122 */ 123 struct cnum64 r64; /* 64-bit range as circular number */ 124 struct cnum32 r32; /* 32-bit range as circular number */ 125 /* For PTR_TO_PACKET, used to find other pointers with the same variable 126 * offset, so they can share range knowledge. 127 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we 128 * came from, when one is tested for != NULL. 129 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation 130 * for the purpose of tracking that it's freed. 131 * For PTR_TO_SOCKET this is used to share which pointers retain the 132 * same reference to the socket, to determine proper reference freeing. 133 * For stack slots that are dynptrs, this is used to track references to 134 * the dynptr to determine proper reference freeing. 135 * Similarly to dynptrs, we use ID to track "belonging" of a reference 136 * to a specific instance of bpf_iter. 137 */ 138 /* 139 * Upper bit of ID is used to remember relationship between "linked" 140 * registers. Example: 141 * r1 = r2; both will have r1->id == r2->id == N 142 * r1 += 10; r1->id == N | BPF_ADD_CONST and r1->delta == 10 143 * r3 = r2; both will have r3->id == r2->id == N 144 * w3 += 10; r3->id == N | BPF_ADD_CONST32 and r3->delta == 10 145 */ 146 #define BPF_ADD_CONST64 (1U << 31) 147 #define BPF_ADD_CONST32 (1U << 30) 148 #define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32) 149 u32 id; 150 /* 151 * Tracks the parent object this register was derived from. 152 * Used for cascading invalidation: when the parent object is 153 * released or invalidated, all registers with matching parent_id 154 * are also invalidated. For example, a slice from bpf_dynptr_data() 155 * gets parent_id set to the dynptr's id. 156 */ 157 u32 parent_id; 158 /* Inside the callee two registers can be both PTR_TO_STACK like 159 * R1=fp-8 and R2=fp-8, but one of them points to this function stack 160 * while another to the caller's stack. To differentiate them 'frameno' 161 * is used which is an index in bpf_verifier_state->frame[] array 162 * pointing to bpf_func_state. 163 */ 164 u32 frameno; 165 /* Tracks subreg definition. The stored value is the insn_idx of the 166 * writing insn. This is safe because subreg_def is used before any insn 167 * patching which only happens after main verification finished. 168 */ 169 s32 subreg_def; 170 /* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */ 171 bool precise; 172 }; 173 174 static inline s64 reg_smin(const struct bpf_reg_state *reg) 175 { 176 return cnum64_smin(reg->r64); 177 } 178 179 static inline s64 reg_smax(const struct bpf_reg_state *reg) 180 { 181 return cnum64_smax(reg->r64); 182 } 183 184 static inline u64 reg_umin(const struct bpf_reg_state *reg) 185 { 186 return cnum64_umin(reg->r64); 187 } 188 189 static inline u64 reg_umax(const struct bpf_reg_state *reg) 190 { 191 return cnum64_umax(reg->r64); 192 } 193 194 static inline s32 reg_s32_min(const struct bpf_reg_state *reg) 195 { 196 return cnum32_smin(reg->r32); 197 } 198 199 static inline s32 reg_s32_max(const struct bpf_reg_state *reg) 200 { 201 return cnum32_smax(reg->r32); 202 } 203 204 static inline u32 reg_u32_min(const struct bpf_reg_state *reg) 205 { 206 return cnum32_umin(reg->r32); 207 } 208 209 static inline u32 reg_u32_max(const struct bpf_reg_state *reg) 210 { 211 return cnum32_umax(reg->r32); 212 } 213 214 static inline void reg_set_srange32(struct bpf_reg_state *reg, s32 smin, s32 smax) 215 { 216 reg->r32 = cnum32_from_srange(smin, smax); 217 } 218 219 static inline void reg_set_urange32(struct bpf_reg_state *reg, u32 umin, u32 umax) 220 { 221 reg->r32 = cnum32_from_urange(umin, umax); 222 } 223 224 static inline void reg_set_srange64(struct bpf_reg_state *reg, s64 smin, s64 smax) 225 { 226 reg->r64 = cnum64_from_srange(smin, smax); 227 } 228 229 static inline void reg_set_urange64(struct bpf_reg_state *reg, u64 umin, u64 umax) 230 { 231 reg->r64 = cnum64_from_urange(umin, umax); 232 } 233 234 enum bpf_stack_slot_type { 235 STACK_INVALID, /* nothing was stored in this stack slot */ 236 STACK_SPILL, /* register spilled into stack */ 237 STACK_MISC, /* BPF program wrote some data into this slot */ 238 STACK_ZERO, /* BPF program wrote constant zero */ 239 /* A dynptr is stored in this stack slot. The type of dynptr 240 * is stored in bpf_stack_state->spilled_ptr.dynptr.type 241 */ 242 STACK_DYNPTR, 243 STACK_ITER, 244 STACK_IRQ_FLAG, 245 STACK_POISON, 246 }; 247 248 #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */ 249 250 /* 4-byte stack slot granularity for liveness analysis */ 251 #define BPF_HALF_REG_SIZE 4 252 #define STACK_SLOT_SZ 4 253 #define STACK_SLOTS (MAX_BPF_STACK / BPF_HALF_REG_SIZE) /* 128 */ 254 255 typedef struct { 256 u64 v[2]; 257 } spis_t; 258 259 #define SPIS_ZERO ((spis_t){}) 260 #define SPIS_ALL ((spis_t){{ U64_MAX, U64_MAX }}) 261 262 static inline bool spis_is_zero(spis_t s) 263 { 264 return s.v[0] == 0 && s.v[1] == 0; 265 } 266 267 static inline bool spis_equal(spis_t a, spis_t b) 268 { 269 return a.v[0] == b.v[0] && a.v[1] == b.v[1]; 270 } 271 272 static inline spis_t spis_or(spis_t a, spis_t b) 273 { 274 return (spis_t){{ a.v[0] | b.v[0], a.v[1] | b.v[1] }}; 275 } 276 277 static inline spis_t spis_and(spis_t a, spis_t b) 278 { 279 return (spis_t){{ a.v[0] & b.v[0], a.v[1] & b.v[1] }}; 280 } 281 282 static inline spis_t spis_not(spis_t s) 283 { 284 return (spis_t){{ ~s.v[0], ~s.v[1] }}; 285 } 286 287 static inline bool spis_test_bit(spis_t s, u32 slot) 288 { 289 return s.v[slot / 64] & BIT_ULL(slot % 64); 290 } 291 292 static inline void spis_or_range(spis_t *mask, u32 lo, u32 hi) 293 { 294 u32 w; 295 296 for (w = lo; w <= hi && w < STACK_SLOTS; w++) 297 mask->v[w / 64] |= BIT_ULL(w % 64); 298 } 299 300 #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \ 301 (1 << BPF_REG_3) | (1 << BPF_REG_4) | \ 302 (1 << BPF_REG_5)) 303 304 #define BPF_MAIN_FUNC (-1) 305 306 #define BPF_DYNPTR_SIZE sizeof(struct bpf_dynptr_kern) 307 #define BPF_DYNPTR_NR_SLOTS (BPF_DYNPTR_SIZE / BPF_REG_SIZE) 308 309 struct bpf_stack_state { 310 struct bpf_reg_state spilled_ptr; 311 u8 slot_type[BPF_REG_SIZE]; 312 }; 313 314 struct bpf_reference_state { 315 /* Each reference object has a type. Ensure REF_TYPE_PTR is zero to 316 * default to pointer reference on zero initialization of a state. 317 */ 318 enum ref_state_type { 319 REF_TYPE_PTR = (1 << 1), 320 REF_TYPE_IRQ = (1 << 2), 321 REF_TYPE_LOCK = (1 << 3), 322 REF_TYPE_RES_LOCK = (1 << 4), 323 REF_TYPE_RES_LOCK_IRQ = (1 << 5), 324 REF_TYPE_LOCK_MASK = REF_TYPE_LOCK | REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, 325 } type; 326 /* Track each reference created with a unique id, even if the same 327 * instruction creates the reference multiple times (eg, via CALL). 328 */ 329 int id; 330 /* Instruction where the allocation of this reference occurred. This 331 * is used purely to inform the user of a reference leak. 332 */ 333 int insn_idx; 334 union { 335 /* For REF_TYPE_PTR */ 336 int parent_id; 337 /* Use to keep track of the source object of a lock, to ensure 338 * it matches on unlock. 339 */ 340 void *ptr; 341 }; 342 }; 343 344 struct bpf_retval_range { 345 s32 minval; 346 s32 maxval; 347 bool return_32bit; 348 }; 349 350 /* state of the program: 351 * type of all registers and stack info 352 */ 353 struct bpf_func_state { 354 struct bpf_reg_state regs[MAX_BPF_REG]; 355 /* index of call instruction that called into this func */ 356 int callsite; 357 /* stack frame number of this function state from pov of 358 * enclosing bpf_verifier_state. 359 * 0 = main function, 1 = first callee. 360 */ 361 u32 frameno; 362 /* subprog number == index within subprog_info 363 * zero == main subprog 364 */ 365 u32 subprogno; 366 /* Every bpf_timer_start will increment async_entry_cnt. 367 * It's used to distinguish: 368 * void foo(void) { for(;;); } 369 * void foo(void) { bpf_timer_set_callback(,foo); } 370 */ 371 u32 async_entry_cnt; 372 struct bpf_retval_range callback_ret_range; 373 bool in_callback_fn; 374 bool in_async_callback_fn; 375 bool in_exception_callback_fn; 376 bool no_stack_arg_load; 377 /* For callback calling functions that limit number of possible 378 * callback executions (e.g. bpf_loop) keeps track of current 379 * simulated iteration number. 380 * Value in frame N refers to number of times callback with frame 381 * N+1 was simulated, e.g. for the following call: 382 * 383 * bpf_loop(..., fn, ...); | suppose current frame is N 384 * | fn would be simulated in frame N+1 385 * | number of simulations is tracked in frame N 386 */ 387 u32 callback_depth; 388 389 /* The following fields should be last. See copy_func_state() */ 390 /* The state of the stack. Each element of the array describes BPF_REG_SIZE 391 * (i.e. 8) bytes worth of stack memory. 392 * stack[0] represents bytes [*(r10-8)..*(r10-1)] 393 * stack[1] represents bytes [*(r10-16)..*(r10-9)] 394 * ... 395 * stack[allocated_stack/8 - 1] represents [*(r10-allocated_stack)..*(r10-allocated_stack+7)] 396 */ 397 struct bpf_stack_state *stack; 398 /* Size of the current stack, in bytes. The stack state is tracked below, in 399 * `stack`. allocated_stack is always a multiple of BPF_REG_SIZE. 400 */ 401 int allocated_stack; 402 403 u16 out_stack_arg_cnt; /* Number of outgoing on-stack argument slots */ 404 struct bpf_reg_state *stack_arg_regs; /* Outgoing on-stack arguments */ 405 }; 406 407 #define MAX_CALL_FRAMES 16 408 409 /* instruction history flags, used in bpf_jmp_history_entry.flags field. 410 * Frame number and SPI are stored in dedicated fields of bpf_jmp_history_entry. 411 */ 412 enum { 413 INSN_F_STACK_ACCESS = BIT(0), 414 415 INSN_F_DST_REG_STACK = BIT(1), /* dst_reg is PTR_TO_STACK */ 416 INSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */ 417 418 INSN_F_STACK_ARG_ACCESS = BIT(3), 419 }; 420 421 struct bpf_jmp_history_entry { 422 /* insn idx can't be bigger than 1 million */ 423 u32 idx : 20; 424 u32 frame : 4; /* stack access frame number */ 425 u32 spi : 6; /* stack slot index (0..63) */ 426 u32 : 2; 427 u32 prev_idx : 20; 428 /* special INSN_F_xxx flags */ 429 u32 flags : 4; 430 u32 : 8; 431 /* 432 * additional registers that need precision tracking when this 433 * jump is backtracked, vector of five 11-bit records 434 */ 435 u64 linked_regs; 436 }; 437 438 static_assert(MAX_CALL_FRAMES <= (1 << 4)); 439 static_assert(MAX_BPF_STACK / 8 <= (1 << 6)); 440 441 /* Maximum number of bpf_reg_state objects that can exist at once */ 442 #define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS) 443 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE + \ 444 MAX_STACK_ARG_SLOTS) * MAX_CALL_FRAMES) 445 struct bpf_verifier_state { 446 /* call stack tracking */ 447 struct bpf_func_state *frame[MAX_CALL_FRAMES]; 448 struct bpf_verifier_state *parent; 449 /* Acquired reference states */ 450 struct bpf_reference_state *refs; 451 /* 452 * 'branches' field is the number of branches left to explore: 453 * 0 - all possible paths from this state reached bpf_exit or 454 * were safely pruned 455 * 1 - at least one path is being explored. 456 * This state hasn't reached bpf_exit 457 * 2 - at least two paths are being explored. 458 * This state is an immediate parent of two children. 459 * One is fallthrough branch with branches==1 and another 460 * state is pushed into stack (to be explored later) also with 461 * branches==1. The parent of this state has branches==1. 462 * The verifier state tree connected via 'parent' pointer looks like: 463 * 1 464 * 1 465 * 2 -> 1 (first 'if' pushed into stack) 466 * 1 467 * 2 -> 1 (second 'if' pushed into stack) 468 * 1 469 * 1 470 * 1 bpf_exit. 471 * 472 * Once do_check() reaches bpf_exit, it calls update_branch_counts() 473 * and the verifier state tree will look: 474 * 1 475 * 1 476 * 2 -> 1 (first 'if' pushed into stack) 477 * 1 478 * 1 -> 1 (second 'if' pushed into stack) 479 * 0 480 * 0 481 * 0 bpf_exit. 482 * After pop_stack() the do_check() will resume at second 'if'. 483 * 484 * If is_state_visited() sees a state with branches > 0 it means 485 * there is a loop. If such state is exactly equal to the current state 486 * it's an infinite loop. Note states_equal() checks for states 487 * equivalency, so two states being 'states_equal' does not mean 488 * infinite loop. The exact comparison is provided by 489 * states_maybe_looping() function. It's a stronger pre-check and 490 * much faster than states_equal(). 491 * 492 * This algorithm may not find all possible infinite loops or 493 * loop iteration count may be too high. 494 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in. 495 */ 496 u32 branches; 497 u32 insn_idx; 498 u32 curframe; 499 500 u32 acquired_refs; 501 u32 active_locks; 502 u32 active_preempt_locks; 503 u32 active_irq_id; 504 u32 active_lock_id; 505 void *active_lock_ptr; 506 u32 active_rcu_locks; 507 508 bool speculative; 509 bool in_sleepable; 510 511 /* first and last insn idx of this verifier state */ 512 u32 first_insn_idx; 513 u32 last_insn_idx; 514 /* if this state is a backedge state then equal_state 515 * records cached state to which this state is equal. 516 */ 517 struct bpf_verifier_state *equal_state; 518 /* jmp history recorded from first to last. 519 * backtracking is using it to go from last to first. 520 * For most states jmp_history_cnt is [0-3]. 521 * For loops can go up to ~40. 522 */ 523 struct bpf_jmp_history_entry *jmp_history; 524 u32 jmp_history_cnt; 525 u32 dfs_depth; 526 u32 callback_unroll_depth; 527 u32 may_goto_depth; 528 }; 529 530 static inline struct bpf_reg_state * 531 bpf_get_spilled_reg(int slot, struct bpf_func_state *frame, u32 mask) 532 { 533 if (slot < frame->allocated_stack / BPF_REG_SIZE && 534 (1 << frame->stack[slot].slot_type[BPF_REG_SIZE - 1]) & mask) 535 return &frame->stack[slot].spilled_ptr; 536 return NULL; 537 } 538 539 static inline struct bpf_reg_state * 540 bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) 541 { 542 if (slot < frame->out_stack_arg_cnt && 543 frame->stack_arg_regs[slot].type != NOT_INIT) 544 return &frame->stack_arg_regs[slot]; 545 return NULL; 546 } 547 548 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */ 549 #define bpf_for_each_spilled_reg(iter, frame, reg, mask) \ 550 for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask); \ 551 iter < frame->allocated_stack / BPF_REG_SIZE; \ 552 iter++, reg = bpf_get_spilled_reg(iter, frame, mask)) 553 554 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled stack arg. */ 555 #define bpf_for_each_spilled_stack_arg(iter, frame, reg) \ 556 for (iter = 0, reg = bpf_get_spilled_stack_arg(iter, frame); \ 557 iter < frame->out_stack_arg_cnt; \ 558 iter++, reg = bpf_get_spilled_stack_arg(iter, frame)) 559 560 #define bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, __stack, __mask, __expr) \ 561 ({ \ 562 struct bpf_verifier_state *___vstate = __vst; \ 563 int ___i, ___j; \ 564 for (___i = 0; ___i <= ___vstate->curframe; ___i++) { \ 565 struct bpf_reg_state *___regs; \ 566 __state = ___vstate->frame[___i]; \ 567 ___regs = __state->regs; \ 568 __stack = NULL; \ 569 for (___j = 0; ___j < MAX_BPF_REG; ___j++) { \ 570 __reg = &___regs[___j]; \ 571 (void)(__expr); \ 572 } \ 573 bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \ 574 if (!__reg) \ 575 continue; \ 576 __stack = &__state->stack[___j]; \ 577 (void)(__expr); \ 578 } \ 579 __stack = NULL; \ 580 bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \ 581 if (!__reg) \ 582 continue; \ 583 (void)(__expr); \ 584 } \ 585 } \ 586 (void)__stack; \ 587 }) 588 589 /* Invoke __expr over regsiters in __vst, setting __state and __reg */ 590 #define bpf_for_each_reg_in_vstate(__vst, __state, __reg, __expr) \ 591 ({ \ 592 struct bpf_stack_state * ___stack; \ 593 (void)___stack; \ 594 bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, ___stack,\ 595 1 << STACK_SPILL, __expr); \ 596 }) 597 598 /* linked list of verifier states used to prune search */ 599 struct bpf_verifier_state_list { 600 struct bpf_verifier_state state; 601 struct list_head node; 602 u32 miss_cnt; 603 u32 hit_cnt:31; 604 u32 in_free_list:1; 605 }; 606 607 struct bpf_loop_inline_state { 608 unsigned int initialized:1; /* set to true upon first entry */ 609 unsigned int fit_for_inline:1; /* true if callback function is the same 610 * at each call and flags are always zero 611 */ 612 u32 callback_subprogno; /* valid when fit_for_inline is true */ 613 }; 614 615 /* pointer and state for maps */ 616 struct bpf_map_ptr_state { 617 struct bpf_map *map_ptr; 618 bool poison; 619 bool unpriv; 620 }; 621 622 /* Possible states for alu_state member. */ 623 #define BPF_ALU_SANITIZE_SRC (1U << 0) 624 #define BPF_ALU_SANITIZE_DST (1U << 1) 625 #define BPF_ALU_NEG_VALUE (1U << 2) 626 #define BPF_ALU_NON_POINTER (1U << 3) 627 #define BPF_ALU_IMMEDIATE (1U << 4) 628 #define BPF_ALU_SANITIZE (BPF_ALU_SANITIZE_SRC | \ 629 BPF_ALU_SANITIZE_DST) 630 631 /* 632 * An array of BPF instructions. 633 * Primary usage: return value of bpf_insn_successors. 634 */ 635 struct bpf_iarray { 636 int cnt; 637 u32 items[]; 638 }; 639 640 struct bpf_insn_aux_data { 641 union { 642 enum bpf_reg_type ptr_type; /* pointer type for load/store insns */ 643 struct bpf_map_ptr_state map_ptr_state; 644 s32 call_imm; /* saved imm field of call insn */ 645 u32 alu_limit; /* limit for add/sub register with pointer */ 646 struct { 647 u32 map_index; /* index into used_maps[] */ 648 u32 map_off; /* offset from value base address */ 649 }; 650 struct { 651 enum bpf_reg_type reg_type; /* type of pseudo_btf_id */ 652 union { 653 struct { 654 struct btf *btf; 655 u32 btf_id; /* btf_id for struct typed var */ 656 }; 657 u32 mem_size; /* mem_size for non-struct typed var */ 658 }; 659 } btf_var; 660 /* if instruction is a call to bpf_loop this field tracks 661 * the state of the relevant registers to make decision about inlining 662 */ 663 struct bpf_loop_inline_state loop_inline_state; 664 }; 665 union { 666 /* remember the size of type passed to bpf_obj_new to rewrite R1 */ 667 u64 obj_new_size; 668 /* remember the offset of node field within type to rewrite */ 669 u64 insert_off; 670 }; 671 struct bpf_iarray *jt; /* jump table for gotox or bpf_tailcall call instruction */ 672 struct btf_struct_meta *kptr_struct_meta; 673 u64 map_key_state; /* constant (32 bit) key tracking for maps */ 674 int ctx_field_size; /* the ctx field size for load insn, maybe 0 */ 675 u32 seen; /* this insn was processed by the verifier at env->pass_cnt */ 676 bool nospec; /* do not execute this instruction speculatively */ 677 bool nospec_result; /* result is unsafe under speculation, nospec must follow */ 678 bool zext_dst; /* this insn zero extends dst reg */ 679 bool needs_zext; /* alu op needs to clear upper bits */ 680 bool non_sleepable; /* helper/kfunc may be called from non-sleepable context */ 681 bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */ 682 bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */ 683 u8 alu_state; /* used in combination with alu_limit */ 684 /* true if STX or LDX instruction is a part of a spill/fill 685 * pattern for a bpf_fastcall call. 686 */ 687 u8 fastcall_pattern:1; 688 /* for CALL instructions, a number of spill/fill pairs in the 689 * bpf_fastcall pattern. 690 */ 691 u8 fastcall_spills_num:3; 692 u8 arg_prog:4; 693 694 /* below fields are initialized once */ 695 unsigned int orig_idx; /* original instruction index */ 696 u32 jmp_point:1; 697 u32 prune_point:1; 698 /* ensure we check state equivalence and save state checkpoint and 699 * this instruction, regardless of any heuristics 700 */ 701 u32 force_checkpoint:1; 702 /* true if instruction is a call to a helper function that 703 * accepts callback function as a parameter. 704 */ 705 u32 calls_callback:1; 706 u32 indirect_target:1; /* if it is an indirect jump target */ 707 /* 708 * CFG strongly connected component this instruction belongs to, 709 * zero if it is a singleton SCC. 710 */ 711 u32 scc; 712 /* registers alive before this instruction. */ 713 u16 live_regs_before; 714 /* 715 * Bitmask of R0-R9 that hold known values at this instruction. 716 * const_reg_mask: scalar constants that fit in 32 bits. 717 * const_reg_map_mask: map pointers, val is map_index into used_maps[]. 718 * const_reg_subprog_mask: subprog pointers, val is subprog number. 719 * const_reg_vals[i] holds the 32-bit value for register i. 720 * Populated by compute_const_regs() pre-pass. 721 */ 722 u16 const_reg_mask; 723 u16 const_reg_map_mask; 724 u16 const_reg_subprog_mask; 725 u32 const_reg_vals[10]; 726 }; 727 728 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */ 729 #define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */ 730 731 #define BPF_VERIFIER_TMP_LOG_SIZE 1024 732 733 struct bpf_verifier_log { 734 /* Logical start and end positions of a "log window" of the verifier log. 735 * start_pos == 0 means we haven't truncated anything. 736 * Once truncation starts to happen, start_pos + len_total == end_pos, 737 * except during log reset situations, in which (end_pos - start_pos) 738 * might get smaller than len_total (see bpf_vlog_reset()). 739 * Generally, (end_pos - start_pos) gives number of useful data in 740 * user log buffer. 741 */ 742 u64 start_pos; 743 u64 end_pos; 744 char __user *ubuf; 745 u32 level; 746 u32 len_total; 747 u32 len_max; 748 char kbuf[BPF_VERIFIER_TMP_LOG_SIZE]; 749 }; 750 751 #define BPF_LOG_LEVEL1 1 752 #define BPF_LOG_LEVEL2 2 753 #define BPF_LOG_STATS 4 754 #define BPF_LOG_FIXED 8 755 #define BPF_LOG_LEVEL (BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2) 756 #define BPF_LOG_MASK (BPF_LOG_LEVEL | BPF_LOG_STATS | BPF_LOG_FIXED) 757 #define BPF_LOG_KERNEL (BPF_LOG_MASK + 1) /* kernel internal flag */ 758 #define BPF_LOG_MIN_ALIGNMENT 8U 759 #define BPF_LOG_ALIGNMENT 40U 760 761 static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log) 762 { 763 return log && log->level; 764 } 765 766 struct bpf_log_attr { 767 char __user *ubuf; 768 u32 size; 769 u32 level; 770 u32 offsetof_true_size; 771 bpfptr_t uattr; 772 }; 773 774 int bpf_log_attr_init(struct bpf_log_attr *log, u64 log_buf, u32 log_size, u32 log_level, 775 u32 offsetof_log_true_size, bpfptr_t uattr, struct bpf_common_attr *common, 776 bpfptr_t uattr_common, u32 size_common); 777 struct bpf_verifier_log *bpf_log_attr_create_vlog(struct bpf_log_attr *attr_log, 778 struct bpf_common_attr *common, bpfptr_t uattr, 779 u32 size); 780 int bpf_log_attr_finalize(struct bpf_log_attr *attr, struct bpf_verifier_log *log); 781 782 #define BPF_MAX_SUBPROGS 256 783 784 struct bpf_subprog_arg_info { 785 enum bpf_arg_type arg_type; 786 union { 787 u32 mem_size; 788 u32 btf_id; 789 }; 790 }; 791 792 enum priv_stack_mode { 793 PRIV_STACK_UNKNOWN, 794 NO_PRIV_STACK, 795 PRIV_STACK_ADAPTIVE, 796 }; 797 798 struct bpf_subprog_info { 799 const char *name; /* name extracted from BTF */ 800 u32 start; /* insn idx of function entry point */ 801 u32 linfo_idx; /* The idx to the main_prog->aux->linfo */ 802 u32 postorder_start; /* The idx to the env->cfg.insn_postorder */ 803 u32 exit_idx; /* Index of one of the BPF_EXIT instructions in this subprogram */ 804 u16 stack_depth; /* max. stack depth used by this function */ 805 u16 stack_extra; 806 u32 insn_processed; 807 /* offsets in range [stack_depth .. fastcall_stack_off) 808 * are used for bpf_fastcall spills and fills. 809 */ 810 s16 fastcall_stack_off; 811 bool has_tail_call: 1; 812 bool might_throw: 1; 813 bool tail_call_reachable: 1; 814 bool has_ld_abs: 1; 815 bool is_cb: 1; 816 bool is_async_cb: 1; 817 bool is_exception_cb: 1; 818 bool args_cached: 1; 819 /* true if bpf_fastcall stack region is used by functions that can't be inlined */ 820 bool keep_fastcall_stack: 1; 821 bool changes_pkt_data: 1; 822 bool might_sleep: 1; 823 u8 arg_cnt:4; 824 825 enum priv_stack_mode priv_stack_mode; 826 struct bpf_subprog_arg_info args[MAX_BPF_FUNC_ARGS]; 827 u16 stack_arg_cnt; /* incoming + max outgoing */ 828 u16 max_out_stack_arg_cnt; 829 }; 830 831 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub) 832 { 833 if (sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) 834 return sub->arg_cnt - MAX_BPF_FUNC_REG_ARGS; 835 return 0; 836 } 837 838 struct bpf_verifier_env; 839 840 struct backtrack_state { 841 struct bpf_verifier_env *env; 842 u32 frame; 843 u32 reg_masks[MAX_CALL_FRAMES]; 844 u64 stack_masks[MAX_CALL_FRAMES]; 845 u8 stack_arg_masks[MAX_CALL_FRAMES]; 846 }; 847 848 struct bpf_id_pair { 849 u32 old; 850 u32 cur; 851 }; 852 853 struct bpf_idmap { 854 u32 tmp_id_gen; 855 u32 cnt; 856 struct bpf_id_pair map[BPF_ID_MAP_SIZE]; 857 }; 858 859 struct bpf_idset { 860 u32 num_ids; 861 struct { 862 u32 id; 863 u32 cnt; 864 } entries[BPF_ID_MAP_SIZE]; 865 }; 866 867 /* see verifier.c:compute_scc_callchain() */ 868 struct bpf_scc_callchain { 869 /* call sites from bpf_verifier_state->frame[*]->callsite leading to this SCC */ 870 u32 callsites[MAX_CALL_FRAMES - 1]; 871 /* last frame in a chain is identified by SCC id */ 872 u32 scc; 873 }; 874 875 /* verifier state waiting for propagate_backedges() */ 876 struct bpf_scc_backedge { 877 struct bpf_scc_backedge *next; 878 struct bpf_verifier_state state; 879 }; 880 881 struct bpf_scc_visit { 882 struct bpf_scc_callchain callchain; 883 /* first state in current verification path that entered SCC 884 * identified by the callchain 885 */ 886 struct bpf_verifier_state *entry_state; 887 struct bpf_scc_backedge *backedges; /* list of backedges */ 888 u32 num_backedges; 889 }; 890 891 /* An array of bpf_scc_visit structs sharing tht same bpf_scc_callchain->scc 892 * but having different bpf_scc_callchain->callsites. 893 */ 894 struct bpf_scc_info { 895 u32 num_visits; 896 struct bpf_scc_visit visits[]; 897 }; 898 899 struct bpf_liveness; 900 901 /* single container for all structs 902 * one verifier_env per bpf_check() call 903 */ 904 struct bpf_verifier_env { 905 u32 insn_idx; 906 u32 prev_insn_idx; 907 struct bpf_prog *prog; /* eBPF program being verified */ 908 const struct bpf_verifier_ops *ops; 909 struct module *attach_btf_mod; /* The owner module of prog->aux->attach_btf */ 910 struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */ 911 int stack_size; /* number of states to be processed */ 912 bool strict_alignment; /* perform strict pointer alignment checks */ 913 bool test_state_freq; /* test verifier with different pruning frequency */ 914 bool test_reg_invariants; /* fail verification on register invariants violations */ 915 struct bpf_verifier_state *cur_state; /* current verifier state */ 916 /* Search pruning optimization, array of list_heads for 917 * lists of struct bpf_verifier_state_list. 918 */ 919 struct list_head *explored_states; 920 struct list_head free_list; /* list of struct bpf_verifier_state_list */ 921 struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */ 922 struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */ 923 struct bpf_map *insn_array_maps[MAX_USED_MAPS]; /* array of INSN_ARRAY map's to be relocated */ 924 u32 used_map_cnt; /* number of used maps */ 925 u32 used_btf_cnt; /* number of used BTF objects */ 926 u32 insn_array_map_cnt; /* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */ 927 u32 id_gen; /* used to generate unique reg IDs */ 928 u32 hidden_subprog_cnt; /* number of hidden subprogs */ 929 int exception_callback_subprog; 930 bool explore_alu_limits; 931 bool allow_ptr_leaks; 932 /* Allow access to uninitialized stack memory. Writes with fixed offset are 933 * always allowed, so this refers to reads (with fixed or variable offset), 934 * to writes with variable offset and to indirect (helper) accesses. 935 */ 936 bool allow_uninit_stack; 937 bool bpf_capable; 938 bool bypass_spec_v1; 939 bool bypass_spec_v4; 940 bool seen_direct_write; 941 bool seen_exception; 942 struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */ 943 const struct bpf_line_info *prev_linfo; 944 struct bpf_verifier_log log; 945 struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */ 946 /* subprog indices sorted in topological order: leaves first, callers last */ 947 int subprog_topo_order[BPF_MAX_SUBPROGS + 2]; 948 union { 949 struct bpf_idmap idmap_scratch; 950 struct bpf_idset idset_scratch; 951 }; 952 struct { 953 int *insn_state; 954 int *insn_stack; 955 /* 956 * vector of instruction indexes sorted in post-order, grouped by subprogram, 957 * see bpf_subprog_info->postorder_start. 958 */ 959 int *insn_postorder; 960 int cur_stack; 961 /* current position in the insn_postorder vector */ 962 int cur_postorder; 963 } cfg; 964 struct backtrack_state bt; 965 struct bpf_jmp_history_entry *cur_hist_ent; 966 /* Per-callsite copy of parent's converged at_stack_in for cross-frame fills. */ 967 struct arg_track **callsite_at_stack; 968 u32 pass_cnt; /* number of times do_check() was called */ 969 u32 subprog_cnt; 970 /* number of instructions analyzed by the verifier */ 971 u32 prev_insn_processed, insn_processed; 972 /* number of jmps, calls, exits analyzed so far */ 973 u32 prev_jmps_processed, jmps_processed; 974 /* maximum combined stack depth */ 975 u32 max_stack_depth; 976 /* total verification time */ 977 u64 verification_time; 978 /* maximum number of verifier states kept in 'branching' instructions */ 979 u32 max_states_per_insn; 980 /* total number of allocated verifier states */ 981 u32 total_states; 982 /* some states are freed during program analysis. 983 * this is peak number of states. this number dominates kernel 984 * memory consumption during verification 985 */ 986 u32 peak_states; 987 /* longest register parentage chain walked for liveness marking */ 988 u32 longest_mark_read_walk; 989 u32 free_list_size; 990 u32 explored_states_size; 991 u32 num_backedges; 992 bpfptr_t fd_array; 993 994 /* bit mask to keep track of whether a register has been accessed 995 * since the last time the function state was printed 996 */ 997 u32 scratched_regs; 998 /* Same as scratched_regs but for stack slots */ 999 u64 scratched_stack_slots; 1000 u64 prev_log_pos, prev_insn_print_pos; 1001 /* buffer used to temporary hold constants as scalar registers */ 1002 struct bpf_reg_state fake_reg[1]; 1003 /* buffers used to save updated reg states while simulating branches */ 1004 struct bpf_reg_state true_reg1, true_reg2, false_reg1, false_reg2; 1005 /* buffer used to generate temporary string representations, 1006 * e.g., in reg_type_str() to generate reg_type string 1007 */ 1008 char tmp_str_buf[TMP_STR_BUF_LEN]; 1009 char tmp_arg_name[32]; 1010 struct bpf_insn insn_buf[INSN_BUF_SIZE]; 1011 struct bpf_insn epilogue_buf[INSN_BUF_SIZE]; 1012 struct bpf_scc_callchain callchain_buf; 1013 struct bpf_liveness *liveness; 1014 /* array of pointers to bpf_scc_info indexed by SCC id */ 1015 struct bpf_scc_info **scc_info; 1016 u32 scc_cnt; 1017 struct bpf_iarray *succ; 1018 struct bpf_iarray *gotox_tmp_buf; 1019 }; 1020 1021 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog) 1022 { 1023 return &env->prog->aux->func_info_aux[subprog]; 1024 } 1025 1026 static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog) 1027 { 1028 return &env->subprog_info[subprog]; 1029 } 1030 1031 struct bpf_call_summary { 1032 u8 num_params; 1033 bool is_void; 1034 bool fastcall; 1035 }; 1036 1037 static inline bool bpf_helper_call(const struct bpf_insn *insn) 1038 { 1039 return insn->code == (BPF_JMP | BPF_CALL) && 1040 insn->src_reg == 0; 1041 } 1042 1043 static inline bool bpf_pseudo_call(const struct bpf_insn *insn) 1044 { 1045 return insn->code == (BPF_JMP | BPF_CALL) && 1046 insn->src_reg == BPF_PSEUDO_CALL; 1047 } 1048 1049 static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 1050 { 1051 return insn->code == (BPF_JMP | BPF_CALL) && 1052 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 1053 } 1054 1055 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log, 1056 const char *fmt, va_list args); 1057 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 1058 const char *fmt, ...); 1059 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 1060 const char *fmt, ...); 1061 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level, 1062 char __user *log_buf, u32 log_size); 1063 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos); 1064 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual); 1065 1066 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env, 1067 u32 insn_off, 1068 const char *prefix_fmt, ...); 1069 1070 #define verifier_bug_if(cond, env, fmt, args...) \ 1071 ({ \ 1072 bool __cond = (cond); \ 1073 if (unlikely(__cond)) \ 1074 verifier_bug(env, fmt " (" #cond ")", ##args); \ 1075 (__cond); \ 1076 }) 1077 #define verifier_bug(env, fmt, args...) \ 1078 ({ \ 1079 BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args); \ 1080 bpf_log(&env->log, "verifier bug: " fmt "\n", ##args); \ 1081 }) 1082 1083 static inline void mark_prune_point(struct bpf_verifier_env *env, int idx) 1084 { 1085 env->insn_aux_data[idx].prune_point = true; 1086 } 1087 1088 static inline bool bpf_is_prune_point(struct bpf_verifier_env *env, int insn_idx) 1089 { 1090 return env->insn_aux_data[insn_idx].prune_point; 1091 } 1092 1093 static inline void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 1094 { 1095 env->insn_aux_data[idx].force_checkpoint = true; 1096 } 1097 1098 static inline bool bpf_is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 1099 { 1100 return env->insn_aux_data[insn_idx].force_checkpoint; 1101 } 1102 1103 static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx) 1104 { 1105 env->insn_aux_data[idx].calls_callback = true; 1106 } 1107 1108 static inline bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx) 1109 { 1110 return env->insn_aux_data[insn_idx].calls_callback; 1111 } 1112 1113 static inline void mark_jmp_point(struct bpf_verifier_env *env, int idx) 1114 { 1115 env->insn_aux_data[idx].jmp_point = true; 1116 } 1117 1118 static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env) 1119 { 1120 struct bpf_verifier_state *cur = env->cur_state; 1121 1122 return cur->frame[cur->curframe]; 1123 } 1124 1125 static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env) 1126 { 1127 return cur_func(env)->regs; 1128 } 1129 1130 int bpf_prog_offload_verifier_prep(struct bpf_prog *prog); 1131 int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env, 1132 int insn_idx, int prev_insn_idx); 1133 int bpf_prog_offload_finalize(struct bpf_verifier_env *env); 1134 void 1135 bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off, 1136 struct bpf_insn *insn); 1137 void 1138 bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt); 1139 1140 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */ 1141 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog, 1142 struct btf *btf, u32 btf_id) 1143 { 1144 if (tgt_prog) 1145 return ((u64)tgt_prog->aux->id << 32) | btf_id; 1146 else 1147 return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id; 1148 } 1149 1150 /* unpack the IDs from the key as constructed above */ 1151 static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id) 1152 { 1153 if (obj_id) 1154 *obj_id = key >> 32; 1155 if (btf_id) 1156 *btf_id = key & 0x7FFFFFFF; 1157 } 1158 1159 int bpf_check_btf_info_early(struct bpf_verifier_env *env, 1160 const union bpf_attr *attr, bpfptr_t uattr); 1161 int bpf_check_btf_info(struct bpf_verifier_env *env, 1162 const union bpf_attr *attr, bpfptr_t uattr); 1163 1164 int bpf_check_attach_target(struct bpf_verifier_log *log, 1165 const struct bpf_prog *prog, 1166 const struct bpf_prog *tgt_prog, 1167 u32 btf_id, 1168 struct bpf_attach_target_info *tgt_info); 1169 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab); 1170 1171 int mark_chain_precision(struct bpf_verifier_env *env, int regno); 1172 1173 int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx); 1174 int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st); 1175 1176 void bpf_clear_jmp_history(struct bpf_verifier_state *state); 1177 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1178 const struct bpf_verifier_state *src); 1179 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx); 1180 void bpf_free_verifier_state(struct bpf_verifier_state *state, bool free_self); 1181 void bpf_free_backedges(struct bpf_scc_visit *visit); 1182 int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 1183 int insn_flags, int spi, int frame, u64 linked_regs); 1184 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist); 1185 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 1186 struct bpf_reg_state *reg); 1187 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg); 1188 void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env, 1189 struct bpf_verifier_state *st); 1190 void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st); 1191 int bpf_mark_chain_precision(struct bpf_verifier_env *env, 1192 struct bpf_verifier_state *starting_state, 1193 int regno, bool *changed); 1194 1195 static inline int bpf_get_spi(s32 off) 1196 { 1197 return (-off - 1) / BPF_REG_SIZE; 1198 } 1199 1200 static inline struct bpf_func_state *bpf_func(struct bpf_verifier_env *env, 1201 const struct bpf_reg_state *reg) 1202 { 1203 struct bpf_verifier_state *cur = env->cur_state; 1204 1205 return cur->frame[reg->frameno]; 1206 } 1207 1208 /* Return IP for a given frame in a call stack */ 1209 static inline u32 bpf_frame_insn_idx(struct bpf_verifier_state *st, u32 frame) 1210 { 1211 return frame == st->curframe 1212 ? st->insn_idx 1213 : st->frame[frame + 1]->callsite; 1214 } 1215 1216 static inline bool bpf_is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 1217 { 1218 return env->insn_aux_data[insn_idx].jmp_point; 1219 } 1220 1221 static inline bool bpf_is_spilled_reg(const struct bpf_stack_state *stack) 1222 { 1223 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1224 } 1225 1226 static inline bool bpf_is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1227 { 1228 return bpf_is_spilled_reg(stack) && stack->spilled_ptr.type == SCALAR_VALUE; 1229 } 1230 1231 static inline bool bpf_register_is_null(struct bpf_reg_state *reg) 1232 { 1233 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 1234 } 1235 1236 static inline void bpf_bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 1237 { 1238 bt->reg_masks[frame] |= 1 << reg; 1239 } 1240 1241 static inline void bpf_bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 1242 { 1243 bt->stack_masks[frame] |= 1ull << slot; 1244 } 1245 1246 static inline void bt_set_frame_stack_arg_slot(struct backtrack_state *bt, u32 frame, u32 slot) 1247 { 1248 bt->stack_arg_masks[frame] |= 1 << slot; 1249 } 1250 1251 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 1252 { 1253 return bt->reg_masks[frame] & (1 << reg); 1254 } 1255 1256 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 1257 { 1258 return bt->stack_masks[frame] & (1ull << slot); 1259 } 1260 1261 bool bpf_map_is_rdonly(const struct bpf_map *map); 1262 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 1263 bool is_ldsx); 1264 1265 #define BPF_BASE_TYPE_MASK GENMASK(BPF_BASE_TYPE_BITS - 1, 0) 1266 1267 /* extract base type from bpf_{arg, return, reg}_type. */ 1268 static inline u32 base_type(u32 type) 1269 { 1270 return type & BPF_BASE_TYPE_MASK; 1271 } 1272 1273 /* extract flags from an extended type. See bpf_type_flag in bpf.h. */ 1274 static inline u32 type_flag(u32 type) 1275 { 1276 return type & ~BPF_BASE_TYPE_MASK; 1277 } 1278 1279 /* only use after check_attach_btf_id() */ 1280 static inline enum bpf_prog_type resolve_prog_type(const struct bpf_prog *prog) 1281 { 1282 return (prog->type == BPF_PROG_TYPE_EXT && prog->aux->saved_dst_prog_type) ? 1283 prog->aux->saved_dst_prog_type : prog->type; 1284 } 1285 1286 static inline bool bpf_prog_check_recur(const struct bpf_prog *prog) 1287 { 1288 switch (resolve_prog_type(prog)) { 1289 case BPF_PROG_TYPE_TRACING: 1290 return prog->expected_attach_type != BPF_TRACE_ITER; 1291 case BPF_PROG_TYPE_STRUCT_OPS: 1292 return prog->aux->jits_use_priv_stack; 1293 case BPF_PROG_TYPE_LSM: 1294 case BPF_PROG_TYPE_SYSCALL: 1295 return false; 1296 default: 1297 return true; 1298 } 1299 } 1300 1301 #define BPF_REG_TRUSTED_MODIFIERS (MEM_ALLOC | PTR_TRUSTED | NON_OWN_REF) 1302 1303 static inline bool bpf_type_has_unsafe_modifiers(u32 type) 1304 { 1305 return type_flag(type) & ~BPF_REG_TRUSTED_MODIFIERS; 1306 } 1307 1308 static inline bool type_is_ptr_alloc_obj(u32 type) 1309 { 1310 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 1311 } 1312 1313 static inline bool type_is_non_owning_ref(u32 type) 1314 { 1315 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 1316 } 1317 1318 static inline bool type_is_pkt_pointer(enum bpf_reg_type type) 1319 { 1320 type = base_type(type); 1321 return type == PTR_TO_PACKET || 1322 type == PTR_TO_PACKET_META; 1323 } 1324 1325 static inline bool type_is_sk_pointer(enum bpf_reg_type type) 1326 { 1327 return type == PTR_TO_SOCKET || 1328 type == PTR_TO_SOCK_COMMON || 1329 type == PTR_TO_TCP_SOCK || 1330 type == PTR_TO_XDP_SOCK; 1331 } 1332 1333 static inline bool type_may_be_null(u32 type) 1334 { 1335 return type & PTR_MAYBE_NULL; 1336 } 1337 1338 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 1339 { 1340 env->scratched_regs |= 1U << regno; 1341 } 1342 1343 static inline void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 1344 { 1345 env->scratched_stack_slots |= 1ULL << spi; 1346 } 1347 1348 static inline bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 1349 { 1350 return (env->scratched_regs >> regno) & 1; 1351 } 1352 1353 static inline bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 1354 { 1355 return (env->scratched_stack_slots >> regno) & 1; 1356 } 1357 1358 static inline bool verifier_state_scratched(const struct bpf_verifier_env *env) 1359 { 1360 return env->scratched_regs || env->scratched_stack_slots; 1361 } 1362 1363 static inline void mark_verifier_state_clean(struct bpf_verifier_env *env) 1364 { 1365 env->scratched_regs = 0U; 1366 env->scratched_stack_slots = 0ULL; 1367 } 1368 1369 /* Used for printing the entire verifier state. */ 1370 static inline void mark_verifier_state_scratched(struct bpf_verifier_env *env) 1371 { 1372 env->scratched_regs = ~0U; 1373 env->scratched_stack_slots = ~0ULL; 1374 } 1375 1376 static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_size) 1377 { 1378 #ifdef __BIG_ENDIAN 1379 off -= spill_size - fill_size; 1380 #endif 1381 1382 return !(off % BPF_REG_SIZE); 1383 } 1384 1385 static inline bool insn_is_gotox(struct bpf_insn *insn) 1386 { 1387 return BPF_CLASS(insn->code) == BPF_JMP && 1388 BPF_OP(insn->code) == BPF_JA && 1389 BPF_SRC(insn->code) == BPF_X; 1390 } 1391 1392 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type); 1393 const char *dynptr_type_str(enum bpf_dynptr_type type); 1394 const char *iter_type_str(const struct btf *btf, u32 btf_id); 1395 const char *iter_state_str(enum bpf_iter_state state); 1396 1397 void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate, 1398 u32 frameno, bool print_all); 1399 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate, 1400 u32 frameno); 1401 u32 bpf_vlog_alignment(u32 pos); 1402 1403 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off); 1404 int bpf_jmp_offset(struct bpf_insn *insn); 1405 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx); 1406 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask); 1407 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog); 1408 1409 int bpf_find_subprog(struct bpf_verifier_env *env, int off); 1410 bool bpf_is_throw_kfunc(struct bpf_insn *insn); 1411 int bpf_compute_const_regs(struct bpf_verifier_env *env); 1412 int bpf_prune_dead_branches(struct bpf_verifier_env *env); 1413 int bpf_check_cfg(struct bpf_verifier_env *env); 1414 int bpf_compute_postorder(struct bpf_verifier_env *env); 1415 int bpf_compute_scc(struct bpf_verifier_env *env); 1416 1417 struct bpf_map_desc { 1418 struct bpf_map *ptr; 1419 int uid; 1420 }; 1421 1422 /* The last initialized dynptr; Populated by process_dynptr_func() */ 1423 struct bpf_dynptr_desc { 1424 enum bpf_dynptr_type type; 1425 u32 id; 1426 u32 parent_id; 1427 }; 1428 1429 /* 1430 * The last seen rereferenced object; Updated by update_ref_obj() when a register refers to a 1431 * referenced object. Used when the helper or kfunc is casting a referenced object, returning 1432 * allocated memory derived from referenced object or creating a dynptr with a referenced 1433 * object as parent. 1434 */ 1435 struct ref_obj_desc { 1436 u32 id; 1437 u32 parent_id; 1438 u8 cnt; 1439 }; 1440 1441 struct bpf_kfunc_call_arg_meta { 1442 /* In parameters */ 1443 struct btf *btf; 1444 u32 func_id; 1445 u32 kfunc_flags; 1446 const struct btf_type *func_proto; 1447 const char *func_name; 1448 /* Out parameters */ 1449 u8 release_regno; 1450 bool r0_rdonly; 1451 u32 ret_btf_id; 1452 u64 r0_size; 1453 u32 subprogno; 1454 struct { 1455 u64 value; 1456 bool found; 1457 } arg_constant; 1458 1459 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 1460 * generally to pass info about user-defined local kptr types to later 1461 * verification logic 1462 * bpf_obj_drop/bpf_percpu_obj_drop 1463 * Record the local kptr type to be drop'd 1464 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 1465 * Record the local kptr type to be refcount_incr'd and use 1466 * arg_owning_ref to determine whether refcount_acquire should be 1467 * fallible 1468 */ 1469 struct btf *arg_btf; 1470 u32 arg_btf_id; 1471 bool arg_owning_ref; 1472 bool arg_prog; 1473 1474 struct { 1475 struct btf_field *field; 1476 } arg_list_head; 1477 struct { 1478 struct btf_field *field; 1479 } arg_rbtree_root; 1480 struct { 1481 u8 spi; 1482 u8 frameno; 1483 } iter; 1484 struct bpf_map_desc map; 1485 struct bpf_dynptr_desc dynptr; 1486 struct ref_obj_desc ref_obj; 1487 u64 mem_size; 1488 }; 1489 1490 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 1491 const struct bpf_func_proto **ptr); 1492 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, s32 func_id, 1493 s16 offset, struct bpf_kfunc_call_arg_meta *meta); 1494 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn); 1495 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn); 1496 static inline bool bpf_is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 1497 { 1498 return meta->kfunc_flags & KF_ITER_NEXT; 1499 } 1500 1501 static inline bool bpf_is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 1502 { 1503 return meta->kfunc_flags & KF_SLEEPABLE; 1504 } 1505 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta); 1506 struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem); 1507 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off); 1508 bool bpf_insn_is_cond_jump(u8 code); 1509 bool bpf_is_may_goto_insn(struct bpf_insn *insn); 1510 1511 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn); 1512 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 1513 struct bpf_call_summary *cs); 1514 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, 1515 struct bpf_insn *insn, int arg, 1516 int insn_idx); 1517 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, 1518 struct bpf_insn *insn, int arg, 1519 int insn_idx); 1520 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env); 1521 1522 int bpf_stack_liveness_init(struct bpf_verifier_env *env); 1523 void bpf_stack_liveness_free(struct bpf_verifier_env *env); 1524 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st); 1525 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi); 1526 int bpf_compute_live_registers(struct bpf_verifier_env *env); 1527 1528 #define BPF_MAP_KEY_POISON (1ULL << 63) 1529 #define BPF_MAP_KEY_SEEN (1ULL << 62) 1530 1531 static inline bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 1532 { 1533 return aux->map_ptr_state.poison; 1534 } 1535 1536 static inline bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 1537 { 1538 return aux->map_ptr_state.unpriv; 1539 } 1540 1541 static inline bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 1542 { 1543 return aux->map_key_state & BPF_MAP_KEY_POISON; 1544 } 1545 1546 static inline bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 1547 { 1548 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 1549 } 1550 1551 static inline u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 1552 { 1553 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 1554 } 1555 1556 #define MAX_PACKET_OFF 0xffff 1557 #define CALLER_SAVED_REGS 6 1558 1559 enum bpf_reg_arg_type { 1560 SRC_OP, /* register is used as source operand */ 1561 DST_OP, /* register is used as destination operand */ 1562 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1563 }; 1564 1565 #define MAX_KFUNC_DESCS 256 1566 1567 struct bpf_kfunc_desc { 1568 struct btf_func_model func_model; 1569 u32 func_id; 1570 s32 imm; 1571 u16 offset; 1572 unsigned long addr; 1573 }; 1574 1575 struct bpf_kfunc_desc_tab { 1576 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 1577 * verification. JITs do lookups by bpf_insn, where func_id may not be 1578 * available, therefore at the end of verification do_misc_fixups() 1579 * sorts this by imm and offset. 1580 */ 1581 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 1582 u32 nr_descs; 1583 }; 1584 1585 /* Functions exported from verifier.c, used by fixups.c */ 1586 bool bpf_is_reg64(struct bpf_insn *insn, u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t); 1587 void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len); 1588 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog); 1589 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env); 1590 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm); 1591 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset); 1592 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 1593 struct bpf_insn *insn_buf, int insn_idx, int *cnt); 1594 1595 /* Functions exported from verifier.c, used by trampoline.c */ 1596 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 1597 struct bpf_attach_target_info *tgt_info); 1598 1599 /* Functions in fixups.c, called from bpf_check() */ 1600 int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env); 1601 int bpf_optimize_bpf_loop(struct bpf_verifier_env *env); 1602 void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env); 1603 int bpf_opt_remove_dead_code(struct bpf_verifier_env *env); 1604 int bpf_opt_remove_nops(struct bpf_verifier_env *env); 1605 int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr); 1606 int bpf_convert_ctx_accesses(struct bpf_verifier_env *env); 1607 int bpf_jit_subprogs(struct bpf_verifier_env *env); 1608 int bpf_fixup_call_args(struct bpf_verifier_env *env); 1609 int bpf_do_misc_fixups(struct bpf_verifier_env *env); 1610 1611 #endif /* _LINUX_BPF_VERIFIER_H */ 1612