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