Refactor verifier object relationship tracking
Subsystems (7)
v5 cover Refactor verifier object relationship tracking
Hi all,
This patchset cleans up dynptr handling, refactors object relationship tracking in the verifier by introducing parent_id, folds ref_obj_id into id with virtual references, and fixes dynptr use-after-free bugs where file/skb dynptrs are not invalidated when the parent referenced object is freed.
* Motivation *
In BPF qdisc programs, an skb can be freed through kfuncs. However, since dynptr does not track the parent referenced object (e.g., skb), the verifier does not invalidate the dynptr after the skb is freed, resulting in use-after-free. The same issue also affects file dynptr.
The figure below shows the current state of object tracking. The verifier tracks objects using three fields: id for nullness tracking, ref_obj_id for lifetime tracking, and dynptr_id for tracking the parent dynptr of a slice (PTR_TO_MEM only). While dynptr_id links slices to their parent dynptr, there is no field that links a dynptr back to its parent skb. When the skb is freed via release_reference(ref_obj_id=1), only objects with ref_obj_id=1 are invalidated. Since skb dynptr is non-referenced (ref_obj_id=0), the dynptr and its derived slices remain accessible.
Current: object (id, ref_obj_id, dynptr_id)
id = unique id of the object (for nullness tracking)
ref_obj_id = id of the referenced object (for lifetime tracking) dynptr_id = id of the parent dynptr (only for PTR_TO_MEM slices)
skb (0,1,0)
^
! No link from dynptr to skb
+-------------------------------+
| bpf_dynptr_clone |
dynptr A (2,0,0) dynptr C (4,0,0)
^ ^
bpf_dynptr_slice | |
| |
slice B (3,0,2) slice D (5,0,4)* Why not simply use ref_obj_id to track the parent? *
A natural first approach is to link dynptr to its parent by sharing the parent's ref_obj_id and propagating it to slices. Now, releasing the skb via release_reference(ref_obj_id=1) correctly invalidates all derived objects.
Attempted fix: share parent's ref_obj_id
skb (0,1,0)
^
+-------------------------------+
| bpf_dynptr_clone |
dynptr A (2,1,0) dynptr C (4,1,0)
^ ^
bpf_dynptr_slice | |
| |
slice B (3,1,2) slice D (5,1,4)However, this approach does not generalize to all dynptr types. Referenced dynptrs such as file dynptr acquire their own ref_obj_id to track the dynptr's lifetime. Since ref_obj_id is already used for the dynptr's own reference, it cannot also be used to point to the parent file object. While it is possible to add specialized handling for individual dynptr types [0], it adds complexity and does not generalize.
An alternative approach is to avoid introducing a new field and instead repurpose ref_obj_id as parent_id by folding lifetime tracking into id [1]. In this design, each object is represented as (id, ref_obj_id) where id is used for both nullness and lifetime tracking, and ref_obj_id tracks the parent object's id.
Attempted: object (id, ref_obj_id)
id = id of the object (for nullness and lifetime tracking)
ref_obj_id = id of the parent object
' = id is referenced
skb (1',0)
^
bpf_dynptr_from_skb +-------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,1') dynptr C (4,1')
^ ^
bpf_dynptr_slice | |
| |
slice B (3,2) slice D (5,4)However, this design cannot express the relationship between referenced socket pointers and their casted counterparts. After pointer casting, the original and casted pointers need the same lifetime (same ref_obj_id in the current design) but different nullness (different id). The casted pointer may be NULL even if the original is valid. With id serving as the only field for both nullness and lifetime, and ref_obj_id repurposed as parent, there is no way to express "different identity, same lifetime."
Referenced socket pointer (expressed using current design):
C = ptr_casting_function(A)
ptr A (1,1,0) ptr C (2,1,0)
^ ^
| |
ptr C may be NULL even if ptr A is valid but they have the same lifetime
* New Design: parent_id and virtual references *
The patchset takes a two-step approach. First, parent_id is added to bpf_reg_state alongside the existing ref_obj_id (patch 5). A child object's parent_id points to the parent object's id. This replaces the PTR_TO_MEM-specific dynptr_id, and does not increase the size of bpf_reg_state on 64-bit machines as there is existing padding. With parent_id, the verifier can precisely track object trees using stack-based DFS.
Then, ref_obj_id is folded into id with virtual references (patch 9). In the new model, id serves both nullness and lifetime tracking. Whether a register is referenced is determined by checking if its id (or its parent_id if is virtual) appears in the reference table, rather than reading a dedicated ref_obj_id field.
To handle cases where objects share the same lifetime but need distinct identities, pointer casting and referenced dynptr clones, virtual references are introduced. A virtual reference is a bpf_reference_state entry with is_virtual=true that serves as a lifetime anchor. It has no backing register or stack slot and exists only in acquired_refs. When releasing a register derived from a virtual reference, release_reference() will start the DFS from the virtual reference instead of reg->id.
For pointer casting, the first cast from a referenced pointer creates a virtual reference. The original pointer and all cast results get parent_id pointing to the virtual ref. Each retains a unique id for independent null-checking. Releasing any of them releases the virtual ref, which cascades to invalidate all siblings. For chained casts (sk -> fullsock -> tp), subsequent casts reuse the same virtual ref.
For referenced dynptrs, the constructor creates a virtual reference instead of a regular one. All clones share the same parent_id (the virtual ref) but get unique ids for independent slice tracking. Releasing a referenced dynptr releases the virtual ref, which in turn invalidates all clones and their derived slices.
Final: object (id, parent_id)
id = unique id of the object (for nullness and lifetime
tracking)
parent_id = id of the parent object (for object relationship
tracking)
V = virtual reference (lifetime anchor in acquired_refs)
' = id is referenced (appears in reference table)
skb (1',0)
^
bpf_dynptr_from_skb +-------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,1') dynptr C (4,1')
^ ^
bpf_dynptr_slice | |
| |
slice B (3,2) slice D (5,4)Pointer casting:
V (2',0) <-- virtual ref
^
+---------------------------+---------------------+
| | |
sk A (1,2') cast -> fullsock B (3,2') cast -> tp C (4,2')* Preserving reg->id after null-check *
For parent_id tracking to work, child objects need to refer to the parent's id. This requires two preparatory changes: assigning reg->id when reading referenced kptrs from program context (patch 3), and preserving reg->id of pointer objects after null-check (patch 4). Previously, null-check would clear reg->id, making it impossible for children to reference the parent afterward. The latter causes a slight increase in verified states for some programs. One selftest object sees +19 states (+5.01%). For Meta BPF objects, the increase is also minor, with the largest being +34 states (+3.63%).
* Object relationship in different scenarios (for reference) *
The figures below show how the final design handles all four combinations of referenced/non-referenced dynptr with referenced/non-referenced parent. V denotes a virtual reference.
(1) Non-referenced dynptr with referenced parent (e.g., skb in Qdisc):
skb (1',0)
^
bpf_dynptr_from_skb +-------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,1') dynptr C (4,1')
dynptr A and C live independently(2) Non-referenced dynptr with non-referenced parent (e.g., skb in TC, always valid):
bpf_dynptr_from_skb
bpf_dynptr_clone(A, C)
dynptr A (1,0) dynptr C (2,0)
dynptr A and C live independently
(3) Referenced dynptr with referenced parent:
file (1',0)
^
bpf_dynptr_from_file |
V (2',1') <-- virtual ref representing freader
^
+---------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (3,2') dynptr C (4,2')
dynptr A and C have the same lifetime (both point to virtual ref V)
Releasing either dynptr releases V, invalidating both. Releasing file (1') detects V as a leaked reference.
(4) Referenced dynptr with non-referenced parent:
bpf_ringbuf_reserve_dynptr
V (1',0) <-- virtual ref representing ringbuf record
^
+---------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,1') dynptr C (3,1')
dynptr A and C have the same lifetime (both point to virtual ref V)
[0] https://lore.kernel.org/bpf/[email protected]/
[1] https://github.com/ameryhung/bpf/commits/obj_relationship_v2_no_parent_id/
Changelog:
v4 -> v5
- Add patch 9 folding ref_obj_id into id and introducing virtual references for pointer casting and referenced dynptr clones (Eduard, Andrii)
- Add patch 10 fixing dynptr ref counting to scan all call frames instead of only the current frame (Eduard)
- Add utility function validate_ref_obj() (Eduard)
v3 -> v4
- Add patch 1 clean up mark_stack_slot_obj_read() and callers (to address v3 ignoring err returned from mark_dynptr_read) (Andrii)
- Fix release_reference() and move the logic allowing destroying a referenced object when refcnt > 1 from destroy_if_stack_slots_dynptr() to release_reference() (Mykyta)
- Add patch 7 introducing ref_obj_desc and unifying ref_obj handling (to address Eduard's concern about unclear meta->{id,ref_obj_id} initialization/use and confusing function arguments of process_dynptr_func())
- Add patch 8 unifying release_regno handling so that bpf_kptr_xchg also use release_reference()
v2 -> v3
- Rebase to bpf-next/master
- Update veristat numbers
- Update commit msg to explain multiple dropped checks (Mykyta, Andrii)
- Reuse idmap as idstack in release_reference() and check for duplicate id (Mykyta, Andrii)
- Change to use RUN_TEST for qdisc dynptr selftest (Eduard)
v1 -> v2
- Redesign: Use object (id, ref_obj_id, parent_id) instead of (id, ref_obj_id) as it cannot express ptr casting without introducing specialized code to handle the case
- Use stack-based DFS to release objects to avoid recursion (Andrii)
- Keep reg->id after null check
- Add dynptr cleanup
- Fix dynptr kfunc arg type determination
- Add a file dynptr UAF selftest
---
Amery Hung (14):
bpf: Simplify mark_stack_slot_obj_read() and callers
bpf: Unify dynptr handling in the verifier
bpf: Assign reg->id when getting referenced kptr from ctx
bpf: Preserve reg->id of pointer objects after null-check
bpf: Refactor object relationship tracking and fix dynptr UAF bug
bpf: Remove redundant dynptr arg check for helper
bpf: Unify referenced object tracking in verifier
bpf: Unify release handling for helpers and kfuncs
bpf: Fold ref_obj_id into id and introduce virtual references
bpf: Fix dynptr ref counting to scan all call frames selftests/bpf: Test creating dynptr from dynptr data and slice selftests/bpf: Test using dynptr after freeing the underlying object selftests/bpf: Test using slice after invalidating dynptr clone selftests/bpf: Test using file dynptr after the reference on file is
dropped
include/linux/bpf.h | 4 +- include/linux/bpf_verifier.h | 102 +- kernel/bpf/btf.c | 2 +- kernel/bpf/fixups.c | 2 +- kernel/bpf/helpers.c | 2 +- kernel/bpf/log.c | 18 +- kernel/bpf/states.c | 11 +- kernel/bpf/verifier.c | 1141 ++++++++--------- .../selftests/bpf/prog_tests/bpf_qdisc.c | 8 + .../selftests/bpf/prog_tests/cb_refs.c | 2 +- .../selftests/bpf/prog_tests/spin_lock.c | 4 +- ..._qdisc_dynptr_use_after_invalidate_clone.c | 74 ++ .../progs/bpf_qdisc_fail__invalid_dynptr.c | 68 + ...f_qdisc_fail__invalid_dynptr_cross_frame.c | 74 ++ .../bpf_qdisc_fail__invalid_dynptr_slice.c | 70 + .../selftests/bpf/progs/cgrp_kfunc_failure.c | 6 +- .../testing/selftests/bpf/progs/dynptr_fail.c | 52 +- .../selftests/bpf/progs/file_reader_fail.c | 60 + .../selftests/bpf/progs/iters_state_safety.c | 4 +- .../selftests/bpf/progs/iters_testmod_seq.c | 12 +- .../selftests/bpf/progs/map_kptr_fail.c | 2 +- .../selftests/bpf/progs/task_kfunc_failure.c | 6 +- .../bpf/progs/test_ringbuf_map_key.c | 11 +- .../selftests/bpf/progs/user_ringbuf_fail.c | 4 +- .../bpf/progs/verifier_global_ptr_args.c | 2 +- .../bpf/progs/verifier_ref_tracking.c | 2 +- .../selftests/bpf/progs/verifier_sock.c | 6 +- .../selftests/bpf/progs/verifier_vfs_reject.c | 2 +- .../selftests/bpf/progs/wakeup_source_fail.c | 2 +- tools/testing/selftests/bpf/verifier/calls.c | 24 - 30 files changed, 1032 insertions(+), 745 deletions(-) create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_dynptr_use_after_invalidate_clone.c create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr.c create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_cross_frame.c create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_slice.c
Signature · 1 line
2.53.0-Meta
PATCH v5 1/14 bpf: Simplify mark_stack_slot_obj_read() and callers
Rename mark_stack_slot_obj_read() as mark_stack_slots_scratched() and directly call it from functions processing iter, dynptr and irq_flag. Commit 6762e3a0bce5 ("bpf: simplify liveness to use (callsite, depth) keyed func_instances") has removed the dynamic liveness component in mark_stack_slot_obj_read(). The function effectively only marks stack slots as scratched and always succeed. Therefore, return void, drop the unused bpf_reg_state argument and rename it to mark_stack_slots_scratched() to reflect what it does now.
In addition, to prepare for unifying dynptr handling, dynptr_get_spi() will be moved out of mark_dynptr_read(). As mark_dynptr_read() would join mark_iter_read() as a thin wrapper of mark_stack_slots_scratched(), just open code these helpers.
--- kernel/bpf/verifier.c | 69 +++++++++++++------------------------------ 1 file changed, 21 insertions(+), 48 deletions(-)
kernel/bpf/verifier.c +21 -48
@@ -3007,50 +3007,13 @@ static int sort_subprogs_topo(struct bpf_verifier_env *env)return ret; } -static int mark_stack_slot_obj_read (struct bpf_verifier_env *env,struct bpf_reg_state *reg, -int spi,int nr_slots) +static void mark_stack_slots_scratched (struct bpf_verifier_env *env, +int spi,int nr_slots) {int i;for (i =0 ; i < nr_slots; i++)mark_stack_slot_scratched (env, spi - i); -return 0 ; -} - -static int mark_dynptr_read (struct bpf_verifier_env *env,struct bpf_reg_state *reg) -{ -int spi; - -/* For CONST_PTR_TO_DYNPTR, it must have already been done by -* check_reg_arg in check_helper_call and mark_btf_func_reg_size in -* check_kfunc_call. -*/ -if (reg->type ==CONST_PTR_TO_DYNPTR ) -return 0 ; - spi =dynptr_get_spi (env, reg); -if (spi <0 ) -return spi; -/* Caller ensures dynptr is valid and initialized, which means spi is in -* bounds and spi is the first dynptr slot. Simply mark stack slot as -* read. -*/ -return mark_stack_slot_obj_read (env, reg, spi,BPF_DYNPTR_NR_SLOTS ); -} - -static int mark_iter_read (struct bpf_verifier_env *env,struct bpf_reg_state *reg, -int spi,int nr_slots) -{ -return mark_stack_slot_obj_read (env, reg, spi, nr_slots); -} - -static int mark_irq_flag_read (struct bpf_verifier_env *env,struct bpf_reg_state *reg) -{ -int spi; - - spi =irq_flag_get_spi (env, reg); -if (spi <0 ) -return spi; -return mark_stack_slot_obj_read (env, reg, spi,1 ); }/* This function is supposed to be used by the following 32-bit optimization
@@ -7256,7 +7219,7 @@ static int process_kptr_func(struct bpf_verifier_env *env, int regno,static int process_dynptr_func (struct bpf_verifier_env *env,struct bpf_reg_state *reg,argno_t argno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id) { -int err; +int spi, err =0 ;if (reg->type !=PTR_TO_STACK && reg->type !=CONST_PTR_TO_DYNPTR ) { verbose(env,
@@ -7318,7 +7281,17 @@ static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_statreturn -EINVAL ; } - err =mark_dynptr_read (env, reg); +if (reg->type !=CONST_PTR_TO_DYNPTR ) { + spi =dynptr_get_spi (env, reg); +if (spi <0 ) +return spi; + +/* +* For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg +* in check_helper_call and mark_btf_func_reg_size in check_kfunc_call. +*/ +mark_stack_slots_scratched (env, spi,BPF_DYNPTR_NR_SLOTS ); + } }return err; }
@@ -7428,9 +7401,7 @@ static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *if (spi <0 )return spi; - err =mark_iter_read (env, reg, spi, nr_slots); -if (err) -return err; +mark_stack_slots_scratched (env, spi, nr_slots);/* remember meta->iter info for process_iter_next_call() */ meta->iter.spi = spi;
@@ -11360,7 +11331,7 @@ static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,static int process_irq_flag (struct bpf_verifier_env *env,struct bpf_reg_state *reg,argno_t argno,struct bpf_kfunc_call_arg_meta *meta) { -int err, kfunc_class =IRQ_NATIVE_KFUNC ; +int err, spi, kfunc_class =IRQ_NATIVE_KFUNC ;bool irq_save; if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
@@ -11401,9 +11372,11 @@ static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *return err; } - err =mark_irq_flag_read (env, reg); -if (err) -return err; + spi =irq_flag_get_spi (env, reg); +if (spi <0 ) +return spi; + +mark_stack_slots_scratched (env, spi,1 ); err =unmark_stack_slot_irq_flag (env, reg, kfunc_class);if (err)
Signature · 1 line
2.53.0-Meta
PATCH v5 2/14 bpf: Unify dynptr handling in the verifier
In reply to Amery HungSimplify dynptr checking for helper and kfunc by unifying it. Remember the initialized dynptr (i.e.,g !(arg_type |= MEM_UNINIT)) pass to a dynptr kfunc during process_dynptr_func() so that we can easily retrieve the information for verification later. By saving it in meta->dynptr, there is no need to call dynptr helpers such as dynptr_id(), dynptr_ref_obj_id() and dynptr_type() in check_func_arg().
Remove and open code the helpers in process_dynptr_func() when saving id, ref_obj_id, and type.
Besides, since dynptr ref_obj_id information is now pass around in meta->bpf_dynptr_desc, drop the check in helper_multiple_ref_obj_use.
--- include/linux/bpf_verifier.h | 13 ++- kernel/bpf/verifier.c | 178 +++++++---------------------------- 2 files changed, 40 insertions(+), 151 deletions(-)
include/linux/bpf_verifier.h +8 -5
@@ -1436,6 +1436,13 @@ struct bpf_map_desc {int uid; }; +/* The last initialized dynptr; Populated by process_dynptr_func() */ +struct bpf_dynptr_desc { +enum bpf_dynptr_type type; +u32 id; +u32 ref_obj_id; +}; +struct bpf_kfunc_call_arg_meta {/* In parameters */ struct btf *btf;
@@ -1476,16 +1483,12 @@ struct bpf_kfunc_call_arg_meta {struct {struct btf_field *field; } arg_rbtree_root; -struct { -enum bpf_dynptr_type type; -u32 id; -u32 ref_obj_id; - } initialized_dynptr;struct {u8 spi;u8 frameno; } iter;struct bpf_map_desc map; +struct bpf_dynptr_desc dynptr;u64 mem_size; };
kernel/bpf/verifier.c +32 -146
300 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
PATCH v5 3/14 bpf: Assign reg->id when getting referenced kptr from ctx
In reply to Amery HungAssign reg->id when getting referenced kptr from read program context to be consistent with R0 of KF_ACQUIRE kfunc. skb dynptr will track the referenced skb in qdisc programs using a new field reg->parent_id in a later patch.
--- kernel/bpf/verifier.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +3 -2
@@ -6209,8 +6209,6 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b }else {mark_reg_known_zero (env, regs, value_regno); -if (type_may_be_null (info.reg_type)) - regs[value_regno].id = ++env->id_gen;/* A load of ctx field could have different * actual load size with the one encoded in the * insn. When the dst is PTR, it is for sure not
@@ -6220,8 +6218,11 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bif (base_type (info.reg_type) ==PTR_TO_BTF_ID ) { regs[value_regno].btf = info.btf; regs[value_regno].btf_id = info.btf_id; + regs[value_regno].id = info.ref_obj_id; regs[value_regno].ref_obj_id = info.ref_obj_id; } +if (type_may_be_null (info.reg_type) && !regs[value_regno].id) + regs[value_regno].id = ++env->id_gen; } regs[value_regno].type = info.reg_type; }
Signature · 1 line
2.53.0-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v5 03/14] bpf: Assign reg->id when getting referenced kptr from ctx
During the v3 review on lore, Eduard Zingerman noted that this patch is mandatory for the series because the .id link is needed to propagate invalidation triggered by free_skb() to child objects.…
Quoted 10 lines
bpf: Assign
reg->idwhen getting referenced kptr from ctxAssign
reg->idwhen getting referenced kptr from read program context to be consistent with R0 ofKF_ACQUIREkfunc. skb dynptr will track the referenced skb in qdisc programs using a new fieldreg->parent_idin a later patch.Acked-by Andrii Nakryiko <[email protected]>Acked-by Eduard Zingerman <[email protected]>Signed-off-by Amery Hung <[email protected]>
During the v3 review on lore, Eduard Zingerman noted that this patch is mandatory for the series because the .id link is needed to propagate invalidation triggered by free_skb() to child objects. Specifically, the test bpf_qdisc_fail__invalid_dynptr_cross_frame.c:invalid_dynptr_cross_frame fails if the line "regs[value_regno].id = info.ref_obj_id;" is commented out. This invalidation propagation aspect is not mentioned in the current commit message.
Reference:
https://lore.kernel.org/bpf/[email protected]/
Date: Wed, 22 Apr 2026 15:50:52 -0700
Reviewer: Eduard Zingerman
Could the commit message be updated to mention the invalidation propagation requirement?
Quoted 15 lines
kernel/bpf/verifier.c +0
-2@@ -6209,8 +6209,6 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b }else {mark_reg_known_zero (env, regs, value_regno); -if (type_may_be_null (info.reg_type)) - regs[value_regno].id = ++env->id_gen;/* A load of ctx field could have different * actual load size with the one encoded in the * insn. When the dst is PTR, it is for sure not @@ -6220,8 +6218,11 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bif (base_type (info.reg_type) ==PTR_TO_BTF_ID ) {
kernel/bpf/verifier.c static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b · line 6228
Quoted 10 lines
kernel/bpf/verifier.c +3
-0regs[value_regno].btf = info.btf; regs[value_regno].btf_id = info.btf_id; + regs[value_regno].id = info.ref_obj_id; regs[value_regno].ref_obj_id = info.ref_obj_id; } +if (type_may_be_null (info.reg_type) && !regs[value_regno].id) + regs[value_regno].id = ++env->id_gen; } regs[value_regno].type = info.reg_type; }
This looks like a bug fix for the id generation logic introduced when support for may-be-null types was added to the check_ctx_access path. The issue is that when getting a referenced kptr from program context (PTR_TO_BTF_ID with ref_obj_id), the code was generating a fresh id for nullable types before assigning ref_obj_id, causing inconsistency with KF_ACQUIRE kfunc behavior where reg->id is set to info.ref_obj_id.
Should this include:
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26116680637
Re: [PATCH bpf-next v5 03/14] bpf: Assign reg->id when getting referenced kptr from ctx
Quoted 61 lines · On Tue, May 19, 2026 at 11:56 AM <[email protected]> wrote:
Quoted 11 lines
bpf: Assign
reg->idwhen getting referenced kptr from ctxAssign
reg->idwhen getting referenced kptr from read program context to be consistent with R0 ofKF_ACQUIREkfunc. skb dynptr will track the referenced skb in qdisc programs using a new fieldreg->parent_idin a later patch.Acked-by Andrii Nakryiko <[email protected]>Acked-by Eduard Zingerman <[email protected]>Signed-off-by Amery Hung <[email protected]>During the v3 review on lore, Eduard Zingerman noted that this patch is mandatory for the series because the .id link is needed to propagate invalidation triggered by
free_skb()to child objects. Specifically, the test bpf_qdisc_fail__invalid_dynptr_cross_frame.c:invalid_dynptr_cross_frame fails if the line "regs[value_regno].id = info.ref_obj_id;" is commented out. This invalidation propagation aspect is not mentioned in the current commit message.Reference:
https://lore.kernel.org/bpf/[email protected]/
Date: Wed, 22 Apr 2026 15:50:52 -0700
Reviewer: Eduard ZingermanCould the commit message be updated to mention the invalidation propagation requirement?
Quoted 15 lines
kernel/bpf/verifier.c +0
-2@@ -6209,8 +6209,6 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b }else {mark_reg_known_zero (env, regs, value_regno); -if (type_may_be_null (info.reg_type)) - regs[value_regno].id = ++env->id_gen;/* A load of ctx field could have different * actual load size with the one encoded in the * insn. When the dst is PTR, it is for sure not @@ -6220,8 +6218,11 @@ static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bif (base_type (info.reg_type) ==PTR_TO_BTF_ID ) {kernel/bpf/verifier.c static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b · line 6228
Quoted 10 lines
kernel/bpf/verifier.c +3
-0regs[value_regno].btf = info.btf; regs[value_regno].btf_id = info.btf_id; + regs[value_regno].id = info.ref_obj_id; regs[value_regno].ref_obj_id = info.ref_obj_id; } +if (type_may_be_null (info.reg_type) && !regs[value_regno].id) + regs[value_regno].id = ++env->id_gen; } regs[value_regno].type = info.reg_type; }This looks like a bug fix for the id generation logic introduced when support for may-be-null types was added to the
check_ctx_accesspath. The issue is that when getting a referenced kptr from program context (PTR_TO_BTF_IDwithref_obj_id), the code was generating a fresh id for nullable types before assigningref_obj_id, causing inconsistency withKF_ACQUIREkfunc behavior wherereg->idis set to info.ref_obj_id.
Quoted 3 lines
Should this include:
Fixes 93c230e3f5bd ("bpf: Enforce id generation for all may-be-null register type")
The inconsistency is not a bug. It is only needed later when I added reg->parent_id that track reg->id. We do not need a fix tag here.
Quoted 7 lines
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/26116680637
PATCH v5 4/14 bpf: Preserve reg->id of pointer objects after null-check
In reply to Amery HungPreserve reg->id of pointer objects after null-checking the register so that children objects derived from it can still refer to it in the new object relationship tracking mechanism introduced in a later patch. This change incurs a slight increase in the number of states in one selftest bpf object, rbtree_search.bpf.o. For Meta bpf objects, the increase of states is also negligible.
Selftest BPF objects with insns_diff > 0
Program Insns (A) Insns (B) Insns (DIFF) States (A) States (B) States (DIFF) ------------------------ --------- --------- -------------- ---------- ---------- -------------
rbtree_search 6820 7326 +506 (+7.42%) 379 398 +19 (+5.01%)
Meta BPF objects with insns_diff > 0
Program Insns (A) Insns (B) Insns (DIFF) States (A) States (B) States (DIFF) ------------------------ --------- --------- -------------- ---------- ---------- ------------- ned_imex_be_tclass 52 57 +5 (+9.62%) 5 6 +1 (+20.00%) ned_imex_be_tclass 52 57 +5 (+9.62%) 5 6 +1 (+20.00%) ned_skop_auto_flowlabel 523 526 +3 (+0.57%) 39 40 +1 (+2.56%) ned_skop_mss 289 292 +3 (+1.04%) 20 20 +0 (+0.00%) ned_skopt_bet_classifier 78 82 +4 (+5.13%) 8 8 +0 (+0.00%) dctcp_update_alpha 252 320 +68 (+26.98%) 21 27 +6 (+28.57%) dctcp_update_alpha 252 320 +68 (+26.98%) 21 27 +6 (+28.57%) ned_ts_func 119 126 +7 (+5.88%) 6 7 +1 (+16.67%) tw_egress 1119 1128 +9 (+0.80%) 95 96 +1 (+1.05%) tw_ingress 1128 1137 +9 (+0.80%) 95 96 +1 (+1.05%) tw_tproxy_router 4380 4465 +85 (+1.94%) 114 118 +4 (+3.51%) tw_tproxy_router4 3093 3170 +77 (+2.49%) 83 88 +5 (+6.02%) ttls_tc_ingress 34656 35717 +1061 (+3.06%) 936 970 +34 (+3.63%) tw_twfw_egress 222327 222338 +11 (+0.00%) 10563 10564 +1 (+0.01%) tw_twfw_ingress 78295 78299 +4 (+0.01%) 3825 3826 +1 (+0.03%) tw_twfw_tc_eg 222839 222859 +20 (+0.01%) 10584 10585 +1 (+0.01%) tw_twfw_tc_in 78295 78299 +4 (+0.01%) 3825 3826 +1 (+0.03%) tw_twfw_egress 8080 8085 +5 (+0.06%) 456 456 +0 (+0.00%) tw_twfw_ingress 8053 8056 +3 (+0.04%) 454 454 +0 (+0.00%) tw_twfw_tc_eg 8154 8174 +20 (+0.25%) 456 457 +1 (+0.22%) tw_twfw_tc_in 8060 8063 +3 (+0.04%) 455 455 +0 (+0.00%) tw_twfw_egress 222327 222338 +11 (+0.00%) 10563 10564 +1 (+0.01%) tw_twfw_ingress 78295 78299 +4 (+0.01%) 3825 3826 +1 (+0.03%) tw_twfw_tc_eg 222839 222859 +20 (+0.01%) 10584 10585 +1 (+0.01%) tw_twfw_tc_in 78295 78299 +4 (+0.01%) 3825 3826 +1 (+0.03%) tw_twfw_egress 8080 8085 +5 (+0.06%) 456 456 +0 (+0.00%) tw_twfw_ingress 8053 8056 +3 (+0.04%) 454 454 +0 (+0.00%) tw_twfw_tc_eg 8154 8174 +20 (+0.25%) 456 457 +1 (+0.22%) tw_twfw_tc_in 8060 8063 +3 (+0.04%) 455 455 +0 (+0.00%)
Looking into rbtree_search, the reason for such increase is that the verifier has to explore the main loop shown below for one more iteration until state pruning decides the current state is safe.
long rbtree_search(void *ctx)
{
...
bpf_spin_lock(&glock0);
rb_n = bpf_rbtree_root(&groot0);
while (can_loop) {
if (!rb_n) {
bpf_spin_unlock(&glock0);
return __LINE__;
}
n = rb_entry(rb_n, struct node_data, r0);
if (lookup_key == n->key0)
break;
if (nr_gc < NR_NODES)
gc_ns[nr_gc++] = rb_n;
if (lookup_key < n->key0)
rb_n = bpf_rbtree_left(&groot0, rb_n);
else
rb_n = bpf_rbtree_right(&groot0, rb_n);
}
...
}Below is what the verifier sees at the start of each iteration (65: may_goto) after preserving id of rb_n. Without id of rb_n, the verifier stops exploring the loop at iter 16.
rb_n gc_ns[15]
iter 15 257 257
iter 16 290 257 rb_n: idmap add 257->290
gc_ns[15]: check 257 != 290 --> state not equal
iter 17 325 257 rb_n: idmap add 290->325
gc_ns[15]: idmap add 257->257 --> state safe
--- kernel/bpf/verifier.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-)
kernel/bpf/verifier.c +4 -9
@@ -15524,15 +15524,10 @@ static void mark_ptr_or_null_reg(struct bpf_func_state *state,mark_ptr_not_null_reg (reg); -if (!reg_may_point_to_spin_lock (reg)) { -/* For not-NULL ptr, reg->ref_obj_id will be reset -* in release_reference(). -* -* reg->id is still used by spin_lock ptr. Other -* than spin_lock ptr type, reg->id can be reset. -*/ - reg->id =0 ; - } +/* +* reg->id is preserved for object relationship tracking +* and spin_lock lock state tracking +*/ } }
Signature · 1 line
2.53.0-Meta
PATCH v5 5/14 bpf: Refactor object relationship tracking and fix dynptr UAF bug
In reply to Amery HungRefactor object relationship tracking in the verifier and fix a dynptr use-after-free bug where file/skb dynptrs are not invalidated when the parent referenced object is freed.
Add parent_id to bpf_reg_state to precisely track child-parent relationships. A child object's parent_id points to the parent object's id. This replaces the PTR_TO_MEM-specific dynptr_id and does not increase the size of bpf_reg_state on 64-bit machines as there is existing padding.
When calling dynptr constructors (i.e., process_dynptr_func() with MEM_UNINIT argument), track the parent's id if the parent is a referenced object. This only applies to file dynptr and skb dynptr, so only pass parent reg->id to kfunc constructors.
For release_reference(), invalidating an object now also invalidates all descendants by traversing the object tree. This is done using stack-based DFS to avoid recursive call chains of release_reference() -> unmark_stack_slots_dynptr() -> release_reference(). Referenced objects encountered during tree traversal cannot be indirectly released. They require an explicit helper/kfunc call to release the acquired resources.
While the new design changes how object relationships are tracked in the verifier, it does not change the verifier's behavior. Here is the implication for dynptr, pointer casting, and owning/non-owning references:
Dynptr:
When initializing a dynptr, referenced dynptrs acquire a reference for ref_obj_id. If the dynptr has a referenced parent, parent_id tracks the parent's id. When cloning, ref_obj_id and parent_id are copied from the original. Releasing a referenced dynptr via release_reference(ref_obj_id) invalidates all clones and derived slices. For non-referenced dynptrs, only the specific dynptr and its children are invalidated.
Pointer casting:
Referenced socket pointers and their casted counterparts share the same lifetime but have different nullness — they have different id but the same ref_obj_id.
Owning to non-owning reference conversion:
After converting owning to non-owning by clearing ref_obj_id (e.g., object(id=1, ref_obj_id=1) -> object(id=1, ref_obj_id=0)), the verifier only needs to release the reference state, so it calls release_reference_nomark() instead of release_reference().
Note that the error message "reference has not been acquired before" in the helper and kfunc release paths is removed. This message was already unreachable. The verifier only calls release_reference() after confirming meta.ref_obj_id is valid, so the condition could never trigger in practice (no selftest exercises it either). With the refactor, release_reference() can now be called with non-acquired ids and have different error conditions. Report directly in release_reference() instead.
--- include/linux/bpf_verifier.h | 24 ++- kernel/bpf/log.c | 8 +- kernel/bpf/states.c | 10 +- kernel/bpf/verifier.c | 305 +++++++++++++++++------------------ 4 files changed, 182 insertions(+), 165 deletions(-)
include/linux/bpf_verifier.h +20 -4
@@ -66,7 +66,6 @@ struct bpf_reg_state {struct {/* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */ u32 mem_size; -u32 dynptr_id;/* for dynptr slices */ };/* For dynptr stack slots */
@@ -188,6 +187,13 @@ struct bpf_reg_state {* allowed and has the same effect as bpf_sk_release(sk). */ u32 ref_obj_id; +/* Tracks the parent object this register was derived from. +* Used for cascading invalidation: when the parent object is +* released or invalidated, all registers with matching parent_id +* are also invalidated. For example, a slice from bpf_dynptr_data() +* gets parent_id set to the dynptr's id. +*/ +u32 parent_id;/* Inside the callee two registers can be both PTR_TO_STACK like * R1=fp-8 and R2=fp-8, but one of them points to this function stack * while another to the caller's stack. To differentiate them 'frameno'
@@ -585,7 +591,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) iter < frame->out_stack_arg_cnt; \ iter++, reg = bpf_get_spilled_stack_arg(iter, frame)) -#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __mask, __expr) \ +#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __stack, __mask, __expr) \ ({ \ struct bpf_verifier_state *___vstate = __vst; \ int ___i, ___j; \
@@ -593,6 +599,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame)struct bpf_reg_state *___regs; \ __state = ___vstate->frame[___i]; \ ___regs = __state->regs; \ + __stack =NULL ; \for (___j =0 ; ___j <MAX_BPF_REG ; ___j++) { \ __reg = &___regs[___j]; \ (void )(__expr); \
@@ -600,19 +607,26 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \ (void )(__expr); \ } \ bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \ (void )(__expr); \ } \ } \ })/* Invoke __expr over regsiters in __vst, setting __state and __reg */ -#define bpf_for_each_reg_in_vstate (__vst, __state, __reg, __expr) \ - bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, 1 << STACK_SPILL, __expr) +#define bpf_for_each_reg_in_vstate (__vst, __state, __reg, __expr) \ + ({ \ + struct bpf_stack_state * ___stack; \ + (void)___stack; \ + bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, ___stack,\ + 1 << STACK_SPILL, __expr); \ + })/* linked list of verifier states used to prune search */ struct bpf_verifier_state_list {
@@ -1441,6 +1455,7 @@ struct bpf_dynptr_desc {enum bpf_dynptr_type type;u32 id;u32 ref_obj_id; +u32 parent_id; };struct bpf_kfunc_call_arg_meta {
@@ -1452,6 +1467,7 @@ struct bpf_kfunc_call_arg_meta {const char *func_name;/* Out parameters */ u32 ref_obj_id; +u32 id;u8 release_regno;bool r0_rdonly;u32 ret_btf_id;
kernel/bpf/log.c +5 -3
@@ -667,6 +667,8 @@ static void print_reg_state(struct bpf_verifier_env *env,verbose (env,"%+d" , reg->delta);if (reg->ref_obj_id)verbose_a ("ref_obj_id=%d" , reg->ref_obj_id); +if (reg->parent_id) +verbose_a ("parent_id=%d" , reg->parent_id);if (type_is_non_owning_ref (reg->type))verbose_a ("%s" ,"non_own_ref" );if (type_is_map_ptr (t)) {
@@ -769,9 +771,9 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifieif (reg->id)verbose_a ("id=%d" , reg->id);if (reg->ref_obj_id) -verbose_a ("ref_id=%d" , reg->ref_obj_id); -if (reg->dynptr_id) -verbose_a ("dynptr_id=%d" , reg->dynptr_id); +verbose_a ("ref_obj_id=%d" , reg->ref_obj_id); +if (reg->parent_id) +verbose_a ("parent_id=%d" , reg->parent_id);verbose (env,")" );break ;case STACK_ITER :
kernel/bpf/states.c +7 -3
@@ -489,7 +489,8 @@ static bool regs_exact(const struct bpf_reg_state *rold, {return memcmp (rold, rcur, offsetof(struct bpf_reg_state , id)) ==0 &&check_ids (rold->id, rcur->id, idmap) && -check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap); +check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap) && +check_ids (rold->parent_id, rcur->parent_id, idmap); }enum exact_level {
@@ -614,7 +615,8 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,range_within (rold, rcur) &&tnum_in (rold->var_off, rcur->var_off) &&check_ids (rold->id, rcur->id, idmap) && -check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap); +check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap) && +check_ids (rold->parent_id, rcur->parent_id, idmap);case PTR_TO_PACKET_META :case PTR_TO_PACKET :/* We must have at least as much range as the old ptr
@@ -794,7 +796,9 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, cur_reg = &cur->stack[spi].spilled_ptr;if (old_reg->dynptr.type != cur_reg->dynptr.type || old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || - !check_ids (old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) + !check_ids (old_reg->id, cur_reg->id, idmap) || + !check_ids (old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || + !check_ids (old_reg->parent_id, cur_reg->parent_id, idmap))return false;break ;case STACK_ITER :
kernel/bpf/verifier.c +150 -155
563 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v5 05/14] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] Incorrect indexing of `__state->stack` for outgoing stack arguments in the…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Incorrect indexing of __state->stack for outgoing stack arguments in the bpf_for_each_reg_in_vstate_mask macro leads to out-of-bounds heap access and potential memory corruption. --
commit 936dee8aae85e40857f1379da85e7a73536e2261
Author: Amery Hung <[email protected]>
bpf: Refactor object relationship tracking and fix dynptr UAF bug
This commit refactors object relationship tracking in the verifier and fixes a dynptr use-after-free bug where file/skb dynptrs are not invalidated when the parent referenced object is freed.
Quoted 4 lines
include/linux/bpf_verifier.h +0
-0
[ ... ]
Quoted 9 lines
include/linux/bpf_verifier.h +1
-1@@ -585,7 +591,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) iter < frame->out_stack_arg_cnt; \ iter++, reg = bpf_get_spilled_stack_arg(iter, frame)) -#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __mask, __expr) \ +#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __stack, __mask, __expr) \ ({ \ struct bpf_verifier_state *___vstate = __vst; \ int ___i, ___j; \
[ ... ]
include/linux/bpf_verifier.h bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) · line 616
Quoted 11 lines
include/linux/bpf_verifier.h +2
-0@@ -600,19 +607,26 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \ (void )(__expr); \ } \ bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \
[Severity: Critical]
Is it safe to index the stack array using the out_stack_arg_cnt index here?
In the bpf_for_each_spilled_stack_arg loop, ___j represents the index into the stack_arg_regs array, which is bounded by out_stack_arg_cnt. However, this line sets __stack = &__state->stack[___j], which indexes the local function stack array (bounded by allocated_stack / BPF_REG_SIZE).
Since a BPF program can push stack arguments without allocating a local stack, ___j might exceed the local stack size, computing an out-of-bounds pointer.
When release_reference() iterates over these registers, it evaluates stack->slot_type[BPF_REG_SIZE - 1], which reads out-of-bounds memory. If this memory coincidentally contains the value for STACK_DYNPTR (2), could this result in invalidate_dynptr() being called erroneously, writing STACK_INVALID across multiple slots and corrupting adjacent kernel memory?
Quoted 4 lines
include/linux/bpf_verifier.h +0
-0(void )(__expr); \ } \ } \ })
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Re: [PATCH bpf-next v5 05/14] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Quoted 57 lines · On Tue, May 19, 2026 at 11:45 AM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Incorrect indexing of__state->stackfor outgoing stack arguments in thebpf_for_each_reg_in_vstate_maskmacro leads to out-of-bounds heap access and potential memory corruption. --commit
936dee8aae85e40857f1379da85e7a73536e2261
Author: Amery Hung <[email protected]>bpf: Refactor object relationship tracking and fix dynptr UAF bug
This commit refactors object relationship tracking in the verifier and fixes a dynptr use-after-free bug where file/skb dynptrs are not invalidated when the parent referenced object is freed.
Quoted 4 lines
include/linux/bpf_verifier.h +0
-0[ ... ]
Quoted 9 lines
include/linux/bpf_verifier.h +1
-1@@ -585,7 +591,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) iter < frame->out_stack_arg_cnt; \ iter++, reg = bpf_get_spilled_stack_arg(iter, frame)) -#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __mask, __expr) \ +#define bpf_for_each_reg_in_vstate_mask (__vst, __state, __reg, __stack, __mask, __expr) \ ({ \ struct bpf_verifier_state *___vstate = __vst; \ int ___i, ___j; \[ ... ]
include/linux/bpf_verifier.h bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) · line 616
Quoted 11 lines
include/linux/bpf_verifier.h +2
-0@@ -600,19 +607,26 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \ (void )(__expr); \ } \ bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \if (!__reg) \continue ; \ + __stack = &__state->stack[___j]; \[Severity: Critical]
Is it safe to index the stack array using theout_stack_arg_cntindex here?In the
bpf_for_each_spilled_stack_argloop,___jrepresents the index into thestack_arg_regsarray, which is bounded byout_stack_arg_cnt. However, this line sets__stack= &__state->stack[___j], which indexes the local function stack array (bounded byallocated_stack/BPF_REG_SIZE).Since a BPF program can push stack arguments without allocating a local stack,
___jmight exceed the local stack size, computing an out-of-bounds pointer.
Quoted 6 lines
When
release_reference()iterates over these registers, it evaluates stack->slot_type[BPF_REG_SIZE - 1], which reads out-of-bounds memory. If this memory coincidentally contains the value forSTACK_DYNPTR(2), could this result ininvalidate_dynptr()being called erroneously, writingSTACK_INVALIDacross multiple slots and corrupting adjacent kernel memory?
Right. I should set __stack to NULL in for stack args.
Quoted 8 lines
include/linux/bpf_verifier.h bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) · line 620
Quoted 5 lines
include/linux/bpf_verifier.h +0
-0(void )(__expr); \ } \ } \ })--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Eduard Zingerman
maintainerRe: [PATCH bpf-next v5 05/14] bpf: Refactor object relationship tracking and fix dynptr UAF bug
In reply to Amery HungOn Tue, 2026-05-19 at 11:13 -0700, Amery Hung wrote:
[...]
Quoted 14 lines
kernel/bpf/verifier.c +0
-0@@ -202,7 +202,7 @@ struct bpf_verifier_stack_elem {
static intacquire_reference(struct bpf_verifier_env *env, int insn_idx); static intrelease_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);kernel/bpf/verifier.c +1
-1-static int release_reference (struct bpf_verifier_env *env,int ref_obj_id); +static int release_reference (struct bpf_verifier_env *env,int id);static void
invalidate_non_owning_refs(struct bpf_verifier_env *env); static boolin_rbtree_lock_required_cb(struct bpf_verifier_env *env); static int ref_set_non_owning(structbpf_verifier_env*env,
kernel/bpf/verifier.c struct bpf_call_arg_meta { · line 245
Quoted 4 lines
kernel/bpf/verifier.c +1
-0@@ -242,6 +242,7 @@ struct bpf_call_arg_meta { int mem_size; u64 msize_max_value; int ref_obj_id; +u32 id;
Is this one used anywhere?
Quoted 3 lines
kernel/bpf/verifier.c +0
-0int func_id; struct btf *btf; u32 btf_id;
[...]
kernel/bpf/verifier.c static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, · line 845
Quoted 8 lines
kernel/bpf/verifier.c +0
-1@@ -839,34 +806,20 @@ static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, verbose(env, "cannot overwrite referenced dynptr\n"); return -EINVAL; } - }kernel/bpf/verifier.c +0
-2-mark_stack_slot_scratched (env, spi); -mark_stack_slot_scratched (env, spi -1 );
Nit: no need to move mark_stack_slot_scratched().
Quoted 36 lines
kernel/bpf/verifier.c +4
-4-/* Writing partially to one dynptr stack slot destroys both. */ -for (i =0 ; i <BPF_REG_SIZE ; i++) { - state->stack[spi].slot_type[i] =STACK_INVALID ; - state->stack[spi -1 ].slot_type[i] =STACK_INVALID ; +invalidate_dynptr (env, &state->stack[spi -1 ]); + }else { +/* Invalidate the dynptr and any derived slices */ + err =release_reference (env, state->stack[spi].spilled_ptr.id);}
kernel/bpf/verifier.c +4
-15- dynptr_id = state->stack[spi].spilled_ptr.id; -/* Invalidate any slices associated with this dynptr */ -bpf_for_each_reg_in_vstate (env->cur_state, fstate, dreg, ({ -/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ -if (dreg->type != (PTR_TO_MEM |PTR_MAYBE_NULL ) && dreg->type !=PTR_TO_MEM ) -continue ; -if (dreg->dynptr_id == dynptr_id) -mark_reg_invalid (env, dreg); - })); - -/* Do not release reference state, we are destroying dynptr on stack, -* not using some helper to release it. Just reset register. -*/ -bpf_mark_reg_not_init (env, &state->stack[spi].spilled_ptr); -bpf_mark_reg_not_init (env, &state->stack[spi -1 ].spilled_ptr); +if (!err) { +mark_stack_slot_scratched (env, spi); +mark_stack_slot_scratched (env, spi -1 ); + }kernel/bpf/verifier.c +1
-1-return 0 ; +return err;}
static boolis_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
[...]
Quoted 48 lines
kernel/bpf/verifier.c +0
-0@@ -8908,26 +8870,76 @@ static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob return -EINVAL; }kernel/bpf/verifier.c +19
-6-/* The pointer with the specified id has released its reference to kernel -* resources. Identify all copies of the same pointer and clear the reference. -* -* This is the release function corresponding to acquire_reference(). Idempotent. -*/ -static int release_reference (struct bpf_verifier_env *env,int ref_obj_id) +static int idstack_push (struct bpf_idmap *idmap,u32 id) +{ +int i; + +if (!id) +return 0 ; + +for (i =0 ; i < idmap->cnt; i++) +if (idmap->map[i].old == id) +return 0 ; + +if (WARN_ON_ONCE (idmap->cnt >=BPF_ID_MAP_SIZE )) +return -EFAULT ; + + idmap->map[idmap->cnt++].old = id; +return 0 ; +} + +static int idstack_pop (struct bpf_idmap *idmap){
kernel/bpf/verifier.c +10
-0+if (!idmap->cnt) +return 0 ; + +return idmap->map[--idmap->cnt].old; +} + +/* Release id and objects referencing the id iteratively in a DFS manner */ +static int release_reference (struct bpf_verifier_env *env,int id) +{ +u32 mask = (1 <<STACK_SPILL ) | (1 <<STACK_DYNPTR );struct
bpf_verifier_state*vstate =env->cur_state;kernel/bpf/verifier.c +2
-0+struct bpf_idmap *idstack = &env->idmap_scratch; +struct bpf_stack_state *stack;struct
bpf_func_state*state;
structbpf_reg_state*reg;kernel/bpf/verifier.c +1
-1-int err; +int root_id = id, err;
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8911
Quoted 5 lines
kernel/bpf/verifier.c +2
-3- err =release_reference_nomark (vstate, ref_obj_id); -if (err) -return err; + idstack->cnt =0 ; +idstack_push (idstack, id);
Nit: check error code or drop error path from idstack_push?
Quoted 10 lines
kernel/bpf/verifier.c +5
-4-bpf_for_each_reg_in_vstate (vstate, state, reg, ({ -if (reg->ref_obj_id == ref_obj_id) -mark_reg_invalid (env, reg); - })); +if (find_reference_state (vstate, id)) +WARN_ON_ONCE (release_reference_nomark (vstate, id)); + +while ((id =idstack_pop (idstack))) { + bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8927
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+if (reg->id != id && reg->parent_id != id && reg->ref_obj_id != id) +continue ; + +if (reg->ref_obj_id && reg->ref_obj_id != root_id) { +struct bpf_reference_state *ref_state; + + ref_state =find_reference_state (env->cur_state, reg->ref_obj_id); +verbose (env,"Leaking reference id=%d alloc_insn=%d. Release it first.\n" , + ref_state->id, ref_state->insn_idx); +return -EINVAL ;
Thinking some more about it, the mere presence of dangling objects with the same lifetime is not an error. The error would happen if such objects are accessed. Should the verifier invalidate such dangling objects instead of signaling an error immediately?
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8931
Quoted 4 lines
kernel/bpf/verifier.c +4
-0+ } + +/* Free objects derived from the current object */ +if (reg->id != id) {
I think this should be changed to reg->parent_id == id, otherwise the reader has to infer that from the logical expression:
!(reg->id != id && reg->parent_id != id && reg->ref_obj_id != id) && !(reg->ref_obj_id && reg->ref_obj_id != root_id) && (reg->id != id)
Quoted 14 lines
kernel/bpf/verifier.c +11
-0+ err =idstack_push (idstack, reg->id); +if (err) +return err; + } + +if (!stack || stack->slot_type[BPF_REG_SIZE -1 ] ==STACK_SPILL ) +mark_reg_invalid (env, reg); +else if (stack->slot_type[BPF_REG_SIZE -1 ] ==STACK_DYNPTR ) +invalidate_dynptr (env, stack); + })); + }
return 0;
}
[...]
Re: [PATCH bpf-next v5 05/14] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Quoted 11 lines · Eduard Zingerman
On Tue, 2026-05-19 at 11:13 -0700, Amery Hung wrote:
[...]
Quoted 6 lines
kernel/bpf/verifier.c +0
-0@@ -202,7 +202,7 @@ struct bpf_verifier_stack_elem {
Quoted 14 lines
kernel/bpf/verifier.c struct bpf_call_arg_meta { · line 245
Quoted 12 lines
kernel/bpf/verifier.c +2
-1static int acquire_reference (struct bpf_verifier_env *env,int insn_idx);static int release_reference_nomark (struct bpf_verifier_state *state,int ref_obj_id); -static int release_reference (struct bpf_verifier_env *env,int ref_obj_id); +static int release_reference (struct bpf_verifier_env *env,int id);static void invalidate_non_owning_refs (struct bpf_verifier_env *env);static bool in_rbtree_lock_required_cb (struct bpf_verifier_env *env); static int ref_set_non_owning(struct bpf_verifier_env *env,@@ -242,6 +242,7 @@ struct bpf_call_arg_meta {int mem_size;u64 msize_max_value;int ref_obj_id; +u32 id;Is this one used anywhere?
Yes. check_func_arg() will record meta->id and meta->ref_obj_id if reg has ref_obj_id.
Quoted 13 lines
Quoted 4 lines
kernel/bpf/verifier.c +0
-0int func_id;struct btf *btf;u32 btf_id;[...]
Quoted 6 lines
kernel/bpf/verifier.c +0
-1@@ -839,34 +806,20 @@ static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,verbose (env,"cannot overwrite referenced dynptr\n" );return -EINVAL ; } - }
Quoted 4 lines
kernel/bpf/verifier.c static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, · line 845
Quoted 2 lines
kernel/bpf/verifier.c +0
-2-mark_stack_slot_scratched (env, spi); -mark_stack_slot_scratched (env, spi -1 );Nit: no need to move
mark_stack_slot_scratched().
Ack.
Quoted 88 lines
Quoted 37 lines
kernel/bpf/verifier.c +9
-20-/* Writing partially to one dynptr stack slot destroys both. */ -for (i =0 ; i <BPF_REG_SIZE ; i++) { - state->stack[spi].slot_type[i] =STACK_INVALID ; - state->stack[spi -1 ].slot_type[i] =STACK_INVALID ; +invalidate_dynptr (env, &state->stack[spi -1 ]); + }else { +/* Invalidate the dynptr and any derived slices */ + err =release_reference (env, state->stack[spi].spilled_ptr.id); } - dynptr_id = state->stack[spi].spilled_ptr.id; -/* Invalidate any slices associated with this dynptr */ -bpf_for_each_reg_in_vstate (env->cur_state, fstate, dreg, ({ -/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ -if (dreg->type != (PTR_TO_MEM |PTR_MAYBE_NULL ) && dreg->type !=PTR_TO_MEM ) -continue ; -if (dreg->dynptr_id == dynptr_id) -mark_reg_invalid (env, dreg); - })); - -/* Do not release reference state, we are destroying dynptr on stack, -* not using some helper to release it. Just reset register. -*/ -bpf_mark_reg_not_init (env, &state->stack[spi].spilled_ptr); -bpf_mark_reg_not_init (env, &state->stack[spi -1 ].spilled_ptr); +if (!err) { +mark_stack_slot_scratched (env, spi); +mark_stack_slot_scratched (env, spi -1 ); + } -return 0 ; +return err; }static bool is_dynptr_reg_valid_uninit (struct bpf_verifier_env *env,struct bpf_reg_state *reg)[...]
Quoted 48 lines
kernel/bpf/verifier.c +32
-7@@ -8908,26 +8870,76 @@ static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obreturn -EINVAL ; } -/* The pointer with the specified id has released its reference to kernel -* resources. Identify all copies of the same pointer and clear the reference. -* -* This is the release function corresponding to acquire_reference(). Idempotent. -*/ -static int release_reference (struct bpf_verifier_env *env,int ref_obj_id) +static int idstack_push (struct bpf_idmap *idmap,u32 id) +{ +int i; + +if (!id) +return 0 ; + +for (i =0 ; i < idmap->cnt; i++) +if (idmap->map[i].old == id) +return 0 ; + +if (WARN_ON_ONCE (idmap->cnt >=BPF_ID_MAP_SIZE )) +return -EFAULT ; + + idmap->map[idmap->cnt++].old = id; +return 0 ; +} + +static int idstack_pop (struct bpf_idmap *idmap) { +if (!idmap->cnt) +return 0 ; + +return idmap->map[--idmap->cnt].old; +} + +/* Release id and objects referencing the id iteratively in a DFS manner */ +static int release_reference (struct bpf_verifier_env *env,int id) +{ +u32 mask = (1 <<STACK_SPILL ) | (1 <<STACK_DYNPTR );struct bpf_verifier_state *vstate = env->cur_state; +struct bpf_idmap *idstack = &env->idmap_scratch; +struct bpf_stack_state *stack;struct bpf_func_state *state;struct bpf_reg_state *reg; -int err; +int root_id = id, err;
Quoted 7 lines
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8911
Quoted 5 lines
kernel/bpf/verifier.c +2
-3- err =release_reference_nomark (vstate, ref_obj_id); -if (err) -return err; + idstack->cnt =0 ; +idstack_push (idstack, id);Nit: check error code or drop error path from
idstack_push?
Ack.
Quoted 18 lines
Quoted 18 lines
kernel/bpf/verifier.c +12
-4-bpf_for_each_reg_in_vstate (vstate, state, reg, ({ -if (reg->ref_obj_id == ref_obj_id) -mark_reg_invalid (env, reg); - })); +if (find_reference_state (vstate, id)) +WARN_ON_ONCE (release_reference_nomark (vstate, id)); + +while ((id =idstack_pop (idstack))) { + bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ + if (reg->id != id && reg->parent_id != id && reg->ref_obj_id != id) + continue; + + if (reg->ref_obj_id && reg->ref_obj_id != root_id) { + struct bpf_reference_state *ref_state; + + ref_state = find_reference_state(env->cur_state, reg->ref_obj_id);
Quoted 8 lines
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8927
Quoted 3 lines
kernel/bpf/verifier.c +3
-0+verbose (env,"Leaking reference id=%d alloc_insn=%d. Release it first.\n" , + ref_state->id, ref_state->insn_idx); +return -EINVAL ;Thinking some more about it, the mere presence of dangling objects with the same lifetime is not an error. The error would happen if such objects are accessed. Should the verifier invalidate such dangling objects instead of signaling an error immediately?
I think the verifier should not allow it. This could lead to resource leak if there were kernel resources associated with the reference.
Quoted 6 lines
kernel/bpf/verifier.c static int release_reference_nomark(struct bpf_verifier_state *state, int ref_ob · line 8931
Quoted 5 lines
kernel/bpf/verifier.c +4
-0+ } + +/* Free objects derived from the current object */ +if (reg->id != id) {
Quoted 6 lines
I think this should be changed to
reg->parent_id == id, otherwise the reader has to infer that from the logical expression:!(reg->id != id && reg->parent_id != id && reg->ref_obj_id != id) && !(reg->ref_obj_id && reg->ref_obj_id != root_id) && (reg->id != id)
Make sense. This is more straightforward to read.
Quoted 17 lines
Quoted 15 lines
kernel/bpf/verifier.c +11
-0+ err =idstack_push (idstack, reg->id); +if (err) +return err; + } + +if (!stack || stack->slot_type[BPF_REG_SIZE -1 ] ==STACK_SPILL ) +mark_reg_invalid (env, reg); +else if (stack->slot_type[BPF_REG_SIZE -1 ] ==STACK_DYNPTR ) +invalidate_dynptr (env, stack); + })); + }return 0 ; }[...]
PATCH v5 6/14 bpf: Remove redundant dynptr arg check for helper
In reply to Amery Hungunmark_stack_slots_dynptr() already makes sure that CONST_PTR_TO_DYNPTR cannot be released. process_dynptr_func() also prevents passing uninitialized dynptr to helpers expecting initialized dynptr. Now that unmark_stack_slots_dynptr() also reports error returned from release_reference(), there should be no reason to keep these redundant checks.
--- kernel/bpf/verifier.c | 21 +------------------ .../testing/selftests/bpf/progs/dynptr_fail.c | 6 +++--- .../selftests/bpf/progs/user_ringbuf_fail.c | 4 ++-- 3 files changed, 6 insertions(+), 25 deletions(-)
kernel/bpf/verifier.c +1 -20
@@ -8205,26 +8205,7 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, skip_type_check:if (arg_type_is_release (arg_type)) { -if (arg_type_is_dynptr (arg_type)) { -struct bpf_func_state *state =bpf_func (env, reg); -int spi; - -/* Only dynptr created on stack can be released, thus -* the get_spi and stack state checks for spilled_ptr -* should only be done before process_dynptr_func for -* PTR_TO_STACK. -*/ -if (reg->type ==PTR_TO_STACK ) { - spi =dynptr_get_spi (env, reg); -if (spi <0 || !state->stack[spi].spilled_ptr.id) { -verbose (env,"arg %d is an unacquired reference\n" , regno); -return -EINVAL ; - } - }else { -verbose (env,"cannot release unowned const bpf_dynptr\n" ); -return -EINVAL ; - } - }else if (!reg->ref_obj_id && !bpf_register_is_null (reg)) { +if (!arg_type_is_dynptr (arg_type) && !reg->ref_obj_id && !bpf_register_is_null (reg)) {verbose (env,"R%d must be referenced when passed to release function\n" , regno);return -EINVAL ;
tools/testing/selftests/bpf/progs/dynptr_fail.c +3 -3
@@ -136,7 +136,7 @@ int ringbuf_missing_release_callback(void *ctx)/* Can't call bpf_ringbuf_submit/discard_dynptr on a non-initialized dynptr */ SEC("?raw_tp") -__failure __msg("arg 1 is an unacquired reference") +__failure __msg("Expected an initialized dynptr as R1")int ringbuf_release_uninit_dynptr (void *ctx) {struct bpf_dynptr ptr;
@@ -650,7 +650,7 @@ int invalid_offset(void *ctx)/* Can't release a dynptr twice */ SEC("?raw_tp") -__failure __msg("arg 1 is an unacquired reference") +__failure __msg("Expected an initialized dynptr as R1")int release_twice (void *ctx) {struct bpf_dynptr ptr;
@@ -677,7 +677,7 @@ static int release_twice_callback_fn(__u32 index, void *data)* within a callback function, fails */ SEC("?raw_tp") -__failure __msg("arg 1 is an unacquired reference") +__failure __msg("Expected an initialized dynptr as R1")int release_twice_callback (void *ctx) {struct bpf_dynptr ptr;
tools/testing/selftests/bpf/progs/user_ringbuf_fail.c +2 -2
@@ -146,7 +146,7 @@ try_discard_dynptr(struct bpf_dynptr *dynptr, void *context)* not be able to read past the end of the pointer. */ SEC("?raw_tp") -__failure __msg("cannot release unowned const bpf_dynptr") +__failure __msg("CONST_PTR_TO_DYNPTR cannot be released")int user_ringbuf_callback_discard_dynptr (void *ctx) {bpf_user_ringbuf_drain (&user_ringbuf, try_discard_dynptr,NULL ,0 );
@@ -166,7 +166,7 @@ try_submit_dynptr(struct bpf_dynptr *dynptr, void *context)* not be able to read past the end of the pointer. */ SEC("?raw_tp") -__failure __msg("cannot release unowned const bpf_dynptr") +__failure __msg("CONST_PTR_TO_DYNPTR cannot be released")int user_ringbuf_callback_submit_dynptr (void *ctx) {bpf_user_ringbuf_drain (&user_ringbuf, try_submit_dynptr,NULL ,0 );
Signature · 1 line
2.53.0-Meta
PATCH v5 7/14 bpf: Unify referenced object tracking in verifier
In reply to Amery HungHelpers and kfuncs independently tracked referenced object metadata (id, ref_obj_id) using separate fields in their respective arg_meta structs. This led to duplicated logic and inconsistent error handling between the two paths.
Introduce struct ref_obj_desc to consolidate these fields along with a count of how many arguments carry a reference. Add update_ref_obj() to populate it from a bpf_reg_state, replacing open-coded assignments in check_func_arg(), check_kfunc_args(), and process_iter_arg(). Add validate_ref_obj() to check for ambiguous ref_obj before using it.
For ref_obj releasing helpers and kfuncs, keep checking it before calling update_ref_obj() for now. A later patch will make these functions not depending on ref_obj. For other users of ref_obj, move the checks to the use locations. For helper, this means moving the checks inside helper_multiple_ref_obj_use() to use locations. is_acquire_function() is dropped as ref_obj is never used.
Pass ref_obj_desc into process_dynptr_func()/mark_stack_slots_dynptr() instead of a bare parent_id to make it less confusing.
Drop the selftest introduced in 7ec899ac90a2 (“selftests/bpf: Negative test case for ref_obj_id in args”) since the verifier no longer complains about ambiguous ref_obj if it is not used.
--- include/linux/bpf_verifier.h | 15 ++- kernel/bpf/verifier.c | 118 +++++++++--------- .../bpf/progs/test_ringbuf_map_key.c | 11 +- tools/testing/selftests/bpf/verifier/calls.c | 24 ---- 4 files changed, 78 insertions(+), 90 deletions(-)
include/linux/bpf_verifier.h +13 -2
@@ -1458,6 +1458,18 @@ struct bpf_dynptr_desc {u32 parent_id; }; +/* +* The last seen rereferenced object; Updated by update_ref_obj() when a register refers to a +* referenced object. Used when the helper or kfunc is releasing a referenced object, casting +* a referenced object, returning allocated memory derived from referenced object or creating +* a dynptr with a referenced object as parent. +*/ +struct ref_obj_desc { +u32 id; +u32 ref_obj_id; +u8 cnt; +}; +struct bpf_kfunc_call_arg_meta {/* In parameters */ struct btf *btf;
@@ -1466,8 +1478,6 @@ struct bpf_kfunc_call_arg_meta {const struct btf_type *func_proto;const char *func_name;/* Out parameters */ -u32 ref_obj_id; -u32 id;u8 release_regno;bool r0_rdonly;u32 ret_btf_id;
@@ -1505,6 +1515,7 @@ struct bpf_kfunc_call_arg_meta { } iter;struct bpf_map_desc map;struct bpf_dynptr_desc dynptr; +struct ref_obj_desc ref_obj;u64 mem_size; };
kernel/bpf/verifier.c +62 -56
256 lines not on this page · raw message
tools/testing/selftests/bpf/progs/test_ringbuf_map_key.c +3 -8
@@ -35,7 +35,7 @@ SEC("fentry/" SYS_PREFIX "sys_getpgid")int test_ringbuf_mem_map_key (void *ctx) {int cur_pid =bpf_get_current_pid_tgid () >>32 ; -struct sample *sample, sample_copy; +struct sample *sample;int *lookup_val;if (cur_pid != pid)
@@ -55,16 +55,11 @@ int test_ringbuf_mem_map_key(void *ctx) lookup_val = (int *)bpf_map_lookup_elem (&hash_map, sample);__sink (lookup_val); -/* workaround - memcpy is necessary so that verifier doesn't -* complain with: -* verifier internal error: more than one arg with ref_obj_id R3 -* when trying to do bpf_map_update_elem(&hash_map, sample, &sample->seq, BPF_ANY); -* +/* * Since bpf_map_lookup_elem above uses 'sample' as key, test using * sample field as value below */ -__builtin_memcpy (&sample_copy, sample,sizeof (struct sample )); -bpf_map_update_elem (&hash_map, &sample_copy, &sample->seq,BPF_ANY ); +bpf_map_update_elem (&hash_map, sample, &sample->seq,BPF_ANY );bpf_ringbuf_submit (sample,0 );return 0 ;
tools/testing/selftests/bpf/verifier/calls.c +0 -24
@@ -2410,27 +2410,3 @@ .errstr_unpriv = "", .prog_type = BPF_PROG_TYPE_CGROUP_SKB, }, -{ - "calls: several args with ref_obj_id", - .insns = { -/* Reserve at least sizeof(struct iphdr) bytes in the ring buffer. -* With a smaller size, the verifier would reject the call to -* bpf_tcp_raw_gen_syncookie_ipv4 before we can reach the -* ref_obj_id error. -*/ -BPF_MOV64_IMM (BPF_REG_2 ,20 ), -BPF_MOV64_IMM (BPF_REG_3 ,0 ), -BPF_LD_MAP_FD (BPF_REG_1 ,0 ), -BPF_RAW_INSN (BPF_JMP |BPF_CALL ,0 ,0 ,0 , BPF_FUNC_ringbuf_reserve), -/* if r0 == 0 goto <exit> */ -BPF_JMP_IMM (BPF_JEQ ,BPF_REG_0 ,0 ,3 ), -BPF_MOV64_REG (BPF_REG_1 ,BPF_REG_0 ), -BPF_MOV64_REG (BPF_REG_2 ,BPF_REG_0 ), -BPF_RAW_INSN (BPF_JMP |BPF_CALL ,0 ,0 ,0 , BPF_FUNC_tcp_raw_gen_syncookie_ipv4), - BPF_EXIT_INSN(), - }, - .fixup_map_ringbuf = { 2 }, - .result = REJECT, - .errstr = "more than one arg with ref_obj_id", - .prog_type = BPF_PROG_TYPE_SCHED_CLS, -},
Signature · 1 line
2.53.0-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v5 07/14] bpf: Unify referenced object tracking in verifier
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Unused legacy fields `ref_obj_id` and `id` remain in `struct bpf_call_arg_meta`. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Unused legacy fields ref_obj_id and id remain in struct bpf_call_arg_meta. --
commit ff3476feb916076d44d843f726cd0727a0a067bc
Author: Amery Hung <[email protected]>
bpf: Unify referenced object tracking in verifier
This commit unifies referenced object tracking in the verifier by introducing struct ref_obj_desc to consolidate the id and ref_obj_id fields. It updates kfuncs and helpers to use this shared structure, replacing open-coded updates with shared helper functions.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 6 lines
kernel/bpf/verifier.c +2
-0@@ -231,9 +231,28 @@ static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) (poisoned ?BPF_MAP_KEY_POISON :0ULL ); } +static void update_ref_obj (struct ref_obj_desc *ref_obj,struct bpf_reg_state *reg) +{
[ ... ]
kernel/bpf/verifier.c static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) · line 258
Quoted 7 lines
struct
bpf_call_arg_meta{kernel/bpf/verifier.c +1
-0struct bpf_map_desc map;struct bpf_dynptr_desc dynptr; +struct ref_obj_desc ref_obj;bool raw_mode;bool pkt_access;u8 release_regno;
[Severity: Low]
Since this patch consolidates id and ref_obj_id into the new ref_obj field, should the legacy ref_obj_id and id fields be removed from struct bpf_call_arg_meta as well?
Looking at the rest of struct bpf_call_arg_meta, it appears these old fields were successfully removed from struct bpf_kfunc_call_arg_meta but were left behind here.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH bpf-next v5 07/14] bpf: Unify referenced object tracking in verifier
Quoted 39 lines · On Tue, May 19, 2026 at 11:55 AM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Unused legacy fieldsref_obj_idandidremain instruct bpf_call_arg_meta. --commit
ff3476feb916076d44d843f726cd0727a0a067bc
Author: Amery Hung <[email protected]>bpf: Unify referenced object tracking in verifier
This commit unifies referenced object tracking in the verifier by introducing struct
ref_obj_descto consolidate the id andref_obj_idfields. It updates kfuncs and helpers to use this shared structure, replacing open-coded updates with shared helper functions.Quoted 4 lines
kernel/bpf/verifier.c +0
-0[ ... ]
Quoted 6 lines
kernel/bpf/verifier.c +2
-0@@ -231,9 +231,28 @@ static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) (poisoned ?BPF_MAP_KEY_POISON :0ULL ); } +static void update_ref_obj (struct ref_obj_desc *ref_obj,struct bpf_reg_state *reg) +{[ ... ]
Quoted 7 lines
struct bpf_call_arg_meta { struct bpf_map_desc map; struct bpf_dynptr_desc dynptr; + struct ref_obj_desc ref_obj; bool raw_mode; bool pkt_access; u8 release_regno;
Quoted 9 lines
[Severity: Low]
Since this patch consolidates id andref_obj_idinto the newref_objfield, should the legacyref_obj_idand id fields be removed from structbpf_call_arg_metaas well?Looking at the rest of struct
bpf_call_arg_meta, it appears these old fields were successfully removed from structbpf_kfunc_call_arg_metabut were left behind here.
Right. bpf_call_arg_meta::id should be removed as part of this patch.
Quoted 2 lines
--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH bpf-next v5 07/14] bpf: Unify referenced object tracking in verifier
In reply to Amery HungQuoted 21 lines · Amery Hung
Helpers and kfuncs independently tracked referenced object metadata (id,
ref_obj_id) using separate fields in their respectivearg_metastructs. This led to duplicated logic and inconsistent error handling between the two paths.Introduce struct
ref_obj_descto consolidate these fields along with a count of how many arguments carry a reference. Addupdate_ref_obj()to populate it from abpf_reg_state, replacing open-coded assignments incheck_func_arg(),check_kfunc_args(), andprocess_iter_arg(). Addvalidate_ref_obj()to check for ambiguousref_objbefore using it.For
ref_objreleasing helpers and kfuncs, keep checking it before callingupdate_ref_obj()for now. A later patch will make these functions not depending onref_obj. For other users ofref_obj, move the checks to the use locations. For helper, this means moving the checks insidehelper_multiple_ref_obj_use()to use locations.is_acquire_function()is dropped asref_objis never used.Pass
ref_obj_descinto process_dynptr_func()/mark_stack_slots_dynptr() instead of a bareparent_idto make it less confusing.
Quoted 6 lines
Drop the selftest introduced in
7ec899ac90a2(“selftests/bpf: Negative test case forref_obj_idin args”) since the verifier no longer complains about ambiguousref_objif it is not used.Signed-off-by Amery Hung <[email protected]>---
[...]
PATCH v5 8/14 bpf: Unify release handling for helpers and kfuncs
In reply to Amery HungIntroduce release_reg() to consolidate the release logic shared by both helpers and kfuncs: dynptr release, kptr_xchg percpu-to-RCU conversion, regular reference release, and NULL pass-through. NULL pass-through is only allowed if the prototype indicates the argument may be null.
Determine release_regno from the function prototype/metadata before argument checking, rather than discovering it dynamically during argument processing. For helpers, scan the arg_type array in check_func_proto() via check_proto_release_reg(). For kfuncs, set release_regno to BPF_REG_1 in bpf_fetch_kfunc_arg_meta() when KF_RELEASE is set. In the future when we start adding decl_tag to kfunc arguments, we can just look at the function prototype instead of a release_regno.
Extract ref_convert_alloc_rcu_protected() and invalidate_rcu_protected_refs() to make it more clear what the code is doing. For ref_convert_alloc_rcu_protected(), it pre-converts MEM_ALLOC | MEM_PERCPU registers to MEM_RCU (clearing ref_obj_id so they survive), then calls release_reference() to invalidate the remaining registers and release the reference state.
Add KF_RELEASE to bpf_dynptr_file_discard() so its release_regno is set via fetch_kfunc_meta rather than being assigned manually in the dynptr argument processing. Set arg_type to ARG_PTR_TO_DYNPTR for KF_ARG_PTR_TO_DYNPTR so that check_func_arg_reg_off() correctly allows non-zero stack offsets for dynptr release arguments same as helper.
--- include/linux/bpf_verifier.h | 6 +- kernel/bpf/helpers.c | 2 +- kernel/bpf/verifier.c | 206 +++++++++--------- .../selftests/bpf/prog_tests/cb_refs.c | 2 +- .../selftests/bpf/progs/cgrp_kfunc_failure.c | 6 +- .../selftests/bpf/progs/map_kptr_fail.c | 2 +- .../selftests/bpf/progs/task_kfunc_failure.c | 6 +- .../bpf/progs/verifier_global_ptr_args.c | 2 +- .../bpf/progs/verifier_ref_tracking.c | 2 +- .../selftests/bpf/progs/verifier_sock.c | 6 +- .../selftests/bpf/progs/verifier_vfs_reject.c | 2 +- 11 files changed, 121 insertions(+), 121 deletions(-)
include/linux/bpf_verifier.h +3 -3
@@ -1460,9 +1460,9 @@ struct bpf_dynptr_desc {/* * The last seen rereferenced object; Updated by update_ref_obj() when a register refers to a -* referenced object. Used when the helper or kfunc is releasing a referenced object, casting -* a referenced object, returning allocated memory derived from referenced object or creating -* a dynptr with a referenced object as parent. +* referenced object. Used when the helper or kfunc is casting a referenced object, returning +* allocated memory derived from referenced object or creating a dynptr with a referenced +* object as parent. */ struct ref_obj_desc {u32 id;
kernel/bpf/helpers.c +1 -1
@@ -4857,7 +4857,7 @@ BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_dynptr_from_file) -BTF_ID_FLAGS(func, bpf_dynptr_file_discard) +BTF_ID_FLAGS(func, bpf_dynptr_file_discard, KF_RELEASE) BTF_ID_FLAGS(func, bpf_timer_cancel_async)BTF_KFUNCS_END (common_btf_ids)
kernel/bpf/verifier.c +103 -103
315 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/cb_refs.c +1 -1
@@ -11,7 +11,7 @@ struct {const char *prog_name;const char *err_msg; } cb_refs_tests[] = { - { "underflow_prog", "must point to scalar, or struct with scalar" }, + { "underflow_prog", "release kfunc bpf_kfunc_call_test_release expects referenced PTR_TO_BTF_ID passed to R1" }, { "leak_prog", "Possibly NULL pointer passed to helper R2" }, { "nested_cb", "Unreleased reference id=4 alloc_insn=2" }, /* alloc_insn=2{4,5} */ { "non_cb_transfer_ref", "Unreleased reference id=4 alloc_insn=1" }, /* alloc_insn=1{1,2} */
tools/testing/selftests/bpf/progs/cgrp_kfunc_failure.c +3 -3
@@ -154,7 +154,7 @@ int BPF_PROG(cgrp_kfunc_xchg_unreleased, struct cgroup *cgrp, const char *path) } SEC("tp_btf/cgroup_mkdir") -__failure __msg("must be referenced or trusted") +__failure __msg("release kfunc bpf_cgroup_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(cgrp_kfunc_rcu_get_release, struct cgroup *cgrp, const char *path) {struct cgroup *kptr;
@@ -191,7 +191,7 @@ int BPF_PROG(cgrp_kfunc_release_untrusted, struct cgroup *cgrp, const char *path } SEC("tp_btf/cgroup_mkdir") -__failure __msg("R1 pointer type STRUCT cgroup must point") +__failure __msg("release kfunc bpf_cgroup_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(cgrp_kfunc_release_fp, struct cgroup *cgrp, const char *path) {struct cgroup *acquired = (struct cgroup *)&path;
@@ -237,7 +237,7 @@ int BPF_PROG(cgrp_kfunc_release_null, struct cgroup *cgrp, const char *path) } SEC("tp_btf/cgroup_mkdir") -__failure __msg("release kernel function bpf_cgroup_release expects") +__failure __msg("release kfunc bpf_cgroup_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(cgrp_kfunc_release_unacquired, struct cgroup *cgrp, const char *path) {/* Cannot release trusted cgroup pointer which was not acquired. */
tools/testing/selftests/bpf/progs/map_kptr_fail.c +1 -1
@@ -252,7 +252,7 @@ int reject_untrusted_store_to_ref(struct __sk_buff *ctx) } SEC("?tc") -__failure __msg("R2 must be referenced") +__failure __msg("release helper bpf_kptr_xchg expects referenced PTR_TO_BTF_ID passed to R2") int reject_untrusted_xchg(struct __sk_buff *ctx) {struct prog_test_ref_kfunc *p;
tools/testing/selftests/bpf/progs/task_kfunc_failure.c +3 -3
@@ -178,7 +178,7 @@ int BPF_PROG(task_kfunc_release_untrusted, struct task_struct *task, u64 clone_f } SEC("tp_btf/task_newtask") -__failure __msg("R1 pointer type STRUCT task_struct must point") +__failure __msg("release kfunc bpf_task_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(task_kfunc_release_fp, struct task_struct *task, u64 clone_flags) {struct task_struct *acquired = (struct task_struct *)&clone_flags;
@@ -224,7 +224,7 @@ int BPF_PROG(task_kfunc_release_null, struct task_struct *task, u64 clone_flags) } SEC("tp_btf/task_newtask") -__failure __msg("release kernel function bpf_task_release expects") +__failure __msg("release kfunc bpf_task_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(task_kfunc_release_unacquired, struct task_struct *task, u64 clone_flags) {/* Cannot release trusted task pointer which was not acquired. */
@@ -313,7 +313,7 @@ int BPF_PROG(task_access_comm4, struct task_struct *task, const char *buf, bool } SEC("tp_btf/task_newtask") -__failure __msg("R1 must be referenced or trusted") +__failure __msg("release kfunc bpf_task_release expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(task_kfunc_release_in_map, struct task_struct *task, u64 clone_flags) {struct task_struct *local;
tools/testing/selftests/bpf/progs/verifier_global_ptr_args.c +1 -1
@@ -153,7 +153,7 @@ __weak int subprog_trusted_destroy(struct task_struct *task __arg_trusted) SEC("?tp_btf/task_newtask") __failure __log_level(2) -__msg("release kernel function bpf_task_release expects refcounted PTR_TO_BTF_ID") +__msg("release kfunc bpf_task_release expects referenced PTR_TO_BTF_ID passed to R1")int BPF_PROG (trusted_destroy_fail ,struct task_struct *task,u64 clone_flags) {return subprog_trusted_destroy (task);
tools/testing/selftests/bpf/progs/verifier_ref_tracking.c +1 -1
@@ -1288,7 +1288,7 @@ l1_%=: r1 = r6; \ SEC("tc") __description("reference tracking: bpf_sk_release(listen_sk)") -__failure __msg("R1 must be referenced when passed to release function") +__failure __msg("release helper bpf_sk_release expects referenced PTR_TO_BTF_ID passed to R1")__naked void bpf_sk_release_listen_sk (void ) { asm volatile (
tools/testing/selftests/bpf/progs/verifier_sock.c +3 -3
@@ -603,7 +603,7 @@ l2_%=: r0 = *(u32*)(r0 + %[bpf_tcp_sock_snd_cwnd]); \ SEC("tc") __description("bpf_sk_release(skb->sk)") -__failure __msg("R1 must be referenced when passed to release function") +__failure __msg("release helper bpf_sk_release expects referenced PTR_TO_BTF_ID passed to R1")__naked void bpf_sk_release_skb_sk (void ) { asm volatile (" \
@@ -620,7 +620,7 @@ l0_%=: r0 = 0; \ SEC("tc") __description("bpf_sk_release(bpf_sk_fullsock(skb->sk))") -__failure __msg("R1 must be referenced when passed to release function") +__failure __msg("release helper bpf_sk_release expects referenced PTR_TO_BTF_ID passed to R1")__naked void bpf_sk_fullsock_skb_sk (void ) { asm volatile (" \
@@ -644,7 +644,7 @@ l1_%=: r1 = r0; \ SEC("tc") __description("bpf_sk_release(bpf_tcp_sock(skb->sk))") -__failure __msg("R1 must be referenced when passed to release function") +__failure __msg("release helper bpf_sk_release expects referenced PTR_TO_BTF_ID passed to R1")__naked void bpf_tcp_sock_skb_sk (void ) { asm volatile (" \
tools/testing/selftests/bpf/progs/verifier_vfs_reject.c +1 -1
@@ -80,7 +80,7 @@ int BPF_PROG(get_task_exe_file_kfunc_unreleased) } SEC("lsm.s/file_open") -__failure __msg("release kernel function bpf_put_file expects") +__failure __msg("release kfunc bpf_put_file expects referenced PTR_TO_BTF_ID passed to R1") int BPF_PROG(put_file_kfunc_unacquired, struct file *file) {/* Can't release an unacquired pointer. */
Signature · 1 line
2.53.0-Meta
PATCH v5 9/14 bpf: Fold ref_obj_id into id and introduce virtual references
In reply to Amery HungRemove ref_obj_id from bpf_reg_state by folding its role into the existing id field. Previously, id tracked pointer identity for null checking while ref_obj_id tracked the owning reference for lifetime management. These are now unified: acquire helpers and kfuncs set id to the acquired reference id, and release paths use id directly.
To handle cases where objects share the same lifetime but need distinct identities, pointer casting (bpf_sk_fullsock, bpf_tcp_sock) and referenced dynptr clones, introduce virtual references. A virtual reference is a bpf_reference_state entry with is_virtual=true that serves as a lifetime anchor. It has no backing register or stack slot and exists only in acquired_refs.
For pointer casting, the first cast from a referenced pointer creates a virtual reference, converts the source to a non-referenced pointer with parent_id pointing to the virtual ref, and gives the cast result its own unique id with the same parent_id. Chained casts reuse the same virtual ref. Each pointer retains a unique id for independent null checking via mark_ptr_or_null_regs, while releasing any of them releases the shared virtual ref and invalidates all siblings.
For referenced dynptrs, the constructor creates a virtual reference instead of a regular one. All clones share the same parent_id (the virtual ref) but get unique ids for independent slice tracking. Releasing a referenced dynptr releases the virtual reference, which in turn invalidates all clones and their derived slices.
The release_reference() DFS is extended to detect virtual refs whose parent is being released and report them as leaked references, matching the existing behavior for regular refs encountered during cascading.
Also add reg_is_referenced() which checks if a register is referenced either directly (id in the reference table) or indirectly (parent_id points to a virtual ref). This replaces all former ref_obj_id checks.
--- include/linux/bpf.h | 4 +- include/linux/bpf_verifier.h | 58 +-- kernel/bpf/btf.c | 2 +- kernel/bpf/fixups.c | 2 +- kernel/bpf/log.c | 12 +- kernel/bpf/states.c | 7 +- kernel/bpf/verifier.c | 392 +++++++++++------- .../selftests/bpf/prog_tests/spin_lock.c | 4 +- .../testing/selftests/bpf/progs/dynptr_fail.c | 4 +- .../selftests/bpf/progs/iters_state_safety.c | 4 +- .../selftests/bpf/progs/iters_testmod_seq.c | 12 +- 11 files changed, 271 insertions(+), 230 deletions(-)
include/linux/bpf.h +2 -2
@@ -1051,7 +1051,7 @@ struct bpf_insn_access_aux {struct {struct btf *btf;u32 btf_id; -u32 ref_obj_id; +u32 ref_id; }; };struct bpf_verifier_log *log;/* for verbose logs */
@@ -1620,7 +1620,7 @@ struct bpf_ctx_arg_aux {enum bpf_reg_type reg_type;struct btf *btf;u32 btf_id; -u32 ref_obj_id; +u32 ref_id;bool refcounted; };
include/linux/bpf_verifier.h +12 -46
82 lines not on this page · raw message
kernel/bpf/btf.c +1 -1
@@ -6957,7 +6957,7 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, info->reg_type = ctx_arg_info->reg_type; info->btf = ctx_arg_info->btf ? : btf_vmlinux; info->btf_id = ctx_arg_info->btf_id; - info->ref_obj_id = ctx_arg_info->ref_obj_id; + info->ref_id = ctx_arg_info->ref_id;return true; } }
kernel/bpf/fixups.c +1 -1
@@ -870,7 +870,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)case PTR_TO_BTF_ID :case PTR_TO_BTF_ID |PTR_UNTRUSTED :/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike -* PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot +* PTR_TO_BTF_ID, and an active id, but the same cannot * be said once it is marked PTR_UNTRUSTED, hence we must handle * any faults for loads into such types. BPF_WRITE is disallowed * for this case.
kernel/bpf/log.c +4 -8
@@ -665,8 +665,6 @@ static void print_reg_state(struct bpf_verifier_env *env,verbose_a ("id=%d" , reg->id & ~BPF_ADD_CONST );if (reg->id &BPF_ADD_CONST )verbose (env,"%+d" , reg->delta); -if (reg->ref_obj_id) -verbose_a ("ref_obj_id=%d" , reg->ref_obj_id);if (reg->parent_id)verbose_a ("parent_id=%d" , reg->parent_id);if (type_is_non_owning_ref (reg->type))
@@ -770,21 +768,19 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifieverbose (env,"=dynptr_%s(" ,dynptr_type_str (reg->dynptr.type));if (reg->id)verbose_a ("id=%d" , reg->id); -if (reg->ref_obj_id) -verbose_a ("ref_obj_id=%d" , reg->ref_obj_id);if (reg->parent_id)verbose_a ("parent_id=%d" , reg->parent_id);verbose (env,")" );break ;case STACK_ITER : -/* only main slot has ref_obj_id set; skip others */ -if (!reg->ref_obj_id) +/* only main slot has id set; skip others */ +if (!reg->id)continue ; -verbose (env," fp%d=iter_%s(ref_id=%d,state=%s,depth=%u)" , +verbose (env," fp%d=iter_%s(id=%d,state=%s,depth=%u)" , (-i -1 ) *BPF_REG_SIZE ,iter_type_str (reg->iter.btf, reg->iter.btf_id), - reg->ref_obj_id,iter_state_str (reg->iter.state), + reg->id,iter_state_str (reg->iter.state), reg->iter.depth);break ;case STACK_MISC :
kernel/bpf/states.c +2 -5
@@ -489,7 +489,6 @@ static bool regs_exact(const struct bpf_reg_state *rold, {return memcmp (rold, rcur, offsetof(struct bpf_reg_state , id)) ==0 &&check_ids (rold->id, rcur->id, idmap) && -check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap) &&check_ids (rold->parent_id, rcur->parent_id, idmap); }
@@ -615,7 +614,6 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,range_within (rold, rcur) &&tnum_in (rold->var_off, rcur->var_off) &&check_ids (rold->id, rcur->id, idmap) && -check_ids (rold->ref_obj_id, rcur->ref_obj_id, idmap) &&check_ids (rold->parent_id, rcur->parent_id, idmap);case PTR_TO_PACKET_META :case PTR_TO_PACKET :
@@ -797,7 +795,6 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,if (old_reg->dynptr.type != cur_reg->dynptr.type || old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || !check_ids (old_reg->id, cur_reg->id, idmap) || - !check_ids (old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || !check_ids (old_reg->parent_id, cur_reg->parent_id, idmap))return false;break ;
@@ -814,13 +811,13 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, old_reg->iter.btf_id != cur_reg->iter.btf_id || old_reg->iter.state != cur_reg->iter.state ||/* ignore {old_reg,cur_reg}->iter.depth, see above */ - !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) + !check_ids(old_reg->id, cur_reg->id, idmap)) return false;break ;case STACK_IRQ_FLAG : old_reg = &old->stack[spi].spilled_ptr; cur_reg = &cur->stack[spi].spilled_ptr; -if (!check_ids (old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || +if (!check_ids (old_reg->id, cur_reg->id, idmap) || old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)return false;break ;
kernel/bpf/verifier.c +237 -155
868 lines not on this page · raw message
tools/testing/selftests/bpf/prog_tests/spin_lock.c +2 -2
@@ -13,8 +13,8 @@ static struct {const char *err_msg; } spin_lock_fail_tests[] = { {"lock_id_kptr_preserve" , -"[0-9]\\+: (bf) r1 = r0 ; R0=ptr_foo(id=2,ref_obj_id=2)" -" R1=ptr_foo(id=2,ref_obj_id=2) refs=2\n" +"[0-9]\\+: (bf) r1 = r0 ; R0=ptr_foo(id=2)" +" R1=ptr_foo(id=2) refs=2\n" "[0-9]\\+: (85) call bpf_this_cpu_ptr#154\n" "R1 type=ptr_ expected=percpu_ptr_" }, { "lock_id_global_zero",
tools/testing/selftests/bpf/progs/dynptr_fail.c +2 -2
@@ -78,7 +78,7 @@ static int get_map_val_dynptr(struct bpf_dynptr *ptr)* bpf_ringbuf_submit/discard_dynptr call */ SEC("?raw_tp") -__failure __msg("Unreleased reference id=2") +__failure __msg("Unreleased reference id=1")int ringbuf_missing_release1 (void *ctx) {struct bpf_dynptr ptr = {};
@@ -91,7 +91,7 @@ int ringbuf_missing_release1(void *ctx) } SEC("?raw_tp") -__failure __msg("Unreleased reference id=4") +__failure __msg("Unreleased reference id=3") int ringbuf_missing_release2(void *ctx) {struct bpf_dynptr ptr1, ptr2;
tools/testing/selftests/bpf/progs/iters_state_safety.c +2 -2
@@ -30,7 +30,7 @@ int force_clang_to_emit_btf_for_externs(void *ctx) SEC("?raw_tp") __success __log_level(2) -__msg("fp-8=iter_num(ref_id=1,state=active,depth=0)") +__msg("fp-8=iter_num(id=1,state=active,depth=0)")int create_and_destroy (void *ctx) {struct bpf_iter_num iter;
@@ -196,7 +196,7 @@ int leak_iter_from_subprog_fail(void *ctx) SEC("?raw_tp") __success __log_level(2) -__msg("fp-8=iter_num(ref_id=1,state=active,depth=0)") +__msg("fp-8=iter_num(id=1,state=active,depth=0)")int valid_stack_reuse (void *ctx) {struct bpf_iter_num iter;
tools/testing/selftests/bpf/progs/iters_testmod_seq.c +6 -6
@@ -20,8 +20,8 @@ __s64 res_empty; SEC("raw_tp/sys_enter") __success __log_level(2) -__msg("fp-16=iter_testmod_seq(ref_id=1,state=active,depth=0)") -__msg("fp-16=iter_testmod_seq(ref_id=1,state=drained,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=active,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=drained,depth=0)") __msg("call bpf_iter_testmod_seq_destroy")int testmod_seq_empty (const void *ctx) {
@@ -38,8 +38,8 @@ __s64 res_full; SEC("raw_tp/sys_enter") __success __log_level(2) -__msg("fp-16=iter_testmod_seq(ref_id=1,state=active,depth=0)") -__msg("fp-16=iter_testmod_seq(ref_id=1,state=drained,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=active,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=drained,depth=0)") __msg("call bpf_iter_testmod_seq_destroy")int testmod_seq_full (const void *ctx) {
@@ -58,8 +58,8 @@ static volatile int zero = 0; SEC("raw_tp/sys_enter") __success __log_level(2) -__msg("fp-16=iter_testmod_seq(ref_id=1,state=active,depth=0)") -__msg("fp-16=iter_testmod_seq(ref_id=1,state=drained,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=active,depth=0)") +__msg("fp-16=iter_testmod_seq(id=1,state=drained,depth=0)") __msg("call bpf_iter_testmod_seq_destroy")int testmod_seq_truncated (const void *ctx) {
Signature · 1 line
2.53.0-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v5 09/14] bpf: Fold ref_obj_id into id and introduce virtual references
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] check_reference_leak() incorrectly rejects valid struct_ops programs that return a pointer derived…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] check_reference_leak() incorrectly rejects valid struct_ops programs that return a pointer derived from a virtual reference (e.g., a casted pointer). --
commit 4171c91972499af3939593f911ee11b4fbbe778d
Author: Amery Hung <[email protected]>
bpf: Fold ref_obj_id into id and introduce virtual references
This commit unifies pointer identity and lifetime tracking by replacing ref_obj_id with id. It introduces virtual references to serve as lifetime anchors for objects that share the same lifetime but need distinct identities, such as pointer casts and referenced dynptr clones.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi · line 9924
Quoted 7 lines
kernel/bpf/verifier.c +1
-1@@ -9854,7 +9920,7 @@ static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi* kernel. Type checks are performed later in check_return_code. */ if (type ==BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && - reg->ref_obj_id == state->refs[i].id) + reg->id == state->refs[i].id)continue ;
[Severity: High]
Will this correctly handle struct_ops programs that return a pointer derived from a virtual reference, such as a casted pointer?
Since a casted pointer in R0 receives a distinct non-reference id while the virtual reference ID is stored in its parent_id, checking reg->id against state->refs[i].id might fail here.
Could this cause the verifier to incorrectly flag an "Unreleased reference" and reject valid struct_ops programs? Should this check also consider reg->parent_id when the reference is virtual?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Re: [PATCH bpf-next v5 09/14] bpf: Fold ref_obj_id into id and introduce virtual references
Quoted 31 lines · On Tue, May 19, 2026 at 11:59 AM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High]check_reference_leak()incorrectly rejects validstruct_opsprograms that return a pointer derived from a virtual reference (e.g., a casted pointer). --commit
4171c91972499af3939593f911ee11b4fbbe778d
Author: Amery Hung <[email protected]>bpf: Fold
ref_obj_idinto id and introduce virtual referencesThis commit unifies pointer identity and lifetime tracking by replacing
ref_obj_idwith id. It introduces virtual references to serve as lifetime anchors for objects that share the same lifetime but need distinct identities, such as pointer casts and referenced dynptr clones.Quoted 3 lines
kernel/bpf/verifier.c +0
-0[ ... ]
kernel/bpf/verifier.c static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi · line 9924
Quoted 7 lines
kernel/bpf/verifier.c +1
-1@@ -9854,7 +9920,7 @@ static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi* kernel. Type checks are performed later in check_return_code. */ if (type ==BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && - reg->ref_obj_id == state->refs[i].id) + reg->id == state->refs[i].id)continue ;[Severity: High]
Will this correctly handlestruct_opsprograms that return a pointer derived from a virtual reference, such as a casted pointer?
Quoted 7 lines
Since a casted pointer in R0 receives a distinct non-reference id while the virtual reference ID is stored in its
parent_id, checkingreg->idagainst state->refs[i].id might fail here.Could this cause the verifier to incorrectly flag an "Unreleased reference" and reject valid
struct_opsprograms? Should this check also considerreg->parent_idwhen the reference is virtual?
There is no struct_ops that can return a register derived from a virtual reference, but to prevent such false positive preemptively, the condition can be changed to:
if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
- reg->ref_obj_id == state->refs[i].id)
+ reg->id == state->refs[i].id || reg->parent_id ==
state->refs[i].id)
Quoted 3 lines
--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Eduard Zingerman
maintainerRe: [PATCH bpf-next v5 09/14] bpf: Fold ref_obj_id into id and introduce virtual references
In reply to Amery HungQuoted 31 lines · Amery Hung
Remove
ref_obj_idfrombpf_reg_stateby folding its role into the existing id field. Previously, id tracked pointer identity for null checking whileref_obj_idtracked the owning reference for lifetime management. These are now unified: acquire helpers and kfuncs set id to the acquired reference id, and release paths use id directly.To handle cases where objects share the same lifetime but need distinct identities, pointer casting (
bpf_sk_fullsock,bpf_tcp_sock) and referenced dynptr clones, introduce virtual references. A virtual reference is abpf_reference_stateentry with is_virtual=true that serves as a lifetime anchor. It has no backing register or stack slot and exists only inacquired_refs.For pointer casting, the first cast from a referenced pointer creates a virtual reference, converts the source to a non-referenced pointer with
parent_idpointing to the virtual ref, and gives the cast result its own unique id with the sameparent_id. Chained casts reuse the same virtual ref. Each pointer retains a unique id for independent null checking viamark_ptr_or_null_regs, while releasing any of them releases the shared virtual ref and invalidates all siblings.For referenced dynptrs, the constructor creates a virtual reference instead of a regular one. All clones share the same
parent_id(the virtual ref) but get unique ids for independent slice tracking. Releasing a referenced dynptr releases the virtual reference, which in turn invalidates all clones and their derived slices.The
release_reference()DFS is extended to detect virtual refs whose parent is being released and report them as leaked references, matching the existing behavior for regular refs encountered during cascading.
Quoted 6 lines
Also add
reg_is_referenced()which checks if a register is referenced either directly (id in the reference table) or indirectly (parent_idpoints to a virtual ref). This replaces all formerref_obj_idchecks.Signed-off-by Amery Hung <[email protected]>---
Consider two modifications:
- A different approach for pointer cast helpers handling:
fork the verifier state at the cast call site:
- Push a NULL branch for later exploration.
- Continue with the non-NULL branch: strip PTR_MAYBE_NULL from r0 and set r0.id = source register's id.
- All cast results share the same id as the original acquired pointer. No new reference entries, no parent_id on cast results. Because reference_id is shared, release of any of the original or cast pointers invalidates all other pointers.
- unmark_stack_slots_dynptr() deciding which reference id to free basing on the pointer type:
release_reference(env, dynptr_type_referenced(reg->dynptr.type)
? reg->parent_id
: reg->id);With these two modifications the following simplifications are possible:
- is_virtual flag is no longer necessary.
- reg_is_referenced() reduces to find_reference_state(reg->id) != NULL.
- acquire_virtual_reference() merges into acquire_reference() with a parent_id parameter.
- cast_from_ref_obj() is no longer necessary.
See the branch [1] for the complete implementation, with commits on top of this series (two fixups, two commits for the changes described above). Existing selftests are passing with these changes.
[1] https://github.com/eddyz87/bpf/tree/refobj-id-v5-suggestion
Wdyt?
PATCH v5 10/14 bpf: Fix dynptr ref counting to scan all call frames
In reply to Amery HungWhen checking whether a referenced dynptr can be overwritten, destroy_if_dynptr_stack_slot only counted sibling dynptrs in the current call frame. If a clone sharing the same virtual ref parent existed in a different frame (e.g., passed to a subprog), it would not be counted, causing the verifier to incorrectly reject the overwrite with "cannot overwrite referenced dynptr".
Fix by extracting the counting into dynptr_ref_cnt() which uses bpf_for_each_reg_in_vstate_mask() to scan dynptr stack slots across all call frames.
--- kernel/bpf/verifier.c | 52 +++++++++++-------- .../selftests/bpf/progs/wakeup_source_fail.c | 2 +- 2 files changed, 30 insertions(+), 24 deletions(-)
kernel/bpf/verifier.c +29 -23
@@ -786,10 +786,29 @@ static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg___mark_reg_unknown (env, reg); } +static int dynptr_ref_cnt (struct bpf_verifier_env *env,int v_parent_id) +{ +struct bpf_stack_state *stack; +struct bpf_func_state *state; +struct bpf_reg_state *reg; +int ref_cnt =0 ; + +bpf_for_each_reg_in_vstate_mask (env->cur_state, state, reg, stack,1 <<STACK_DYNPTR , ({ +if (!stack || stack->slot_type[0 ] !=STACK_DYNPTR ) +continue ; +if (!stack->spilled_ptr.dynptr.first_slot) +continue ; +if (stack->spilled_ptr.parent_id == v_parent_id) + ref_cnt++; + })); + +return ref_cnt; +} +static int destroy_if_dynptr_stack_slot (struct bpf_verifier_env *env,struct bpf_func_state *state,int spi) { -int i, err =0 ; +int err =0 ;/* We always ensure that STACK_DYNPTR is never set partially, * hence just checking for slot_type[0] is enough. This is
@@ -803,28 +822,15 @@ static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,if (!state->stack[spi].spilled_ptr.dynptr.first_slot) spi = spi +1 ; -if (dynptr_type_referenced (state->stack[spi].spilled_ptr.dynptr.type)) { -int v_parent_id = state->stack[spi].spilled_ptr.parent_id; -int ref_cnt =0 ; - -/* -* A referenced dynptr can be overwritten only if there is at -* least one other dynptr sharing the same virtual ref parent, -* ensuring the reference can still be properly released. -*/ -for (i =0 ; i < state->allocated_stack /BPF_REG_SIZE ; i++) { -if (state->stack[i].slot_type[0 ] !=STACK_DYNPTR ) -continue ; -if (!state->stack[i].spilled_ptr.dynptr.first_slot) -continue ; -if (state->stack[i].spilled_ptr.parent_id == v_parent_id) - ref_cnt++; - } - -if (ref_cnt <=1 ) { -verbose (env,"cannot overwrite referenced dynptr\n" ); -return -EINVAL ; - } +/* +* A referenced dynptr can be overwritten only if there is at +* least one other dynptr sharing the same virtual ref parent, +* ensuring the reference can still be properly released. +*/ +if (dynptr_type_referenced (state->stack[spi].spilled_ptr.dynptr.type) && +dynptr_ref_cnt (env, state->stack[spi].spilled_ptr.parent_id) <=1 ) { +verbose (env,"cannot overwrite referenced dynptr\n" ); +return -EINVAL ; }/* Invalidate the dynptr and any derived slices */
tools/testing/selftests/bpf/progs/wakeup_source_fail.c +1 -1
@@ -42,7 +42,7 @@ int wakeup_source_access_lock_fields(void *ctx) } SEC("syscall") -__failure __msg("type=scalar expected=fp") +__failure __msg("release kfunc bpf_wakeup_sources_read_unlock expects referenced PTR_TO_BTF_ID passed to R1") int wakeup_source_unlock_no_lock(void *ctx) {struct bpf_ws_lock *lock = (void *)0x1 ;
Signature · 1 line
2.53.0-Meta
[email protected]
AI reviewRe: [PATCH bpf-next v5 10/14] bpf: Fix dynptr ref counting to scan all call frames
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] The macro `bpf_for_each_reg_in_vstate_mask` incorrectly computes the `stack` pointer when…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] The macro bpf_for_each_reg_in_vstate_mask incorrectly computes the stack pointer when iterating over outgoing stack arguments. The new dynptr_ref_cnt function uses this macro and dereferences the invalid pointer, leading to a verifier crash or security bypass. --
commit 2fbeda3e91d76b77c3a4fe5a3269d7a89c9d8588
Author: Amery Hung <[email protected]>
bpf: Fix dynptr ref counting to scan all call frames
This commit extracts dynptr reference counting into a new dynptr_ref_cnt() function to check whether a referenced dynptr can be overwritten. It uses bpf_for_each_reg_in_vstate_mask() to scan dynptr stack slots across all call frames instead of just the current frame.
Quoted 5 lines
kernel/bpf/verifier.c +0
-0@@ -786,10 +786,29 @@ static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_
[ ... ]
kernel/bpf/verifier.c static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_ · line 798
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+static int dynptr_ref_cnt (struct bpf_verifier_env *env,int v_parent_id) +{ +struct bpf_stack_state *stack; +struct bpf_func_state *state; +struct bpf_reg_state *reg; +int ref_cnt =0 ; + + bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ + if (!stack || stack->slot_type[0] != STACK_DYNPTR) + continue;
[Severity: Critical]
Does bpf_for_each_reg_in_vstate_mask() safely provide the stack pointer when iterating over outgoing stack arguments?
Looking at the macro definition in include/linux/bpf_verifier.h:
bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \
if (!__reg) \
continue; \
__stack = &__state->stack[___j]; \
(void)(__expr); \
}When iterating over outgoing stack arguments, it calculates __stack using the local stack array (__state->stack). Since out_stack_arg_cnt is independent of allocated_stack, __state->stack could be NULL.
If ___j > 0 and __state->stack is NULL, __stack would evaluate to a non-NULL offset. Would this bypass the !stack check above and result in an out-of-bounds read or page fault when evaluating stack->slot_type[0]?
Additionally, if __state->stack is valid, could this evaluate the same local stack slot twice, artificially inflating ref_cnt and potentially bypassing the ref_cnt <= 1 check?
Quoted 8 lines
kernel/bpf/verifier.c +8
-0+if (!stack->spilled_ptr.dynptr.first_slot) +continue ; +if (stack->spilled_ptr.parent_id == v_parent_id) + ref_cnt++; + })); + +return ref_cnt; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Re: [PATCH bpf-next v5 10/14] bpf: Fix dynptr ref counting to scan all call frames
Quoted 49 lines · On Tue, May 19, 2026 at 12:03 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] The macrobpf_for_each_reg_in_vstate_maskincorrectly computes thestackpointer when iterating over outgoing stack arguments. The newdynptr_ref_cntfunction uses this macro and dereferences the invalid pointer, leading to a verifier crash or security bypass. --commit
2fbeda3e91d76b77c3a4fe5a3269d7a89c9d8588
Author: Amery Hung <[email protected]>bpf: Fix dynptr ref counting to scan all call frames
This commit extracts dynptr reference counting into a new
dynptr_ref_cnt()function to check whether a referenced dynptr can be overwritten. It usesbpf_for_each_reg_in_vstate_mask()to scan dynptr stack slots across all call frames instead of just the current frame.Quoted 5 lines
kernel/bpf/verifier.c +0
-0@@ -786,10 +786,29 @@ static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_[ ... ]
kernel/bpf/verifier.c static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_ · line 798
Quoted 10 lines
kernel/bpf/verifier.c +10
-0+static int dynptr_ref_cnt (struct bpf_verifier_env *env,int v_parent_id) +{ +struct bpf_stack_state *stack; +struct bpf_func_state *state; +struct bpf_reg_state *reg; +int ref_cnt =0 ; + + bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ + if (!stack || stack->slot_type[0] != STACK_DYNPTR) + continue;[Severity: Critical]
Doesbpf_for_each_reg_in_vstate_mask()safely provide the stack pointer when iterating over outgoing stack arguments?Looking at the macro definition in
include/linux/bpf_verifier.h:bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \ if (!__reg) \ continue; \ __stack = &__state->stack[___j]; \ (void)(__expr); \ }When iterating over outgoing stack arguments, it calculates
__stackusing the local stack array (__state->stack). Sinceout_stack_arg_cntis independent ofallocated_stack,__state->stackcould be NULL.
Quoted 7 lines
If
___j> 0 and__state->stackis NULL,__stackwould evaluate to a non-NULL offset. Would this bypass the !stack check above and result in an out-of-bounds read or page fault when evaluating stack->slot_type[0]?Additionally, if
__state->stackis valid, could this evaluate the same local stack slot twice, artificially inflatingref_cntand potentially bypassing theref_cnt<= 1 check?
Sashiko already pointed out the issue in patch 5. The fix is to assign NULL to __stack for stack args and then the existing !stack check will be enough.
Quoted 12 lines
kernel/bpf/verifier.c static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_ · line 806
Quoted 9 lines
kernel/bpf/verifier.c +8
-0+if (!stack->spilled_ptr.dynptr.first_slot) +continue ; +if (stack->spilled_ptr.parent_id == v_parent_id) + ref_cnt++; + })); + +return ref_cnt; +}--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Re: [PATCH bpf-next v5 10/14] bpf: Fix dynptr ref counting to scan all call frames
In reply to Amery HungQuoted 7 lines · Amery Hung
When checking whether a referenced dynptr can be overwritten,
destroy_if_dynptr_stack_slotonly counted sibling dynptrs in the current call frame. If a clone sharing the same virtual ref parent existed in a different frame (e.g., passed to a subprog), it would not be counted, causing the verifier to incorrectly reject the overwrite with "cannot overwrite referenced dynptr".
Quoted 8 lines
Fix by extracting the counting into
dynptr_ref_cnt()which usesbpf_for_each_reg_in_vstate_mask()to scan dynptr stack slots across all call frames.Fixes 017f5c4ef73c ("bpf: Allow overwriting referenced dynptr when refcnt > 1")Reported-by Eduard Zingerman <[email protected]>Signed-off-by Amery Hung <[email protected]>---
[...]
tools/testing/selftests/bpf/progs/wakeup_source_fail.c int wakeup_source_access_lock_fields(void *ctx) · line 45
Quoted 10 lines
tools/testing/selftests/bpf/progs/wakeup_source_fail.c +0
-0@@ -42,7 +42,7 @@ int wakeup_source_access_lock_fields(void *ctx) }
SEC("syscall")tools/testing/selftests/bpf/progs/wakeup_source_fail.c +1
-1-__failure __msg("type=scalar expected=fp") +__failure __msg("release kfunc bpf_wakeup_sources_read_unlock expects referenced PTR_TO_BTF_ID passed to R1")
Nit: this change seem unrelated.
Quoted 3 lines
int
wakeup_source_unlock_no_lock(void *ctx)
{
structbpf_ws_lock*lock = (void *)0x1;
Re: [PATCH bpf-next v5 10/14] bpf: Fix dynptr ref counting to scan all call frames
Quoted 29 lines · Eduard Zingerman
Quoted 7 lines · Amery Hung
When checking whether a referenced dynptr can be overwritten,
destroy_if_dynptr_stack_slotonly counted sibling dynptrs in the current call frame. If a clone sharing the same virtual ref parent existed in a different frame (e.g., passed to a subprog), it would not be counted, causing the verifier to incorrectly reject the overwrite with "cannot overwrite referenced dynptr".Quoted 8 lines
Fix by extracting the counting into
dynptr_ref_cnt()which usesbpf_for_each_reg_in_vstate_mask()to scan dynptr stack slots across all call frames.Fixes 017f5c4ef73c ("bpf: Allow overwriting referenced dynptr when refcnt > 1")Reported-by Eduard Zingerman <[email protected]>Signed-off-by Amery Hung <[email protected]>---
Acked-by Eduard Zingerman <[email protected]>[...]
Quoted 7 lines
tools/testing/selftests/bpf/progs/wakeup_source_fail.c +0
-0@@ -42,7 +42,7 @@ int wakeup_source_access_lock_fields(void *ctx) }
Quoted 5 lines
tools/testing/selftests/bpf/progs/wakeup_source_fail.c int wakeup_source_access_lock_fields(void *ctx) · line 45
Quoted 3 lines
tools/testing/selftests/bpf/progs/wakeup_source_fail.c +1
-1SEC("syscall") -__failure __msg("type=scalar expected=fp") +__failure __msg("release kfunc bpf_wakeup_sources_read_unlock expects referenced PTR_TO_BTF_ID passed to R1")Nit: this change seem unrelated.
Indeed. I fixed up this piece to the wrong patch. Should be patch 8.
Quoted 4 lines
Quoted 4 lines
tools/testing/selftests/bpf/progs/wakeup_source_fail.c +0
-0int wakeup_source_unlock_no_lock (void *ctx) {struct bpf_ws_lock *lock = (void *)0x1 ;
PATCH v5 11/14 selftests/bpf: Test creating dynptr from dynptr data and slice
In reply to Amery HungThe verifier currently does not allow creating dynptr from dynptr data or slice. Add a selftest to test this explicitly.
--- .../testing/selftests/bpf/progs/dynptr_fail.c | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+)
tools/testing/selftests/bpf/progs/dynptr_fail.c +42 -0
@@ -705,6 +705,48 @@ int dynptr_from_mem_invalid_api(void *ctx)return 0 ; } +/* Cannot create dynptr from dynptr data */ +SEC("?raw_tp") +__failure __msg("Unsupported reg type mem for bpf_dynptr_from_mem data") +int dynptr_from_dynptr_data(void *ctx) +{ +struct bpf_dynptr ptr, ptr2; +__u8 *data; + +if (get_map_val_dynptr (&ptr)) +return 0 ; + + data =bpf_dynptr_data (&ptr,0 ,sizeof (__u32)); +if (!data) +return 0 ; + +/* this should fail */ +bpf_dynptr_from_mem (data,sizeof (__u32),0 , &ptr2); + +return 0 ; +} + +/* Cannot create dynptr from dynptr slice */ +SEC("?tc") +__failure __msg("Unsupported reg type mem for bpf_dynptr_from_mem data") +int dynptr_from_dynptr_slice(struct __sk_buff *skb) +{ +struct bpf_dynptr ptr, ptr2; +struct ethhdr *hdr; +char buffer[sizeof (*hdr)] = {}; + +bpf_dynptr_from_skb (skb,0 , &ptr); + + hdr =bpf_dynptr_slice_rdwr (&ptr,0 , buffer,sizeof (buffer)); +if (!hdr) +return SK_DROP ; + +/* this should fail */ +bpf_dynptr_from_mem (hdr,sizeof (*hdr),0 , &ptr2); + +return SK_PASS ; +} + SEC("?tc") __failure __msg("cannot overwrite referenced dynptr") __log_level(2)int dynptr_pruning_overwrite (struct __sk_buff *ctx)
Signature · 1 line
2.53.0-Meta
PATCH v5 12/14 selftests/bpf: Test using dynptr after freeing the underlying object
In reply to Amery HungMake sure the verifier invalidates the dynptr and dynptr slice derived from an skb after the skb is freed.
--- .../selftests/bpf/prog_tests/bpf_qdisc.c | 6 ++ .../progs/bpf_qdisc_fail__invalid_dynptr.c | 68 +++++++++++++++++ ...f_qdisc_fail__invalid_dynptr_cross_frame.c | 74 +++++++++++++++++++ .../bpf_qdisc_fail__invalid_dynptr_slice.c | 70 ++++++++++++++++++ 4 files changed, 218 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr.c create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_cross_frame.c create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_slice.c
tools/testing/selftests/bpf/prog_tests/bpf_qdisc.c +6 -0
@@ -8,6 +8,9 @@#include "bpf_qdisc_fifo.skel.h" #include "bpf_qdisc_fq.skel.h" #include "bpf_qdisc_fail__incompl_ops.skel.h" +#include "bpf_qdisc_fail__invalid_dynptr.skel.h" +#include "bpf_qdisc_fail__invalid_dynptr_slice.skel.h" +#include "bpf_qdisc_fail__invalid_dynptr_cross_frame.skel.h" #define LO_IFINDEX 1
@@ -223,6 +226,9 @@ void test_ns_bpf_qdisc(void)test_qdisc_attach_to_non_root ();if (test__start_subtest ("incompl_ops" ))test_incompl_ops (); +RUN_TESTS (bpf_qdisc_fail__invalid_dynptr); +RUN_TESTS (bpf_qdisc_fail__invalid_dynptr_cross_frame); +RUN_TESTS (bpf_qdisc_fail__invalid_dynptr_slice); }void serial_test_bpf_qdisc_default (void )
tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr.c new file +68 -0
68 lines not on this page · raw message
tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_cross_frame.c new file +74 -0
74 lines not on this page · raw message
tools/testing/selftests/bpf/progs/bpf_qdisc_fail__invalid_dynptr_slice.c new file +70 -0
70 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
PATCH v5 13/14 selftests/bpf: Test using slice after invalidating dynptr clone
In reply to Amery HungThe parent object of a cloned dynptr is skb not the original dynptr. Invalidate the original dynptr should not prevent the program from using the slice derived from the cloned dynptr.
--- .../selftests/bpf/prog_tests/bpf_qdisc.c | 2 + ..._qdisc_dynptr_use_after_invalidate_clone.c | 74 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 tools/testing/selftests/bpf/progs/bpf_qdisc_dynptr_use_after_invalidate_clone.c
tools/testing/selftests/bpf/prog_tests/bpf_qdisc.c +2 -0
@@ -11,6 +11,7 @@#include "bpf_qdisc_fail__invalid_dynptr.skel.h" #include "bpf_qdisc_fail__invalid_dynptr_slice.skel.h" #include "bpf_qdisc_fail__invalid_dynptr_cross_frame.skel.h" +#include "bpf_qdisc_dynptr_use_after_invalidate_clone.skel.h" #define LO_IFINDEX 1
@@ -229,6 +230,7 @@ void test_ns_bpf_qdisc(void)RUN_TESTS (bpf_qdisc_fail__invalid_dynptr);RUN_TESTS (bpf_qdisc_fail__invalid_dynptr_cross_frame);RUN_TESTS (bpf_qdisc_fail__invalid_dynptr_slice); +RUN_TESTS (bpf_qdisc_dynptr_use_after_invalidate_clone); }void serial_test_bpf_qdisc_default (void )
tools/testing/selftests/bpf/progs/bpf_qdisc_dynptr_use_after_invalidate_clone.c new file +74 -0
74 lines not on this page · raw message
Signature · 1 line
2.53.0-Meta
PATCH v5 14/14 selftests/bpf: Test using file dynptr after the reference on file is dropped
In reply to Amery HungFile dynptr and slice should be invalidated when the parent file's reference is dropped in the program. Without the verifier tracking dyntpr's parent referenced object, the dynptr would continute to be incorrectly used even if the underlying file is being tear down or gone.
--- .../selftests/bpf/progs/file_reader_fail.c | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+)
tools/testing/selftests/bpf/progs/file_reader_fail.c +60 -0
@@ -50,3 +50,63 @@ int xdp_no_dynptr_type(struct xdp_md *xdp)bpf_dynptr_file_discard (&dynptr);return 0 ; } + +SEC("lsm/file_open") +__failure +__msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") +int use_file_dynptr_after_put_file(void *ctx) +{ +struct task_struct *task =bpf_get_current_task_btf (); +struct file *file =bpf_get_task_exe_file (task); +struct bpf_dynptr dynptr; +char buf[64 ]; + +if (!file) +return 0 ; + +if (bpf_dynptr_from_file (file,0 , &dynptr)) + goto out; + +/* this should fail - file dynptr should be discarded first to prevent resource leak */ +bpf_put_file (file); + +bpf_dynptr_read (buf,sizeof (buf), &dynptr,0 ,0 ); +return 0 ; + +out: +bpf_dynptr_file_discard (&dynptr); +bpf_put_file (file); +return 0 ; +} + +SEC("lsm/file_open") +__failure +__msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") +int use_file_dynptr_slice_after_put_file(void *ctx) +{ +struct task_struct *task =bpf_get_current_task_btf (); +struct file *file =bpf_get_task_exe_file (task); +struct bpf_dynptr dynptr; +char *data; + +if (!file) +return 0 ; + +if (bpf_dynptr_from_file (file,0 , &dynptr)) + goto out; + + data =bpf_dynptr_data (&dynptr,0 ,1 ); +if (!data) + goto out; + +/* this should fail - file dynptr should be discarded first to prevent resource leak */ +bpf_put_file (file); + + *data ='x' ; +return 0 ; + +out: +bpf_dynptr_file_discard (&dynptr); +bpf_put_file (file); +return 0 ; +}
Signature · 1 line
2.53.0-Meta