1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ 3 4 #include <linux/bpf_verifier.h> 5 #include <linux/btf.h> 6 #include <linux/hashtable.h> 7 #include <linux/jhash.h> 8 #include <linux/slab.h> 9 #include <linux/sort.h> 10 11 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args) 12 13 /* 14 * Stack liveness is tracked with a 4-byte (half register) granularity. 15 * Half-slot 0 covers [fp-4, fp), half-slot 1 covers [fp-8, fp-4), and so on, 16 * hence FRAME_HALF_SPIS - 1 is the deepest half-slot a frame can have. 17 */ 18 #define FRAME_HALF_SPIS (MAX_BPF_STACK_JIT / BPF_HALF_REG_SIZE) 19 #define FRAME_MAX_WORDS BITS_TO_LONGS(FRAME_HALF_SPIS) 20 21 /* Masks tracked for each instruction of a frame */ 22 enum { 23 FM_MAY_READ, /* stack slots that may be read by this instruction */ 24 FM_MUST_WRITE, /* stack slots written by this instruction */ 25 FM_LIVE_BEFORE, /* stack slots that may be read by this insn and its successors */ 26 FM_MAY_WRITE, /* stack slots that may be written by this instruction */ 27 FM_MASK_CNT, 28 }; 29 30 /* 31 * Per instruction stack masks for one frame of a function instance. 32 * 33 * Most frames use only a fraction of the stack budget, so instead of masks 34 * wide enough for every half-slot of the largest possible frame, all masks 35 * of one array share the width @words, and the marking functions widen the 36 * array as deeper half-slots are recorded. Mask @kind of the instruction at 37 * relative index @i is at &bits[(i * FM_MASK_CNT + kind) * words]. A 38 * half-slot at or past @words * BITS_PER_LONG is never read by this frame, 39 * hence never live. An instruction that may read the whole frame, such as a 40 * call passing a frame pointer to another subprog, widens the array to the 41 * program's stack budget, the deepest an accepted program can reach, so 42 * that the read cannot lose half-slots to a later widening. 43 */ 44 struct frame_masks { 45 u32 words; 46 unsigned long bits[]; 47 }; 48 49 /* 50 * A function instance keyed by (callsite, depth). 51 * Encapsulates read and write marks for each instruction in the function. 52 * Marks are tracked for each frame up to @depth. 53 */ 54 struct func_instance { 55 struct hlist_node hl_node; 56 u32 callsite; /* call insn that invoked this subprog (subprog_start for depth 0) */ 57 u32 depth; /* call depth (0 = entry subprog) */ 58 u32 subprog; /* subprog index */ 59 u32 subprog_start; /* cached env->subprog_info[subprog].start */ 60 u32 insn_cnt; /* cached number of insns in the function */ 61 /* Per frame, per instruction masks, frames allocated lazily. */ 62 struct frame_masks *frames[MAX_CALL_FRAMES]; 63 bool must_write_initialized; 64 }; 65 66 struct live_stack_query { 67 struct func_instance *instances[MAX_CALL_FRAMES]; /* valid in range [0..curframe] */ 68 u32 callsites[MAX_CALL_FRAMES]; /* callsite[i] = insn calling frame i+1 */ 69 u32 curframe; 70 u32 insn_idx; 71 }; 72 73 struct bpf_liveness { 74 DECLARE_HASHTABLE(func_instances, 8); /* maps (depth, callsite) to func_instance */ 75 struct live_stack_query live_stack_query; /* cache to avoid repetitive ht lookups */ 76 u32 subprog_calls; /* analyze_subprog() invocations */ 77 }; 78 79 /* 80 * Hash/compare key for func_instance: (depth, callsite). 81 * For depth == 0 (entry subprog), @callsite is the subprog start insn. 82 * For depth > 0, @callsite is the call instruction index that invoked the subprog. 83 */ 84 static u32 instance_hash(u32 callsite, u32 depth) 85 { 86 u32 key[2] = { depth, callsite }; 87 88 return jhash2(key, 2, 0); 89 } 90 91 static struct func_instance *find_instance(struct bpf_verifier_env *env, 92 u32 callsite, u32 depth) 93 { 94 struct bpf_liveness *liveness = env->liveness; 95 struct func_instance *f; 96 u32 key = instance_hash(callsite, depth); 97 98 hash_for_each_possible(liveness->func_instances, f, hl_node, key) 99 if (f->depth == depth && f->callsite == callsite) 100 return f; 101 return NULL; 102 } 103 104 static struct func_instance *call_instance(struct bpf_verifier_env *env, 105 struct func_instance *caller, 106 u32 callsite, int subprog) 107 { 108 u32 depth = caller ? caller->depth + 1 : 0; 109 u32 subprog_start = env->subprog_info[subprog].start; 110 u32 lookup_key = depth > 0 ? callsite : subprog_start; 111 struct func_instance *f; 112 u32 hash; 113 114 f = find_instance(env, lookup_key, depth); 115 if (f) 116 return f; 117 118 f = kvzalloc_obj(*f, GFP_KERNEL_ACCOUNT); 119 if (!f) 120 return ERR_PTR(-ENOMEM); 121 f->callsite = lookup_key; 122 f->depth = depth; 123 f->subprog = subprog; 124 f->subprog_start = subprog_start; 125 f->insn_cnt = (env->subprog_info + subprog + 1)->start - subprog_start; 126 hash = instance_hash(lookup_key, depth); 127 hash_add(env->liveness->func_instances, &f->hl_node, hash); 128 return f; 129 } 130 131 static struct func_instance *lookup_instance(struct bpf_verifier_env *env, 132 struct bpf_verifier_state *st, 133 u32 frameno) 134 { 135 u32 callsite, subprog_start; 136 struct func_instance *f; 137 u32 key, depth; 138 139 subprog_start = env->subprog_info[st->frame[frameno]->subprogno].start; 140 callsite = frameno > 0 ? st->frame[frameno]->callsite : subprog_start; 141 142 for (depth = frameno; ; depth--) { 143 key = depth > 0 ? callsite : subprog_start; 144 f = find_instance(env, key, depth); 145 if (f || depth == 0) 146 return f; 147 } 148 } 149 150 int bpf_stack_liveness_init(struct bpf_verifier_env *env) 151 { 152 env->liveness = kvzalloc_obj(*env->liveness, GFP_KERNEL_ACCOUNT); 153 if (!env->liveness) 154 return -ENOMEM; 155 hash_init(env->liveness->func_instances); 156 return 0; 157 } 158 159 void bpf_stack_liveness_free(struct bpf_verifier_env *env) 160 { 161 struct func_instance *instance; 162 struct hlist_node *tmp; 163 int bkt, i; 164 165 if (!env->liveness) 166 return; 167 hash_for_each_safe(env->liveness->func_instances, bkt, tmp, instance, hl_node) { 168 for (i = 0; i <= instance->depth; i++) 169 kvfree(instance->frames[i]); 170 kvfree(instance); 171 } 172 kvfree(env->liveness); 173 } 174 175 /* 176 * Convert absolute instruction index @insn_idx to an index relative 177 * to start of the function corresponding to @instance. 178 */ 179 static int relative_idx(struct func_instance *instance, u32 insn_idx) 180 { 181 return insn_idx - instance->subprog_start; 182 } 183 184 static u32 frame_mask_bits(struct frame_masks *fm) 185 { 186 return fm->words * BITS_PER_LONG; 187 } 188 189 static size_t frame_mask_words(struct func_instance *instance, u32 words) 190 { 191 return (size_t)instance->insn_cnt * FM_MASK_CNT * words; 192 } 193 194 /* Mask @kind of the instruction at relative index @rel */ 195 static unsigned long *rel_mask(struct frame_masks *fm, u32 rel, u32 kind) 196 { 197 return fm->bits + ((size_t)rel * FM_MASK_CNT + kind) * fm->words; 198 } 199 200 /* 201 * Make sure @frame has a mask array at least @words wide, allocating it or 202 * copying the existing masks into the wider stride as needed. 203 * @words must be in range [1, FRAME_MAX_WORDS]. 204 */ 205 static struct frame_masks *widen_frame_masks(struct func_instance *instance, 206 u32 frame, u32 words) 207 { 208 struct frame_masks *old = instance->frames[frame], *new; 209 u32 i, kind; 210 211 if (old && old->words >= words) 212 return old; 213 new = kvzalloc_flex(*new, bits, frame_mask_words(instance, words), GFP_KERNEL_ACCOUNT); 214 if (!new) 215 return NULL; 216 new->words = words; 217 if (old) { 218 for (i = 0; i < instance->insn_cnt; i++) 219 for (kind = 0; kind < FM_MASK_CNT; kind++) 220 memcpy(rel_mask(new, i, kind), rel_mask(old, i, kind), 221 old->words * sizeof(*old->bits)); 222 kvfree(old); 223 } 224 instance->frames[frame] = new; 225 return new; 226 } 227 228 /* 229 * Set the inclusive half-slot range [lo, hi] in mask @kind of @frame at @insn_idx. 230 * An empty range, including one with a negative @hi as computed for a write 231 * that does not fully cover any half-slot, marks nothing. 232 */ 233 static int mark_stack_range(struct func_instance *instance, u32 frame, u32 insn_idx, 234 u32 kind, s32 lo, s32 hi) 235 { 236 struct frame_masks *fm; 237 238 /* 239 * An access past the frame bottom is rejected by the main verifier 240 * pass later, liveness only has to avoid running off the masks. 241 */ 242 hi = min_t(s32, hi, FRAME_HALF_SPIS - 1); 243 if (lo > hi) 244 return 0; 245 fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(hi + 1)); 246 if (!fm) 247 return -ENOMEM; 248 bitmap_set(rel_mask(fm, relative_idx(instance, insn_idx), kind), lo, hi - lo + 1); 249 return 0; 250 } 251 252 /* Accumulate may_read for half-slots [lo, hi] of @frame at @insn_idx */ 253 static int mark_stack_read(struct func_instance *instance, u32 frame, u32 insn_idx, 254 s32 lo, s32 hi) 255 { 256 return mark_stack_range(instance, frame, insn_idx, FM_MAY_READ, lo, hi); 257 } 258 259 /* Accumulate must_write for half-slots [lo, hi] of @frame at @insn_idx */ 260 static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_idx, 261 s32 lo, s32 hi) 262 { 263 return mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi); 264 } 265 266 static int mark_stack_may_write(struct func_instance *instance, u32 frame, u32 insn_idx, 267 s32 lo, s32 hi) 268 { 269 return mark_stack_range(instance, frame, insn_idx, FM_MAY_WRITE, lo, hi); 270 } 271 272 /* 273 * Mark every half-slot of @frame as possibly read by @insn_idx. This widens 274 * the masks to the program's stack budget: a full read recorded at a narrower 275 * width would leave the bits added by a later widening clear and lose part of 276 * it. No verifier state holds a slot past the budget, so no liveness query 277 * reaches beyond it; an access past the budget in unreachable code may still 278 * widen a frame's masks further, which is harmless. 279 */ 280 static int mark_stack_read_all(struct bpf_verifier_env *env, struct func_instance *instance, 281 u32 frame, u32 insn_idx) 282 { 283 return mark_stack_read(instance, frame, insn_idx, 0, 284 env->stack_limit / BPF_HALF_REG_SIZE - 1); 285 } 286 287 static int mark_stack_may_write_all(struct bpf_verifier_env *env, struct func_instance *instance, 288 u32 frame, u32 insn_idx) 289 { 290 return mark_stack_may_write(instance, frame, insn_idx, 0, 291 env->stack_limit / BPF_HALF_REG_SIZE - 1); 292 } 293 294 /* Accumulate @src, a mask @src_words wide, into @kind mask of @frame at @insn_idx */ 295 static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_idx, u32 kind, 296 const unsigned long *src, u32 src_words) 297 { 298 u32 nbits = src_words * BITS_PER_LONG; 299 struct frame_masks *fm; 300 unsigned long *dst; 301 u32 last, w; 302 303 last = find_last_bit(src, nbits); 304 if (last == nbits) 305 return 0; 306 fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1)); 307 if (!fm) 308 return -ENOMEM; 309 dst = rel_mask(fm, relative_idx(instance, insn_idx), kind); 310 /* @src has no bits set past @last, hence none past @fm->words either */ 311 src_words = min(src_words, fm->words); 312 for (w = 0; w < src_words; w++) 313 dst[w] |= src[w]; 314 return 0; 315 } 316 317 static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx, 318 const unsigned long *src, u32 src_words) 319 { 320 return mark_stack_mask(instance, frame, insn_idx, FM_MAY_READ, src, src_words); 321 } 322 323 int bpf_jmp_offset(struct bpf_insn *insn) 324 { 325 u8 code = insn->code; 326 327 if (code == (BPF_JMP32 | BPF_JA)) 328 return insn->imm; 329 return insn->off; 330 } 331 332 __diag_push(); 333 __diag_ignore_all("-Woverride-init", "Allow field initialization overrides for opcode_info_tbl"); 334 335 /* 336 * Returns an array of instructions succ, with succ->items[0], ..., 337 * succ->items[n-1] with successor instructions, where n=succ->cnt 338 */ 339 inline struct bpf_iarray * 340 bpf_insn_successors(struct bpf_verifier_env *env, u32 idx) 341 { 342 static const struct opcode_info { 343 bool can_jump; 344 bool can_fallthrough; 345 } opcode_info_tbl[256] = { 346 [0 ... 255] = {.can_jump = false, .can_fallthrough = true}, 347 #define _J(code, ...) \ 348 [BPF_JMP | code] = __VA_ARGS__, \ 349 [BPF_JMP32 | code] = __VA_ARGS__ 350 351 _J(BPF_EXIT, {.can_jump = false, .can_fallthrough = false}), 352 _J(BPF_JA, {.can_jump = true, .can_fallthrough = false}), 353 _J(BPF_JEQ, {.can_jump = true, .can_fallthrough = true}), 354 _J(BPF_JNE, {.can_jump = true, .can_fallthrough = true}), 355 _J(BPF_JLT, {.can_jump = true, .can_fallthrough = true}), 356 _J(BPF_JLE, {.can_jump = true, .can_fallthrough = true}), 357 _J(BPF_JGT, {.can_jump = true, .can_fallthrough = true}), 358 _J(BPF_JGE, {.can_jump = true, .can_fallthrough = true}), 359 _J(BPF_JSGT, {.can_jump = true, .can_fallthrough = true}), 360 _J(BPF_JSGE, {.can_jump = true, .can_fallthrough = true}), 361 _J(BPF_JSLT, {.can_jump = true, .can_fallthrough = true}), 362 _J(BPF_JSLE, {.can_jump = true, .can_fallthrough = true}), 363 _J(BPF_JCOND, {.can_jump = true, .can_fallthrough = true}), 364 _J(BPF_JSET, {.can_jump = true, .can_fallthrough = true}), 365 #undef _J 366 }; 367 struct bpf_prog *prog = env->prog; 368 struct bpf_insn *insn = &prog->insnsi[idx]; 369 const struct opcode_info *opcode_info; 370 struct bpf_iarray *succ, *jt; 371 int insn_sz; 372 373 /* pre-allocated array of size up to 2; reset cnt, as it may have been used already */ 374 succ = env->succ; 375 succ->cnt = 0; 376 377 /* All gotox of a subprogram share its jump table, see compute_subprog_jts() */ 378 if (unlikely(insn_is_gotox(insn))) { 379 jt = bpf_find_containing_subprog(env, idx)->jt; 380 if (verifier_bug_if(!jt, env, "no jump table for gotox insn %u", idx)) 381 return succ; 382 return jt; 383 } 384 385 opcode_info = &opcode_info_tbl[BPF_CLASS(insn->code) | BPF_OP(insn->code)]; 386 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 387 if (opcode_info->can_fallthrough) 388 succ->items[succ->cnt++] = idx + insn_sz; 389 390 if (opcode_info->can_jump) 391 succ->items[succ->cnt++] = idx + bpf_jmp_offset(insn) + 1; 392 393 /* 394 * tail_call upon success and ld_{abs,ind} upon load failure return 395 * from the subprogram, which is a hidden edge to its exit. A subprogram 396 * without an exit insn has no exit to model. 397 */ 398 if (unlikely((bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) || 399 (BPF_CLASS(insn->code) == BPF_LD && 400 (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)))) { 401 u32 exit_idx = bpf_find_containing_subprog(env, idx)->exit_idx; 402 403 if (exit_idx != U32_MAX) 404 succ->items[succ->cnt++] = exit_idx; 405 } 406 407 return succ; 408 } 409 410 __diag_pop(); 411 412 static inline bool update_insn(struct bpf_verifier_env *env, 413 struct func_instance *instance, u32 frame, u32 insn_idx) 414 { 415 unsigned long new_after[FRAME_MAX_WORDS] = {}; 416 unsigned long *may_read, *must_write, *live_before; 417 struct frame_masks *fm = instance->frames[frame]; 418 u32 rel = relative_idx(instance, insn_idx); 419 struct bpf_iarray *succ; 420 bool changed = false; 421 u32 s, w; 422 423 succ = bpf_insn_successors(env, insn_idx); 424 if (succ->cnt == 0) 425 return false; 426 427 /* All instructions of one frame array share the same mask width */ 428 for (s = 0; s < succ->cnt; ++s) { 429 unsigned long *succ_live; 430 431 succ_live = rel_mask(fm, relative_idx(instance, succ->items[s]), FM_LIVE_BEFORE); 432 for (w = 0; w < fm->words; w++) 433 new_after[w] |= succ_live[w]; 434 } 435 may_read = rel_mask(fm, rel, FM_MAY_READ); 436 must_write = rel_mask(fm, rel, FM_MUST_WRITE); 437 live_before = rel_mask(fm, rel, FM_LIVE_BEFORE); 438 /* 439 * New "live_before" is a union of all "live_before" of successors 440 * minus slots written by instruction plus slots read by instruction. 441 * new_before = (new_after & ~insn->must_write) | insn->may_read 442 */ 443 for (w = 0; w < fm->words; w++) { 444 unsigned long new_before = (new_after[w] & ~must_write[w]) | may_read[w]; 445 446 if (new_before != live_before[w]) { 447 live_before[w] = new_before; 448 changed = true; 449 } 450 } 451 return changed; 452 } 453 454 /* Fixed-point computation of @live_before marks */ 455 static void update_instance(struct bpf_verifier_env *env, struct func_instance *instance) 456 { 457 u32 i, frame, po_start, po_end; 458 int *insn_postorder = env->cfg.insn_postorder; 459 struct bpf_subprog_info *subprog; 460 bool changed; 461 462 instance->must_write_initialized = true; 463 subprog = &env->subprog_info[instance->subprog]; 464 po_start = subprog->postorder_start; 465 po_end = (subprog + 1)->postorder_start; 466 /* repeat until fixed point is reached */ 467 do { 468 changed = false; 469 for (frame = 0; frame <= instance->depth; frame++) { 470 if (!instance->frames[frame]) 471 continue; 472 473 for (i = po_start; i < po_end; i++) 474 changed |= update_insn(env, instance, frame, insn_postorder[i]); 475 } 476 } while (changed); 477 } 478 479 static bool is_live_before(struct func_instance *instance, u32 insn_idx, u32 frameno, u32 half_spi) 480 { 481 struct frame_masks *fm = instance->frames[frameno]; 482 483 /* No recorded access reaches past the masks, so nothing there is live */ 484 if (!fm || half_spi >= frame_mask_bits(fm)) 485 return false; 486 return test_bit(half_spi, rel_mask(fm, relative_idx(instance, insn_idx), FM_LIVE_BEFORE)); 487 } 488 489 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 490 { 491 struct live_stack_query *q = &env->liveness->live_stack_query; 492 struct func_instance *instance; 493 u32 frame; 494 495 memset(q, 0, sizeof(*q)); 496 for (frame = 0; frame <= st->curframe; frame++) { 497 instance = lookup_instance(env, st, frame); 498 if (IS_ERR_OR_NULL(instance)) 499 q->instances[frame] = NULL; 500 else 501 q->instances[frame] = instance; 502 if (frame < st->curframe) 503 q->callsites[frame] = st->frame[frame + 1]->callsite; 504 } 505 q->curframe = st->curframe; 506 q->insn_idx = st->insn_idx; 507 return 0; 508 } 509 510 /* 511 * Stack slots of outer frames that the callee may read are accounted as read 512 * by the @callsite insn itself, i.e. they are live before @callsite and may be 513 * dead after it, when: 514 * - @callsite calls a callback, which may be called several times; 515 * - @callsite is callx. Its callee is not known when stack liveness is 516 * computed, so there is no func instance for it at @callsite. While 517 * the verifier is in the callee lookup_instance() finds its standalone 518 * instance that knows nothing about outer frames. What the callee may read 519 * there is recorded by record_call_access(). 520 */ 521 static bool callee_stack_access_at_callsite(struct bpf_verifier_env *env, u32 callsite) 522 { 523 return bpf_calls_callback(env, callsite) || 524 bpf_is_callx(&env->prog->insnsi[callsite]); 525 } 526 527 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi) 528 { 529 /* 530 * Slot is alive if it is read before q->insn_idx in current func instance, 531 * or if for some outer func instance: 532 * - alive before callsite if callsite calls callback or is callx, otherwise 533 * - alive after callsite 534 */ 535 struct live_stack_query *q = &env->liveness->live_stack_query; 536 struct func_instance *instance, *curframe_instance; 537 u32 i, callsite, rel; 538 int cur_delta, delta; 539 bool alive = false; 540 541 curframe_instance = q->instances[q->curframe]; 542 if (!curframe_instance) 543 return true; 544 cur_delta = (int)curframe_instance->depth - (int)q->curframe; 545 rel = frameno + cur_delta; 546 if (rel <= curframe_instance->depth) 547 alive = is_live_before(curframe_instance, q->insn_idx, rel, half_spi); 548 549 if (alive) 550 return true; 551 552 for (i = frameno; i < q->curframe; i++) { 553 instance = q->instances[i]; 554 if (!instance) 555 return true; 556 /* Map actual frameno to frame index within this instance */ 557 delta = (int)instance->depth - (int)i; 558 rel = frameno + delta; 559 if (rel > instance->depth) 560 return true; 561 562 /* Get callsite from verifier state, not from instance callchain */ 563 callsite = q->callsites[i]; 564 565 alive = callee_stack_access_at_callsite(env, callsite) 566 ? is_live_before(instance, callsite, rel, half_spi) 567 : is_live_before(instance, callsite + 1, rel, half_spi); 568 if (alive) 569 return true; 570 } 571 572 return false; 573 } 574 575 static char *fmt_subprog(struct bpf_verifier_env *env, int subprog) 576 { 577 const char *name = env->subprog_info[subprog].name; 578 579 snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf), 580 "subprog#%d%s%s", subprog, name ? " " : "", name ? name : ""); 581 return env->tmp_str_buf; 582 } 583 584 static char *fmt_instance(struct bpf_verifier_env *env, struct func_instance *instance) 585 { 586 snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf), 587 "(d%d,cs%d)", instance->depth, instance->callsite); 588 return env->tmp_str_buf; 589 } 590 591 static int spi_off(int spi) 592 { 593 return -(spi + 1) * BPF_REG_SIZE; 594 } 595 596 /* 597 * When both halves of an 8-byte SPI are set, print as "-8","-16",... 598 * When only one half is set, print as "-4h","-8h",... 599 * Runs of 3+ consecutive fully-set SPIs are collapsed: "fp0-8..-24" 600 */ 601 static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first, 602 const unsigned long *spis, u32 words) 603 { 604 int buf_sz = sizeof(env->tmp_str_buf); 605 int spi_cnt = words * BITS_PER_LONG / 2; 606 char *buf = env->tmp_str_buf; 607 int spi, n, run_start; 608 609 buf[0] = '\0'; 610 611 for (spi = 0; spi < spi_cnt && buf_sz > 0; spi++) { 612 bool lo = test_bit(spi * 2, spis); 613 bool hi = test_bit(spi * 2 + 1, spis); 614 const char *space = first ? "" : " "; 615 616 if (!lo && !hi) 617 continue; 618 619 if (!lo || !hi) { 620 /* half-spi */ 621 n = scnprintf(buf, buf_sz, "%sfp%d%d%s", 622 space, frame, spi_off(spi) + (lo ? STACK_SLOT_SZ : 0), "h"); 623 } else if (spi + 2 < spi_cnt && 624 test_bit(spi * 2 + 2, spis) && 625 test_bit(spi * 2 + 3, spis) && 626 test_bit(spi * 2 + 4, spis) && 627 test_bit(spi * 2 + 5, spis)) { 628 /* 3+ consecutive full spis */ 629 run_start = spi; 630 while (spi + 1 < spi_cnt && 631 test_bit((spi + 1) * 2, spis) && 632 test_bit((spi + 1) * 2 + 1, spis)) 633 spi++; 634 n = scnprintf(buf, buf_sz, "%sfp%d%d..%d", 635 space, frame, spi_off(run_start), spi_off(spi)); 636 } else { 637 /* just a full spi */ 638 n = scnprintf(buf, buf_sz, "%sfp%d%d", space, frame, spi_off(spi)); 639 } 640 first = false; 641 buf += n; 642 buf_sz -= n; 643 } 644 return env->tmp_str_buf; 645 } 646 647 /* Print mask @kind of the instruction at relative index @i for every frame, if any bit is set. */ 648 static bool print_mask(struct bpf_verifier_env *env, struct func_instance *instance, int i, 649 const char *name, u32 kind) 650 { 651 struct frame_masks *fm; 652 bool printed = false; 653 unsigned long *mask; 654 int frame; 655 u64 pos; 656 657 pos = env->log.end_pos; 658 verbose(env, "%s", name); 659 for (frame = instance->depth; frame >= 0; --frame) { 660 fm = instance->frames[frame]; 661 if (!fm) 662 continue; 663 mask = rel_mask(fm, i, kind); 664 if (bitmap_empty(mask, frame_mask_bits(fm))) 665 continue; 666 verbose(env, "%s", fmt_spis_mask(env, frame, !printed, mask, fm->words)); 667 printed = true; 668 } 669 if (!printed) 670 bpf_vlog_reset(&env->log, pos); 671 return printed; 672 } 673 674 static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance) 675 { 676 int start = env->subprog_info[instance->subprog].start; 677 struct bpf_insn *insns = env->prog->insnsi; 678 int len = instance->insn_cnt; 679 u64 pos, insn_pos; 680 int insn_idx, i; 681 bool printed; 682 683 if (!(env->log.level & BPF_LOG_LEVEL2)) 684 return; 685 686 verbose(env, "stack use/def %s ", fmt_subprog(env, instance->subprog)); 687 verbose(env, "%s:\n", fmt_instance(env, instance)); 688 for (i = 0; i < len; i++) { 689 insn_idx = start + i; 690 pos = env->log.end_pos; 691 verbose(env, "%3d: ", insn_idx); 692 bpf_verbose_insn(env, &insns[insn_idx]); 693 insn_pos = env->log.end_pos; 694 verbose(env, "%*c;", bpf_vlog_alignment(insn_pos - pos), ' '); 695 printed = false; 696 printed |= print_mask(env, instance, i, " use: ", FM_MAY_READ); 697 printed |= print_mask(env, instance, i, " def: ", FM_MUST_WRITE); 698 printed |= print_mask(env, instance, i, " may_def: ", FM_MAY_WRITE); 699 if (!printed) 700 bpf_vlog_reset(&env->log, insn_pos); 701 verbose(env, "\n"); 702 if (bpf_is_ldimm64(&insns[insn_idx])) 703 i++; 704 } 705 } 706 707 static int cmp_instances(const void *pa, const void *pb) 708 { 709 struct func_instance *a = *(struct func_instance **)pa; 710 struct func_instance *b = *(struct func_instance **)pb; 711 int dcallsite = (int)a->callsite - b->callsite; 712 int ddepth = (int)a->depth - b->depth; 713 714 if (dcallsite) 715 return dcallsite; 716 if (ddepth) 717 return ddepth; 718 return 0; 719 } 720 721 /* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */ 722 static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits) 723 { 724 u32 slot; 725 726 for (slot = 0; slot < MAX_BPF_STACK_SLOTS && slot * 2 + 1 < nbits; slot++) 727 if (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask)) 728 __set_bit(slot, slots); 729 } 730 731 /* 732 * Precompute, for each instruction, the OR of may_write and live_before masks 733 * over its top frame across all func_instances reaching it, stash them in the 734 * insn_aux_data. 735 */ 736 static void compute_may_write_masks(struct bpf_verifier_env *env) 737 { 738 struct bpf_insn_aux_data *aux = env->insn_aux_data; 739 struct bpf_liveness *liveness = env->liveness; 740 struct func_instance *instance; 741 struct frame_masks *fm; 742 u32 nbits; 743 int bkt, i; 744 745 hash_for_each(liveness->func_instances, bkt, instance, hl_node) { 746 fm = instance->frames[instance->depth]; 747 if (!fm) 748 continue; 749 nbits = frame_mask_bits(fm); 750 for (i = 0; i < instance->insn_cnt; i++) { 751 half_spis_to_slots(aux[instance->subprog_start + i].may_write_mask, 752 rel_mask(fm, i, FM_MAY_WRITE), nbits); 753 half_spis_to_slots(aux[instance->subprog_start + i].live_stack_before, 754 rel_mask(fm, i, FM_LIVE_BEFORE), nbits); 755 } 756 } 757 } 758 759 const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx) 760 { 761 return env->insn_aux_data[insn_idx].may_write_mask; 762 } 763 764 /* print use/def slots for all instances ordered by callsite first, then by depth */ 765 static int print_instances(struct bpf_verifier_env *env) 766 { 767 struct func_instance *instance, **sorted_instances; 768 struct bpf_liveness *liveness = env->liveness; 769 int i, bkt, cnt; 770 771 cnt = 0; 772 hash_for_each(liveness->func_instances, bkt, instance, hl_node) 773 cnt++; 774 sorted_instances = kvmalloc_objs(*sorted_instances, cnt, GFP_KERNEL_ACCOUNT); 775 if (!sorted_instances) 776 return -ENOMEM; 777 cnt = 0; 778 hash_for_each(liveness->func_instances, bkt, instance, hl_node) 779 sorted_instances[cnt++] = instance; 780 sort(sorted_instances, cnt, sizeof(*sorted_instances), cmp_instances, NULL); 781 for (i = 0; i < cnt; i++) 782 print_instance(env, sorted_instances[i]); 783 kvfree(sorted_instances); 784 return 0; 785 } 786 787 /* 788 * Per-register tracking state for compute_subprog_args(). 789 * Tracks which frame's FP a value is derived from 790 * and the byte offset from that frame's FP. 791 * 792 * The .frame field forms a lattice with three levels of precision: 793 * 794 * precise {frame=N, off=V} -- known absolute frame index and byte offset 795 * | 796 * offset-imprecise {frame=N, cnt=0} 797 * | -- known frame identity, unknown offset 798 * fully-imprecise {frame=ARG_IMPRECISE, mask=bitmask} 799 * -- unknown frame identity; .mask is a 800 * bitmask of which frame indices might be 801 * involved 802 * 803 * At CFG merge points, arg_track_join() moves down the lattice: 804 * - same frame + same offset -> precise 805 * - same frame + different offset -> offset-imprecise 806 * - different frames -> fully-imprecise (bitmask OR) 807 * 808 * At memory access sites (LDX/STX/ST), offset-imprecise marks the known 809 * frame as fully read, while fully-imprecise iterates bits in the bitmask 810 * and routes each frame to its target. 811 */ 812 #define MAX_ARG_OFFSETS 4 813 814 struct arg_track { 815 union { 816 s16 off[MAX_ARG_OFFSETS]; /* byte offsets; off_cnt says how many */ 817 u16 mask; /* arg bitmask when arg == ARG_IMPRECISE */ 818 }; 819 s8 frame; /* absolute frame index, or enum arg_track_state */ 820 s8 off_cnt; /* 0 = offset-imprecise, 1-4 = # of precise offsets */ 821 }; 822 823 enum arg_track_state { 824 ARG_NONE = -1, /* not derived from any argument */ 825 ARG_UNVISITED = -2, /* not yet reached by dataflow */ 826 ARG_IMPRECISE = -3, /* lost identity; .mask is arg bitmask */ 827 }; 828 829 /* 830 * The tracker follows as many spill slots as a subprog addresses directly 831 * through R10, see subprog_spill_slots(). A frame's slots at a call site are 832 * kept in a snapshot for the callees that receive pointers into that frame. 833 */ 834 struct spill_snapshot { 835 u32 slots; 836 struct arg_track at[]; 837 }; 838 839 /* 840 * Combined register + stack arg tracking: R0-R10 at indices 0-10, 841 * outgoing stack arg slots at indices MAX_BPF_REG..MAX_BPF_REG+6. 842 */ 843 #define MAX_AT_TRACK_REGS (MAX_BPF_REG + MAX_STACK_ARG_SLOTS) 844 845 static int stack_arg_off_to_slot(s16 off) 846 { 847 int aoff = off < 0 ? -off : off; 848 849 if (aoff / 8 > MAX_STACK_ARG_SLOTS) 850 return -1; 851 return aoff / 8 - 1; 852 } 853 854 static bool arg_is_visited(const struct arg_track *at) 855 { 856 return at->frame != ARG_UNVISITED; 857 } 858 859 static bool arg_is_fp(const struct arg_track *at) 860 { 861 return at->frame >= 0 || at->frame == ARG_IMPRECISE; 862 } 863 864 static void verbose_arg_track(struct bpf_verifier_env *env, struct arg_track *at) 865 { 866 int i; 867 868 switch (at->frame) { 869 case ARG_NONE: verbose(env, "_"); break; 870 case ARG_UNVISITED: verbose(env, "?"); break; 871 case ARG_IMPRECISE: verbose(env, "IMP%x", at->mask); break; 872 default: 873 /* frame >= 0: absolute frame index */ 874 if (at->off_cnt == 0) { 875 verbose(env, "fp%d ?", at->frame); 876 } else { 877 for (i = 0; i < at->off_cnt; i++) { 878 if (i) 879 verbose(env, "|"); 880 verbose(env, "fp%d%+d", at->frame, at->off[i]); 881 } 882 } 883 break; 884 } 885 } 886 887 static bool arg_track_eq(const struct arg_track *a, const struct arg_track *b) 888 { 889 int i; 890 891 if (a->frame != b->frame) 892 return false; 893 if (a->frame == ARG_IMPRECISE) 894 return a->mask == b->mask; 895 if (a->frame < 0) 896 return true; 897 if (a->off_cnt != b->off_cnt) 898 return false; 899 for (i = 0; i < a->off_cnt; i++) 900 if (a->off[i] != b->off[i]) 901 return false; 902 return true; 903 } 904 905 static struct arg_track arg_single(s8 arg, s16 off) 906 { 907 struct arg_track at = {}; 908 909 at.frame = arg; 910 at.off[0] = off; 911 at.off_cnt = 1; 912 return at; 913 } 914 915 /* 916 * Merge two sorted offset arrays, deduplicate. 917 * Returns off_cnt=0 if the result exceeds MAX_ARG_OFFSETS. 918 * Both args must have the same frame and off_cnt > 0. 919 */ 920 static struct arg_track arg_merge_offsets(struct arg_track a, struct arg_track b) 921 { 922 struct arg_track result = { .frame = a.frame }; 923 struct arg_track imp = { .frame = a.frame }; 924 int i = 0, j = 0, k = 0; 925 926 while (i < a.off_cnt && j < b.off_cnt) { 927 s16 v; 928 929 if (a.off[i] <= b.off[j]) { 930 v = a.off[i++]; 931 if (v == b.off[j]) 932 j++; 933 } else { 934 v = b.off[j++]; 935 } 936 if (k > 0 && result.off[k - 1] == v) 937 continue; 938 if (k >= MAX_ARG_OFFSETS) 939 return imp; 940 result.off[k++] = v; 941 } 942 while (i < a.off_cnt) { 943 if (k >= MAX_ARG_OFFSETS) 944 return imp; 945 result.off[k++] = a.off[i++]; 946 } 947 while (j < b.off_cnt) { 948 if (k >= MAX_ARG_OFFSETS) 949 return imp; 950 result.off[k++] = b.off[j++]; 951 } 952 result.off_cnt = k; 953 return result; 954 } 955 956 /* 957 * Merge two arg_tracks into ARG_IMPRECISE, collecting the frame 958 * bits from both operands. Precise frame indices (frame >= 0) 959 * contribute a single bit; existing ARG_IMPRECISE values 960 * contribute their full bitmask. 961 */ 962 static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_track b) 963 { 964 u32 m = 0; 965 966 if (a.frame >= 0) 967 m |= BIT(a.frame); 968 else if (a.frame == ARG_IMPRECISE) 969 m |= a.mask; 970 971 if (b.frame >= 0) 972 m |= BIT(b.frame); 973 else if (b.frame == ARG_IMPRECISE) 974 m |= b.mask; 975 976 return (struct arg_track){ .mask = m, .frame = ARG_IMPRECISE }; 977 } 978 979 /* 980 * 'a' or a value that is not a pointer to stack. A single fp-N gets a fake fp+0, 981 * to keep stack_use and prevent stack_def. fp+0 itself would stay a single offset. 982 */ 983 static struct arg_track arg_or_none(struct arg_track a) 984 { 985 if (a.off_cnt != 1) 986 return a; 987 if (!a.off[0]) 988 return (struct arg_track){ .frame = a.frame }; 989 return arg_merge_offsets(a, arg_single(a.frame, 0)); 990 } 991 992 /* Join two arg_track values at merge points */ 993 static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b) 994 { 995 if (!arg_is_visited(&b)) 996 return a; 997 if (!arg_is_visited(&a)) 998 return b; 999 if (a.frame == b.frame && a.frame >= 0) { 1000 /* Both offset-imprecise: stay imprecise */ 1001 if (a.off_cnt == 0 || b.off_cnt == 0) 1002 return (struct arg_track){ .frame = a.frame }; 1003 /* Merge offset sets; falls back to off_cnt=0 if >4 */ 1004 return arg_merge_offsets(a, b); 1005 } 1006 1007 /* 1008 * args are different, but one of them is known 1009 * arg + none -> arg 1010 * none + arg -> arg 1011 * 1012 * none + none -> none 1013 */ 1014 if (a.frame == ARG_NONE && b.frame == ARG_NONE) 1015 return a; 1016 if (a.frame >= 0 && b.frame == ARG_NONE) 1017 return arg_or_none(a); 1018 if (b.frame >= 0 && a.frame == ARG_NONE) 1019 return arg_or_none(b); 1020 1021 return arg_join_imprecise(a, b); 1022 } 1023 1024 static bool arg_track_join(struct bpf_verifier_env *env, int idx, int target, int r, 1025 struct arg_track *in, struct arg_track out) 1026 { 1027 struct arg_track old = *in; 1028 struct arg_track new_val = __arg_track_join(old, out); 1029 1030 if (arg_track_eq(&new_val, &old)) 1031 return false; 1032 1033 *in = new_val; 1034 if (!(env->log.level & BPF_LOG_LEVEL2) || !arg_is_visited(&old)) 1035 return true; 1036 1037 verbose(env, "arg JOIN insn %d -> %d ", idx, target); 1038 if (r >= MAX_BPF_REG) 1039 verbose(env, "sa%d: ", r - MAX_BPF_REG); 1040 else if (r >= 0) 1041 verbose(env, "r%d: ", r); 1042 else 1043 verbose(env, "fp%+d: ", r * 8); 1044 verbose_arg_track(env, &old); 1045 verbose(env, " + "); 1046 verbose_arg_track(env, &out); 1047 verbose(env, " => "); 1048 verbose_arg_track(env, &new_val); 1049 verbose(env, "\n"); 1050 return true; 1051 } 1052 1053 /* 1054 * Compute the result when an ALU op destroys offset precision. 1055 * If a single arg is identifiable, preserve it with OFF_IMPRECISE. 1056 * If two different args are involved or one is already ARG_IMPRECISE, 1057 * the result is fully ARG_IMPRECISE. 1058 */ 1059 static void arg_track_alu64(struct arg_track *dst, const struct arg_track *src) 1060 { 1061 WARN_ON_ONCE(!arg_is_visited(dst)); 1062 WARN_ON_ONCE(!arg_is_visited(src)); 1063 1064 if (dst->frame >= 0 && (src->frame == ARG_NONE || src->frame == dst->frame)) { 1065 /* 1066 * rX += rY where rY is not arg derived 1067 * rX += rX 1068 */ 1069 dst->off_cnt = 0; 1070 return; 1071 } 1072 if (src->frame >= 0 && dst->frame == ARG_NONE) { 1073 /* 1074 * rX += rY where rX is not arg derived 1075 * rY identity leaks into rX 1076 */ 1077 dst->off_cnt = 0; 1078 dst->frame = src->frame; 1079 return; 1080 } 1081 1082 if (dst->frame == ARG_NONE && src->frame == ARG_NONE) 1083 return; 1084 1085 *dst = arg_join_imprecise(*dst, *src); 1086 } 1087 1088 static bool arg_add(s16 off, s64 delta, s16 *out) 1089 { 1090 s16 d = delta; 1091 1092 if (d != delta) 1093 return true; 1094 return check_add_overflow(off, d, out); 1095 } 1096 1097 static void arg_padd(struct arg_track *at, s64 delta) 1098 { 1099 int i; 1100 1101 if (at->off_cnt == 0) 1102 return; 1103 for (i = 0; i < at->off_cnt; i++) { 1104 s16 new_off; 1105 1106 if (arg_add(at->off[i], delta, &new_off)) { 1107 at->off_cnt = 0; 1108 return; 1109 } 1110 at->off[i] = new_off; 1111 } 1112 } 1113 1114 /* 1115 * Slots the spill tracker may follow for a subprog of @len instructions 1116 * without its per-instruction tables costing more than they could for the 1117 * largest program while every frame stayed within MAX_BPF_STACK: as many 1118 * entries as 64 slots need for BPF_COMPLEXITY_LIMIT_INSNS instructions. 1119 */ 1120 static u32 spill_slots_affordable(int len) 1121 { 1122 u32 base = MAX_BPF_STACK / BPF_REG_SIZE; 1123 1124 return max_t(u32, base, base * BPF_COMPLEXITY_LIMIT_INSNS / len); 1125 } 1126 1127 /* 1128 * Number of 8-byte spill slots to track for the instructions in [@start, @end): 1129 * the 64 slots of a MAX_BPF_STACK frame, which the tracker has always 1130 * followed, or the deepest 8-byte stack access made directly through R10 when 1131 * that reaches further, up to the program's stack budget. Spills and fills are 1132 * compiled as direct R10 accesses, so the count covers them whatever the frame 1133 * size; a fill through a derived pointer that reaches past it is treated as 1134 * imprecise, as one past the frame always was. 1135 */ 1136 static u32 subprog_spill_slots(struct bpf_verifier_env *env, int start, int end) 1137 { 1138 struct bpf_insn *insns = env->prog->insnsi; 1139 int deepest = 0; 1140 1141 for (int i = start; i < end; i++) { 1142 struct bpf_insn *insn = &insns[i]; 1143 u8 class = BPF_CLASS(insn->code); 1144 u8 base; 1145 1146 if (BPF_SIZE(insn->code) != BPF_DW) 1147 continue; 1148 if (class == BPF_LDX) 1149 base = insn->src_reg; 1150 else if (class == BPF_STX || class == BPF_ST) 1151 base = insn->dst_reg; 1152 else 1153 continue; 1154 if (base == BPF_REG_FP && insn->off < 0) 1155 deepest = max(deepest, -insn->off); 1156 } 1157 return clamp_t(u32, DIV_ROUND_UP(deepest, 8), MAX_BPF_STACK / BPF_REG_SIZE, 1158 env->stack_limit / BPF_REG_SIZE); 1159 } 1160 1161 /* 1162 * Convert a byte offset from FP to one of the @nslots tracked stack slots. 1163 * Returns -1 if out of range or not 8-byte aligned. 1164 * Slot 0 = fp-8, slot 1 = fp-16, ..., slot 7 = fp-64, .... 1165 */ 1166 static int fp_off_to_slot(s16 off, u32 nslots) 1167 { 1168 if (off >= 0 || off < -(int)(nslots * 8)) 1169 return -1; 1170 if (off % 8) 1171 return -1; 1172 return (-off) / 8 - 1; 1173 } 1174 1175 static struct arg_track fill_from_stack(struct bpf_insn *insn, 1176 struct arg_track *at_out, int reg, 1177 struct arg_track *at_stack_out, u32 nslots, 1178 int depth) 1179 { 1180 struct arg_track imp = { 1181 .mask = (1u << (depth + 1)) - 1, 1182 .frame = ARG_IMPRECISE 1183 }; 1184 struct arg_track result = { .frame = ARG_NONE }; 1185 int cnt, i; 1186 1187 if (reg == BPF_REG_FP) { 1188 int slot = fp_off_to_slot(insn->off, nslots); 1189 1190 return slot >= 0 ? at_stack_out[slot] : imp; 1191 } 1192 cnt = at_out[reg].off_cnt; 1193 if (cnt == 0) 1194 return imp; 1195 1196 for (i = 0; i < cnt; i++) { 1197 s16 fp_off, slot; 1198 1199 if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) 1200 return imp; 1201 slot = fp_off_to_slot(fp_off, nslots); 1202 if (slot < 0) 1203 return imp; 1204 result = __arg_track_join(result, at_stack_out[slot]); 1205 } 1206 return result; 1207 } 1208 1209 /* 1210 * Spill @val to all possible stack slots indicated by the FP offsets in @reg. 1211 * For an 8-byte store, single candidate slot gets @val. multi-slots are joined. 1212 * sub-8-byte store joins with ARG_NONE. 1213 * When exact offset is unknown conservatively add reg values to all slots in at_stack_out. 1214 */ 1215 static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, 1216 int reg, struct arg_track *at_stack_out, u32 nslots, 1217 struct arg_track *val, u32 sz) 1218 { 1219 struct arg_track none = { .frame = ARG_NONE }; 1220 struct arg_track new_val = sz == 8 ? *val : none; 1221 int cnt, i; 1222 1223 if (reg == BPF_REG_FP) { 1224 int slot = fp_off_to_slot(insn->off, nslots); 1225 1226 if (slot >= 0) 1227 at_stack_out[slot] = new_val; 1228 return; 1229 } 1230 cnt = at_out[reg].off_cnt; 1231 if (cnt == 0) { 1232 for (int slot = 0; slot < nslots; slot++) 1233 at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val); 1234 return; 1235 } 1236 for (i = 0; i < cnt; i++) { 1237 s16 fp_off; 1238 int slot; 1239 1240 if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) 1241 continue; 1242 slot = fp_off_to_slot(fp_off, nslots); 1243 if (slot < 0) 1244 continue; 1245 if (cnt == 1) 1246 at_stack_out[slot] = new_val; 1247 else 1248 at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val); 1249 } 1250 } 1251 1252 /* 1253 * Clear all tracked callee stack slots overlapping the byte range 1254 * [off, off+sz-1] where off is a negative FP-relative offset. 1255 */ 1256 static void clear_overlapping_stack_slots(struct arg_track *at_stack, u32 nslots, s16 off, 1257 u32 sz, int cnt) 1258 { 1259 struct arg_track none = { .frame = ARG_NONE }; 1260 1261 if (cnt == 0) { 1262 for (int i = 0; i < nslots; i++) 1263 at_stack[i] = __arg_track_join(at_stack[i], none); 1264 return; 1265 } 1266 for (int i = 0; i < nslots; i++) { 1267 int slot_start = -((i + 1) * 8); 1268 int slot_end = slot_start + 8; 1269 1270 if (slot_start < off + (int)sz && slot_end > off) { 1271 if (cnt == 1) 1272 at_stack[i] = none; 1273 else 1274 at_stack[i] = __arg_track_join(at_stack[i], none); 1275 } 1276 } 1277 } 1278 1279 /* 1280 * Clear stack slots overlapping all possible FP offsets in @reg. 1281 */ 1282 static void clear_stack_for_all_offs(struct bpf_insn *insn, 1283 struct arg_track *at_out, int reg, 1284 struct arg_track *at_stack_out, u32 nslots, u32 sz) 1285 { 1286 int cnt, i; 1287 1288 if (reg == BPF_REG_FP) { 1289 clear_overlapping_stack_slots(at_stack_out, nslots, insn->off, sz, 1); 1290 return; 1291 } 1292 cnt = at_out[reg].off_cnt; 1293 if (cnt == 0) { 1294 clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, cnt); 1295 return; 1296 } 1297 for (i = 0; i < cnt; i++) { 1298 s16 fp_off; 1299 1300 if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) { 1301 clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, 0); 1302 break; 1303 } 1304 clear_overlapping_stack_slots(at_stack_out, nslots, fp_off, sz, cnt); 1305 } 1306 } 1307 1308 static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, int idx, 1309 struct arg_track *at_in, struct arg_track *at_stack_in, 1310 struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots) 1311 { 1312 bool printed = false; 1313 int i; 1314 1315 if (!(env->log.level & BPF_LOG_LEVEL2)) 1316 return; 1317 for (i = 0; i < MAX_BPF_REG; i++) { 1318 if (arg_track_eq(&at_out[i], &at_in[i])) 1319 continue; 1320 if (!printed) { 1321 verbose(env, "%3d: ", idx); 1322 bpf_verbose_insn(env, insn); 1323 printed = true; 1324 } 1325 verbose(env, "\tr%d: ", i); verbose_arg_track(env, &at_in[i]); 1326 verbose(env, " -> "); verbose_arg_track(env, &at_out[i]); 1327 } 1328 /* Log outgoing stack arg slot transitions at indices MAX_BPF_REG..MAX_AT_TRACK_REGS-1 */ 1329 for (i = 0; i < MAX_STACK_ARG_SLOTS; i++) { 1330 int ai = MAX_BPF_REG + i; 1331 1332 if (arg_track_eq(&at_out[ai], &at_in[ai])) 1333 continue; 1334 if (!printed) { 1335 verbose(env, "%3d: ", idx); 1336 bpf_verbose_insn(env, insn); 1337 printed = true; 1338 } 1339 verbose(env, "\tsa%d: ", i); verbose_arg_track(env, &at_in[ai]); 1340 verbose(env, " -> "); verbose_arg_track(env, &at_out[ai]); 1341 } 1342 for (i = 0; i < nslots; i++) { 1343 if (arg_track_eq(&at_stack_out[i], &at_stack_in[i])) 1344 continue; 1345 if (!printed) { 1346 verbose(env, "%3d: ", idx); 1347 bpf_verbose_insn(env, insn); 1348 printed = true; 1349 } 1350 verbose(env, "\tfp%+d: ", -(i + 1) * 8); verbose_arg_track(env, &at_stack_in[i]); 1351 verbose(env, " -> "); verbose_arg_track(env, &at_stack_out[i]); 1352 } 1353 if (printed) 1354 verbose(env, "\n"); 1355 } 1356 1357 static bool can_be_local_fp(int depth, int regno, struct arg_track *at) 1358 { 1359 return regno == BPF_REG_FP || at->frame == depth || 1360 (at->frame == ARG_IMPRECISE && (at->mask & BIT(depth))); 1361 } 1362 1363 /* 1364 * Model 8-byte reads through @reg, including load-acquire 1365 * and the old value fetched by atomic operations. 1366 */ 1367 static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf_insn *insn, 1368 struct arg_track *at_out, int reg, 1369 struct arg_track *at_stack_out, u32 nslots, 1370 int depth, u32 *callsites) 1371 { 1372 struct arg_track *ptr = &at_out[reg]; 1373 1374 if (can_be_local_fp(depth, reg, ptr)) 1375 return fill_from_stack(insn, at_out, reg, at_stack_out, nslots, depth); 1376 if (ptr->frame >= 0 && ptr->frame < depth) { 1377 struct spill_snapshot *parent = env->callsite_at_stack[callsites[ptr->frame]]; 1378 1379 return fill_from_stack(insn, at_out, reg, parent->at, parent->slots, ptr->frame); 1380 } 1381 if (ptr->frame == ARG_IMPRECISE && !(ptr->mask & BIT(depth)) && ptr->mask) 1382 return *ptr; 1383 return (struct arg_track){ .frame = ARG_NONE }; 1384 } 1385 1386 /* 1387 * True if the call at @insn_idx can pass a pointer to the frame at @depth to a static subprog 1388 * or to a callback. They use it as a pointer to stack, a global subprog gets plain memory. 1389 * It errs on the safe side: it looks at all argument registers and stack args, also at those 1390 * that this callee doesn't take. 1391 */ 1392 static bool subprog_gets_local_fp(struct bpf_verifier_env *env, struct bpf_insn *insn, int insn_idx, 1393 struct arg_track *at, int depth) 1394 { 1395 int r; 1396 1397 if (bpf_pseudo_call(insn)) { 1398 r = bpf_find_subprog(env, insn_idx + insn->imm + 1); 1399 if (r >= 0 && bpf_subprog_is_global(env, r)) 1400 return false; 1401 } else if (!bpf_is_callx(insn) && !bpf_calls_callback(env, insn_idx)) { 1402 return false; 1403 } 1404 /* R1-R5 and stack args */ 1405 for (r = BPF_REG_1; r < MAX_AT_TRACK_REGS; r++) 1406 if ((r <= BPF_REG_5 || r >= MAX_BPF_REG) && can_be_local_fp(depth, r, &at[r])) 1407 return true; 1408 return false; 1409 } 1410 1411 /* 1412 * Pure dataflow transfer function for arg_track state. 1413 * Updates at_out[] based on how the instruction modifies registers. 1414 * Tracks spill/fill, but not other memory accesses. 1415 */ 1416 static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, 1417 int insn_idx, 1418 struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots, 1419 const struct arg_track *at_stack_arg_entry, 1420 struct func_instance *instance, 1421 u32 *callsites) 1422 { 1423 int depth = instance->depth; 1424 u8 class = BPF_CLASS(insn->code); 1425 u8 code = BPF_OP(insn->code); 1426 struct arg_track *dst = &at_out[insn->dst_reg]; 1427 struct arg_track *src = &at_out[insn->src_reg]; 1428 struct arg_track none = { .frame = ARG_NONE }; 1429 int r, slot; 1430 1431 /* Handle stack arg stores and loads. */ 1432 if (is_stack_arg_st(insn) || is_stack_arg_stx(insn)) { 1433 slot = stack_arg_off_to_slot(insn->off); 1434 if (slot >= 0) { 1435 if (is_stack_arg_stx(insn)) 1436 at_out[MAX_BPF_REG + slot] = at_out[insn->src_reg]; 1437 else 1438 at_out[MAX_BPF_REG + slot] = none; 1439 } 1440 } else if (is_stack_arg_ldx(insn)) { 1441 slot = stack_arg_off_to_slot(insn->off); 1442 at_out[insn->dst_reg] = (slot >= 0) ? at_stack_arg_entry[slot] : none; 1443 } else if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_K) { 1444 if (code == BPF_MOV) { 1445 *dst = none; 1446 } else if (dst->frame >= 0) { 1447 if (code == BPF_ADD) 1448 arg_padd(dst, insn->imm); 1449 else if (code == BPF_SUB) 1450 arg_padd(dst, -(s64)insn->imm); 1451 else 1452 /* Any other 64-bit alu on the pointer makes it imprecise */ 1453 dst->off_cnt = 0; 1454 } /* else if dst->frame is imprecise it stays so */ 1455 } else if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_X) { 1456 if (code == BPF_MOV) { 1457 if (insn->off == 0) { 1458 *dst = *src; 1459 } else { 1460 /* addr_space_cast destroys a pointer */ 1461 *dst = none; 1462 } 1463 } else { 1464 arg_track_alu64(dst, src); 1465 } 1466 } else if (class == BPF_ALU) { 1467 /* 1468 * 32-bit alu destroys the pointer. 1469 * If src was a pointer it cannot leak into dst 1470 */ 1471 *dst = none; 1472 } else if (class == BPF_JMP && code == BPF_CALL) { 1473 /* 1474 * Helpers, kfuncs and global subprogs can scratch stack slots. The verifier reads 1475 * a scalar from a scratched slot, but at_stack_out[slot] is not cleared, and 1476 * fill_from_stack() returns the stale spill: an FP-derived arg_track for a scalar. 1477 * A scalar can't be dereferenced, so the stale value can only set liveness bits 1478 * for stack accesses that don't happen. That is conservative. 1479 * 1480 * Static subprogs and callbacks can't store an FP-derived pointer into the frame of 1481 * the caller, but they can store any other pointer there. The caller can fill it 1482 * and store through it. With the stale spill that store would be a definite write 1483 * to a stack slot, and it doesn't touch the stack. Callees are analyzed after the 1484 * caller, and they reach the whole frame from one pointer to it. So after the call 1485 * every slot holds what it held before or a value that is not FP-derived. 1486 */ 1487 if (subprog_gets_local_fp(env, insn, insn_idx, at_out, depth)) 1488 for (slot = 0; slot < nslots; slot++) 1489 at_stack_out[slot] = __arg_track_join(at_stack_out[slot], none); 1490 for (r = BPF_REG_0; r <= BPF_REG_5; r++) 1491 at_out[r] = none; 1492 } else if (class == BPF_LDX) { 1493 /* Only an 8-byte BPF_MEM load can be a fill, see arg_track_deref(). */ 1494 if (BPF_MODE(insn->code) == BPF_MEM && BPF_SIZE(insn->code) == BPF_DW) 1495 *dst = arg_track_deref(env, insn, at_out, insn->src_reg, 1496 at_stack_out, nslots, depth, callsites); 1497 else 1498 *dst = none; 1499 } else if (class == BPF_LD && BPF_MODE(insn->code) == BPF_IMM) { 1500 *dst = none; 1501 } else if (class == BPF_STX) { 1502 u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1503 bool dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst); 1504 u8 mode = BPF_MODE(insn->code); 1505 1506 if (mode == BPF_MEM || (mode == BPF_ATOMIC && insn->imm == BPF_STORE_REL)) { 1507 if (dst_is_local_fp) 1508 spill_to_stack(insn, at_out, insn->dst_reg, 1509 at_stack_out, nslots, src, sz); 1510 } else if (mode == BPF_ATOMIC && insn->imm == BPF_LOAD_ACQ) { 1511 if (sz == 8) 1512 *dst = arg_track_deref(env, insn, at_out, insn->src_reg, 1513 at_stack_out, nslots, depth, callsites); 1514 else 1515 *dst = none; 1516 } else if (mode == BPF_ATOMIC) { 1517 /* BPF_XCHG, BPF_CMPXCHG or BPF_{ADD,AND,OR,XOR} | [BPF_FETCH] */ 1518 struct arg_track old = none; 1519 1520 r = bpf_atomic_load_reg(insn); 1521 if (r >= 0 && sz == 8) 1522 old = arg_track_deref(env, insn, at_out, insn->dst_reg, 1523 at_stack_out, nslots, depth, callsites); 1524 if (dst_is_local_fp) 1525 clear_stack_for_all_offs(insn, at_out, insn->dst_reg, 1526 at_stack_out, nslots, sz); 1527 if (r >= 0) 1528 at_out[r] = old; 1529 } 1530 } else if (class == BPF_ST && BPF_MODE(insn->code) == BPF_MEM) { 1531 u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1532 bool dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst); 1533 1534 /* BPF_ST to FP-derived dst: clear overlapping stack slots */ 1535 if (dst_is_local_fp) 1536 clear_stack_for_all_offs(insn, at_out, insn->dst_reg, 1537 at_stack_out, nslots, sz); 1538 } 1539 } 1540 1541 /* 1542 * Record possible reads and writes for every touched half-slot. A definite 1543 * write requires full coverage, a known size, and a single possible offset. 1544 */ 1545 static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg, 1546 s64 off_idx, struct arg_access_info info, 1547 u32 frame, u32 insn_idx) 1548 { 1549 s64 fp_off = arg->off[off_idx]; 1550 s32 slot_hi, slot_lo; 1551 int err; 1552 1553 if (fp_off >= 0) 1554 /* 1555 * out of bounds stack access doesn't contribute 1556 * into actual stack liveness. It will be rejected 1557 * by the main verifier pass later. 1558 */ 1559 return 0; 1560 1561 /* 1562 * Read and may_write marks include partially covered slots. 1563 * An unknown access size may reach from fp_off to the frame top. 1564 */ 1565 slot_hi = (-fp_off - 1) / STACK_SLOT_SZ; 1566 slot_lo = info.size == U32_MAX 1567 ? 0 1568 : max_t(s32, (-fp_off - info.size) / STACK_SLOT_SZ, 0); 1569 if (info.may_read) { 1570 err = mark_stack_read(instance, frame, insn_idx, slot_lo, slot_hi); 1571 if (err) 1572 return err; 1573 } 1574 if (info.may_write) { 1575 err = mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi); 1576 if (err) 1577 return err; 1578 } 1579 if (info.must_write && info.size != U32_MAX && arg->off_cnt == 1) { 1580 /* Mark only fully covered slots as def */ 1581 slot_hi = (-fp_off) / STACK_SLOT_SZ - 1; 1582 slot_lo = max_t(s32, (-fp_off - info.size + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0); 1583 return mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi); 1584 } 1585 return 0; 1586 } 1587 1588 /* Record access through a pointer with a known frame and possibly known offsets. */ 1589 static int record_stack_access(struct bpf_verifier_env *env, 1590 struct func_instance *instance, 1591 const struct arg_track *arg, 1592 struct arg_access_info info, u32 frame, u32 insn_idx) 1593 { 1594 int i, err; 1595 1596 if (!info.size) 1597 return 0; 1598 if (arg->off_cnt == 0) { 1599 if (info.may_read) { 1600 err = mark_stack_read_all(env, instance, frame, insn_idx); 1601 if (err) 1602 return err; 1603 } 1604 if (info.may_write) { 1605 err = mark_stack_may_write_all(env, instance, frame, insn_idx); 1606 if (err) 1607 return err; 1608 } 1609 return 0; 1610 } 1611 for (i = 0; i < arg->off_cnt; i++) { 1612 err = record_stack_access_off(instance, arg, i, info, frame, insn_idx); 1613 if (err) 1614 return err; 1615 } 1616 return 0; 1617 } 1618 1619 /* Record possible effects on every candidate frame of an imprecise pointer. */ 1620 static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *instance, 1621 struct arg_access_info info, u32 mask, u32 insn_idx) 1622 { 1623 int depth = instance->depth; 1624 int f, err; 1625 1626 for (f = 0; mask; f++, mask >>= 1) { 1627 if (!(mask & 1)) 1628 continue; 1629 if (f <= depth) { 1630 if (info.may_read) { 1631 err = mark_stack_read_all(env, instance, f, insn_idx); 1632 if (err) 1633 return err; 1634 } 1635 if (info.may_write) { 1636 err = mark_stack_may_write_all(env, instance, f, insn_idx); 1637 if (err) 1638 return err; 1639 } 1640 } 1641 } 1642 return 0; 1643 } 1644 1645 /* Record load/store access for a given 'at' state of 'insn'. */ 1646 static int record_load_store_access(struct bpf_verifier_env *env, 1647 struct func_instance *instance, 1648 struct arg_track *at, int insn_idx) 1649 { 1650 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 1651 struct arg_access_info info = {}; 1652 int depth = instance->depth; 1653 u8 class = BPF_CLASS(insn->code); 1654 bool read = false, write = false; 1655 struct arg_track resolved, *ptr; 1656 int oi; 1657 1658 /* 1659 * Stack arg insns use dst_reg/src_reg=BPF_REG_PARAMS(11). Since at[] 1660 * is extended to MAX_AT_TRACK_REGS, at[11] holds the arg_track for 1661 * outgoing stack arg slot 0 — not the pointer used for the memory 1662 * access. Skip so the slot's tracked value isn't confused with the 1663 * base register that record_stack_access() expects. 1664 */ 1665 if (is_stack_arg_stx(insn) || is_stack_arg_st(insn) || is_stack_arg_ldx(insn)) 1666 return 0; 1667 1668 switch (class) { 1669 case BPF_LDX: 1670 ptr = &at[insn->src_reg]; 1671 read = true; 1672 break; 1673 case BPF_STX: 1674 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 1675 switch (insn->imm) { 1676 case BPF_LOAD_ACQ: 1677 ptr = &at[insn->src_reg]; 1678 read = true; 1679 break; 1680 case BPF_STORE_REL: 1681 ptr = &at[insn->dst_reg]; 1682 write = true; 1683 break; 1684 default: 1685 /* ADD/AND/OR/XOR(+FETCH), XCHG, CMPXCHG */ 1686 ptr = &at[insn->dst_reg]; 1687 read = true; 1688 write = true; 1689 break; 1690 } 1691 } else { 1692 ptr = &at[insn->dst_reg]; 1693 write = true; 1694 } 1695 break; 1696 case BPF_ST: 1697 ptr = &at[insn->dst_reg]; 1698 write = true; 1699 break; 1700 default: 1701 return 0; 1702 } 1703 1704 /* Resolve offsets: fold insn->off into arg_track */ 1705 if (ptr->off_cnt > 0) { 1706 resolved.off_cnt = ptr->off_cnt; 1707 resolved.frame = ptr->frame; 1708 for (oi = 0; oi < ptr->off_cnt; oi++) { 1709 if (arg_add(ptr->off[oi], insn->off, &resolved.off[oi])) { 1710 resolved.off_cnt = 0; 1711 break; 1712 } 1713 } 1714 ptr = &resolved; 1715 } 1716 1717 info.may_read = read; 1718 info.may_write = write; 1719 info.must_write = write; 1720 info.size = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1721 if (ptr->frame >= 0 && ptr->frame <= depth) 1722 return record_stack_access(env, instance, ptr, info, ptr->frame, insn_idx); 1723 if (ptr->frame == ARG_IMPRECISE) 1724 return record_imprecise(env, instance, info, ptr->mask, insn_idx); 1725 /* ARG_NONE: not derived from any frame pointer, skip */ 1726 return 0; 1727 } 1728 1729 static int record_arg_access(struct bpf_verifier_env *env, 1730 struct func_instance *instance, 1731 struct bpf_insn *insn, 1732 struct arg_track *at, int arg_idx, 1733 int insn_idx) 1734 { 1735 struct arg_access_info info; 1736 int depth = instance->depth; 1737 int frame = at->frame; 1738 int err = 0; 1739 1740 if (!arg_is_fp(at)) 1741 return 0; 1742 1743 if (bpf_helper_call(insn)) { 1744 info = bpf_helper_stack_access_bytes(env, insn, arg_idx, insn_idx); 1745 } else if (bpf_pseudo_kfunc_call(insn)) { 1746 info = bpf_kfunc_stack_access_bytes(env, insn, arg_idx, insn_idx); 1747 } else if (bpf_pseudo_call(insn)) { 1748 info = bpf_global_subprog_stack_access_bytes(env, insn, arg_idx, insn_idx); 1749 } else { 1750 for (int f = 0; f <= depth; f++) { 1751 err = mark_stack_read_all(env, instance, f, insn_idx); 1752 if (err) 1753 return err; 1754 err = mark_stack_may_write_all(env, instance, f, insn_idx); 1755 if (err) 1756 return err; 1757 } 1758 return 0; 1759 } 1760 if (!info.size) 1761 return 0; 1762 1763 if (frame >= 0 && frame <= depth) 1764 err = record_stack_access(env, instance, at, info, frame, insn_idx); 1765 else if (frame == ARG_IMPRECISE) 1766 err = record_imprecise(env, instance, info, at->mask, insn_idx); 1767 return err; 1768 } 1769 1770 /* Record stack access for a given 'at' state of helper/kfunc/global subprog 'insn' */ 1771 static int record_call_access(struct bpf_verifier_env *env, 1772 struct func_instance *instance, 1773 struct arg_track *at, 1774 int insn_idx) 1775 { 1776 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 1777 struct bpf_call_summary cs; 1778 int r, err, callee, arg_slot_cnt = 5; 1779 1780 if (bpf_pseudo_call(insn)) { 1781 /* 1782 * analyze_subprog() handles static callees. For global callees, 1783 * derive effects from argument types so may_write marks remain 1784 * conservative under freplace. 1785 */ 1786 callee = bpf_find_subprog(env, insn_idx + insn->imm + 1); 1787 if (callee < 0 || !bpf_subprog_is_global(env, callee)) 1788 return 0; 1789 arg_slot_cnt = MAX_BPF_FUNC_ARGS; 1790 } else if (bpf_is_callx(insn)) 1791 /* 1792 * The callee is not known statically. Assume that all arg 1793 * slots are passed and let record_arg_access() conservatively 1794 * mark the stack of all frames as read if any of them is 1795 * derived from a frame pointer. 1796 */ 1797 arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS + MAX_STACK_ARG_SLOTS; 1798 else if (bpf_get_call_summary(env, insn, &cs)) 1799 arg_slot_cnt = cs.arg_slot_cnt; 1800 1801 for (r = BPF_REG_1; r < BPF_REG_1 + min(arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); r++) { 1802 err = record_arg_access(env, instance, insn, &at[r], r - 1, insn_idx); 1803 if (err) 1804 return err; 1805 } 1806 1807 for (r = 0; r < MAX_STACK_ARG_SLOTS && r < arg_slot_cnt - MAX_BPF_FUNC_REG_ARGS; r++) { 1808 err = record_arg_access(env, instance, insn, &at[MAX_BPF_REG + r], 1809 r + MAX_BPF_FUNC_REG_ARGS, insn_idx); 1810 if (err) 1811 return err; 1812 } 1813 return 0; 1814 } 1815 1816 /* 1817 * For a calls_callback helper, find the callback subprog and determine 1818 * which caller register maps to which callback register for FP passthrough. 1819 */ 1820 static int find_callback_subprog(struct bpf_verifier_env *env, 1821 struct bpf_insn *insn, int insn_idx, 1822 int *caller_reg, int *callee_reg) 1823 { 1824 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 1825 int cb_reg = -1; 1826 1827 *caller_reg = -1; 1828 *callee_reg = -1; 1829 1830 if (!bpf_helper_call(insn)) 1831 return -1; 1832 switch (insn->imm) { 1833 case BPF_FUNC_loop: 1834 /* bpf_loop(nr, cb, ctx, flags): cb=R2, R3->cb R2 */ 1835 cb_reg = BPF_REG_2; 1836 *caller_reg = BPF_REG_3; 1837 *callee_reg = BPF_REG_2; 1838 break; 1839 case BPF_FUNC_for_each_map_elem: 1840 /* for_each_map_elem(map, cb, ctx, flags): cb=R2, R3->cb R4 */ 1841 cb_reg = BPF_REG_2; 1842 *caller_reg = BPF_REG_3; 1843 *callee_reg = BPF_REG_4; 1844 break; 1845 case BPF_FUNC_find_vma: 1846 /* find_vma(task, addr, cb, ctx, flags): cb=R3, R4->cb R3 */ 1847 cb_reg = BPF_REG_3; 1848 *caller_reg = BPF_REG_4; 1849 *callee_reg = BPF_REG_3; 1850 break; 1851 case BPF_FUNC_user_ringbuf_drain: 1852 /* user_ringbuf_drain(map, cb, ctx, flags): cb=R2, R3->cb R2 */ 1853 cb_reg = BPF_REG_2; 1854 *caller_reg = BPF_REG_3; 1855 *callee_reg = BPF_REG_2; 1856 break; 1857 default: 1858 return -1; 1859 } 1860 1861 if (!(aux->const_reg_subprog_mask & BIT(cb_reg))) 1862 return -2; 1863 1864 return aux->const_reg_vals[cb_reg]; 1865 } 1866 1867 /* Per-subprog intermediate state kept alive across analysis phases */ 1868 struct subprog_at_info { 1869 struct arg_track (*at_in)[MAX_AT_TRACK_REGS]; 1870 int len; 1871 }; 1872 1873 static void print_subprog_arg_access(struct bpf_verifier_env *env, 1874 int subprog, 1875 struct subprog_at_info *info, 1876 struct arg_track *at_stack_in, u32 nslots) 1877 { 1878 struct bpf_insn *insns = env->prog->insnsi; 1879 int start = env->subprog_info[subprog].start; 1880 int len = info->len; 1881 int i, r; 1882 1883 if (!(env->log.level & BPF_LOG_LEVEL2)) 1884 return; 1885 1886 verbose(env, "%s:\n", fmt_subprog(env, subprog)); 1887 for (i = 0; i < len; i++) { 1888 int idx = start + i; 1889 bool has_extra = false; 1890 u8 cls = BPF_CLASS(insns[idx].code); 1891 bool is_ldx_stx_call = cls == BPF_LDX || cls == BPF_STX || 1892 (cls == BPF_JMP && BPF_OP(insns[idx].code) == BPF_CALL); 1893 1894 verbose(env, "%3d: ", idx); 1895 bpf_verbose_insn(env, &insns[idx]); 1896 verbose(env, "\n"); 1897 1898 /* Collect what needs printing */ 1899 if (is_ldx_stx_call && 1900 arg_is_visited(&info->at_in[i][0])) { 1901 for (r = 0; r < MAX_BPF_REG - 1; r++) 1902 if (arg_is_fp(&info->at_in[i][r])) 1903 has_extra = true; 1904 for (r = 0; r < MAX_STACK_ARG_SLOTS; r++) 1905 if (arg_is_fp(&info->at_in[i][MAX_BPF_REG + r])) 1906 has_extra = true; 1907 } 1908 if (is_ldx_stx_call) { 1909 for (r = 0; r < nslots; r++) 1910 if (arg_is_fp(&at_stack_in[(size_t)i * nslots + r])) 1911 has_extra = true; 1912 } 1913 1914 if (!has_extra) { 1915 if (bpf_is_ldimm64(&insns[idx])) 1916 i++; 1917 continue; 1918 } 1919 1920 bpf_vlog_reset(&env->log, env->log.end_pos - 1); 1921 verbose(env, " //"); 1922 1923 if (is_ldx_stx_call && info->at_in && 1924 arg_is_visited(&info->at_in[i][0])) { 1925 for (r = 0; r < MAX_BPF_REG - 1; r++) { 1926 if (!arg_is_fp(&info->at_in[i][r])) 1927 continue; 1928 verbose(env, " r%d=", r); 1929 verbose_arg_track(env, &info->at_in[i][r]); 1930 } 1931 for (r = 0; r < MAX_STACK_ARG_SLOTS; r++) { 1932 if (!arg_is_fp(&info->at_in[i][MAX_BPF_REG + r])) 1933 continue; 1934 verbose(env, " sa%d=", r); 1935 verbose_arg_track(env, &info->at_in[i][MAX_BPF_REG + r]); 1936 } 1937 } 1938 1939 if (is_ldx_stx_call) { 1940 for (r = 0; r < nslots; r++) { 1941 if (!arg_is_fp(&at_stack_in[(size_t)i * nslots + r])) 1942 continue; 1943 verbose(env, " fp%+d=", -(r + 1) * 8); 1944 verbose_arg_track(env, &at_stack_in[(size_t)i * nslots + r]); 1945 } 1946 } 1947 1948 verbose(env, "\n"); 1949 if (bpf_is_ldimm64(&insns[idx])) 1950 i++; 1951 } 1952 } 1953 1954 static void record_stack_ptrs(struct bpf_verifier_env *env, int idx, struct arg_track *at_in) 1955 { 1956 u16 r, mask = 0; 1957 1958 for (r = 0; r < MAX_BPF_REG; r++) 1959 if (arg_is_fp(&at_in[r])) 1960 mask |= BIT(r); 1961 1962 env->insn_aux_data[idx].stack_ptrs |= mask; 1963 } 1964 1965 /* 1966 * Compute arg tracking dataflow for a single subprog. 1967 * Runs forward fixed-point with arg_track_xfer(), then records 1968 * memory accesses in a single linear pass over converged state. 1969 * 1970 * @callee_entry: pre-populated entry state for R1-R5 and stack args 1971 * NULL for main (subprog 0). 1972 * @info: stores at_in, len for debug printing. 1973 */ 1974 static int compute_subprog_args(struct bpf_verifier_env *env, 1975 struct subprog_at_info *info, 1976 struct arg_track *callee_entry, 1977 struct func_instance *instance, 1978 u32 *callsites) 1979 { 1980 int subprog = instance->subprog; 1981 struct bpf_insn *insns = env->prog->insnsi; 1982 int depth = instance->depth; 1983 int start = env->subprog_info[subprog].start; 1984 int po_start = env->subprog_info[subprog].postorder_start; 1985 int end = env->subprog_info[subprog + 1].start; 1986 int po_end = env->subprog_info[subprog + 1].postorder_start; 1987 int len = end - start; 1988 u32 nslots = min(subprog_spill_slots(env, start, end), spill_slots_affordable(len)); 1989 struct arg_track (*at_in)[MAX_AT_TRACK_REGS] = NULL; 1990 struct arg_track at_out[MAX_AT_TRACK_REGS]; 1991 struct arg_track *at_stack_in = NULL; 1992 struct arg_track *at_stack_out = NULL; 1993 struct arg_track at_stack_arg_entry[MAX_STACK_ARG_SLOTS]; 1994 struct arg_track unvisited = { .frame = ARG_UNVISITED }; 1995 struct arg_track none = { .frame = ARG_NONE }; 1996 bool changed; 1997 int i, p, r, err = -ENOMEM; 1998 1999 at_in = kvmalloc_objs(*at_in, len, GFP_KERNEL_ACCOUNT); 2000 if (!at_in) 2001 goto err_free; 2002 2003 at_stack_in = kvmalloc_objs(*at_stack_in, (size_t)len * nslots, GFP_KERNEL_ACCOUNT); 2004 if (!at_stack_in) 2005 goto err_free; 2006 2007 at_stack_out = kvmalloc_objs(*at_stack_out, nslots, GFP_KERNEL_ACCOUNT); 2008 if (!at_stack_out) 2009 goto err_free; 2010 2011 for (i = 0; i < len; i++) { 2012 for (r = 0; r < MAX_AT_TRACK_REGS; r++) 2013 at_in[i][r] = unvisited; 2014 for (r = 0; r < nslots; r++) 2015 at_stack_in[(size_t)i * nslots + r] = unvisited; 2016 } 2017 2018 for (r = 0; r < MAX_AT_TRACK_REGS; r++) 2019 at_in[0][r] = none; 2020 2021 /* Entry: R10 is always precisely the current frame's FP */ 2022 at_in[0][BPF_REG_FP] = arg_single(depth, 0); 2023 2024 /* R1-R5: from caller or ARG_NONE for main */ 2025 if (callee_entry) { 2026 for (r = BPF_REG_1; r <= BPF_REG_5; r++) 2027 at_in[0][r] = callee_entry[r]; 2028 } 2029 2030 /* Entry: all stack slots are ARG_NONE */ 2031 for (r = 0; r < nslots; r++) 2032 at_stack_in[r] = none; 2033 2034 /* Entry: incoming stack args from caller, or ARG_NONE for main */ 2035 for (r = 0; r < MAX_STACK_ARG_SLOTS; r++) 2036 at_stack_arg_entry[r] = callee_entry ? callee_entry[MAX_BPF_REG + r] : none; 2037 2038 if (env->log.level & BPF_LOG_LEVEL2) 2039 verbose(env, "subprog#%d: analyzing (depth %d)...\n", subprog, depth); 2040 2041 /* Forward fixed-point iteration in reverse post order */ 2042 redo: 2043 changed = false; 2044 for (p = po_end - 1; p >= po_start; p--) { 2045 int idx = env->cfg.insn_postorder[p]; 2046 int i = idx - start; 2047 struct bpf_insn *insn = &insns[idx]; 2048 struct bpf_iarray *succ; 2049 2050 if (!arg_is_visited(&at_in[i][0]) && !arg_is_visited(&at_in[i][1])) 2051 continue; 2052 2053 memcpy(at_out, at_in[i], sizeof(at_out)); 2054 memcpy(at_stack_out, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*at_stack_out)); 2055 2056 arg_track_xfer(env, insn, idx, at_out, at_stack_out, nslots, 2057 at_stack_arg_entry, instance, callsites); 2058 arg_track_log(env, insn, idx, at_in[i], &at_stack_in[(size_t)i * nslots], at_out, 2059 at_stack_out, nslots); 2060 2061 /* Propagate to successors within this subprogram */ 2062 succ = bpf_insn_successors(env, idx); 2063 for (int s = 0; s < succ->cnt; s++) { 2064 int target = succ->items[s]; 2065 int ti; 2066 2067 /* Filter: stay within the subprogram's range */ 2068 if (target < start || target >= end) 2069 continue; 2070 ti = target - start; 2071 2072 for (r = 0; r < MAX_AT_TRACK_REGS; r++) 2073 changed |= arg_track_join(env, idx, target, r, 2074 &at_in[ti][r], at_out[r]); 2075 2076 for (r = 0; r < nslots; r++) 2077 changed |= arg_track_join(env, idx, target, -r - 1, 2078 &at_stack_in[(size_t)ti * nslots + r], 2079 at_stack_out[r]); 2080 } 2081 } 2082 if (changed) 2083 goto redo; 2084 2085 /* Record memory accesses using converged at_in (RPO skips dead code) */ 2086 for (p = po_end - 1; p >= po_start; p--) { 2087 int idx = env->cfg.insn_postorder[p]; 2088 int i = idx - start; 2089 struct bpf_insn *insn = &insns[idx]; 2090 2091 err = record_load_store_access(env, instance, at_in[i], idx); 2092 if (err) 2093 goto err_free; 2094 2095 if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) { 2096 err = record_call_access(env, instance, at_in[i], idx); 2097 if (err) 2098 goto err_free; 2099 } 2100 2101 if (bpf_pseudo_call(insn) || bpf_calls_callback(env, idx)) { 2102 struct spill_snapshot *snap; 2103 2104 kvfree(env->callsite_at_stack[idx]); 2105 env->callsite_at_stack[idx] = kvmalloc_flex(*snap, at, nslots, GFP_KERNEL_ACCOUNT); 2106 snap = env->callsite_at_stack[idx]; 2107 if (!snap) { 2108 err = -ENOMEM; 2109 goto err_free; 2110 } 2111 snap->slots = nslots; 2112 memcpy(snap->at, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap->at)); 2113 } 2114 2115 record_stack_ptrs(env, idx, at_in[i]); 2116 } 2117 2118 info->at_in = at_in; 2119 at_in = NULL; 2120 info->len = len; 2121 print_subprog_arg_access(env, subprog, info, at_stack_in, nslots); 2122 err = 0; 2123 2124 err_free: 2125 kvfree(at_stack_out); 2126 kvfree(at_stack_in); 2127 kvfree(at_in); 2128 return err; 2129 } 2130 2131 /* Return true if any of R1-R5 or stack args is derived from a frame pointer. */ 2132 static bool has_fp_args(struct arg_track *args) 2133 { 2134 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 2135 if (arg_is_fp(&args[r])) 2136 return true; 2137 for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++) 2138 if (arg_is_fp(&args[MAX_BPF_REG + r])) 2139 return true; 2140 return false; 2141 } 2142 2143 /* 2144 * Merge a freshly analyzed instance into the original. 2145 * may_read: union (any pass might read the slot). 2146 * may_write: union (slots written on ANY pass). 2147 * must_write: intersection (only slots written on ALL passes are guaranteed). 2148 * live_before is recomputed by a subsequent update_instance() on @dst. 2149 * 2150 * The two instances may have settled on different mask widths for the same 2151 * frame, so @dst is widened to cover @src first. A word only @dst has counts 2152 * as zero on the @src side: it unions into may_read as a no-op and intersects 2153 * must_write to empty. 2154 */ 2155 static int merge_instances(struct func_instance *dst, struct func_instance *src) 2156 { 2157 struct frame_masks *d, *s; 2158 u32 f, i, w; 2159 2160 for (f = 0; f <= dst->depth; f++) { 2161 s = src->frames[f]; 2162 d = dst->frames[f]; 2163 if (!s) { 2164 /* This pass didn't touch frame f — must_write intersects with empty. */ 2165 if (d) 2166 for (i = 0; i < dst->insn_cnt; i++) 2167 bitmap_zero(rel_mask(d, i, FM_MUST_WRITE), 2168 frame_mask_bits(d)); 2169 continue; 2170 } 2171 if (!d) { 2172 /* Previous pass didn't touch frame f — take src, zero must_write. */ 2173 dst->frames[f] = s; 2174 src->frames[f] = NULL; 2175 for (i = 0; i < dst->insn_cnt; i++) 2176 bitmap_zero(rel_mask(s, i, FM_MUST_WRITE), frame_mask_bits(s)); 2177 continue; 2178 } 2179 d = widen_frame_masks(dst, f, s->words); 2180 if (!d) 2181 return -ENOMEM; 2182 for (i = 0; i < dst->insn_cnt; i++) { 2183 unsigned long *dst_read = rel_mask(d, i, FM_MAY_READ); 2184 unsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE); 2185 unsigned long *dst_may_write = rel_mask(d, i, FM_MAY_WRITE); 2186 unsigned long *src_read = rel_mask(s, i, FM_MAY_READ); 2187 unsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE); 2188 unsigned long *src_may_write = rel_mask(s, i, FM_MAY_WRITE); 2189 2190 for (w = 0; w < d->words; w++) { 2191 dst_read[w] |= w < s->words ? src_read[w] : 0; 2192 dst_write[w] &= w < s->words ? src_write[w] : 0; 2193 dst_may_write[w] |= w < s->words ? src_may_write[w] : 0; 2194 } 2195 } 2196 } 2197 return 0; 2198 } 2199 2200 /* 2201 * Fold a fully analyzed callee instance writes to upper frames as 2202 * may_write marks at callsite in caller's frames. 2203 */ 2204 static int merge_may_write(struct func_instance *caller, struct func_instance *callee) 2205 { 2206 DECLARE_BITMAP(acc, FRAME_HALF_SPIS); 2207 u32 call_idx = callee->callsite; 2208 struct frame_masks *fm; 2209 u32 f, i, nbits; 2210 int err; 2211 2212 for (f = 0; f < callee->depth; f++) { 2213 fm = callee->frames[f]; 2214 if (!fm) 2215 continue; 2216 nbits = frame_mask_bits(fm); 2217 bitmap_zero(acc, nbits); 2218 for (i = 0; i < callee->insn_cnt; i++) 2219 bitmap_or(acc, acc, rel_mask(fm, i, FM_MAY_WRITE), nbits); 2220 if (bitmap_empty(acc, nbits)) 2221 continue; 2222 err = mark_stack_mask(caller, f, call_idx, FM_MAY_WRITE, acc, fm->words); 2223 if (err) 2224 return err; 2225 } 2226 return 0; 2227 } 2228 2229 static struct func_instance *fresh_instance(struct func_instance *src) 2230 { 2231 struct func_instance *f; 2232 2233 f = kvzalloc_obj(*f, GFP_KERNEL_ACCOUNT); 2234 if (!f) 2235 return ERR_PTR(-ENOMEM); 2236 f->callsite = src->callsite; 2237 f->depth = src->depth; 2238 f->subprog = src->subprog; 2239 f->subprog_start = src->subprog_start; 2240 f->insn_cnt = src->insn_cnt; 2241 return f; 2242 } 2243 2244 static void free_instance(struct func_instance *instance) 2245 { 2246 int i; 2247 2248 for (i = 0; i <= instance->depth; i++) 2249 kvfree(instance->frames[i]); 2250 kvfree(instance); 2251 } 2252 2253 /* 2254 * Recursively analyze a subprog with specific 'entry_args'. 2255 * Each callee is analyzed with the exact args from its call site. 2256 * 2257 * Args are recomputed for each call because the dataflow result at_in[] 2258 * depends on the entry args and frame depth. Consider: A->C->D and B->C->D 2259 * Callsites in A and B pass different args into C, so C is recomputed. 2260 * Then within C the same callsite passes different args into D. 2261 */ 2262 static int analyze_subprog(struct bpf_verifier_env *env, 2263 struct arg_track *entry_args, 2264 struct subprog_at_info *info, 2265 struct func_instance *instance, 2266 u32 *callsites) 2267 { 2268 int subprog = instance->subprog; 2269 int depth = instance->depth; 2270 struct bpf_insn *insns = env->prog->insnsi; 2271 int start = env->subprog_info[subprog].start; 2272 int po_start = env->subprog_info[subprog].postorder_start; 2273 int po_end = env->subprog_info[subprog + 1].postorder_start; 2274 struct func_instance *prev_instance = NULL; 2275 int j, err; 2276 2277 if (++env->liveness->subprog_calls > 10000) { 2278 verbose(env, "liveness analysis exceeded complexity limit (%d calls)\n", 2279 env->liveness->subprog_calls); 2280 return -E2BIG; 2281 } 2282 2283 if (need_resched()) 2284 cond_resched(); 2285 2286 /* 2287 * When an instance is reused (must_write_initialized == true), 2288 * record into a fresh instance and merge afterward. This avoids 2289 * stale must_write marks for instructions not reached in this pass. 2290 */ 2291 if (instance->must_write_initialized) { 2292 struct func_instance *fresh = fresh_instance(instance); 2293 2294 if (IS_ERR(fresh)) 2295 return PTR_ERR(fresh); 2296 prev_instance = instance; 2297 instance = fresh; 2298 } 2299 2300 /* Free prior analysis if this subprog was already visited */ 2301 kvfree(info[subprog].at_in); 2302 info[subprog].at_in = NULL; 2303 2304 err = compute_subprog_args(env, &info[subprog], entry_args, instance, callsites); 2305 if (err) 2306 goto out_free; 2307 2308 /* For each reachable call site in the subprog, recurse into callees */ 2309 for (int p = po_start; p < po_end; p++) { 2310 int idx = env->cfg.insn_postorder[p]; 2311 struct arg_track callee_args[MAX_AT_TRACK_REGS] = {}; 2312 struct arg_track none = { .frame = ARG_NONE }; 2313 struct bpf_insn *insn = &insns[idx]; 2314 struct func_instance *callee_instance; 2315 int callee, target; 2316 int caller_reg, cb_callee_reg; 2317 2318 j = idx - start; /* relative index within this subprog */ 2319 2320 if (bpf_pseudo_call(insn)) { 2321 target = idx + insn->imm + 1; 2322 callee = bpf_find_subprog(env, target); 2323 /* 2324 * Global subprograms can be freplaced, so conservatively derive 2325 * their stack effects from their BTF signatures instead of 2326 * analyzing them in the context of their callers. 2327 */ 2328 if (callee < 0 || bpf_subprog_is_global(env, callee)) 2329 continue; 2330 2331 /* Build entry args: R1-R5 and stack args from at_in at call site */ 2332 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 2333 callee_args[r] = info[subprog].at_in[j][r]; 2334 for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++) 2335 callee_args[MAX_BPF_REG + r] = info[subprog].at_in[j][MAX_BPF_REG + r]; 2336 } else if (bpf_calls_callback(env, idx)) { 2337 callee = find_callback_subprog(env, insn, idx, &caller_reg, &cb_callee_reg); 2338 if (callee == -2) { 2339 /* 2340 * same bpf_loop() calls two different callbacks and passes 2341 * stack pointer to them 2342 */ 2343 if (info[subprog].at_in[j][caller_reg].frame == ARG_NONE) 2344 continue; 2345 for (int f = 0; f <= depth; f++) { 2346 err = mark_stack_read_all(env, instance, f, idx); 2347 if (err) 2348 goto out_free; 2349 err = mark_stack_may_write_all(env, instance, f, idx); 2350 if (err) 2351 goto out_free; 2352 } 2353 continue; 2354 } 2355 if (callee < 0) 2356 continue; 2357 2358 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 2359 callee_args[r] = none; 2360 for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++) 2361 callee_args[MAX_BPF_REG + r] = none; 2362 callee_args[cb_callee_reg] = info[subprog].at_in[j][caller_reg]; 2363 } else { 2364 continue; 2365 } 2366 2367 if (!has_fp_args(callee_args)) 2368 continue; 2369 2370 if (depth == MAX_CALL_FRAMES - 1) { 2371 err = -EINVAL; 2372 goto out_free; 2373 } 2374 2375 callee_instance = call_instance(env, instance, idx, callee); 2376 if (IS_ERR(callee_instance)) { 2377 err = PTR_ERR(callee_instance); 2378 goto out_free; 2379 } 2380 callsites[depth] = idx; 2381 err = analyze_subprog(env, callee_args, info, callee_instance, callsites); 2382 if (err) 2383 goto out_free; 2384 2385 /* Pull callee's entry liveness back to caller's callsite */ 2386 { 2387 u32 callee_start = callee_instance->subprog_start; 2388 struct frame_masks *callee_fm; 2389 2390 for (int f = 0; f < callee_instance->depth; f++) { 2391 callee_fm = callee_instance->frames[f]; 2392 if (!callee_fm) 2393 continue; 2394 err = mark_stack_read_mask(instance, f, idx, 2395 rel_mask(callee_fm, 2396 relative_idx(callee_instance, 2397 callee_start), 2398 FM_LIVE_BEFORE), 2399 callee_fm->words); 2400 if (err) 2401 goto out_free; 2402 } 2403 } 2404 2405 /* Summarize callee's writes to ancestor frames onto the callsite */ 2406 err = merge_may_write(instance, callee_instance); 2407 if (err) 2408 goto out_free; 2409 } 2410 2411 if (prev_instance) { 2412 err = merge_instances(prev_instance, instance); 2413 free_instance(instance); 2414 instance = prev_instance; 2415 if (err) 2416 return err; 2417 } 2418 update_instance(env, instance); 2419 return 0; 2420 2421 out_free: 2422 if (prev_instance) 2423 free_instance(instance); 2424 return err; 2425 } 2426 2427 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env) 2428 { 2429 u32 callsites[MAX_CALL_FRAMES] = {}; 2430 int insn_cnt = env->prog->len; 2431 struct func_instance *instance; 2432 struct subprog_at_info *info; 2433 int k, err = 0; 2434 2435 info = kvzalloc_objs(*info, env->subprog_cnt, GFP_KERNEL_ACCOUNT); 2436 if (!info) 2437 return -ENOMEM; 2438 2439 env->callsite_at_stack = kvzalloc_objs(*env->callsite_at_stack, insn_cnt, 2440 GFP_KERNEL_ACCOUNT); 2441 if (!env->callsite_at_stack) { 2442 kvfree(info); 2443 return -ENOMEM; 2444 } 2445 2446 /* 2447 * Analyze every subprog in reverse topological order (callers 2448 * before callees) so that each subprog is analyzed before its 2449 * callees, allowing the recursive walk inside analyze_subprog() 2450 * to naturally reach callees that receive FP-derived args. 2451 * 2452 * Subprogs and callbacks that don't receive FP-derived arguments 2453 * cannot access ancestor stack frames are analyzed independently. 2454 * Async callbacks (timer, workqueue) are handled the same way. 2455 */ 2456 for (k = env->subprog_cnt - 1; k >= 0; k--) { 2457 int sub = env->subprog_topo_order[k]; 2458 2459 if (info[sub].at_in && !bpf_subprog_is_global(env, sub)) 2460 continue; 2461 instance = call_instance(env, NULL, 0, sub); 2462 if (IS_ERR(instance)) { 2463 err = PTR_ERR(instance); 2464 goto out; 2465 } 2466 err = analyze_subprog(env, NULL, info, instance, callsites); 2467 if (err) 2468 goto out; 2469 } 2470 2471 compute_may_write_masks(env); 2472 2473 if (env->log.level & BPF_LOG_LEVEL2) 2474 err = print_instances(env); 2475 2476 out: 2477 for (k = 0; k < insn_cnt; k++) 2478 kvfree(env->callsite_at_stack[k]); 2479 kvfree(env->callsite_at_stack); 2480 env->callsite_at_stack = NULL; 2481 for (k = 0; k < env->subprog_cnt; k++) 2482 kvfree(info[k].at_in); 2483 kvfree(info); 2484 return err; 2485 } 2486 2487 /* Each field is a register bitmask */ 2488 struct insn_live_regs { 2489 u32 use; /* registers read by instruction */ 2490 u32 def; /* registers written by instruction */ 2491 u32 in; /* registers that may be alive before instruction */ 2492 u32 out; /* registers that may be alive after instruction */ 2493 }; 2494 2495 /* Bitmask with 1s for all caller saved registers */ 2496 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 2497 2498 static inline u32 reg32_mask(u32 n) { return BIT(n); } 2499 static inline u32 reg64_mask(u32 n) { return BIT(n) | BIT(n + 16); } 2500 static inline u32 mask_widen(u32 m) { return m | (m << 16); } 2501 static inline u16 mask_lo(u32 m) { return (u16)m; } 2502 static inline u16 mask_hi(u32 m) { return (u16)(m >> 16); } 2503 2504 /* Index of the subprogram called by pseudo call @insn */ 2505 static int callee_subprog(struct bpf_verifier_env *env, const struct bpf_insn *insn) 2506 { 2507 return bpf_find_subprog(env, insn - env->prog->insnsi + insn->imm + 1); 2508 } 2509 2510 /* Compute info->{use,def} fields for the instruction */ 2511 static void compute_insn_live_regs(struct bpf_verifier_env *env, 2512 struct bpf_insn *insn, 2513 struct insn_live_regs *info, 2514 bool ret_reg_pair) 2515 { 2516 struct bpf_call_summary cs; 2517 const u8 class = BPF_CLASS(insn->code); 2518 const u8 code = BPF_OP(insn->code); 2519 const u8 mode = BPF_MODE(insn->code); 2520 const u8 size = BPF_SIZE(insn->code); 2521 const u32 src = reg64_mask(insn->src_reg); 2522 const u32 dst = reg64_mask(insn->dst_reg); 2523 const u32 src32 = mask_lo(src); 2524 const u32 dst32 = mask_lo(dst); 2525 const u32 r0 = reg64_mask(0); 2526 const u32 r2 = reg64_mask(BPF_REG_2); 2527 int subprog, reg_args; 2528 u32 def = 0; 2529 u32 use = U32_MAX; 2530 2531 switch (class) { 2532 case BPF_LD: 2533 switch (mode) { 2534 case BPF_IMM: 2535 if (BPF_SIZE(insn->code) == BPF_DW) { 2536 def = dst; 2537 use = 0; 2538 } 2539 break; 2540 case BPF_ABS: 2541 case BPF_IND: 2542 /* stick with defaults */ 2543 break; 2544 } 2545 break; 2546 case BPF_LDX: 2547 switch (mode) { 2548 case BPF_MEM: 2549 /* a narrow load still redefines the whole register */ 2550 def = dst; 2551 use = src; 2552 break; 2553 case BPF_MEMSX: 2554 /* 2555 * sign extension defines the whole register; 2556 * src holds a pointer, hence is used as 64-bit. 2557 */ 2558 def = dst; 2559 use = src; 2560 break; 2561 } 2562 break; 2563 case BPF_ST: 2564 switch (mode) { 2565 case BPF_MEM: 2566 def = 0; 2567 use = dst; 2568 break; 2569 } 2570 break; 2571 case BPF_STX: 2572 switch (mode) { 2573 case BPF_MEM: 2574 def = 0; 2575 use = dst | (size == BPF_DW ? src : src32); 2576 break; 2577 case BPF_ATOMIC: { 2578 /* 2579 * dst holds a pointer and is always used as 64-bit; 2580 * the value operand and r0 are read as 32-bit for BPF_W atomics. 2581 */ 2582 u32 srcv = size == BPF_DW ? src : src32; 2583 u32 r0v = size == BPF_DW ? r0 : mask_lo(r0); 2584 2585 switch (insn->imm) { 2586 case BPF_CMPXCHG: 2587 use = r0v | dst | srcv; 2588 def = r0; 2589 break; 2590 case BPF_LOAD_ACQ: 2591 def = dst; 2592 use = src; 2593 break; 2594 case BPF_STORE_REL: 2595 def = 0; 2596 use = dst | srcv; 2597 break; 2598 default: 2599 use = dst | srcv; 2600 if (insn->imm & BPF_FETCH) 2601 def = src; 2602 else 2603 def = 0; 2604 } 2605 break; 2606 } 2607 } 2608 break; 2609 case BPF_ALU: 2610 case BPF_ALU64: 2611 switch (code) { 2612 case BPF_END: 2613 use = dst; 2614 def = dst; 2615 break; 2616 case BPF_MOV: 2617 def = dst; 2618 if (BPF_SRC(insn->code) == BPF_K) 2619 use = 0; 2620 else 2621 use = class == BPF_ALU64 ? src : src32; 2622 break; 2623 default: 2624 def = dst; 2625 if (BPF_SRC(insn->code) == BPF_K) 2626 use = class == BPF_ALU64 ? dst : dst32; 2627 else 2628 use = class == BPF_ALU64 ? (dst | src) : (dst32 | src32); 2629 } 2630 break; 2631 case BPF_JMP: 2632 case BPF_JMP32: 2633 switch (code) { 2634 case BPF_JA: 2635 def = 0; 2636 if (BPF_SRC(insn->code) == BPF_X) 2637 use = dst; 2638 else 2639 use = 0; 2640 break; 2641 case BPF_JCOND: 2642 def = 0; 2643 use = 0; 2644 break; 2645 case BPF_EXIT: 2646 def = 0; 2647 use = ret_reg_pair ? (r0 | r2) : r0; 2648 break; 2649 case BPF_CALL: 2650 def = ALL_CALLER_SAVED_REGS; 2651 use = def & ~BIT(BPF_REG_0); 2652 if (bpf_get_call_summary(env, insn, &cs)) { 2653 use = GENMASK(min_t(u8, cs.arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS), 1); 2654 } else if (bpf_pseudo_call(insn)) { 2655 /* a static callee's reads are added in bpf_compute_live_registers() */ 2656 subprog = callee_subprog(env, insn); 2657 if (bpf_subprog_is_global(env, subprog)) { 2658 reg_args = min_t(u8, env->subprog_info[subprog].arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); 2659 use = GENMASK(reg_args, 1); 2660 } else { 2661 use = 0; 2662 } 2663 } 2664 def = mask_widen(def); 2665 use = mask_widen(use); 2666 /* callx reads the address of the callee from dst_reg */ 2667 if (bpf_is_callx(insn)) 2668 use |= dst; 2669 break; 2670 default: 2671 def = 0; 2672 use = class == BPF_JMP ? dst : dst32; 2673 if (BPF_SRC(insn->code) == BPF_X) 2674 use |= class == BPF_JMP ? src : src32; 2675 } 2676 break; 2677 } 2678 2679 info->def = def; 2680 info->use = use; 2681 } 2682 2683 /* Compute may-live registers after each instruction in the program. 2684 * The register is live after the instruction I if it is read by some 2685 * instruction S following I during program execution and is not 2686 * overwritten between I and S. 2687 * 2688 * Store result in env->insn_aux_data[i].live_regs. 2689 */ 2690 int bpf_compute_live_registers(struct bpf_verifier_env *env) 2691 { 2692 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 2693 struct bpf_insn *insns = env->prog->insnsi; 2694 struct insn_live_regs *state; 2695 int insn_cnt = env->prog->len; 2696 int err = 0, i, subprog, start, end; 2697 bool changed, ret_reg_pair; 2698 2699 /* Use the following algorithm: 2700 * - define the following: 2701 * - I.use : a set of all registers read by instruction I; 2702 * - I.def : a set of all registers written by instruction I; 2703 * - I.in : a set of all registers that may be alive before I execution; 2704 * - I.out : a set of all registers that may be alive after I execution; 2705 * - insn_successors(I): a set of instructions S that might immediately 2706 * follow I for some program execution; 2707 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 2708 * - visit each instruction in a postorder and update 2709 * state[i].in, state[i].out as follows: 2710 * 2711 * state[i].out = U [state[s].in for S in insn_successors(i)] 2712 * state[i].in = (state[i].out / state[i].def) U state[i].use 2713 * 2714 * (where U stands for set union, / stands for set difference) 2715 * - repeat the computation while {in,out} fields changes for 2716 * any instruction. 2717 */ 2718 state = kvzalloc_objs(*state, insn_cnt, GFP_KERNEL_ACCOUNT); 2719 if (!state) { 2720 err = -ENOMEM; 2721 goto out; 2722 } 2723 2724 for (subprog = 0; subprog < env->subprog_cnt; subprog++) { 2725 start = env->subprog_info[subprog].start; 2726 end = env->subprog_info[subprog + 1].start; 2727 ret_reg_pair = bpf_ret_reg_pair(env, subprog); 2728 2729 for (i = start; i < end; ++i) 2730 compute_insn_live_regs(env, &insns[i], &state[i], ret_reg_pair); 2731 } 2732 2733 /* Forward pass: resolve stack access through FP-derived pointers */ 2734 err = bpf_compute_subprog_arg_access(env); 2735 if (err) 2736 goto out; 2737 2738 changed = true; 2739 while (changed) { 2740 changed = false; 2741 for (i = 0; i < env->cfg.cur_postorder; ++i) { 2742 int insn_idx = env->cfg.insn_postorder[i]; 2743 struct insn_live_regs *live = &state[insn_idx]; 2744 struct bpf_iarray *succ; 2745 u32 new_out = 0; 2746 u32 new_in = 0; 2747 u32 use; 2748 2749 succ = bpf_insn_successors(env, insn_idx); 2750 for (int s = 0; s < succ->cnt; ++s) 2751 new_out |= state[succ->items[s]].in; 2752 use = live->use; 2753 /* 2754 * For a call to a static subprogram include the callee's 2755 * entry 'in' as computed so far. 2756 */ 2757 if (bpf_pseudo_call(&insns[insn_idx]) && 2758 !bpf_subprog_is_global(env, callee_subprog(env, &insns[insn_idx]))) 2759 use |= state[insn_idx + insns[insn_idx].imm + 1].in & 2760 mask_widen(GENMASK(BPF_REG_5, BPF_REG_1)); 2761 new_in = (new_out & ~live->def) | use; 2762 if (new_out != live->out || new_in != live->in) { 2763 live->in = new_in; 2764 live->out = new_out; 2765 changed = true; 2766 } 2767 } 2768 } 2769 2770 for (i = 0; i < insn_cnt; ++i) { 2771 int def32 = bpf_insn_def32(env->prog, &insns[i]); 2772 u32 out = state[i].out; 2773 u32 in = state[i].in; 2774 2775 insn_aux[i].live_regs_before = mask_lo(in) | mask_hi(in); 2776 /* 2777 * On architectures where 32-bit operations do not reset upper halves 2778 * of the registers, the verifier needs to zero extend a destination 2779 * register if an instruction defines a 32-bit subregister and the 2780 * upper half of that register is alive after the instruction. 2781 */ 2782 insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32)); 2783 } 2784 2785 out: 2786 kvfree(state); 2787 return err; 2788 } 2789