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 struct per_frame_masks { 14 spis_t may_read; /* stack slots that may be read by this instruction */ 15 spis_t must_write; /* stack slots written by this instruction */ 16 spis_t live_before; /* stack slots that may be read by this insn and its successors */ 17 }; 18 19 /* 20 * A function instance keyed by (callsite, depth). 21 * Encapsulates read and write marks for each instruction in the function. 22 * Marks are tracked for each frame up to @depth. 23 */ 24 struct func_instance { 25 struct hlist_node hl_node; 26 u32 callsite; /* call insn that invoked this subprog (subprog_start for depth 0) */ 27 u32 depth; /* call depth (0 = entry subprog) */ 28 u32 subprog; /* subprog index */ 29 u32 subprog_start; /* cached env->subprog_info[subprog].start */ 30 u32 insn_cnt; /* cached number of insns in the function */ 31 /* Per frame, per instruction masks, frames allocated lazily. */ 32 struct per_frame_masks *frames[MAX_CALL_FRAMES]; 33 bool must_write_initialized; 34 }; 35 36 struct live_stack_query { 37 struct func_instance *instances[MAX_CALL_FRAMES]; /* valid in range [0..curframe] */ 38 u32 callsites[MAX_CALL_FRAMES]; /* callsite[i] = insn calling frame i+1 */ 39 u32 curframe; 40 u32 insn_idx; 41 }; 42 43 struct bpf_liveness { 44 DECLARE_HASHTABLE(func_instances, 8); /* maps (depth, callsite) to func_instance */ 45 struct live_stack_query live_stack_query; /* cache to avoid repetitive ht lookups */ 46 u32 subprog_calls; /* analyze_subprog() invocations */ 47 }; 48 49 /* 50 * Hash/compare key for func_instance: (depth, callsite). 51 * For depth == 0 (entry subprog), @callsite is the subprog start insn. 52 * For depth > 0, @callsite is the call instruction index that invoked the subprog. 53 */ 54 static u32 instance_hash(u32 callsite, u32 depth) 55 { 56 u32 key[2] = { depth, callsite }; 57 58 return jhash2(key, 2, 0); 59 } 60 61 static struct func_instance *find_instance(struct bpf_verifier_env *env, 62 u32 callsite, u32 depth) 63 { 64 struct bpf_liveness *liveness = env->liveness; 65 struct func_instance *f; 66 u32 key = instance_hash(callsite, depth); 67 68 hash_for_each_possible(liveness->func_instances, f, hl_node, key) 69 if (f->depth == depth && f->callsite == callsite) 70 return f; 71 return NULL; 72 } 73 74 static struct func_instance *call_instance(struct bpf_verifier_env *env, 75 struct func_instance *caller, 76 u32 callsite, int subprog) 77 { 78 u32 depth = caller ? caller->depth + 1 : 0; 79 u32 subprog_start = env->subprog_info[subprog].start; 80 u32 lookup_key = depth > 0 ? callsite : subprog_start; 81 struct func_instance *f; 82 u32 hash; 83 84 f = find_instance(env, lookup_key, depth); 85 if (f) 86 return f; 87 88 f = kvzalloc(sizeof(*f), GFP_KERNEL_ACCOUNT); 89 if (!f) 90 return ERR_PTR(-ENOMEM); 91 f->callsite = lookup_key; 92 f->depth = depth; 93 f->subprog = subprog; 94 f->subprog_start = subprog_start; 95 f->insn_cnt = (env->subprog_info + subprog + 1)->start - subprog_start; 96 hash = instance_hash(lookup_key, depth); 97 hash_add(env->liveness->func_instances, &f->hl_node, hash); 98 return f; 99 } 100 101 static struct func_instance *lookup_instance(struct bpf_verifier_env *env, 102 struct bpf_verifier_state *st, 103 u32 frameno) 104 { 105 u32 callsite, subprog_start; 106 struct func_instance *f; 107 u32 key, depth; 108 109 subprog_start = env->subprog_info[st->frame[frameno]->subprogno].start; 110 callsite = frameno > 0 ? st->frame[frameno]->callsite : subprog_start; 111 112 for (depth = frameno; ; depth--) { 113 key = depth > 0 ? callsite : subprog_start; 114 f = find_instance(env, key, depth); 115 if (f || depth == 0) 116 return f; 117 } 118 } 119 120 int bpf_stack_liveness_init(struct bpf_verifier_env *env) 121 { 122 env->liveness = kvzalloc_obj(*env->liveness, GFP_KERNEL_ACCOUNT); 123 if (!env->liveness) 124 return -ENOMEM; 125 hash_init(env->liveness->func_instances); 126 return 0; 127 } 128 129 void bpf_stack_liveness_free(struct bpf_verifier_env *env) 130 { 131 struct func_instance *instance; 132 struct hlist_node *tmp; 133 int bkt, i; 134 135 if (!env->liveness) 136 return; 137 hash_for_each_safe(env->liveness->func_instances, bkt, tmp, instance, hl_node) { 138 for (i = 0; i <= instance->depth; i++) 139 kvfree(instance->frames[i]); 140 kvfree(instance); 141 } 142 kvfree(env->liveness); 143 } 144 145 /* 146 * Convert absolute instruction index @insn_idx to an index relative 147 * to start of the function corresponding to @instance. 148 */ 149 static int relative_idx(struct func_instance *instance, u32 insn_idx) 150 { 151 return insn_idx - instance->subprog_start; 152 } 153 154 static struct per_frame_masks *get_frame_masks(struct func_instance *instance, 155 u32 frame, u32 insn_idx) 156 { 157 if (!instance->frames[frame]) 158 return NULL; 159 160 return &instance->frames[frame][relative_idx(instance, insn_idx)]; 161 } 162 163 static struct per_frame_masks *alloc_frame_masks(struct func_instance *instance, 164 u32 frame, u32 insn_idx) 165 { 166 struct per_frame_masks *arr; 167 168 if (!instance->frames[frame]) { 169 arr = kvzalloc_objs(*arr, instance->insn_cnt, 170 GFP_KERNEL_ACCOUNT); 171 instance->frames[frame] = arr; 172 if (!arr) 173 return ERR_PTR(-ENOMEM); 174 } 175 return get_frame_masks(instance, frame, insn_idx); 176 } 177 178 /* Accumulate may_read masks for @frame at @insn_idx */ 179 static int mark_stack_read(struct func_instance *instance, u32 frame, u32 insn_idx, spis_t mask) 180 { 181 struct per_frame_masks *masks; 182 183 masks = alloc_frame_masks(instance, frame, insn_idx); 184 if (IS_ERR(masks)) 185 return PTR_ERR(masks); 186 masks->may_read = spis_or(masks->may_read, mask); 187 return 0; 188 } 189 190 static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_idx, spis_t mask) 191 { 192 struct per_frame_masks *masks; 193 194 masks = alloc_frame_masks(instance, frame, insn_idx); 195 if (IS_ERR(masks)) 196 return PTR_ERR(masks); 197 masks->must_write = spis_or(masks->must_write, mask); 198 return 0; 199 } 200 201 int bpf_jmp_offset(struct bpf_insn *insn) 202 { 203 u8 code = insn->code; 204 205 if (code == (BPF_JMP32 | BPF_JA)) 206 return insn->imm; 207 return insn->off; 208 } 209 210 __diag_push(); 211 __diag_ignore_all("-Woverride-init", "Allow field initialization overrides for opcode_info_tbl"); 212 213 /* 214 * Returns an array of instructions succ, with succ->items[0], ..., 215 * succ->items[n-1] with successor instructions, where n=succ->cnt 216 */ 217 inline struct bpf_iarray * 218 bpf_insn_successors(struct bpf_verifier_env *env, u32 idx) 219 { 220 static const struct opcode_info { 221 bool can_jump; 222 bool can_fallthrough; 223 } opcode_info_tbl[256] = { 224 [0 ... 255] = {.can_jump = false, .can_fallthrough = true}, 225 #define _J(code, ...) \ 226 [BPF_JMP | code] = __VA_ARGS__, \ 227 [BPF_JMP32 | code] = __VA_ARGS__ 228 229 _J(BPF_EXIT, {.can_jump = false, .can_fallthrough = false}), 230 _J(BPF_JA, {.can_jump = true, .can_fallthrough = false}), 231 _J(BPF_JEQ, {.can_jump = true, .can_fallthrough = true}), 232 _J(BPF_JNE, {.can_jump = true, .can_fallthrough = true}), 233 _J(BPF_JLT, {.can_jump = true, .can_fallthrough = true}), 234 _J(BPF_JLE, {.can_jump = true, .can_fallthrough = true}), 235 _J(BPF_JGT, {.can_jump = true, .can_fallthrough = true}), 236 _J(BPF_JGE, {.can_jump = true, .can_fallthrough = true}), 237 _J(BPF_JSGT, {.can_jump = true, .can_fallthrough = true}), 238 _J(BPF_JSGE, {.can_jump = true, .can_fallthrough = true}), 239 _J(BPF_JSLT, {.can_jump = true, .can_fallthrough = true}), 240 _J(BPF_JSLE, {.can_jump = true, .can_fallthrough = true}), 241 _J(BPF_JCOND, {.can_jump = true, .can_fallthrough = true}), 242 _J(BPF_JSET, {.can_jump = true, .can_fallthrough = true}), 243 #undef _J 244 }; 245 struct bpf_prog *prog = env->prog; 246 struct bpf_insn *insn = &prog->insnsi[idx]; 247 const struct opcode_info *opcode_info; 248 struct bpf_iarray *succ, *jt; 249 int insn_sz; 250 251 jt = env->insn_aux_data[idx].jt; 252 if (unlikely(jt)) 253 return jt; 254 255 /* pre-allocated array of size up to 2; reset cnt, as it may have been used already */ 256 succ = env->succ; 257 succ->cnt = 0; 258 259 opcode_info = &opcode_info_tbl[BPF_CLASS(insn->code) | BPF_OP(insn->code)]; 260 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 261 if (opcode_info->can_fallthrough) 262 succ->items[succ->cnt++] = idx + insn_sz; 263 264 if (opcode_info->can_jump) 265 succ->items[succ->cnt++] = idx + bpf_jmp_offset(insn) + 1; 266 267 return succ; 268 } 269 270 __diag_pop(); 271 272 273 static inline bool update_insn(struct bpf_verifier_env *env, 274 struct func_instance *instance, u32 frame, u32 insn_idx) 275 { 276 spis_t new_before, new_after; 277 struct per_frame_masks *insn, *succ_insn; 278 struct bpf_iarray *succ; 279 u32 s; 280 bool changed; 281 282 succ = bpf_insn_successors(env, insn_idx); 283 if (succ->cnt == 0) 284 return false; 285 286 changed = false; 287 insn = get_frame_masks(instance, frame, insn_idx); 288 new_before = SPIS_ZERO; 289 new_after = SPIS_ZERO; 290 for (s = 0; s < succ->cnt; ++s) { 291 succ_insn = get_frame_masks(instance, frame, succ->items[s]); 292 new_after = spis_or(new_after, succ_insn->live_before); 293 } 294 /* 295 * New "live_before" is a union of all "live_before" of successors 296 * minus slots written by instruction plus slots read by instruction. 297 * new_before = (new_after & ~insn->must_write) | insn->may_read 298 */ 299 new_before = spis_or(spis_and(new_after, spis_not(insn->must_write)), 300 insn->may_read); 301 changed |= !spis_equal(new_before, insn->live_before); 302 insn->live_before = new_before; 303 return changed; 304 } 305 306 /* Fixed-point computation of @live_before marks */ 307 static void update_instance(struct bpf_verifier_env *env, struct func_instance *instance) 308 { 309 u32 i, frame, po_start, po_end; 310 int *insn_postorder = env->cfg.insn_postorder; 311 struct bpf_subprog_info *subprog; 312 bool changed; 313 314 instance->must_write_initialized = true; 315 subprog = &env->subprog_info[instance->subprog]; 316 po_start = subprog->postorder_start; 317 po_end = (subprog + 1)->postorder_start; 318 /* repeat until fixed point is reached */ 319 do { 320 changed = false; 321 for (frame = 0; frame <= instance->depth; frame++) { 322 if (!instance->frames[frame]) 323 continue; 324 325 for (i = po_start; i < po_end; i++) 326 changed |= update_insn(env, instance, frame, insn_postorder[i]); 327 } 328 } while (changed); 329 } 330 331 static bool is_live_before(struct func_instance *instance, u32 insn_idx, u32 frameno, u32 half_spi) 332 { 333 struct per_frame_masks *masks; 334 335 masks = get_frame_masks(instance, frameno, insn_idx); 336 return masks && spis_test_bit(masks->live_before, half_spi); 337 } 338 339 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 340 { 341 struct live_stack_query *q = &env->liveness->live_stack_query; 342 struct func_instance *instance; 343 u32 frame; 344 345 memset(q, 0, sizeof(*q)); 346 for (frame = 0; frame <= st->curframe; frame++) { 347 instance = lookup_instance(env, st, frame); 348 if (IS_ERR_OR_NULL(instance)) 349 q->instances[frame] = NULL; 350 else 351 q->instances[frame] = instance; 352 if (frame < st->curframe) 353 q->callsites[frame] = st->frame[frame + 1]->callsite; 354 } 355 q->curframe = st->curframe; 356 q->insn_idx = st->insn_idx; 357 return 0; 358 } 359 360 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi) 361 { 362 /* 363 * Slot is alive if it is read before q->insn_idx in current func instance, 364 * or if for some outer func instance: 365 * - alive before callsite if callsite calls callback, otherwise 366 * - alive after callsite 367 */ 368 struct live_stack_query *q = &env->liveness->live_stack_query; 369 struct func_instance *instance, *curframe_instance; 370 u32 i, callsite, rel; 371 int cur_delta, delta; 372 bool alive = false; 373 374 curframe_instance = q->instances[q->curframe]; 375 if (!curframe_instance) 376 return true; 377 cur_delta = (int)curframe_instance->depth - (int)q->curframe; 378 rel = frameno + cur_delta; 379 if (rel <= curframe_instance->depth) 380 alive = is_live_before(curframe_instance, q->insn_idx, rel, half_spi); 381 382 if (alive) 383 return true; 384 385 for (i = frameno; i < q->curframe; i++) { 386 instance = q->instances[i]; 387 if (!instance) 388 return true; 389 /* Map actual frameno to frame index within this instance */ 390 delta = (int)instance->depth - (int)i; 391 rel = frameno + delta; 392 if (rel > instance->depth) 393 return true; 394 395 /* Get callsite from verifier state, not from instance callchain */ 396 callsite = q->callsites[i]; 397 398 alive = bpf_calls_callback(env, callsite) 399 ? is_live_before(instance, callsite, rel, half_spi) 400 : is_live_before(instance, callsite + 1, rel, half_spi); 401 if (alive) 402 return true; 403 } 404 405 return false; 406 } 407 408 static char *fmt_subprog(struct bpf_verifier_env *env, int subprog) 409 { 410 const char *name = env->subprog_info[subprog].name; 411 412 snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf), 413 "subprog#%d%s%s", subprog, name ? " " : "", name ? name : ""); 414 return env->tmp_str_buf; 415 } 416 417 static char *fmt_instance(struct bpf_verifier_env *env, struct func_instance *instance) 418 { 419 snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf), 420 "(d%d,cs%d)", instance->depth, instance->callsite); 421 return env->tmp_str_buf; 422 } 423 424 static int spi_off(int spi) 425 { 426 return -(spi + 1) * BPF_REG_SIZE; 427 } 428 429 /* 430 * When both halves of an 8-byte SPI are set, print as "-8","-16",... 431 * When only one half is set, print as "-4h","-8h",... 432 * Runs of 3+ consecutive fully-set SPIs are collapsed: "fp0-8..-24" 433 */ 434 static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first, spis_t spis) 435 { 436 int buf_sz = sizeof(env->tmp_str_buf); 437 char *buf = env->tmp_str_buf; 438 int spi, n, run_start; 439 440 buf[0] = '\0'; 441 442 for (spi = 0; spi < STACK_SLOTS / 2 && buf_sz > 0; spi++) { 443 bool lo = spis_test_bit(spis, spi * 2); 444 bool hi = spis_test_bit(spis, spi * 2 + 1); 445 const char *space = first ? "" : " "; 446 447 if (!lo && !hi) 448 continue; 449 450 if (!lo || !hi) { 451 /* half-spi */ 452 n = scnprintf(buf, buf_sz, "%sfp%d%d%s", 453 space, frame, spi_off(spi) + (lo ? STACK_SLOT_SZ : 0), "h"); 454 } else if (spi + 2 < STACK_SLOTS / 2 && 455 spis_test_bit(spis, spi * 2 + 2) && 456 spis_test_bit(spis, spi * 2 + 3) && 457 spis_test_bit(spis, spi * 2 + 4) && 458 spis_test_bit(spis, spi * 2 + 5)) { 459 /* 3+ consecutive full spis */ 460 run_start = spi; 461 while (spi + 1 < STACK_SLOTS / 2 && 462 spis_test_bit(spis, (spi + 1) * 2) && 463 spis_test_bit(spis, (spi + 1) * 2 + 1)) 464 spi++; 465 n = scnprintf(buf, buf_sz, "%sfp%d%d..%d", 466 space, frame, spi_off(run_start), spi_off(spi)); 467 } else { 468 /* just a full spi */ 469 n = scnprintf(buf, buf_sz, "%sfp%d%d", space, frame, spi_off(spi)); 470 } 471 first = false; 472 buf += n; 473 buf_sz -= n; 474 } 475 return env->tmp_str_buf; 476 } 477 478 static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance) 479 { 480 int start = env->subprog_info[instance->subprog].start; 481 struct bpf_insn *insns = env->prog->insnsi; 482 struct per_frame_masks *masks; 483 int len = instance->insn_cnt; 484 int insn_idx, frame, i; 485 bool has_use, has_def; 486 u64 pos, insn_pos; 487 488 if (!(env->log.level & BPF_LOG_LEVEL2)) 489 return; 490 491 verbose(env, "stack use/def %s ", fmt_subprog(env, instance->subprog)); 492 verbose(env, "%s:\n", fmt_instance(env, instance)); 493 for (i = 0; i < len; i++) { 494 insn_idx = start + i; 495 has_use = false; 496 has_def = false; 497 pos = env->log.end_pos; 498 verbose(env, "%3d: ", insn_idx); 499 bpf_verbose_insn(env, &insns[insn_idx]); 500 bpf_vlog_reset(&env->log, env->log.end_pos - 1); /* remove \n */ 501 insn_pos = env->log.end_pos; 502 verbose(env, "%*c;", bpf_vlog_alignment(insn_pos - pos), ' '); 503 pos = env->log.end_pos; 504 verbose(env, " use: "); 505 for (frame = instance->depth; frame >= 0; --frame) { 506 masks = get_frame_masks(instance, frame, insn_idx); 507 if (!masks || spis_is_zero(masks->may_read)) 508 continue; 509 verbose(env, "%s", fmt_spis_mask(env, frame, !has_use, masks->may_read)); 510 has_use = true; 511 } 512 if (!has_use) 513 bpf_vlog_reset(&env->log, pos); 514 pos = env->log.end_pos; 515 verbose(env, " def: "); 516 for (frame = instance->depth; frame >= 0; --frame) { 517 masks = get_frame_masks(instance, frame, insn_idx); 518 if (!masks || spis_is_zero(masks->must_write)) 519 continue; 520 verbose(env, "%s", fmt_spis_mask(env, frame, !has_def, masks->must_write)); 521 has_def = true; 522 } 523 if (!has_def) 524 bpf_vlog_reset(&env->log, has_use ? pos : insn_pos); 525 verbose(env, "\n"); 526 if (bpf_is_ldimm64(&insns[insn_idx])) 527 i++; 528 } 529 } 530 531 static int cmp_instances(const void *pa, const void *pb) 532 { 533 struct func_instance *a = *(struct func_instance **)pa; 534 struct func_instance *b = *(struct func_instance **)pb; 535 int dcallsite = (int)a->callsite - b->callsite; 536 int ddepth = (int)a->depth - b->depth; 537 538 if (dcallsite) 539 return dcallsite; 540 if (ddepth) 541 return ddepth; 542 return 0; 543 } 544 545 /* print use/def slots for all instances ordered by callsite first, then by depth */ 546 static int print_instances(struct bpf_verifier_env *env) 547 { 548 struct func_instance *instance, **sorted_instances; 549 struct bpf_liveness *liveness = env->liveness; 550 int i, bkt, cnt; 551 552 cnt = 0; 553 hash_for_each(liveness->func_instances, bkt, instance, hl_node) 554 cnt++; 555 sorted_instances = kvmalloc_objs(*sorted_instances, cnt, GFP_KERNEL_ACCOUNT); 556 if (!sorted_instances) 557 return -ENOMEM; 558 cnt = 0; 559 hash_for_each(liveness->func_instances, bkt, instance, hl_node) 560 sorted_instances[cnt++] = instance; 561 sort(sorted_instances, cnt, sizeof(*sorted_instances), cmp_instances, NULL); 562 for (i = 0; i < cnt; i++) 563 print_instance(env, sorted_instances[i]); 564 kvfree(sorted_instances); 565 return 0; 566 } 567 568 /* 569 * Per-register tracking state for compute_subprog_args(). 570 * Tracks which frame's FP a value is derived from 571 * and the byte offset from that frame's FP. 572 * 573 * The .frame field forms a lattice with three levels of precision: 574 * 575 * precise {frame=N, off=V} -- known absolute frame index and byte offset 576 * | 577 * offset-imprecise {frame=N, off=OFF_IMPRECISE} 578 * | -- known frame identity, unknown offset 579 * fully-imprecise {frame=ARG_IMPRECISE, mask=bitmask} 580 * -- unknown frame identity; .mask is a 581 * bitmask of which frame indices might be 582 * involved 583 * 584 * At CFG merge points, arg_track_join() moves down the lattice: 585 * - same frame + same offset -> precise 586 * - same frame + different offset -> offset-imprecise 587 * - different frames -> fully-imprecise (bitmask OR) 588 * 589 * At memory access sites (LDX/STX/ST), offset-imprecise marks only 590 * the known frame's access mask as SPIS_ALL, while fully-imprecise 591 * iterates bits in the bitmask and routes each frame to its target. 592 */ 593 #define MAX_ARG_OFFSETS 4 594 595 struct arg_track { 596 union { 597 s16 off[MAX_ARG_OFFSETS]; /* byte offsets; off_cnt says how many */ 598 u16 mask; /* arg bitmask when arg == ARG_IMPRECISE */ 599 }; 600 s8 frame; /* absolute frame index, or enum arg_track_state */ 601 s8 off_cnt; /* 0 = offset-imprecise, 1-4 = # of precise offsets */ 602 }; 603 604 enum arg_track_state { 605 ARG_NONE = -1, /* not derived from any argument */ 606 ARG_UNVISITED = -2, /* not yet reached by dataflow */ 607 ARG_IMPRECISE = -3, /* lost identity; .mask is arg bitmask */ 608 }; 609 610 #define OFF_IMPRECISE S16_MIN /* arg identity known but offset unknown */ 611 612 /* Track callee stack slots fp-8 through fp-512 (64 slots of 8 bytes each) */ 613 #define MAX_ARG_SPILL_SLOTS 64 614 615 static bool arg_is_visited(const struct arg_track *at) 616 { 617 return at->frame != ARG_UNVISITED; 618 } 619 620 static bool arg_is_fp(const struct arg_track *at) 621 { 622 return at->frame >= 0 || at->frame == ARG_IMPRECISE; 623 } 624 625 /* 626 * Clear all tracked callee stack slots overlapping the byte range 627 * [off, off+sz-1] where off is a negative FP-relative offset. 628 */ 629 static void clear_overlapping_stack_slots(struct arg_track *at_stack, s16 off, u32 sz) 630 { 631 struct arg_track none = { .frame = ARG_NONE }; 632 633 if (off == OFF_IMPRECISE) { 634 for (int i = 0; i < MAX_ARG_SPILL_SLOTS; i++) 635 at_stack[i] = none; 636 return; 637 } 638 for (int i = 0; i < MAX_ARG_SPILL_SLOTS; i++) { 639 int slot_start = -((i + 1) * 8); 640 int slot_end = slot_start + 8; 641 642 if (slot_start < off + (int)sz && slot_end > off) 643 at_stack[i] = none; 644 } 645 } 646 647 static void verbose_arg_track(struct bpf_verifier_env *env, struct arg_track *at) 648 { 649 int i; 650 651 switch (at->frame) { 652 case ARG_NONE: verbose(env, "_"); break; 653 case ARG_UNVISITED: verbose(env, "?"); break; 654 case ARG_IMPRECISE: verbose(env, "IMP%x", at->mask); break; 655 default: 656 /* frame >= 0: absolute frame index */ 657 if (at->off_cnt == 0) { 658 verbose(env, "fp%d ?", at->frame); 659 } else { 660 for (i = 0; i < at->off_cnt; i++) { 661 if (i) 662 verbose(env, "|"); 663 verbose(env, "fp%d%+d", at->frame, at->off[i]); 664 } 665 } 666 break; 667 } 668 } 669 670 static bool arg_track_eq(const struct arg_track *a, const struct arg_track *b) 671 { 672 int i; 673 674 if (a->frame != b->frame) 675 return false; 676 if (a->frame == ARG_IMPRECISE) 677 return a->mask == b->mask; 678 if (a->frame < 0) 679 return true; 680 if (a->off_cnt != b->off_cnt) 681 return false; 682 for (i = 0; i < a->off_cnt; i++) 683 if (a->off[i] != b->off[i]) 684 return false; 685 return true; 686 } 687 688 static struct arg_track arg_single(s8 arg, s16 off) 689 { 690 struct arg_track at = {}; 691 692 at.frame = arg; 693 at.off[0] = off; 694 at.off_cnt = 1; 695 return at; 696 } 697 698 /* 699 * Merge two sorted offset arrays, deduplicate. 700 * Returns off_cnt=0 if the result exceeds MAX_ARG_OFFSETS. 701 * Both args must have the same frame and off_cnt > 0. 702 */ 703 static struct arg_track arg_merge_offsets(struct arg_track a, struct arg_track b) 704 { 705 struct arg_track result = { .frame = a.frame }; 706 struct arg_track imp = { .frame = a.frame }; 707 int i = 0, j = 0, k = 0; 708 709 while (i < a.off_cnt && j < b.off_cnt) { 710 s16 v; 711 712 if (a.off[i] <= b.off[j]) { 713 v = a.off[i++]; 714 if (v == b.off[j]) 715 j++; 716 } else { 717 v = b.off[j++]; 718 } 719 if (k > 0 && result.off[k - 1] == v) 720 continue; 721 if (k >= MAX_ARG_OFFSETS) 722 return imp; 723 result.off[k++] = v; 724 } 725 while (i < a.off_cnt) { 726 if (k >= MAX_ARG_OFFSETS) 727 return imp; 728 result.off[k++] = a.off[i++]; 729 } 730 while (j < b.off_cnt) { 731 if (k >= MAX_ARG_OFFSETS) 732 return imp; 733 result.off[k++] = b.off[j++]; 734 } 735 result.off_cnt = k; 736 return result; 737 } 738 739 /* 740 * Merge two arg_tracks into ARG_IMPRECISE, collecting the frame 741 * bits from both operands. Precise frame indices (frame >= 0) 742 * contribute a single bit; existing ARG_IMPRECISE values 743 * contribute their full bitmask. 744 */ 745 static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_track b) 746 { 747 u32 m = 0; 748 749 if (a.frame >= 0) 750 m |= BIT(a.frame); 751 else if (a.frame == ARG_IMPRECISE) 752 m |= a.mask; 753 754 if (b.frame >= 0) 755 m |= BIT(b.frame); 756 else if (b.frame == ARG_IMPRECISE) 757 m |= b.mask; 758 759 return (struct arg_track){ .mask = m, .frame = ARG_IMPRECISE }; 760 } 761 762 /* Join two arg_track values at merge points */ 763 static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b) 764 { 765 if (!arg_is_visited(&b)) 766 return a; 767 if (!arg_is_visited(&a)) 768 return b; 769 if (a.frame == b.frame && a.frame >= 0) { 770 /* Both offset-imprecise: stay imprecise */ 771 if (a.off_cnt == 0 || b.off_cnt == 0) 772 return (struct arg_track){ .frame = a.frame }; 773 /* Merge offset sets; falls back to off_cnt=0 if >4 */ 774 return arg_merge_offsets(a, b); 775 } 776 777 /* 778 * args are different, but one of them is known 779 * arg + none -> arg 780 * none + arg -> arg 781 * 782 * none + none -> none 783 */ 784 if (a.frame == ARG_NONE && b.frame == ARG_NONE) 785 return a; 786 if (a.frame >= 0 && b.frame == ARG_NONE) { 787 /* 788 * When joining single fp-N add fake fp+0 to 789 * keep stack_use and prevent stack_def 790 */ 791 if (a.off_cnt == 1) 792 return arg_merge_offsets(a, arg_single(a.frame, 0)); 793 return a; 794 } 795 if (b.frame >= 0 && a.frame == ARG_NONE) { 796 if (b.off_cnt == 1) 797 return arg_merge_offsets(b, arg_single(b.frame, 0)); 798 return b; 799 } 800 801 return arg_join_imprecise(a, b); 802 } 803 804 static bool arg_track_join(struct bpf_verifier_env *env, int idx, int target, int r, 805 struct arg_track *in, struct arg_track out) 806 { 807 struct arg_track old = *in; 808 struct arg_track new_val = __arg_track_join(old, out); 809 810 if (arg_track_eq(&new_val, &old)) 811 return false; 812 813 *in = new_val; 814 if (!(env->log.level & BPF_LOG_LEVEL2) || !arg_is_visited(&old)) 815 return true; 816 817 verbose(env, "arg JOIN insn %d -> %d ", idx, target); 818 if (r >= 0) 819 verbose(env, "r%d: ", r); 820 else 821 verbose(env, "fp%+d: ", r * 8); 822 verbose_arg_track(env, &old); 823 verbose(env, " + "); 824 verbose_arg_track(env, &out); 825 verbose(env, " => "); 826 verbose_arg_track(env, &new_val); 827 verbose(env, "\n"); 828 return true; 829 } 830 831 /* 832 * Compute the result when an ALU op destroys offset precision. 833 * If a single arg is identifiable, preserve it with OFF_IMPRECISE. 834 * If two different args are involved or one is already ARG_IMPRECISE, 835 * the result is fully ARG_IMPRECISE. 836 */ 837 static void arg_track_alu64(struct arg_track *dst, const struct arg_track *src) 838 { 839 WARN_ON_ONCE(!arg_is_visited(dst)); 840 WARN_ON_ONCE(!arg_is_visited(src)); 841 842 if (dst->frame >= 0 && (src->frame == ARG_NONE || src->frame == dst->frame)) { 843 /* 844 * rX += rY where rY is not arg derived 845 * rX += rX 846 */ 847 dst->off_cnt = 0; 848 return; 849 } 850 if (src->frame >= 0 && dst->frame == ARG_NONE) { 851 /* 852 * rX += rY where rX is not arg derived 853 * rY identity leaks into rX 854 */ 855 dst->off_cnt = 0; 856 dst->frame = src->frame; 857 return; 858 } 859 860 if (dst->frame == ARG_NONE && src->frame == ARG_NONE) 861 return; 862 863 *dst = arg_join_imprecise(*dst, *src); 864 } 865 866 static s16 arg_add(s16 off, s64 delta) 867 { 868 s64 res; 869 870 if (off == OFF_IMPRECISE) 871 return OFF_IMPRECISE; 872 res = (s64)off + delta; 873 if (res < S16_MIN + 1 || res > S16_MAX) 874 return OFF_IMPRECISE; 875 return res; 876 } 877 878 static void arg_padd(struct arg_track *at, s64 delta) 879 { 880 int i; 881 882 if (at->off_cnt == 0) 883 return; 884 for (i = 0; i < at->off_cnt; i++) { 885 s16 new_off = arg_add(at->off[i], delta); 886 887 if (new_off == OFF_IMPRECISE) { 888 at->off_cnt = 0; 889 return; 890 } 891 at->off[i] = new_off; 892 } 893 } 894 895 /* 896 * Convert a byte offset from FP to a callee stack slot index. 897 * Returns -1 if out of range or not 8-byte aligned. 898 * Slot 0 = fp-8, slot 1 = fp-16, ..., slot 7 = fp-64, .... 899 */ 900 static int fp_off_to_slot(s16 off) 901 { 902 if (off == OFF_IMPRECISE) 903 return -1; 904 if (off >= 0 || off < -(int)(MAX_ARG_SPILL_SLOTS * 8)) 905 return -1; 906 if (off % 8) 907 return -1; 908 return (-off) / 8 - 1; 909 } 910 911 static struct arg_track fill_from_stack(struct bpf_insn *insn, 912 struct arg_track *at_out, int reg, 913 struct arg_track *at_stack_out, 914 int depth) 915 { 916 struct arg_track imp = { 917 .mask = (1u << (depth + 1)) - 1, 918 .frame = ARG_IMPRECISE 919 }; 920 struct arg_track result = { .frame = ARG_NONE }; 921 int cnt, i; 922 923 if (reg == BPF_REG_FP) { 924 int slot = fp_off_to_slot(insn->off); 925 926 return slot >= 0 ? at_stack_out[slot] : imp; 927 } 928 cnt = at_out[reg].off_cnt; 929 if (cnt == 0) 930 return imp; 931 932 for (i = 0; i < cnt; i++) { 933 s16 fp_off = arg_add(at_out[reg].off[i], insn->off); 934 int slot = fp_off_to_slot(fp_off); 935 936 if (slot < 0) 937 return imp; 938 result = __arg_track_join(result, at_stack_out[slot]); 939 } 940 return result; 941 } 942 943 /* 944 * Spill @val to all possible stack slots indicated by the FP offsets in @reg. 945 * For an 8-byte store, single candidate slot gets @val. multi-slots are joined. 946 * sub-8-byte store joins with ARG_NONE. 947 * When exact offset is unknown conservatively add reg values to all slots in at_stack_out. 948 */ 949 static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, 950 int reg, struct arg_track *at_stack_out, 951 struct arg_track *val, u32 sz) 952 { 953 struct arg_track none = { .frame = ARG_NONE }; 954 struct arg_track new_val = sz == 8 ? *val : none; 955 int cnt, i; 956 957 if (reg == BPF_REG_FP) { 958 int slot = fp_off_to_slot(insn->off); 959 960 if (slot >= 0) 961 at_stack_out[slot] = new_val; 962 return; 963 } 964 cnt = at_out[reg].off_cnt; 965 if (cnt == 0) { 966 for (int slot = 0; slot < MAX_ARG_SPILL_SLOTS; slot++) 967 at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val); 968 return; 969 } 970 for (i = 0; i < cnt; i++) { 971 s16 fp_off = arg_add(at_out[reg].off[i], insn->off); 972 int slot = fp_off_to_slot(fp_off); 973 974 if (slot < 0) 975 continue; 976 if (cnt == 1) 977 at_stack_out[slot] = new_val; 978 else 979 at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val); 980 } 981 } 982 983 /* 984 * Clear stack slots overlapping all possible FP offsets in @reg. 985 */ 986 static void clear_stack_for_all_offs(struct bpf_insn *insn, 987 struct arg_track *at_out, int reg, 988 struct arg_track *at_stack_out, u32 sz) 989 { 990 int cnt, i; 991 992 if (reg == BPF_REG_FP) { 993 clear_overlapping_stack_slots(at_stack_out, insn->off, sz); 994 return; 995 } 996 cnt = at_out[reg].off_cnt; 997 if (cnt == 0) { 998 clear_overlapping_stack_slots(at_stack_out, OFF_IMPRECISE, sz); 999 return; 1000 } 1001 for (i = 0; i < cnt; i++) { 1002 s16 fp_off = arg_add(at_out[reg].off[i], insn->off); 1003 1004 clear_overlapping_stack_slots(at_stack_out, fp_off, sz); 1005 } 1006 } 1007 1008 static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, int idx, 1009 struct arg_track *at_in, struct arg_track *at_stack_in, 1010 struct arg_track *at_out, struct arg_track *at_stack_out) 1011 { 1012 bool printed = false; 1013 int i; 1014 1015 if (!(env->log.level & BPF_LOG_LEVEL2)) 1016 return; 1017 for (i = 0; i < MAX_BPF_REG; i++) { 1018 if (arg_track_eq(&at_out[i], &at_in[i])) 1019 continue; 1020 if (!printed) { 1021 verbose(env, "%3d: ", idx); 1022 bpf_verbose_insn(env, insn); 1023 bpf_vlog_reset(&env->log, env->log.end_pos - 1); 1024 printed = true; 1025 } 1026 verbose(env, "\tr%d: ", i); verbose_arg_track(env, &at_in[i]); 1027 verbose(env, " -> "); verbose_arg_track(env, &at_out[i]); 1028 } 1029 for (i = 0; i < MAX_ARG_SPILL_SLOTS; i++) { 1030 if (arg_track_eq(&at_stack_out[i], &at_stack_in[i])) 1031 continue; 1032 if (!printed) { 1033 verbose(env, "%3d: ", idx); 1034 bpf_verbose_insn(env, insn); 1035 bpf_vlog_reset(&env->log, env->log.end_pos - 1); 1036 printed = true; 1037 } 1038 verbose(env, "\tfp%+d: ", -(i + 1) * 8); verbose_arg_track(env, &at_stack_in[i]); 1039 verbose(env, " -> "); verbose_arg_track(env, &at_stack_out[i]); 1040 } 1041 if (printed) 1042 verbose(env, "\n"); 1043 } 1044 1045 /* 1046 * Pure dataflow transfer function for arg_track state. 1047 * Updates at_out[] based on how the instruction modifies registers. 1048 * Tracks spill/fill, but not other memory accesses. 1049 */ 1050 static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, 1051 int insn_idx, 1052 struct arg_track *at_out, struct arg_track *at_stack_out, 1053 struct func_instance *instance, 1054 u32 *callsites) 1055 { 1056 int depth = instance->depth; 1057 u8 class = BPF_CLASS(insn->code); 1058 u8 code = BPF_OP(insn->code); 1059 struct arg_track *dst = &at_out[insn->dst_reg]; 1060 struct arg_track *src = &at_out[insn->src_reg]; 1061 struct arg_track none = { .frame = ARG_NONE }; 1062 int r; 1063 1064 if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_K) { 1065 if (code == BPF_MOV) { 1066 *dst = none; 1067 } else if (dst->frame >= 0) { 1068 if (code == BPF_ADD) 1069 arg_padd(dst, insn->imm); 1070 else if (code == BPF_SUB) 1071 arg_padd(dst, -(s64)insn->imm); 1072 else 1073 /* Any other 64-bit alu on the pointer makes it imprecise */ 1074 dst->off_cnt = 0; 1075 } /* else if dst->frame is imprecise it stays so */ 1076 } else if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_X) { 1077 if (code == BPF_MOV) { 1078 if (insn->off == 0) { 1079 *dst = *src; 1080 } else { 1081 /* addr_space_cast destroys a pointer */ 1082 *dst = none; 1083 } 1084 } else { 1085 arg_track_alu64(dst, src); 1086 } 1087 } else if (class == BPF_ALU) { 1088 /* 1089 * 32-bit alu destroys the pointer. 1090 * If src was a pointer it cannot leak into dst 1091 */ 1092 *dst = none; 1093 } else if (class == BPF_JMP && code == BPF_CALL) { 1094 /* 1095 * at_stack_out[slot] is not cleared by the helper and subprog calls. 1096 * The fill_from_stack() may return the stale spill — which is an FP-derived arg_track 1097 * (the value that was originally spilled there). The loaded register then carries 1098 * a phantom FP-derived identity that doesn't correspond to what's actually in the slot. 1099 * This phantom FP pointer propagates forward, and wherever it's subsequently used 1100 * (as a helper argument, another store, etc.), it sets stack liveness bits. 1101 * Those bits correspond to stack accesses that don't actually happen. 1102 * So the effect is over-reporting stack liveness — marking slots as live that aren't 1103 * actually accessed. The verifier preserves more state than necessary across calls, 1104 * which is conservative. 1105 * 1106 * helpers can scratch stack slots, but they won't make a valid pointer out of it. 1107 * subprogs are allowed to write into parent slots, but they cannot write 1108 * _any_ FP-derived pointer into it (either their own or parent's FP). 1109 */ 1110 for (r = BPF_REG_0; r <= BPF_REG_5; r++) 1111 at_out[r] = none; 1112 } else if (class == BPF_LDX) { 1113 u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1114 bool src_is_local_fp = insn->src_reg == BPF_REG_FP || src->frame == depth || 1115 (src->frame == ARG_IMPRECISE && (src->mask & BIT(depth))); 1116 1117 /* 1118 * Reload from callee stack: if src is current-frame FP-derived 1119 * and the load is an 8-byte BPF_MEM, try to restore the spill 1120 * identity. For imprecise sources fill_from_stack() returns 1121 * ARG_IMPRECISE (off_cnt == 0). 1122 */ 1123 if (src_is_local_fp && BPF_MODE(insn->code) == BPF_MEM && sz == 8) { 1124 *dst = fill_from_stack(insn, at_out, insn->src_reg, at_stack_out, depth); 1125 } else if (src->frame >= 0 && src->frame < depth && 1126 BPF_MODE(insn->code) == BPF_MEM && sz == 8) { 1127 struct arg_track *parent_stack = 1128 env->callsite_at_stack[callsites[src->frame]]; 1129 1130 *dst = fill_from_stack(insn, at_out, insn->src_reg, 1131 parent_stack, src->frame); 1132 } else if (src->frame == ARG_IMPRECISE && 1133 !(src->mask & BIT(depth)) && src->mask && 1134 BPF_MODE(insn->code) == BPF_MEM && sz == 8) { 1135 /* 1136 * Imprecise src with only parent-frame bits: 1137 * conservative fallback. 1138 */ 1139 *dst = *src; 1140 } else { 1141 *dst = none; 1142 } 1143 } else if (class == BPF_LD && BPF_MODE(insn->code) == BPF_IMM) { 1144 *dst = none; 1145 } else if (class == BPF_STX) { 1146 u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1147 bool dst_is_local_fp; 1148 1149 /* Track spills to current-frame FP-derived callee stack */ 1150 dst_is_local_fp = insn->dst_reg == BPF_REG_FP || dst->frame == depth; 1151 if (dst_is_local_fp && BPF_MODE(insn->code) == BPF_MEM) 1152 spill_to_stack(insn, at_out, insn->dst_reg, 1153 at_stack_out, src, sz); 1154 1155 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 1156 if (dst_is_local_fp && insn->imm != BPF_LOAD_ACQ) 1157 clear_stack_for_all_offs(insn, at_out, insn->dst_reg, 1158 at_stack_out, sz); 1159 1160 if (insn->imm == BPF_CMPXCHG) 1161 at_out[BPF_REG_0] = none; 1162 else if (insn->imm == BPF_LOAD_ACQ) 1163 *dst = none; 1164 else if (insn->imm & BPF_FETCH) 1165 *src = none; 1166 } 1167 } else if (class == BPF_ST && BPF_MODE(insn->code) == BPF_MEM) { 1168 u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1169 bool dst_is_local_fp = insn->dst_reg == BPF_REG_FP || dst->frame == depth; 1170 1171 /* BPF_ST to FP-derived dst: clear overlapping stack slots */ 1172 if (dst_is_local_fp) 1173 clear_stack_for_all_offs(insn, at_out, insn->dst_reg, 1174 at_stack_out, sz); 1175 } 1176 } 1177 1178 /* 1179 * Record access_bytes from helper/kfunc or load/store insn. 1180 * access_bytes > 0: stack read 1181 * access_bytes < 0: stack write 1182 * access_bytes == S64_MIN: unknown — conservative, mark [0..slot] as read 1183 * access_bytes == 0: no access 1184 * 1185 */ 1186 static int record_stack_access_off(struct func_instance *instance, s64 fp_off, 1187 s64 access_bytes, u32 frame, u32 insn_idx) 1188 { 1189 s32 slot_hi, slot_lo; 1190 spis_t mask; 1191 1192 if (fp_off >= 0) 1193 /* 1194 * out of bounds stack access doesn't contribute 1195 * into actual stack liveness. It will be rejected 1196 * by the main verifier pass later. 1197 */ 1198 return 0; 1199 if (access_bytes == S64_MIN) { 1200 /* helper/kfunc read unknown amount of bytes from fp_off until fp+0 */ 1201 slot_hi = (-fp_off - 1) / STACK_SLOT_SZ; 1202 mask = SPIS_ZERO; 1203 spis_or_range(&mask, 0, slot_hi); 1204 return mark_stack_read(instance, frame, insn_idx, mask); 1205 } 1206 if (access_bytes > 0) { 1207 /* Mark any touched slot as use */ 1208 slot_hi = (-fp_off - 1) / STACK_SLOT_SZ; 1209 slot_lo = max_t(s32, (-fp_off - access_bytes) / STACK_SLOT_SZ, 0); 1210 mask = SPIS_ZERO; 1211 spis_or_range(&mask, slot_lo, slot_hi); 1212 return mark_stack_read(instance, frame, insn_idx, mask); 1213 } else if (access_bytes < 0) { 1214 /* Mark only fully covered slots as def */ 1215 access_bytes = -access_bytes; 1216 slot_hi = (-fp_off) / STACK_SLOT_SZ - 1; 1217 slot_lo = max_t(s32, (-fp_off - access_bytes + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0); 1218 if (slot_lo <= slot_hi) { 1219 mask = SPIS_ZERO; 1220 spis_or_range(&mask, slot_lo, slot_hi); 1221 return mark_stack_write(instance, frame, insn_idx, mask); 1222 } 1223 } 1224 return 0; 1225 } 1226 1227 /* 1228 * 'arg' is FP-derived argument to helper/kfunc or load/store that 1229 * reads (positive) or writes (negative) 'access_bytes' into 'use' or 'def'. 1230 */ 1231 static int record_stack_access(struct func_instance *instance, 1232 const struct arg_track *arg, 1233 s64 access_bytes, u32 frame, u32 insn_idx) 1234 { 1235 int i, err; 1236 1237 if (access_bytes == 0) 1238 return 0; 1239 if (arg->off_cnt == 0) { 1240 if (access_bytes > 0 || access_bytes == S64_MIN) 1241 return mark_stack_read(instance, frame, insn_idx, SPIS_ALL); 1242 return 0; 1243 } 1244 if (access_bytes != S64_MIN && access_bytes < 0 && arg->off_cnt != 1) 1245 /* multi-offset write cannot set stack_def */ 1246 return 0; 1247 1248 for (i = 0; i < arg->off_cnt; i++) { 1249 err = record_stack_access_off(instance, arg->off[i], access_bytes, frame, insn_idx); 1250 if (err) 1251 return err; 1252 } 1253 return 0; 1254 } 1255 1256 /* 1257 * When a pointer is ARG_IMPRECISE, conservatively mark every frame in 1258 * the bitmask as fully used. 1259 */ 1260 static int record_imprecise(struct func_instance *instance, u32 mask, u32 insn_idx) 1261 { 1262 int depth = instance->depth; 1263 int f, err; 1264 1265 for (f = 0; mask; f++, mask >>= 1) { 1266 if (!(mask & 1)) 1267 continue; 1268 if (f <= depth) { 1269 err = mark_stack_read(instance, f, insn_idx, SPIS_ALL); 1270 if (err) 1271 return err; 1272 } 1273 } 1274 return 0; 1275 } 1276 1277 /* Record load/store access for a given 'at' state of 'insn'. */ 1278 static int record_load_store_access(struct bpf_verifier_env *env, 1279 struct func_instance *instance, 1280 struct arg_track *at, int insn_idx) 1281 { 1282 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 1283 int depth = instance->depth; 1284 s32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); 1285 u8 class = BPF_CLASS(insn->code); 1286 struct arg_track resolved, *ptr; 1287 int oi; 1288 1289 switch (class) { 1290 case BPF_LDX: 1291 ptr = &at[insn->src_reg]; 1292 break; 1293 case BPF_STX: 1294 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 1295 if (insn->imm == BPF_STORE_REL) 1296 sz = -sz; 1297 if (insn->imm == BPF_LOAD_ACQ) 1298 ptr = &at[insn->src_reg]; 1299 else 1300 ptr = &at[insn->dst_reg]; 1301 } else { 1302 ptr = &at[insn->dst_reg]; 1303 sz = -sz; 1304 } 1305 break; 1306 case BPF_ST: 1307 ptr = &at[insn->dst_reg]; 1308 sz = -sz; 1309 break; 1310 default: 1311 return 0; 1312 } 1313 1314 /* Resolve offsets: fold insn->off into arg_track */ 1315 if (ptr->off_cnt > 0) { 1316 resolved.off_cnt = ptr->off_cnt; 1317 resolved.frame = ptr->frame; 1318 for (oi = 0; oi < ptr->off_cnt; oi++) { 1319 resolved.off[oi] = arg_add(ptr->off[oi], insn->off); 1320 if (resolved.off[oi] == OFF_IMPRECISE) { 1321 resolved.off_cnt = 0; 1322 break; 1323 } 1324 } 1325 ptr = &resolved; 1326 } 1327 1328 if (ptr->frame >= 0 && ptr->frame <= depth) 1329 return record_stack_access(instance, ptr, sz, ptr->frame, insn_idx); 1330 if (ptr->frame == ARG_IMPRECISE) 1331 return record_imprecise(instance, ptr->mask, insn_idx); 1332 /* ARG_NONE: not derived from any frame pointer, skip */ 1333 return 0; 1334 } 1335 1336 /* Record stack access for a given 'at' state of helper/kfunc 'insn' */ 1337 static int record_call_access(struct bpf_verifier_env *env, 1338 struct func_instance *instance, 1339 struct arg_track *at, 1340 int insn_idx) 1341 { 1342 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 1343 int depth = instance->depth; 1344 struct bpf_call_summary cs; 1345 int r, err = 0, num_params = 5; 1346 1347 if (bpf_pseudo_call(insn)) 1348 return 0; 1349 1350 if (bpf_get_call_summary(env, insn, &cs)) 1351 num_params = cs.num_params; 1352 1353 for (r = BPF_REG_1; r < BPF_REG_1 + num_params; r++) { 1354 int frame = at[r].frame; 1355 s64 bytes; 1356 1357 if (!arg_is_fp(&at[r])) 1358 continue; 1359 1360 if (bpf_helper_call(insn)) { 1361 bytes = bpf_helper_stack_access_bytes(env, insn, r - 1, insn_idx); 1362 } else if (bpf_pseudo_kfunc_call(insn)) { 1363 bytes = bpf_kfunc_stack_access_bytes(env, insn, r - 1, insn_idx); 1364 } else { 1365 for (int f = 0; f <= depth; f++) { 1366 err = mark_stack_read(instance, f, insn_idx, SPIS_ALL); 1367 if (err) 1368 return err; 1369 } 1370 return 0; 1371 } 1372 if (bytes == 0) 1373 continue; 1374 1375 if (frame >= 0 && frame <= depth) 1376 err = record_stack_access(instance, &at[r], bytes, frame, insn_idx); 1377 else if (frame == ARG_IMPRECISE) 1378 err = record_imprecise(instance, at[r].mask, insn_idx); 1379 if (err) 1380 return err; 1381 } 1382 return 0; 1383 } 1384 1385 /* 1386 * For a calls_callback helper, find the callback subprog and determine 1387 * which caller register maps to which callback register for FP passthrough. 1388 */ 1389 static int find_callback_subprog(struct bpf_verifier_env *env, 1390 struct bpf_insn *insn, int insn_idx, 1391 int *caller_reg, int *callee_reg) 1392 { 1393 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 1394 int cb_reg = -1; 1395 1396 *caller_reg = -1; 1397 *callee_reg = -1; 1398 1399 if (!bpf_helper_call(insn)) 1400 return -1; 1401 switch (insn->imm) { 1402 case BPF_FUNC_loop: 1403 /* bpf_loop(nr, cb, ctx, flags): cb=R2, R3->cb R2 */ 1404 cb_reg = BPF_REG_2; 1405 *caller_reg = BPF_REG_3; 1406 *callee_reg = BPF_REG_2; 1407 break; 1408 case BPF_FUNC_for_each_map_elem: 1409 /* for_each_map_elem(map, cb, ctx, flags): cb=R2, R3->cb R4 */ 1410 cb_reg = BPF_REG_2; 1411 *caller_reg = BPF_REG_3; 1412 *callee_reg = BPF_REG_4; 1413 break; 1414 case BPF_FUNC_find_vma: 1415 /* find_vma(task, addr, cb, ctx, flags): cb=R3, R4->cb R3 */ 1416 cb_reg = BPF_REG_3; 1417 *caller_reg = BPF_REG_4; 1418 *callee_reg = BPF_REG_3; 1419 break; 1420 case BPF_FUNC_user_ringbuf_drain: 1421 /* user_ringbuf_drain(map, cb, ctx, flags): cb=R2, R3->cb R2 */ 1422 cb_reg = BPF_REG_2; 1423 *caller_reg = BPF_REG_3; 1424 *callee_reg = BPF_REG_2; 1425 break; 1426 default: 1427 return -1; 1428 } 1429 1430 if (!(aux->const_reg_subprog_mask & BIT(cb_reg))) 1431 return -2; 1432 1433 return aux->const_reg_vals[cb_reg]; 1434 } 1435 1436 /* Per-subprog intermediate state kept alive across analysis phases */ 1437 struct subprog_at_info { 1438 struct arg_track (*at_in)[MAX_BPF_REG]; 1439 int len; 1440 }; 1441 1442 static void print_subprog_arg_access(struct bpf_verifier_env *env, 1443 int subprog, 1444 struct subprog_at_info *info, 1445 struct arg_track (*at_stack_in)[MAX_ARG_SPILL_SLOTS]) 1446 { 1447 struct bpf_insn *insns = env->prog->insnsi; 1448 int start = env->subprog_info[subprog].start; 1449 int len = info->len; 1450 int i, r; 1451 1452 if (!(env->log.level & BPF_LOG_LEVEL2)) 1453 return; 1454 1455 verbose(env, "%s:\n", fmt_subprog(env, subprog)); 1456 for (i = 0; i < len; i++) { 1457 int idx = start + i; 1458 bool has_extra = false; 1459 u8 cls = BPF_CLASS(insns[idx].code); 1460 bool is_ldx_stx_call = cls == BPF_LDX || cls == BPF_STX || 1461 insns[idx].code == (BPF_JMP | BPF_CALL); 1462 1463 verbose(env, "%3d: ", idx); 1464 bpf_verbose_insn(env, &insns[idx]); 1465 1466 /* Collect what needs printing */ 1467 if (is_ldx_stx_call && 1468 arg_is_visited(&info->at_in[i][0])) { 1469 for (r = 0; r < MAX_BPF_REG - 1; r++) 1470 if (arg_is_fp(&info->at_in[i][r])) 1471 has_extra = true; 1472 } 1473 if (is_ldx_stx_call) { 1474 for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) 1475 if (arg_is_fp(&at_stack_in[i][r])) 1476 has_extra = true; 1477 } 1478 1479 if (!has_extra) { 1480 if (bpf_is_ldimm64(&insns[idx])) 1481 i++; 1482 continue; 1483 } 1484 1485 bpf_vlog_reset(&env->log, env->log.end_pos - 1); 1486 verbose(env, " //"); 1487 1488 if (is_ldx_stx_call && info->at_in && 1489 arg_is_visited(&info->at_in[i][0])) { 1490 for (r = 0; r < MAX_BPF_REG - 1; r++) { 1491 if (!arg_is_fp(&info->at_in[i][r])) 1492 continue; 1493 verbose(env, " r%d=", r); 1494 verbose_arg_track(env, &info->at_in[i][r]); 1495 } 1496 } 1497 1498 if (is_ldx_stx_call) { 1499 for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) { 1500 if (!arg_is_fp(&at_stack_in[i][r])) 1501 continue; 1502 verbose(env, " fp%+d=", -(r + 1) * 8); 1503 verbose_arg_track(env, &at_stack_in[i][r]); 1504 } 1505 } 1506 1507 verbose(env, "\n"); 1508 if (bpf_is_ldimm64(&insns[idx])) 1509 i++; 1510 } 1511 } 1512 1513 /* 1514 * Compute arg tracking dataflow for a single subprog. 1515 * Runs forward fixed-point with arg_track_xfer(), then records 1516 * memory accesses in a single linear pass over converged state. 1517 * 1518 * @callee_entry: pre-populated entry state for R1-R5 1519 * NULL for main (subprog 0). 1520 * @info: stores at_in, len for debug printing. 1521 */ 1522 static int compute_subprog_args(struct bpf_verifier_env *env, 1523 struct subprog_at_info *info, 1524 struct arg_track *callee_entry, 1525 struct func_instance *instance, 1526 u32 *callsites) 1527 { 1528 int subprog = instance->subprog; 1529 struct bpf_insn *insns = env->prog->insnsi; 1530 int depth = instance->depth; 1531 int start = env->subprog_info[subprog].start; 1532 int po_start = env->subprog_info[subprog].postorder_start; 1533 int end = env->subprog_info[subprog + 1].start; 1534 int po_end = env->subprog_info[subprog + 1].postorder_start; 1535 int len = end - start; 1536 struct arg_track (*at_in)[MAX_BPF_REG] = NULL; 1537 struct arg_track at_out[MAX_BPF_REG]; 1538 struct arg_track (*at_stack_in)[MAX_ARG_SPILL_SLOTS] = NULL; 1539 struct arg_track *at_stack_out = NULL; 1540 struct arg_track unvisited = { .frame = ARG_UNVISITED }; 1541 struct arg_track none = { .frame = ARG_NONE }; 1542 bool changed; 1543 int i, p, r, err = -ENOMEM; 1544 1545 at_in = kvmalloc_objs(*at_in, len, GFP_KERNEL_ACCOUNT); 1546 if (!at_in) 1547 goto err_free; 1548 1549 at_stack_in = kvmalloc_objs(*at_stack_in, len, GFP_KERNEL_ACCOUNT); 1550 if (!at_stack_in) 1551 goto err_free; 1552 1553 at_stack_out = kvmalloc_objs(*at_stack_out, MAX_ARG_SPILL_SLOTS, GFP_KERNEL_ACCOUNT); 1554 if (!at_stack_out) 1555 goto err_free; 1556 1557 for (i = 0; i < len; i++) { 1558 for (r = 0; r < MAX_BPF_REG; r++) 1559 at_in[i][r] = unvisited; 1560 for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) 1561 at_stack_in[i][r] = unvisited; 1562 } 1563 1564 for (r = 0; r < MAX_BPF_REG; r++) 1565 at_in[0][r] = none; 1566 1567 /* Entry: R10 is always precisely the current frame's FP */ 1568 at_in[0][BPF_REG_FP] = arg_single(depth, 0); 1569 1570 /* R1-R5: from caller or ARG_NONE for main */ 1571 if (callee_entry) { 1572 for (r = BPF_REG_1; r <= BPF_REG_5; r++) 1573 at_in[0][r] = callee_entry[r]; 1574 } 1575 1576 /* Entry: all stack slots are ARG_NONE */ 1577 for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) 1578 at_stack_in[0][r] = none; 1579 1580 if (env->log.level & BPF_LOG_LEVEL2) 1581 verbose(env, "subprog#%d: analyzing (depth %d)...\n", subprog, depth); 1582 1583 /* Forward fixed-point iteration in reverse post order */ 1584 redo: 1585 changed = false; 1586 for (p = po_end - 1; p >= po_start; p--) { 1587 int idx = env->cfg.insn_postorder[p]; 1588 int i = idx - start; 1589 struct bpf_insn *insn = &insns[idx]; 1590 struct bpf_iarray *succ; 1591 1592 if (!arg_is_visited(&at_in[i][0]) && !arg_is_visited(&at_in[i][1])) 1593 continue; 1594 1595 memcpy(at_out, at_in[i], sizeof(at_out)); 1596 memcpy(at_stack_out, at_stack_in[i], MAX_ARG_SPILL_SLOTS * sizeof(*at_stack_out)); 1597 1598 arg_track_xfer(env, insn, idx, at_out, at_stack_out, instance, callsites); 1599 arg_track_log(env, insn, idx, at_in[i], at_stack_in[i], at_out, at_stack_out); 1600 1601 /* Propagate to successors within this subprogram */ 1602 succ = bpf_insn_successors(env, idx); 1603 for (int s = 0; s < succ->cnt; s++) { 1604 int target = succ->items[s]; 1605 int ti; 1606 1607 /* Filter: stay within the subprogram's range */ 1608 if (target < start || target >= end) 1609 continue; 1610 ti = target - start; 1611 1612 for (r = 0; r < MAX_BPF_REG; r++) 1613 changed |= arg_track_join(env, idx, target, r, 1614 &at_in[ti][r], at_out[r]); 1615 1616 for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) 1617 changed |= arg_track_join(env, idx, target, -r - 1, 1618 &at_stack_in[ti][r], at_stack_out[r]); 1619 } 1620 } 1621 if (changed) 1622 goto redo; 1623 1624 /* Record memory accesses using converged at_in (RPO skips dead code) */ 1625 for (p = po_end - 1; p >= po_start; p--) { 1626 int idx = env->cfg.insn_postorder[p]; 1627 int i = idx - start; 1628 struct bpf_insn *insn = &insns[idx]; 1629 1630 err = record_load_store_access(env, instance, at_in[i], idx); 1631 if (err) 1632 goto err_free; 1633 1634 if (insn->code == (BPF_JMP | BPF_CALL)) { 1635 err = record_call_access(env, instance, at_in[i], idx); 1636 if (err) 1637 goto err_free; 1638 } 1639 1640 if (bpf_pseudo_call(insn) || bpf_calls_callback(env, idx)) { 1641 kvfree(env->callsite_at_stack[idx]); 1642 env->callsite_at_stack[idx] = 1643 kvmalloc_objs(*env->callsite_at_stack[idx], 1644 MAX_ARG_SPILL_SLOTS, GFP_KERNEL_ACCOUNT); 1645 if (!env->callsite_at_stack[idx]) { 1646 err = -ENOMEM; 1647 goto err_free; 1648 } 1649 memcpy(env->callsite_at_stack[idx], 1650 at_stack_in[i], sizeof(struct arg_track) * MAX_ARG_SPILL_SLOTS); 1651 } 1652 } 1653 1654 info->at_in = at_in; 1655 at_in = NULL; 1656 info->len = len; 1657 print_subprog_arg_access(env, subprog, info, at_stack_in); 1658 err = 0; 1659 1660 err_free: 1661 kvfree(at_stack_out); 1662 kvfree(at_stack_in); 1663 kvfree(at_in); 1664 return err; 1665 } 1666 1667 /* Return true if any of R1-R5 is derived from a frame pointer. */ 1668 static bool has_fp_args(struct arg_track *args) 1669 { 1670 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 1671 if (args[r].frame != ARG_NONE) 1672 return true; 1673 return false; 1674 } 1675 1676 /* 1677 * Merge a freshly analyzed instance into the original. 1678 * may_read: union (any pass might read the slot). 1679 * must_write: intersection (only slots written on ALL passes are guaranteed). 1680 * live_before is recomputed by a subsequent update_instance() on @dst. 1681 */ 1682 static void merge_instances(struct func_instance *dst, struct func_instance *src) 1683 { 1684 int f, i; 1685 1686 for (f = 0; f <= dst->depth; f++) { 1687 if (!src->frames[f]) { 1688 /* This pass didn't touch frame f — must_write intersects with empty. */ 1689 if (dst->frames[f]) 1690 for (i = 0; i < dst->insn_cnt; i++) 1691 dst->frames[f][i].must_write = SPIS_ZERO; 1692 continue; 1693 } 1694 if (!dst->frames[f]) { 1695 /* Previous pass didn't touch frame f — take src, zero must_write. */ 1696 dst->frames[f] = src->frames[f]; 1697 src->frames[f] = NULL; 1698 for (i = 0; i < dst->insn_cnt; i++) 1699 dst->frames[f][i].must_write = SPIS_ZERO; 1700 continue; 1701 } 1702 for (i = 0; i < dst->insn_cnt; i++) { 1703 dst->frames[f][i].may_read = 1704 spis_or(dst->frames[f][i].may_read, 1705 src->frames[f][i].may_read); 1706 dst->frames[f][i].must_write = 1707 spis_and(dst->frames[f][i].must_write, 1708 src->frames[f][i].must_write); 1709 } 1710 } 1711 } 1712 1713 static struct func_instance *fresh_instance(struct func_instance *src) 1714 { 1715 struct func_instance *f; 1716 1717 f = kvzalloc_obj(*f, GFP_KERNEL_ACCOUNT); 1718 if (!f) 1719 return ERR_PTR(-ENOMEM); 1720 f->callsite = src->callsite; 1721 f->depth = src->depth; 1722 f->subprog = src->subprog; 1723 f->subprog_start = src->subprog_start; 1724 f->insn_cnt = src->insn_cnt; 1725 return f; 1726 } 1727 1728 static void free_instance(struct func_instance *instance) 1729 { 1730 int i; 1731 1732 for (i = 0; i <= instance->depth; i++) 1733 kvfree(instance->frames[i]); 1734 kvfree(instance); 1735 } 1736 1737 /* 1738 * Recursively analyze a subprog with specific 'entry_args'. 1739 * Each callee is analyzed with the exact args from its call site. 1740 * 1741 * Args are recomputed for each call because the dataflow result at_in[] 1742 * depends on the entry args and frame depth. Consider: A->C->D and B->C->D 1743 * Callsites in A and B pass different args into C, so C is recomputed. 1744 * Then within C the same callsite passes different args into D. 1745 */ 1746 static int analyze_subprog(struct bpf_verifier_env *env, 1747 struct arg_track *entry_args, 1748 struct subprog_at_info *info, 1749 struct func_instance *instance, 1750 u32 *callsites) 1751 { 1752 int subprog = instance->subprog; 1753 int depth = instance->depth; 1754 struct bpf_insn *insns = env->prog->insnsi; 1755 int start = env->subprog_info[subprog].start; 1756 int po_start = env->subprog_info[subprog].postorder_start; 1757 int po_end = env->subprog_info[subprog + 1].postorder_start; 1758 struct func_instance *prev_instance = NULL; 1759 int j, err; 1760 1761 if (++env->liveness->subprog_calls > 10000) { 1762 verbose(env, "liveness analysis exceeded complexity limit (%d calls)\n", 1763 env->liveness->subprog_calls); 1764 return -E2BIG; 1765 } 1766 1767 if (need_resched()) 1768 cond_resched(); 1769 1770 1771 /* 1772 * When an instance is reused (must_write_initialized == true), 1773 * record into a fresh instance and merge afterward. This avoids 1774 * stale must_write marks for instructions not reached in this pass. 1775 */ 1776 if (instance->must_write_initialized) { 1777 struct func_instance *fresh = fresh_instance(instance); 1778 1779 if (IS_ERR(fresh)) 1780 return PTR_ERR(fresh); 1781 prev_instance = instance; 1782 instance = fresh; 1783 } 1784 1785 /* Free prior analysis if this subprog was already visited */ 1786 kvfree(info[subprog].at_in); 1787 info[subprog].at_in = NULL; 1788 1789 err = compute_subprog_args(env, &info[subprog], entry_args, instance, callsites); 1790 if (err) 1791 goto out_free; 1792 1793 /* For each reachable call site in the subprog, recurse into callees */ 1794 for (int p = po_start; p < po_end; p++) { 1795 int idx = env->cfg.insn_postorder[p]; 1796 struct arg_track callee_args[BPF_REG_5 + 1]; 1797 struct arg_track none = { .frame = ARG_NONE }; 1798 struct bpf_insn *insn = &insns[idx]; 1799 struct func_instance *callee_instance; 1800 int callee, target; 1801 int caller_reg, cb_callee_reg; 1802 1803 j = idx - start; /* relative index within this subprog */ 1804 1805 if (bpf_pseudo_call(insn)) { 1806 target = idx + insn->imm + 1; 1807 callee = bpf_find_subprog(env, target); 1808 if (callee < 0) 1809 continue; 1810 1811 /* Build entry args: R1-R5 from at_in at call site */ 1812 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 1813 callee_args[r] = info[subprog].at_in[j][r]; 1814 } else if (bpf_calls_callback(env, idx)) { 1815 callee = find_callback_subprog(env, insn, idx, &caller_reg, &cb_callee_reg); 1816 if (callee == -2) { 1817 /* 1818 * same bpf_loop() calls two different callbacks and passes 1819 * stack pointer to them 1820 */ 1821 if (info[subprog].at_in[j][caller_reg].frame == ARG_NONE) 1822 continue; 1823 for (int f = 0; f <= depth; f++) { 1824 err = mark_stack_read(instance, f, idx, SPIS_ALL); 1825 if (err) 1826 goto out_free; 1827 } 1828 continue; 1829 } 1830 if (callee < 0) 1831 continue; 1832 1833 for (int r = BPF_REG_1; r <= BPF_REG_5; r++) 1834 callee_args[r] = none; 1835 callee_args[cb_callee_reg] = info[subprog].at_in[j][caller_reg]; 1836 } else { 1837 continue; 1838 } 1839 1840 if (!has_fp_args(callee_args)) 1841 continue; 1842 1843 if (depth == MAX_CALL_FRAMES - 1) { 1844 err = -EINVAL; 1845 goto out_free; 1846 } 1847 1848 callee_instance = call_instance(env, instance, idx, callee); 1849 if (IS_ERR(callee_instance)) { 1850 err = PTR_ERR(callee_instance); 1851 goto out_free; 1852 } 1853 callsites[depth] = idx; 1854 err = analyze_subprog(env, callee_args, info, callee_instance, callsites); 1855 if (err) 1856 goto out_free; 1857 1858 /* Pull callee's entry liveness back to caller's callsite */ 1859 { 1860 u32 callee_start = callee_instance->subprog_start; 1861 struct per_frame_masks *entry; 1862 1863 for (int f = 0; f < callee_instance->depth; f++) { 1864 entry = get_frame_masks(callee_instance, f, callee_start); 1865 if (!entry) 1866 continue; 1867 err = mark_stack_read(instance, f, idx, entry->live_before); 1868 if (err) 1869 goto out_free; 1870 } 1871 } 1872 } 1873 1874 if (prev_instance) { 1875 merge_instances(prev_instance, instance); 1876 free_instance(instance); 1877 instance = prev_instance; 1878 } 1879 update_instance(env, instance); 1880 return 0; 1881 1882 out_free: 1883 if (prev_instance) 1884 free_instance(instance); 1885 return err; 1886 } 1887 1888 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env) 1889 { 1890 u32 callsites[MAX_CALL_FRAMES] = {}; 1891 int insn_cnt = env->prog->len; 1892 struct func_instance *instance; 1893 struct subprog_at_info *info; 1894 int k, err = 0; 1895 1896 info = kvzalloc_objs(*info, env->subprog_cnt, GFP_KERNEL_ACCOUNT); 1897 if (!info) 1898 return -ENOMEM; 1899 1900 env->callsite_at_stack = kvzalloc_objs(*env->callsite_at_stack, insn_cnt, 1901 GFP_KERNEL_ACCOUNT); 1902 if (!env->callsite_at_stack) { 1903 kvfree(info); 1904 return -ENOMEM; 1905 } 1906 1907 instance = call_instance(env, NULL, 0, 0); 1908 if (IS_ERR(instance)) { 1909 err = PTR_ERR(instance); 1910 goto out; 1911 } 1912 err = analyze_subprog(env, NULL, info, instance, callsites); 1913 if (err) 1914 goto out; 1915 1916 /* 1917 * Subprogs and callbacks that don't receive FP-derived arguments 1918 * cannot access ancestor stack frames, so they were skipped during 1919 * the recursive walk above. Async callbacks (timer, workqueue) are 1920 * also not reachable from the main program's call graph. Analyze 1921 * all unvisited subprogs as independent roots at depth 0. 1922 * 1923 * Use reverse topological order (callers before callees) so that 1924 * each subprog is analyzed before its callees, allowing the 1925 * recursive walk inside analyze_subprog() to naturally 1926 * reach nested callees that also lack FP-derived args. 1927 */ 1928 for (k = env->subprog_cnt - 1; k >= 0; k--) { 1929 int sub = env->subprog_topo_order[k]; 1930 1931 if (info[sub].at_in && !bpf_subprog_is_global(env, sub)) 1932 continue; 1933 instance = call_instance(env, NULL, 0, sub); 1934 if (IS_ERR(instance)) { 1935 err = PTR_ERR(instance); 1936 goto out; 1937 } 1938 err = analyze_subprog(env, NULL, info, instance, callsites); 1939 if (err) 1940 goto out; 1941 } 1942 1943 if (env->log.level & BPF_LOG_LEVEL2) 1944 err = print_instances(env); 1945 1946 out: 1947 for (k = 0; k < insn_cnt; k++) 1948 kvfree(env->callsite_at_stack[k]); 1949 kvfree(env->callsite_at_stack); 1950 env->callsite_at_stack = NULL; 1951 for (k = 0; k < env->subprog_cnt; k++) 1952 kvfree(info[k].at_in); 1953 kvfree(info); 1954 return err; 1955 } 1956 1957 /* Each field is a register bitmask */ 1958 struct insn_live_regs { 1959 u16 use; /* registers read by instruction */ 1960 u16 def; /* registers written by instruction */ 1961 u16 in; /* registers that may be alive before instruction */ 1962 u16 out; /* registers that may be alive after instruction */ 1963 }; 1964 1965 /* Bitmask with 1s for all caller saved registers */ 1966 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 1967 1968 /* Compute info->{use,def} fields for the instruction */ 1969 static void compute_insn_live_regs(struct bpf_verifier_env *env, 1970 struct bpf_insn *insn, 1971 struct insn_live_regs *info) 1972 { 1973 struct bpf_call_summary cs; 1974 u8 class = BPF_CLASS(insn->code); 1975 u8 code = BPF_OP(insn->code); 1976 u8 mode = BPF_MODE(insn->code); 1977 u16 src = BIT(insn->src_reg); 1978 u16 dst = BIT(insn->dst_reg); 1979 u16 r0 = BIT(0); 1980 u16 def = 0; 1981 u16 use = 0xffff; 1982 1983 switch (class) { 1984 case BPF_LD: 1985 switch (mode) { 1986 case BPF_IMM: 1987 if (BPF_SIZE(insn->code) == BPF_DW) { 1988 def = dst; 1989 use = 0; 1990 } 1991 break; 1992 case BPF_LD | BPF_ABS: 1993 case BPF_LD | BPF_IND: 1994 /* stick with defaults */ 1995 break; 1996 } 1997 break; 1998 case BPF_LDX: 1999 switch (mode) { 2000 case BPF_MEM: 2001 case BPF_MEMSX: 2002 def = dst; 2003 use = src; 2004 break; 2005 } 2006 break; 2007 case BPF_ST: 2008 switch (mode) { 2009 case BPF_MEM: 2010 def = 0; 2011 use = dst; 2012 break; 2013 } 2014 break; 2015 case BPF_STX: 2016 switch (mode) { 2017 case BPF_MEM: 2018 def = 0; 2019 use = dst | src; 2020 break; 2021 case BPF_ATOMIC: 2022 switch (insn->imm) { 2023 case BPF_CMPXCHG: 2024 use = r0 | dst | src; 2025 def = r0; 2026 break; 2027 case BPF_LOAD_ACQ: 2028 def = dst; 2029 use = src; 2030 break; 2031 case BPF_STORE_REL: 2032 def = 0; 2033 use = dst | src; 2034 break; 2035 default: 2036 use = dst | src; 2037 if (insn->imm & BPF_FETCH) 2038 def = src; 2039 else 2040 def = 0; 2041 } 2042 break; 2043 } 2044 break; 2045 case BPF_ALU: 2046 case BPF_ALU64: 2047 switch (code) { 2048 case BPF_END: 2049 use = dst; 2050 def = dst; 2051 break; 2052 case BPF_MOV: 2053 def = dst; 2054 if (BPF_SRC(insn->code) == BPF_K) 2055 use = 0; 2056 else 2057 use = src; 2058 break; 2059 default: 2060 def = dst; 2061 if (BPF_SRC(insn->code) == BPF_K) 2062 use = dst; 2063 else 2064 use = dst | src; 2065 } 2066 break; 2067 case BPF_JMP: 2068 case BPF_JMP32: 2069 switch (code) { 2070 case BPF_JA: 2071 def = 0; 2072 if (BPF_SRC(insn->code) == BPF_X) 2073 use = dst; 2074 else 2075 use = 0; 2076 break; 2077 case BPF_JCOND: 2078 def = 0; 2079 use = 0; 2080 break; 2081 case BPF_EXIT: 2082 def = 0; 2083 use = r0; 2084 break; 2085 case BPF_CALL: 2086 def = ALL_CALLER_SAVED_REGS; 2087 use = def & ~BIT(BPF_REG_0); 2088 if (bpf_get_call_summary(env, insn, &cs)) 2089 use = GENMASK(cs.num_params, 1); 2090 break; 2091 default: 2092 def = 0; 2093 if (BPF_SRC(insn->code) == BPF_K) 2094 use = dst; 2095 else 2096 use = dst | src; 2097 } 2098 break; 2099 } 2100 2101 info->def = def; 2102 info->use = use; 2103 } 2104 2105 /* Compute may-live registers after each instruction in the program. 2106 * The register is live after the instruction I if it is read by some 2107 * instruction S following I during program execution and is not 2108 * overwritten between I and S. 2109 * 2110 * Store result in env->insn_aux_data[i].live_regs. 2111 */ 2112 int bpf_compute_live_registers(struct bpf_verifier_env *env) 2113 { 2114 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 2115 struct bpf_insn *insns = env->prog->insnsi; 2116 struct insn_live_regs *state; 2117 int insn_cnt = env->prog->len; 2118 int err = 0, i, j; 2119 bool changed; 2120 2121 /* Use the following algorithm: 2122 * - define the following: 2123 * - I.use : a set of all registers read by instruction I; 2124 * - I.def : a set of all registers written by instruction I; 2125 * - I.in : a set of all registers that may be alive before I execution; 2126 * - I.out : a set of all registers that may be alive after I execution; 2127 * - insn_successors(I): a set of instructions S that might immediately 2128 * follow I for some program execution; 2129 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 2130 * - visit each instruction in a postorder and update 2131 * state[i].in, state[i].out as follows: 2132 * 2133 * state[i].out = U [state[s].in for S in insn_successors(i)] 2134 * state[i].in = (state[i].out / state[i].def) U state[i].use 2135 * 2136 * (where U stands for set union, / stands for set difference) 2137 * - repeat the computation while {in,out} fields changes for 2138 * any instruction. 2139 */ 2140 state = kvzalloc_objs(*state, insn_cnt, GFP_KERNEL_ACCOUNT); 2141 if (!state) { 2142 err = -ENOMEM; 2143 goto out; 2144 } 2145 2146 for (i = 0; i < insn_cnt; ++i) 2147 compute_insn_live_regs(env, &insns[i], &state[i]); 2148 2149 /* Forward pass: resolve stack access through FP-derived pointers */ 2150 err = bpf_compute_subprog_arg_access(env); 2151 if (err) 2152 goto out; 2153 2154 changed = true; 2155 while (changed) { 2156 changed = false; 2157 for (i = 0; i < env->cfg.cur_postorder; ++i) { 2158 int insn_idx = env->cfg.insn_postorder[i]; 2159 struct insn_live_regs *live = &state[insn_idx]; 2160 struct bpf_iarray *succ; 2161 u16 new_out = 0; 2162 u16 new_in = 0; 2163 2164 succ = bpf_insn_successors(env, insn_idx); 2165 for (int s = 0; s < succ->cnt; ++s) 2166 new_out |= state[succ->items[s]].in; 2167 new_in = (new_out & ~live->def) | live->use; 2168 if (new_out != live->out || new_in != live->in) { 2169 live->in = new_in; 2170 live->out = new_out; 2171 changed = true; 2172 } 2173 } 2174 } 2175 2176 for (i = 0; i < insn_cnt; ++i) 2177 insn_aux[i].live_regs_before = state[i].in; 2178 2179 if (env->log.level & BPF_LOG_LEVEL2) { 2180 verbose(env, "Live regs before insn:\n"); 2181 for (i = 0; i < insn_cnt; ++i) { 2182 if (env->insn_aux_data[i].scc) 2183 verbose(env, "%3d ", env->insn_aux_data[i].scc); 2184 else 2185 verbose(env, " "); 2186 verbose(env, "%3d: ", i); 2187 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 2188 if (insn_aux[i].live_regs_before & BIT(j)) 2189 verbose(env, "%d", j); 2190 else 2191 verbose(env, "."); 2192 verbose(env, " "); 2193 bpf_verbose_insn(env, &insns[i]); 2194 if (bpf_is_ldimm64(&insns[i])) 2195 i++; 2196 } 2197 } 2198 2199 out: 2200 kvfree(state); 2201 return err; 2202 } 2203