Refactor verifier object relationship tracking
Subsystems (6)
v4 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, 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 *
To track precise object relationships, u32 parent_id is added to bpf_reg_state. 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.
After: object (id, ref_obj_id, parent_id)
id = unique id of the object (for nullness tracking)
ref_obj_id = id of the referenced object; objects with the same
ref_obj_id share the same lifetime
parent_id = id of the parent object; points to parent's id
(for object relationship tracking)
skb (1,1,0)
^
bpf_dynptr_from_skb +-------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,0,1) dynptr C (4,0,1)
^ ^
bpf_dynptr_slice | |
| |
slice B (3,0,2) slice D (5,0,4)
^
bpf_dynptr_from_mem |
(NOT allowed yet) |
dynptr E (6,0,3)With parent_id, the verifier can precisely track object trees. When the skb is freed, the verifier traverses the tree rooted at skb (id=1) and invalidates all descendants — dynptr A, dynptr C, and their slices. When dynptr A is destroyed by overwriting the stack slot, only dynptr A and its children (slice B, dynptr E) are invalidated; skb, dynptr C, and slice D remain valid.
For referenced dynptr (e.g., file dynptr), the original and its clones share the same ref_obj_id so they are all invalidated together when any one of them is released. For non-referenced dynptr (e.g., skb dynptr), clones live independently since they have ref_obj_id=0.
To avoid recursive call chains when releasing objects (e.g., release_reference() -> unmark_stack_slots_dynptr() -> release_reference()), release_reference() now uses stack-based DFS to find and invalidate all registers and stack slots with matching id or ref_obj_id and all descendants whose parent_id matches. Currently, it skips id == 0, which could be a valid id (e.g., pkt pointer by reading ctx). Future work may start assigning > 0 id to them. This does not affect the current use cases where skb and file parents are both given id > 0.
* 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 2), and preserving reg->id of pointer objects after null-check (patch 3). 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 new design handles all four combinations of referenced/non-referenced dynptr with referenced/non-referenced parent. The relationship between slices and dynptrs is omitted as it is the same across all cases. The main difference is how cloned dynptrs are represented. Since bpf_dynptr_clone() does not initialize a new reference, clones of referenced dynptrs share the same ref_obj_id and must be invalidated together. For non-referenced dynptrs, the original and clones live independently.
(1) Non-referenced dynptr with referenced parent (e.g., skb in Qdisc):
skb (1,1,0)
^
bpf_dynptr_from_skb +-------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,0,1) dynptr C (4,0,1)(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,0) dynptr C (2,0,0)
dynptr A and C live independently
(3) Referenced dynptr with referenced parent:
file (1,1,0)
^
bpf_dynptr_from_file +---------------------------------+
| bpf_dynptr_clone(A, C) |
dynptr A (2,3,1) dynptr C (4,3,1)
^ ^
| |
dynptr A and C have the same lifetime(4) Referenced dynptr with non-referenced parent:
bpf_ringbuf_reserve_dynptr
bpf_dynptr_clone(A, C)
dynptr A (1,1,0) dynptr C (2,1,0)
^ ^
| |
dynptr A and C have the same lifetime
[0] https://lore.kernel.org/bpf/[email protected]/
[1] https://github.com/ameryhung/bpf/commits/obj_relationship_v2_no_parent_id/
Changelog:
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 7 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 (12):
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 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_verifier.h | 49 +- kernel/bpf/helpers.c | 2 +- kernel/bpf/log.c | 8 +- kernel/bpf/states.c | 10 +- kernel/bpf/verifier.c | 847 +++++++----------- .../selftests/bpf/prog_tests/bpf_qdisc.c | 8 + .../selftests/bpf/prog_tests/cb_refs.c | 2 +- ..._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 | 66 +- .../selftests/bpf/progs/file_reader_fail.c | 60 ++ .../selftests/bpf/progs/map_kptr_fail.c | 2 +- .../selftests/bpf/progs/task_kfunc_failure.c | 6 +- .../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 +- tools/testing/selftests/bpf/verifier/calls.c | 24 - 22 files changed, 819 insertions(+), 573 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.52.0
PATCH v4 1/12 bpf: Simplify mark_stack_slot_obj_read() and callers
Directly call mark_stack_slot_obj_read() from function processing iter, dynptr and irq_flag. 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_slot_obj_read(), just open code the helpers.
In addition, since 6762e3a0bce5 ("bpf: simplify liveness to use (callsite, depth) keyed func_instances") has made mark_stack_slot_obj_read() always succeed. Return void and drop the now unused bpf_reg_state argument.
--- kernel/bpf/verifier.c | 69 +++++++++++++------------------------------ 1 file changed, 21 insertions(+), 48 deletions(-)
kernel/bpf/verifier.c +21 -48
@@ -2972,50 +2972,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_slot_obj_read (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
@@ -7078,7 +7041,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,
@@ -7140,7 +7103,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_slot_obj_read (env, spi,BPF_DYNPTR_NR_SLOTS ); + } }return err; }
@@ -7250,9 +7223,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_slot_obj_read (env, spi, nr_slots);/* remember meta->iter info for process_iter_next_call() */ meta->iter.spi = spi;
@@ -11150,7 +11121,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] ||
@@ -11191,9 +11162,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_slot_obj_read (env, spi,1 ); err =unmark_stack_slot_irq_flag (env, reg, kfunc_class);if (err)
Signature · 1 line
2.52.0
Re: [PATCH bpf-next v4 01/12] bpf: Simplify mark_stack_slot_obj_read() and callers
Quoted 6 lines · Amery Hung
Directly call
mark_stack_slot_obj_read()from function processing iter, dynptr andirq_flag. To prepare for unifying dynptr handling,dynptr_get_spi()will be moved out ofmark_dynptr_read(), Asmark_dynptr_read()would joinmark_iter_read()as a thin wrapper ofmark_stack_slot_obj_read(), just open code the helpers.
Quoted 7 lines
In addition, since
6762e3a0bce5("bpf: simplify liveness to use (callsite, depth) keyedfunc_instances") has mademark_stack_slot_obj_read()always succeed. Return void and drop the now unusedbpf_reg_stateargument.Signed-off-by Amery Hung <[email protected]>---
[...]
kernel/bpf/verifier.c static int sort_subprogs_topo(struct bpf_verifier_env *env) · line 2976
Quoted 2 lines
kernel/bpf/verifier.c +2
-0+static void mark_stack_slot_obj_read (struct bpf_verifier_env *env, +int spi,int nr_slots)
Nit: this is probably a leftover from the stack liveness commit,
but I think that a better name for this function would now be mark_stack_slots_scratched.
[...]
Re: [PATCH bpf-next v4 01/12] bpf: Simplify mark_stack_slot_obj_read() and callers
Quoted 18 lines · Eduard Zingerman
Quoted 6 lines · Amery Hung
Directly call
mark_stack_slot_obj_read()from function processing iter, dynptr andirq_flag. To prepare for unifying dynptr handling,dynptr_get_spi()will be moved out ofmark_dynptr_read(), Asmark_dynptr_read()would joinmark_iter_read()as a thin wrapper ofmark_stack_slot_obj_read(), just open code the helpers.Quoted 7 lines
In addition, since
6762e3a0bce5("bpf: simplify liveness to use (callsite, depth) keyedfunc_instances") has mademark_stack_slot_obj_read()always succeed. Return void and drop the now unusedbpf_reg_stateargument.Signed-off-by Amery Hung <[email protected]>---
Acked-by Eduard Zingerman <[email protected]>
Quoted 8 lines
[...]
kernel/bpf/verifier.c static int sort_subprogs_topo(struct bpf_verifier_env *env) · line 2976
Quoted 2 lines
kernel/bpf/verifier.c +2
-0+static void mark_stack_slot_obj_read (struct bpf_verifier_env *env, +int spi,int nr_slots)Nit: this is probably a leftover from the stack liveness commit,
but I think that a better name for this function would now bemark_stack_slots_scratched.
Make sense. Will change it to mark_stack_slots_scratched.
Quoted 2 lines
[...]
PATCH v4 2/12 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
@@ -1376,6 +1376,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;
@@ -1416,16 +1423,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.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v4 02/12] bpf: Unify dynptr handling in the verifier
A review comment from Mykyta Yatsenko requested that a comment be added to the ref_obj_id field explaining what it's for:
Quoted 5 lines
include/linux/bpf_verifier.h +0
-0
include/linux/bpf_verifier.h struct bpf_map_desc { · line 1385
Quoted 10 lines
include/linux/bpf_verifier.h +7
-0@@ -1376,6 +1376,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; +}; +
A review comment from Mykyta Yatsenko requested that a comment be added to the ref_obj_id field explaining what it's for:
https://lore.kernel.org/bpf/[email protected]/
The author mentioned in v3 that comments for id, ref_obj_id, and parent_id would be added in a later refactor patch. However, should this struct have inline documentation now for clarity, particularly for the ref_obj_id field?
[ ... ]
---
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/25442456702
Re: [PATCH bpf-next v4 02/12] bpf: Unify dynptr handling in the verifier
Quoted 20 lines · On Wed, May 6, 2026 at 4:27 PM <[email protected]> wrote:
Quoted 6 lines
include/linux/bpf_verifier.h +0
-0include/linux/bpf_verifier.h struct bpf_map_desc { · line 1385
Quoted 10 lines
include/linux/bpf_verifier.h +7
-0@@ -1376,6 +1376,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; +}; +A review comment from Mykyta Yatsenko requested that a comment be added to the
ref_obj_idfield explaining what it's for:
Quoted 5 lines
https://lore.kernel.org/bpf/[email protected]/
The author mentioned in v3 that comments for id,
ref_obj_id, andparent_idwould be added in a later refactor patch. However, should this struct have inline documentation now for clarity, particularly for theref_obj_idfield?
For the meaning of id, ref_obj_id and parent_id, keep the documentation in where they are defined: bpf_verifier.h
Quoted 9 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/25442456702
PATCH v4 3/12 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
@@ -6057,8 +6057,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
@@ -6068,8 +6066,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.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v4 03/12] bpf: Assign reg->id when getting referenced kptr from ctx
Does this introduce a bug when reading the same nullable context field multiple times?
Quoted 13 lines
kernel/bpf/verifier.c +0
-2@@ -6057,8 +6057,6 @@ struct bpf_insn_access_aux info = { }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
kernel/bpf/verifier.c struct bpf_insn_access_aux info = { · line 6069
Quoted 4 lines
kernel/bpf/verifier.c +1
-0@@ -6068,8 +6066,11 @@ struct bpf_insn_access_aux info = {if (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;
^^^^
Does this introduce a bug when reading the same nullable context field multiple times?
The new code sets reg->id = info.ref_obj_id, where ref_obj_id comes from ctx_arg_info->ref_obj_id. The ctx_arg_info structure is initialized once during program type setup in check_attach_btf_id(), making ref_obj_id a static value per context field, not per read.
When a BPF program reads the same nullable context field into different registers, they would share the same ID:
r1 = ctx->nullable_kptr; // r1->id = ref_obj_id = 5
r2 = ctx->nullable_kptr; // r2->id = ref_obj_id = 5 (SAME!)
if (r1 != NULL) {
// mark_ptr_or_null_regs(id=5) marks ALL registers with id==5
// Both r1 AND r2 are now considered safe
use(r2); // BUG: r2 was never checked but verifier allows use
}The mark_ptr_or_null_reg() function uses reg->id to identify which registers should be updated together after a NULL check. With shared IDs, independent reads are incorrectly treated as aliases.
The old code generated a unique ID via ++env->id_gen for each nullable read, ensuring proper NULL-check tracking.
kernel/bpf/verifier.c static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b · line 6073
Quoted 4 lines
kernel/bpf/verifier.c +2
-0regs[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;
Would this fallback path prevent fresh ID generation when id was already set to ref_obj_id? The condition '!regs[value_regno].id' is now false for nullable PTR_TO_BTF_ID pointers, so each read gets the same static ID instead of a unique one.
Eduard Zingerman's review comment from v3 suggested that the commit message should mention that this patch is mandatory for proper invalidation propagation in later patches. He noted that without the line 'regs[value_regno].id = info.ref_obj_id;', the test 'bpf_qdisc_fail__invalid_dynptr_cross_frame.c:invalid_dynptr_cross_frame' fails because the .id link is needed to propagate invalidation triggered by 'free_skb(skb);' to 'hdr'. The current commit message mentions consistency and parent_id tracking but does not explicitly mention the invalidation propagation aspect.
---
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/25442456702
Re: [PATCH bpf-next v4 03/12] bpf: Assign reg->id when getting referenced kptr from ctx
Quoted 39 lines · On Wed, May 6, 2026 at 4:27 PM <[email protected]> wrote:
Quoted 14 lines
kernel/bpf/verifier.c +0
-2@@ -6057,8 +6057,6 @@ struct bpf_insn_access_aux info = { }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 kernel/bpf/verifier.c struct bpf_insn_access_aux info = { · line 6069
Quoted 4 lines
kernel/bpf/verifier.c +1
-0@@ -6068,8 +6066,11 @@ struct bpf_insn_access_aux info = {if (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;^^^^Does this introduce a bug when reading the same nullable context field multiple times?
The new code sets
reg->id= info.ref_obj_id, whereref_obj_idcomes fromctx_arg_info->ref_obj_id. Thectx_arg_infostructure is initialized once during program type setup incheck_attach_btf_id(), makingref_obj_ida static value per context field, not per read.When a BPF program reads the same nullable context field into different registers, they would share the same ID:
r1 = ctx->nullable_kptr; // r1->id = ref_obj_id = 5 r2 = ctx->nullable_kptr; // r2->id = ref_obj_id = 5 (SAME!) if (r1 != NULL) { // mark_ptr_or_null_regs(id=5) marks ALL registers with id==5 // Both r1 AND r2 are now considered safe use(r2); // BUG: r2 was never checked but verifier allows use }
Quoted 3 lines
The
mark_ptr_or_null_reg()function usesreg->idto identify which registers should be updated together after a NULL check. With shared IDs, independent reads are incorrectly treated as aliases.
I don't think this is a bug. They are indeed aliases. The referenced kptr acquired from struct_ops argument, if valid, should always have the same ref_obj_id (also id) because they point to the same kernel object
Quoted 9 lines
The old code generated a unique ID via ++env->id_gen for each nullable read, ensuring proper NULL-check tracking.
kernel/bpf/verifier.c static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct b · line 6073
Quoted 4 lines
kernel/bpf/verifier.c +2
-0regs[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;
Quoted 4 lines
Would this fallback path prevent fresh ID generation when id was already set to
ref_obj_id? The condition '!regs[value_regno].id' is now false for nullablePTR_TO_BTF_IDpointers, so each read gets the same static ID instead of a unique one.
Yes. It is intentional. This mirror referenced object obtained through KF_ACQUIRE kfunc, where id == ref_obj.
Quoted 17 lines
Eduard Zingerman's review comment from v3 suggested that the commit message should mention that this patch is mandatory for proper invalidation propagation in later patches. He noted that without the line 'regs[value_regno].id = info.ref_obj_id;', the test 'bpf_qdisc_fail__invalid_dynptr_cross_frame.c:invalid_dynptr_cross_frame' fails because the .id link is needed to propagate invalidation triggered by '
free_skb(skb);' to 'hdr'. The current commit message mentions consistency andparent_idtracking but does not explicitly mention the invalidation propagation aspect.---
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/25442456702
Re: [PATCH bpf-next v4 03/12] bpf: Assign reg->id when getting referenced kptr from ctx
In reply to Amery HungQuoted 8 lines · Amery Hung
Assign
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]>Signed-off-by Amery Hung <[email protected]>---
PATCH v4 4/12 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
@@ -15268,15 +15268,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.52.0
Re: [PATCH bpf-next v4 04/12] bpf: Preserve reg->id of pointer objects after null-check
Quoted 83 lines · Amery Hung
Preserve
reg->idof 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> 0Program Insns (A) Insns (B) Insns (DIFF) States (A) States (B) States (DIFF) ------------------------ --------- --------- -------------- ---------- ---------- -------------
rbtree_search6820 7326 +506 (+7.42%) 379 398 +19 (+5.01%)Meta BPF objects with
insns_diff> 0Program 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 ofrb_n. Without id ofrb_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
Quoted 8 lines
gc_ns[15]: check 257 != 290 --> state not equaliter 17 325 257
rb_n: idmap add 290->325gc_ns[15]: idmap add 257->257 --> state safeAcked-by Andrii Nakryiko <[email protected]>Signed-off-by Amery Hung <[email protected]>---
[...]
PATCH v4 5/12 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 | 23 +- kernel/bpf/log.c | 8 +- kernel/bpf/states.c | 10 +- kernel/bpf/verifier.c | 332 +++++++++--------- .../testing/selftests/bpf/progs/dynptr_fail.c | 18 +- 5 files changed, 203 insertions(+), 188 deletions(-)
include/linux/bpf_verifier.h +19 -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'
@@ -563,7 +569,7 @@ struct bpf_verifier_state { iter < frame->allocated_stack /BPF_REG_SIZE ; \ iter++, reg = bpf_get_spilled_reg(iter, frame, mask)) -#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; \
@@ -571,6 +577,7 @@ struct bpf_verifier_state {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); \
@@ -578,14 +585,20 @@ struct bpf_verifier_state { bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \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 {
@@ -1381,6 +1394,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 {
@@ -1392,6 +1406,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 +163 -169
567 lines not on this page · raw message
tools/testing/selftests/bpf/progs/dynptr_fail.c +9 -9
@@ -471,7 +471,7 @@ int invalid_write1(void *ctx)* offset */ SEC("?raw_tp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int invalid_write2 (void *ctx) {struct bpf_dynptr ptr;
@@ -495,7 +495,7 @@ int invalid_write2(void *ctx)* non-const offset */ SEC("?raw_tp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int invalid_write3 (void *ctx) {struct bpf_dynptr ptr;
@@ -527,7 +527,7 @@ static int invalid_write4_callback(__u32 index, void *data)* be invalidated as a dynptr */ SEC("?raw_tp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int invalid_write4 (void *ctx) {struct bpf_dynptr ptr;
@@ -706,7 +706,7 @@ int dynptr_from_mem_invalid_api(void *ctx) } SEC("?tc") -__failure __msg("cannot overwrite referenced dynptr") __log_level(2) +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") __log_level(2)int dynptr_pruning_overwrite (struct __sk_buff *ctx) { asm volatile (
@@ -768,7 +768,7 @@ int dynptr_pruning_stacksafe(struct __sk_buff *ctx) } SEC("?tc") -__failure __msg("cannot overwrite referenced dynptr") __log_level(2) +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") __log_level(2)int dynptr_pruning_type_confusion (struct __sk_buff *ctx) { asm volatile (
@@ -880,7 +880,7 @@ int dynptr_var_off_overwrite(struct __sk_buff *ctx) } SEC("?tc") -__failure __msg("cannot overwrite referenced dynptr") __log_level(2) +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") __log_level(2)int dynptr_partial_slot_invalidate (struct __sk_buff *ctx) { asm volatile (
@@ -1056,7 +1056,7 @@ int dynptr_invalidate_slice_success(void *ctx)/* Overwriting referenced dynptr should be rejected */ SEC("?raw_tp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int dynptr_overwrite_ref (void *ctx) {struct bpf_dynptr ptr;
@@ -1708,7 +1708,7 @@ int clone_invalid1(void *ctx)/* Can't overwrite an existing dynptr when cloning */ SEC("?xdp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int clone_invalid2 (struct xdp_md *xdp) {struct bpf_dynptr ptr1;
@@ -2015,7 +2015,7 @@ int dynptr_overwrite_ref_with_clone(void *ctx)/* Overwriting the last referenced dynptr should still be rejected */ SEC("?raw_tp") -__failure __msg("cannot overwrite referenced dynptr") +__failure __msg("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.")int dynptr_overwrite_ref_last_clone (void *ctx) {struct bpf_dynptr ptr, clone;
Signature · 1 line
2.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v4 05/12] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Eduard Zingerman raised a suggestion in v3 about adding documentation comments to struct bpf_dynptr_desc. The structure still lacks comments explaining when the id, ref_obj_id, and parent_id fields…
Quoted 4 lines
include/linux/bpf_verifier.h +0
-0
[ ... ]
include/linux/bpf_verifier.h struct bpf_dynptr_desc { · line 1398
Quoted 6 lines
include/linux/bpf_verifier.h +1
-0@@ -1381,6 +1394,7 @@ struct bpf_dynptr_desc {enum bpf_dynptr_type type;u32 id;u32 ref_obj_id; +u32 parent_id; };
Eduard Zingerman raised a suggestion in v3 about adding documentation comments to struct bpf_dynptr_desc. The structure still lacks comments explaining when the id, ref_obj_id, and parent_id fields are populated. Would it help readers to document when these fields are set?
include/linux/bpf_verifier.h struct bpf_kfunc_call_arg_meta { · line 1412
Quoted 10 lines
include/linux/bpf_verifier.h +1
-0struct bpf_kfunc_call_arg_meta {@@ -1392,6 +1406,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;
Eduard Zingerman suggested in v3 adding a comment for the new id field in struct bpf_kfunc_call_arg_meta. The field remains undocumented. Would a comment clarifying its purpose improve code readability?
[ ... ]
---
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/25442456702
Re: [PATCH bpf-next v4 05/12] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Quoted 21 lines · On Wed, May 6, 2026 at 4:27 PM <[email protected]> wrote:
Quoted 5 lines
include/linux/bpf_verifier.h +0
-0[ ... ]
include/linux/bpf_verifier.h struct bpf_dynptr_desc { · line 1398
Quoted 6 lines
include/linux/bpf_verifier.h +1
-0@@ -1381,6 +1394,7 @@ struct bpf_dynptr_desc {enum bpf_dynptr_type type;u32 id;u32 ref_obj_id; +u32 parent_id; };Eduard Zingerman raised a suggestion in v3 about adding documentation comments to struct
bpf_dynptr_desc. The structure still lacks comments explaining when the id,ref_obj_id, andparent_idfields are populated. Would it help readers to document when these fields are set?Quoted 1 line
Quoted 13 lines
include/linux/bpf_verifier.h struct bpf_kfunc_call_arg_meta { · line 1412
Quoted 9 lines
struct
bpf_kfunc_call_arg_meta{include/linux/bpf_verifier.h +1
-0@@ -1392,6 +1406,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;Eduard Zingerman suggested in v3 adding a comment for the new id field in struct
bpf_kfunc_call_arg_meta. The field remains undocumented. Would a comment clarifying its purpose improve code readability?
The readability should be improved in patch 7 where ref_obj_id and id are moved into ref_obj_desc.
For the meaning of id and ref_obj_id, we should keep it in where they are defined: bpf_verifier.h
Quoted 9 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/25442456702
[email protected]
AI reviewRe: [PATCH bpf-next v4 05/12] bpf: Refactor object relationship tracking and fix dynptr UAF bug
In reply to Amery HungThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Critical] Dynptrs constructed from referenced objects are assigned a `parent_id` of 0, breaking…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Dynptrs constructed from referenced objects are assigned a parent_id of 0, breaking cascading invalidation and leading to Use-After-Free. --
commit 5c82adaba693d44fcc105cb9d8d86e76a67e2a64
Author: Amery Hung <[email protected]>
bpf: Refactor object relationship tracking and fix dynptr UAF bug
This commit refactors verifier object relationship tracking by replacing the PTR_TO_MEM-specific dynptr_id with a general parent_id in bpf_reg_state. It updates release_reference() to use a DFS approach for cascading invalidation when parent objects are freed.
Quoted 3 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_ · line 11816
Quoted 9 lines
kernel/bpf/verifier.c +1
-1@@ -11804,15 +11810,10 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_ } dynptr_arg_type |= (unsigned int )get_dynptr_type_flag (parent_type); } ret =process_dynptr_func (env, reg, argno, insn_idx, dynptr_arg_type, - clone_ref_obj_id, &meta->dynptr); + meta->ref_obj_id ? meta->id :0 , &meta->dynptr);
Does this code assign 0 to the dynptr's parent_id instead of the actual parent's ID?
For referenced objects acquired with PTR_MAYBE_NULL, the BPF program must perform a NULL check before passing the pointer to the constructor. Upon a successful NULL check, the verifier clears reg->id to 0 while preserving reg->ref_obj_id.
Consequently, meta->id appears to be unconditionally 0 when the dynptr is constructed here.
When the parent object is subsequently released, the DFS traversal in release_reference() searches for descendants matching reg->parent_id == id. Because the dynptr's parent_id was initialized to 0, does this cause the dynptr to evade invalidation and remain fully active, leading to a use-after-free regression?
Should this pass meta->ref_obj_id instead of meta->id?
Quoted 3 lines
kernel/bpf/verifier.c +0
-0if (ret <0 )return ret;break ;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Re: [PATCH bpf-next v4 05/12] bpf: Refactor object relationship tracking and fix dynptr UAF bug
Quoted 25 lines · On Wed, May 6, 2026 at 10:54 PM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] Dynptrs constructed from referenced objects are assigned aparent_idof 0, breaking cascading invalidation and leading to Use-After-Free. --commit
5c82adaba693d44fcc105cb9d8d86e76a67e2a64
Author: Amery Hung <[email protected]>bpf: Refactor object relationship tracking and fix dynptr UAF bug
This commit refactors verifier object relationship tracking by replacing the PTR_TO_MEM-specific
dynptr_idwith a generalparent_idinbpf_reg_state. It updatesrelease_reference()to use a DFS approach for cascading invalidation when parent objects are freed.Quoted 3 lines
kernel/bpf/verifier.c +0
-0[ ... ]
Quoted 6 lines
kernel/bpf/verifier.c +0
-0@@ -11804,15 +11810,10 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_ } dynptr_arg_type |= (unsigned int )get_dynptr_type_flag (parent_type); }
Quoted 6 lines
kernel/bpf/verifier.c static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_ · line 11816
Quoted 3 lines
kernel/bpf/verifier.c +1
-1ret =process_dynptr_func (env, reg, argno, insn_idx, dynptr_arg_type, - clone_ref_obj_id, &meta->dynptr); + meta->ref_obj_id ? meta->id :0 , &meta->dynptr);Does this code assign 0 to the dynptr's
parent_idinstead of the actual parent's ID?
Yes. In this case, the parent is not a referenced object, so tracking is unnecessary.
While we can track parent_id unconditionally, we should avoid doing it now until every obj, referenced or not, has an id. Otherwise, it becomes hard to reason where the parent_id is valid or not.
I will clarify this in parent_id's comment:parent_id is only tracked when the parent object is referenced or is dynptr.
Although for a slice derived from a non-referenced dynptr, we don't need to track the parent (allowing it to be accessed even when the dynptr stack slot is destroyed). The slice should be destroyed when the parent dynptr is destroyed in the dyntpr's mental model.
Quoted 5 lines
For referenced objects acquired with
PTR_MAYBE_NULL, the BPF program must perform a NULL check before passing the pointer to the constructor. Upon a successful NULL check, the verifier clearsreg->idto 0 while preservingreg->ref_obj_id.
Not any more. See patch 4. Hence the following comments can be ignored.
Quoted 18 lines
Consequently,
meta->idappears to be unconditionally 0 when the dynptr is constructed here.When the parent object is subsequently released, the DFS traversal in
release_reference()searches for descendants matchingreg->parent_id== id. Because the dynptr'sparent_idwas initialized to 0, does this cause the dynptr to evade invalidation and remain fully active, leading to a use-after-free regression?Should this pass
meta->ref_obj_idinstead ofmeta->id?kernel/bpf/verifier.c static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_ · line 11819
Quoted 3 lines
kernel/bpf/verifier.c +0
-0if (ret <0 )return ret;break ;--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Eduard Zingerman
maintainerRe: [PATCH bpf-next v4 05/12] bpf: Refactor object relationship tracking and fix dynptr UAF bug
In reply to Amery HungOn Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
[...]
Quoted 30 lines
(quoted diff) +17
-8+/* 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; - err = release_reference_nomark(vstate, ref_obj_id); - if (err) - return err; + idstack->cnt = 0; + idstack_push(idstack, id); - 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, ({ + int ref_obj_cnt = 1; + + if (reg->id != id && reg->parent_id != id && reg->ref_obj_id != id)
Review
Quoted 10 lines
(quoted diff) +10
-0+ continue; + + /* + * A referenced dynptr can be overwritten only if there is at + * least one other dynptr sharing the same ref_obj_id, + * ensuring the reference can still be properly released. + */ + if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR && + dynptr_type_referenced(reg->dynptr.type)) + ref_obj_cnt = dynptr_get_refcnt(state, reg->ref_obj_id);
Note that dynptr_get_refcnt() only looks for objects in the state's frame, dynptrs in other frames are ignored. This can lead to false rejections, as in the attached test cases, which verifier refuses to load with the following error message:
; *(volatile __u8 *)&clone = 0; @ dynptr_fail.c:2160
19: (73) *(u8 *)(r10 -16) = r1
Leaking reference id=2 alloc_insn=7. Release it first.
processed 14 insns (limit 1000000) max_states_per_insn 1 total_states 1 peak_states 1 mark_read 0
Quoted 26 lines
(quoted diff) +23
-0+ + if (reg->ref_obj_id && reg->ref_obj_id != root_id && ref_obj_cnt <= 1) { + 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; + } + + /* Free objects derived from the current object */ + if (reg->id != id) { + 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; }
[...]
tools/testing/selftests/bpf/progs/dynptr_fail.c +30 -0
@@ -2150,3 +2150,33 @@ int dynptr_overwrite_ref_clone_slice_valid(void *ctx)return 0 ; } + +static __noinline void overwrite_clone_in_callee(struct bpf_dynptr *parent) +{ +struct bpf_dynptr clone; + +bpf_dynptr_clone (parent, &clone); +/* Overwrite the clone - parent in caller frame still holds the ref */ + *(volatile __u8 *)&clone =0 ; +} + +/* +* Overwriting a clone in a callee frame should be allowed when the parent +* in the caller frame still holds the ref. dynptr_get_refcnt() currently +* only counts dynptrs in the current frame, missing the parent in the +* caller frame. +*/ +SEC("?raw_tp") +__success +int dynptr_overwrite_clone_cross_frame (void *ctx) +{ +struct bpf_dynptr ptr; + +bpf_ringbuf_reserve_dynptr (&ringbuf,64 ,0 , &ptr); + +overwrite_clone_in_callee (&ptr); + +bpf_ringbuf_discard_dynptr (&ptr,0 ); + +return 0 ; +}
PATCH v4 6/12 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 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
@@ -8015,26 +8015,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.52.0
Re: [PATCH bpf-next v4 06/12] bpf: Remove redundant dynptr arg check for helper
Quoted 9 lines · Amery Hung
unmark_stack_slots_dynptr()already makes sure thatCONST_PTR_TO_DYNPTRcannot be released.process_dynptr_func()also prevents passing uninitialized dynptr to helpers expecting initialized dynptr. Now thatunmark_stack_slots_dynptr()also error returned fromrelease_reference(), there should be no reason to keep these redundant checks.Signed-off-by Amery Hung <[email protected]>---
[...]
PATCH v4 7/12 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 on 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().
Both helper and kfunc now use ref_obj.cnt to detect ambiguous ref_obj args. 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 | 111 +++++++++---------- tools/testing/selftests/bpf/verifier/calls.c | 24 ---- 3 files changed, 68 insertions(+), 82 deletions(-)
include/linux/bpf_verifier.h +13 -2
@@ -1397,6 +1397,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;
@@ -1405,8 +1417,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;
@@ -1444,6 +1454,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 +55 -56
237 lines not on this page · raw message
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.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The verifier uses `verifier_bug()` to handle ambiguous referenced object arguments, allowing…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The verifier uses verifier_bug() to handle ambiguous referenced object arguments, allowing user input to potentially trigger kernel warnings. --
commit e4dc51a4e8f54da451d3c9dcfb864ea9abe239c6
Author: Amery Hung <[email protected]>
bpf: Unify referenced object tracking in verifier
This commit unifies the reference tracking logic used by helpers and kfuncs into a common ref_obj_desc structure. It updates tracking mechanisms and pushes validation of ambiguous referenced objects out to their use locations.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
kernel/bpf/verifier.c static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ · line 709
Quoted 11 lines
kernel/bpf/verifier.c +7
-0@@ -713,6 +700,13 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_return ref_obj_id; }/* Track parent's id if the parent is a referenced object */ +if (ref_obj && ref_obj->ref_obj_id) { +if (ref_obj->cnt >1 ) { +verifier_bug (env,"function expects only one referenced object but got %d\n" , ref_obj->cnt); +return -EFAULT ; + } + parent_id = ref_obj->id; + }
Since ref_obj->cnt is determined by the number of referenced arguments provided by the BPF program, is it possible for a user to intentionally trigger this verifier_bug() by passing multiple referenced objects?
Since verifier_bug() expands to BPF_WARN_ONCE(), triggering a warning via unprivileged or user-controlled input could be problematic if panic_on_warn is enabled.
Would it be safer to gracefully reject the program using verbose() and returning -EINVAL, similar to how it is handled for release kfuncs earlier in this patch?
This same pattern appears in a few other places introduced by this patch:
[ ... ]
Quoted 19 lines
kernel/bpf/verifier.c +6
-7@@ -10165,15 +10160,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insnif (type_may_be_null (regs[BPF_REG_0 ].type)) regs[BPF_REG_0 ].id = ++env->id_gen; -if (helper_multiple_ref_obj_use (func_id, meta.map.ptr)) { -verifier_bug (env,"func %s#%d sets ref_obj_id more than once" , -func_id_name (func_id), func_id); -return -EFAULT ; - } -if (is_ptr_cast_function (func_id)) {/* For release_reference() */ - regs[BPF_REG_0 ].ref_obj_id = meta.ref_obj_id; +if (meta.ref_obj.cnt >1 ) { +verifier_bug (env,"function expects only one referenced object but got %d\n" , + meta.ref_obj.cnt); +return -EFAULT ; + } + regs[BPF_REG_0 ].ref_obj_id = meta.ref_obj.ref_obj_id;
[ ... ]
Quoted 14 lines
kernel/bpf/verifier.c +8
-2@@ -12740,8 +12733,14 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, regs[BPF_REG_0 ].type |=MEM_RDONLY ;/* Ensures we don't access the memory after a release_reference() */ -if (meta.ref_obj_id) - regs[BPF_REG_0 ].parent_id = meta.ref_obj_id; +if (meta.ref_obj.ref_obj_id) { +if (meta.ref_obj.cnt >1 ) { +verifier_bug (env,"function expects only one referenced object but got %d\n" , + meta.ref_obj.cnt); +return -EFAULT ; + } + regs[BPF_REG_0 ].parent_id = meta.ref_obj.ref_obj_id; + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 14 lines · On Wed, May 6, 2026 at 11:48 PM <[email protected]> wrote:
kernel/bpf/verifier.c static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ · line 709
Quoted 9 lines
} /* Track parent's id if the parent is a referenced object */kernel/bpf/verifier.c +7
-0+if (ref_obj && ref_obj->ref_obj_id) { +if (ref_obj->cnt >1 ) { +verifier_bug (env,"function expects only one referenced object but got %d\n" , ref_obj->cnt); +return -EFAULT ; + } + parent_id = ref_obj->id; + }Since
ref_obj->cntis determined by the number of referenced arguments provided by the BPF program, is it possible for a user to intentionally trigger thisverifier_bug()by passing multiple referenced objects?
Quoted 7 lines
Since
verifier_bug()expands toBPF_WARN_ONCE(), triggering a warning via unprivileged or user-controlled input could be problematic ifpanic_on_warnis enabled.Would it be safer to gracefully reject the program using
verbose()and returning-EINVAL, similar to how it is handled for release kfuncs earlier in this patch?
Ack. Will change to verbsoe().
Quoted 2 lines
This same pattern appears in a few other places introduced by this patch:
Eduard Zingerman
maintainerRe: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
In reply to Amery HungOn Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 12 lines
kernel/bpf/verifier.c +4
-4@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);
I think this should be reported from update_ref_obj() itself, it is more consistent logically and also avoids reporting code duplication in check_kfunc_args() and check_kfunc_call(). Also, technically the reg_arg_name() is an independent fix.
Quoted 3 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.
On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
Quoted 8 lines
kernel/bpf/verifier.c +1
-2return -EACCES ; } - meta->ref_obj_id = reg->ref_obj_id; - meta->id = reg->id; +update_ref_obj (&meta->ref_obj, reg); }switch (base_type (arg_type)) {
[...]
Re: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 10 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
Quoted 3 lines
(quoted diff) +0
-0@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }
Quoted 14 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 9 lines
kernel/bpf/verifier.c +4
-4if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);I think this should be reported from
update_ref_obj()itself, it is more consistent logically and also avoids reporting code duplication incheck_kfunc_args()andcheck_kfunc_call(). Also, technically thereg_arg_name()is an independent fix.
We have kfuncs that have more than one ref_obj. This is not a problem unless ref_obj is referenced in the verification and is ambiguous (e.g., used it to tie the lifetime of the allocated memory with ref_obj). Therefore, it is kept at the location of use instead of update_ref_obj() to prevent breaking existing kfuncs.
Quoted 7 lines
Quoted 4 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.On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
A utility function like below makes sense if we fold ref_obj_id into id. It would be too cumbersome for v3 as we may need two of this for ref_obj->ref_obj_id and ref_obj->id.
static int get_ref_obj_id()
{
if (ref_obj->cnt > 1) {
verifier_bug(env, "function expects only one
referenced object but got %d\n", ref_obj->cnt);
return -EFAULT;
}
return ref_obj->id;
}Quoted 11 lines
Quoted 9 lines
return -EACCES; }kernel/bpf/verifier.c +1
-2- meta->ref_obj_id = reg->ref_obj_id; - meta->id = reg->id; +update_ref_obj (&meta->ref_obj, reg); }switch (base_type (arg_type)) {[...]
Eduard Zingerman
maintainerRe: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 26 lines · Amery Hung
Quoted 10 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
Quoted 3 lines
(quoted diff) +0
-0@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }Quoted 14 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 9 lines
kernel/bpf/verifier.c +4
-4if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);I think this should be reported from
update_ref_obj()itself, it is more consistent logically and also avoids reporting code duplication incheck_kfunc_args()andcheck_kfunc_call(). Also, technically thereg_arg_name()is an independent fix.
Quoted 5 lines
We have kfuncs that have more than one
ref_obj. This is not a problem unlessref_objis referenced in the verification and is ambiguous (e.g., used it to tie the lifetime of the allocated memory withref_obj). Therefore, it is kept at the location of use instead ofupdate_ref_obj()to prevent breaking existing kfuncs.
Ack, thank you for explaining.
Quoted 16 lines
Quoted 7 lines
Quoted 4 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.On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
A utility function like below makes sense if we fold
ref_obj_idinto id. It would be too cumbersome for v3 as we may need two of this forref_obj->ref_obj_idandref_obj->id.static int
get_ref_obj_id()
{
if (ref_obj->cnt> 1) {
verifier_bug(env, "function expects only one
Quoted 5 lines
referenced object but got %d\n", ref_obj->cnt);
return -EFAULT;
}
return ref_obj->id;
}Maybe just like this:
static void validate_ref_obj(struct ref_obj_desc *d) { ... }
?
Re: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 58 lines · Eduard Zingerman
Quoted 26 lines · Amery Hung
Quoted 10 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
Quoted 3 lines
(quoted diff) +0
-0@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }Quoted 14 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 9 lines
kernel/bpf/verifier.c +4
-4if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);I think this should be reported from
update_ref_obj()itself, it is more consistent logically and also avoids reporting code duplication incheck_kfunc_args()andcheck_kfunc_call(). Also, technically thereg_arg_name()is an independent fix.Quoted 5 lines
We have kfuncs that have more than one
ref_obj. This is not a problem unlessref_objis referenced in the verification and is ambiguous (e.g., used it to tie the lifetime of the allocated memory withref_obj). Therefore, it is kept at the location of use instead ofupdate_ref_obj()to prevent breaking existing kfuncs.Ack, thank you for explaining.
Quoted 16 lines
Quoted 7 lines
Quoted 4 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.On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
A utility function like below makes sense if we fold
ref_obj_idinto id. It would be too cumbersome for v3 as we may need two of this forref_obj->ref_obj_idandref_obj->id.static int
get_ref_obj_id()
{
if (ref_obj->cnt> 1) {
verifier_bug(env, "function expects only oneQuoted 5 lines
referenced object but got %d\n", ref_obj->cnt); return -EFAULT; } return ref_obj->id; }
Quoted 4 lines
Maybe just like this:
static void
validate_ref_obj(struct ref_obj_desc *d){ ... }
Do you mean:
static int validate_ref_obj(struct ref_obj_desc *d) { ... }
Then to use it:
err = validate_ref_obj(meta.ref_obj);
if (err)
return err;
regs[BPF_REG_0].ref_obj_id = meta.ref_obj.ref_obj_id;
Quoted 1 line
?
Eduard Zingerman
maintainerRe: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 67 lines · Amery Hung
Quoted 58 lines · Eduard Zingerman
Quoted 26 lines · Amery Hung
Quoted 10 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
Quoted 3 lines
(quoted diff) +0
-0@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }Quoted 14 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 9 lines
kernel/bpf/verifier.c +4
-4if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);I think this should be reported from
update_ref_obj()itself, it is more consistent logically and also avoids reporting code duplication incheck_kfunc_args()andcheck_kfunc_call(). Also, technically thereg_arg_name()is an independent fix.Quoted 5 lines
We have kfuncs that have more than one
ref_obj. This is not a problem unlessref_objis referenced in the verification and is ambiguous (e.g., used it to tie the lifetime of the allocated memory withref_obj). Therefore, it is kept at the location of use instead ofupdate_ref_obj()to prevent breaking existing kfuncs.Ack, thank you for explaining.
Quoted 16 lines
Quoted 7 lines
Quoted 4 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.On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
A utility function like below makes sense if we fold
ref_obj_idinto id. It would be too cumbersome for v3 as we may need two of this forref_obj->ref_obj_idandref_obj->id.static int
get_ref_obj_id()
{
if (ref_obj->cnt> 1) {
verifier_bug(env, "function expects only oneQuoted 5 lines
referenced object but got %d\n", ref_obj->cnt); return -EFAULT; } return ref_obj->id; }Quoted 4 lines
Maybe just like this:
static void
validate_ref_obj(struct ref_obj_desc *d){ ... }Do you mean:
static intvalidate_ref_obj(struct ref_obj_desc *d){ ... }
Quoted 8 lines
Then to use it:
err =validate_ref_obj(meta.ref_obj);
if (err)return err;regs[BPF_REG_0].ref_obj_id = meta.ref_obj.ref_obj_id;
Quoted 1 line
?
Yes, like that, sorry.
Re: [PATCH bpf-next v4 07/12] bpf: Unify referenced object tracking in verifier
Quoted 74 lines · Eduard Zingerman
Quoted 72 lines · Amery Hung
Quoted 58 lines · Eduard Zingerman
Quoted 26 lines · Amery Hung
Quoted 10 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, a nit below.
[...]
Quoted 3 lines
(quoted diff) +0
-0@@ -8028,14 +8024,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg, }Quoted 14 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8030
Quoted 9 lines
kernel/bpf/verifier.c +4
-4if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->ref_obj_id) { -verbose (env,"more than one arg with ref_obj_id R%d %u %u" , - regno, reg->ref_obj_id, - meta->ref_obj_id); +if (meta->release_regno && meta->ref_obj.cnt) { +verbose (env,"more than one arg with ref_obj_id %s %u %u" , +reg_arg_name (env, argno), reg->ref_obj_id, + meta->ref_obj.ref_obj_id);I think this should be reported from
update_ref_obj()itself, it is more consistent logically and also avoids reporting code duplication incheck_kfunc_args()andcheck_kfunc_call(). Also, technically thereg_arg_name()is an independent fix.Quoted 5 lines
We have kfuncs that have more than one
ref_obj. This is not a problem unlessref_objis referenced in the verification and is ambiguous (e.g., used it to tie the lifetime of the allocated memory withref_obj). Therefore, it is kept at the location of use instead ofupdate_ref_obj()to prevent breaking existing kfuncs.Ack, thank you for explaining.
Quoted 16 lines
Quoted 7 lines
Quoted 4 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.On the other hand, if you think that this property is worth having, then maybe wrap the check with in some utility function?
A utility function like below makes sense if we fold
ref_obj_idinto id. It would be too cumbersome for v3 as we may need two of this forref_obj->ref_obj_idandref_obj->id.static int
get_ref_obj_id()
{
if (ref_obj->cnt> 1) {
verifier_bug(env, "function expects only oneQuoted 5 lines
referenced object but got %d\n", ref_obj->cnt); return -EFAULT; } return ref_obj->id; }Quoted 4 lines
Maybe just like this:
static void
validate_ref_obj(struct ref_obj_desc *d){ ... }Do you mean:
static intvalidate_ref_obj(struct ref_obj_desc *d){ ... }Then to use it:
err =validate_ref_obj(meta.ref_obj);
if (err)return err;
Quoted 5 lines
Quoted 3 lines
regs[BPF_REG_0].ref_obj_id = meta.ref_obj.ref_obj_id;
Quoted 1 line
?
Yes, like that, sorry.
Np. Thanks for the suggestion. I will add the utility function.
PATCH v4 8/12 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 | 194 +++++++++--------- .../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, 120 insertions(+), 110 deletions(-)
include/linux/bpf_verifier.h +3 -3
@@ -1399,9 +1399,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 +102 -92
303 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.52.0
[email protected]
AI reviewRe: [PATCH bpf-next v4 08/12] bpf: Unify release handling for helpers and kfuncs
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Hardcoding meta->release_regno = BPF_REG_1 for KF_RELEASE kfuncs creates a Use-After-Free…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Hardcoding meta->release_regno = BPF_REG_1 for KF_RELEASE kfuncs creates a Use-After-Free vulnerability for kfuncs releasing non-first arguments.
- [Medium] Incorrect evaluation of the release_dynptr flag leads to false rejection of valid BPF programs.
--
commit e0e1bbafcfda45d42ce5635352bc4b69c0d713c6
Author: Amery Hung <[email protected]>
bpf: Unify release handling for helpers and kfuncs
Introduce release_reg() to consolidate the release logic shared by both helpers and kfuncs. The patch determines release_regno from the function prototype or metadata before argument checking.
Quoted 4 lines
kernel/bpf/verifier.c +0
-0
[ ... ]
Quoted 4 lines
kernel/bpf/verifier.c +0
-0@@ -9870,37 +9928,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn }if (meta.release_regno) {
[ ... ]
kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 9938
Quoted 8 lines
kernel/bpf/verifier.c +5
-0+struct bpf_reg_state *reg = ®s[meta.release_regno]; +bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) &&in_rcu_cs (env) && + (reg->type &MEM_ALLOC ) && (reg->type &MEM_PERCPU ); + + err =release_reg (env, reg, convert_rcu, !!meta.dynptr.ref_obj_id);if (err)return err; }
Does passing !!meta.dynptr.ref_obj_id as the release_dynptr flag cause valid programs to be rejected?
If a kfunc or helper accepts both a normal PTR_TO_BTF_ID to be released and a referenced dynptr as a normal (non-release) argument, meta.dynptr.ref_obj_id would be set. This would cause release_reg() to mistakenly invoke unmark_stack_slots_dynptr() on the non-dynptr release register, returning -EINVAL.
Could the release condition be strictly derived from the argument type of the specific release register instead?
[ ... ]
kernel/bpf/verifier.c int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, · line 12114
Quoted 9 lines
kernel/bpf/verifier.c +3
-0@@ -12083,6 +12107,9 @@ int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, meta->kfunc_flags = *kfunc.flags; +if (is_kfunc_release (meta)) + meta->release_regno =BPF_REG_1 ; +return 0 ; }
By unconditionally hardcoding BPF_REG_1 here, could this create a use-after-free if a kernel module defines a release kfunc that frees an argument other than the first?
If a BPF program passes a dummy referenced object to R1 and the actual target object to R2, the verifier might drop the reference for R1 while retaining R2, even though the kfunc frees R2 at runtime.
Should we still rely on dynamically discovering the release register based on the argument type to avoid this?
[ ... ]
Quoted 1 line
kernel/bpf/verifier.c +0
-0@@ -12622,13 +12638,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
[ ... ]
kernel/bpf/verifier.c static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 12644
Quoted 12 lines
kernel/bpf/verifier.c +1
-7if (meta.release_regno) { -struct bpf_reg_state *reg = ®s[meta.release_regno]; - -if (meta.dynptr.ref_obj_id) { - err =unmark_stack_slots_dynptr (env, reg); - }else { - err =release_reference (env, reg->ref_obj_id); - } + err =release_reg (env, ®s[meta.release_regno], false, !!meta.dynptr.ref_obj_id);if (err)return err; }
Similar to the check_helper_call() case above, does this global dynptr metadata check safely handle mixed arguments when releasing registers?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Re: [PATCH bpf-next v4 08/12] bpf: Unify release handling for helpers and kfuncs
Quoted 37 lines · On Thu, May 7, 2026 at 12:59 AM <[email protected]> wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Hardcodingmeta->release_regno=BPF_REG_1forKF_RELEASEkfuncs creates a Use-After-Free vulnerability for kfuncs releasing non-first arguments.
- [Medium] Incorrect evaluation of therelease_dynptrflag leads to false rejection of valid BPF programs.
--commit
e0e1bbafcfda45d42ce5635352bc4b69c0d713c6
Author: Amery Hung <[email protected]>bpf: Unify release handling for helpers and kfuncs
Introduce
release_reg()to consolidate the release logic shared by both helpers and kfuncs. The patch determinesrelease_regnofrom the function prototype or metadata before argument checking.Quoted 4 lines
kernel/bpf/verifier.c +0
-0[ ... ]
Quoted 4 lines
kernel/bpf/verifier.c +0
-0@@ -9870,37 +9928,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn }if (meta.release_regno) {[ ... ]
kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 9938
Quoted 8 lines
kernel/bpf/verifier.c +5
-0+struct bpf_reg_state *reg = ®s[meta.release_regno]; +bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) &&in_rcu_cs (env) && + (reg->type &MEM_ALLOC ) && (reg->type &MEM_PERCPU ); + + err =release_reg (env, reg, convert_rcu, !!meta.dynptr.ref_obj_id);if (err)return err; }Does passing !!meta.dynptr.ref_obj_id as the
release_dynptrflag cause valid programs to be rejected?
Quoted 8 lines
If a kfunc or helper accepts both a normal
PTR_TO_BTF_IDto be released and a referenced dynptr as a normal (non-release) argument, meta.dynptr.ref_obj_id would be set. This would causerelease_reg()to mistakenly invokeunmark_stack_slots_dynptr()on the non-dynptr release register, returning-EINVAL.Could the release condition be strictly derived from the argument type of the specific release register instead?
No existing helper and kfunc releases a ref_obj that also has another dynptr argument.
Kfunc already use this check and I choose to make helper align with kfunc to make it the same without overcomplicating things. In the future when there is a universal proto for heleprs and kfuncs, we can check meta->fn->arg_type[release_regno] to make it more robust.
Quoted 16 lines
[ ... ]
kernel/bpf/verifier.c int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, · line 12114
Quoted 9 lines
kernel/bpf/verifier.c +3
-0@@ -12083,6 +12107,9 @@ int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, meta->kfunc_flags = *kfunc.flags; +if (is_kfunc_release (meta)) + meta->release_regno =BPF_REG_1 ; +return 0 ; }By unconditionally hardcoding
BPF_REG_1here, could this create a use-after-free if a kernel module defines a release kfunc that frees an argument other than the first?
Quoted 6 lines
If a BPF program passes a dummy referenced object to R1 and the actual target object to R2, the verifier might drop the reference for R1 while retaining R2, even though the kfunc frees R2 at runtime.
Should we still rely on dynamically discovering the release register based on the argument type to avoid this?
If anyone is developing a new kfunc whose ref_obj to be released is not BPF_REG_1, the verifier should scream "unreleased reference", so the bug is unlikely to make it into the kernel.
Some reason for this approach: The longterm goal is to remove the dependency of bpf_reg_state from kfunc proto generation. In this case, I want to tag OBJ_RELEASE by looking at the proto. This is currently impossible since we haved enable decl_tag for kfunc arguments yet. I think hardcode to BPF_REG_1 is a reasonable workaround for now.
If this sounds okay. I will add this temporary constraint to kfuncs.rst.
Quoted 22 lines
[ ... ]
Quoted 1 line
kernel/bpf/verifier.c +0
-0@@ -12622,13 +12638,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,[ ... ]
kernel/bpf/verifier.c static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 12644
Quoted 12 lines
if (meta.release_regno) {kernel/bpf/verifier.c +1
-7-struct bpf_reg_state *reg = ®s[meta.release_regno]; - -if (meta.dynptr.ref_obj_id) { - err =unmark_stack_slots_dynptr (env, reg); - }else { - err =release_reference (env, reg->ref_obj_id); - } + err =release_reg (env, ®s[meta.release_regno], false, !!meta.dynptr.ref_obj_id);if (err)return err; }Similar to the
check_helper_call()case above, does this global dynptr metadata check safely handle mixed arguments when releasing registers?--
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Eduard Zingerman
maintainerRe: [PATCH bpf-next v4 08/12] bpf: Unify release handling for helpers and kfuncs
In reply to Amery HungOn Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, one question below.
Quoted 10 lines
kernel/bpf/verifier.c +0
-6@@ -8010,28 +8010,15 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,return err; skip_type_check: -if (arg_type_is_release (arg_type)) { -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 ; - }
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8017
Quoted 10 lines
kernel/bpf/verifier.c +5
-5-if (meta->release_regno) { -verifier_bug (env,"more than one release argument" ); -return -EFAULT ; - } - meta->release_regno = regno; +if (arg_type_is_release (arg_type) && !arg_type_is_dynptr (arg_type) && + !reg->ref_obj_id && !bpf_register_is_null (reg)) { +verbose (env,"release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n" , +func_id_name (meta->func_id),reg_arg_name (env, argno)); +return -EINVAL ;
Nit: a similar check is added in check_kfunc_args(),
can these be wrapped in some utility function?
Quoted 15 lines
kernel/bpf/verifier.c +1
-8} -if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->release_regno && meta->ref_obj.cnt) { -verbose (env,"more than one arg with ref_obj_id %s %u %u" , -reg_arg_name (env, argno), reg->ref_obj_id, - meta->ref_obj.ref_obj_id); -return -EACCES ; - } +if (reg->ref_obj_id)update_ref_obj (&meta->ref_obj, reg); - }switch (base_type (arg_type)) {case ARG_CONST_MAP_PTR :
[...]
Quoted 22 lines
kernel/bpf/verifier.c +1
-10@@ -9825,7 +9883,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insnmemset (&meta,0 ,sizeof (meta)); meta.pkt_access = fn->pkt_access; - err =check_func_proto (fn); + err =check_func_proto (fn, &meta);if (err) {verifier_bug (env,"incorrect func proto %s#%d" ,func_id_name (func_id), func_id);return err;@@ -9870,37 +9928,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn }if (meta.release_regno) { - err = -EINVAL ; -if (arg_type_is_dynptr (fn->arg_type[meta.release_regno -BPF_REG_1 ])) { - err =unmark_stack_slots_dynptr (env, ®s[meta.release_regno]); - }else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj.ref_obj_id) { -u32 ref_obj_id = meta.ref_obj.ref_obj_id; -bool in_rcu =in_rcu_cs (env); -struct bpf_func_state *state; -struct bpf_reg_state *reg; -
kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 9891
Quoted 10 lines
kernel/bpf/verifier.c +0
-10- err =release_reference_nomark (env->cur_state, ref_obj_id); -if (!err) { - bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ - if (reg->ref_obj_id == ref_obj_id) { - if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { - reg->ref_obj_id = 0; - reg->type &= ~MEM_ALLOC; - reg->type |= MEM_RCU; - } else { - mark_reg_invalid(env, reg);
Note: release_reg() does not have this 'else' path, but it seem to be not a problem,
assuming that MEM_ALLOC | MEM_PERCPU registers are generated only from some other cmp_xchg call. Is that the case?
Quoted 20 lines
kernel/bpf/verifier.c +5
-12- } - } - })); - } - }else if (meta.ref_obj.ref_obj_id) { - err =release_reference (env, meta.ref_obj.ref_obj_id); - }else if (bpf_register_is_null (®s[meta.release_regno])) { -/* meta.ref_obj.ref_obj_id can only be 0 if register that is meant to be -* released is NULL, which must be > R0. -*/ - err =0 ; - } +struct bpf_reg_state *reg = ®s[meta.release_regno]; +bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) &&in_rcu_cs (env) && + (reg->type &MEM_ALLOC ) && (reg->type &MEM_PERCPU ); + + err =release_reg (env, reg, convert_rcu, !!meta.dynptr.ref_obj_id);if (err)return err; }
[...]
Quoted 27 lines
kernel/bpf/verifier.c +8
-10@@ -11609,18 +11640,16 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_return -EACCES ; } -if (reg->ref_obj_id) { -if (is_kfunc_release (meta) && meta->ref_obj.cnt) { -verbose (env,"more than one arg with ref_obj_id %s %u %u" , -reg_arg_name (env, argno), reg->ref_obj_id, - meta->ref_obj.ref_obj_id); -return -EFAULT ; - } -update_ref_obj (&meta->ref_obj, reg); -if (is_kfunc_release (meta)) - meta->release_regno = regno; +if (regno == meta->release_regno && !is_kfunc_arg_dynptr (meta->btf, &args[i]) && + !reg->ref_obj_id && !bpf_register_is_null (reg)) { +verbose (env,"release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n" , + func_name,reg_arg_name (env, argno)); +return -EINVAL ; } +if (reg->ref_obj_id) +update_ref_obj (&meta->ref_obj, reg); + ref_t =btf_type_skip_modifiers (btf, t->type, &ref_id); ref_tname =btf_name_by_offset (btf, ref_t->name_off);
[...]
Re: [PATCH bpf-next v4 08/12] bpf: Unify release handling for helpers and kfuncs
Quoted 20 lines · Eduard Zingerman
On Wed, 2026-05-06 at 07:27 -0700, Amery Hung wrote:
LGTM, one question below.
Quoted 15 lines
kernel/bpf/verifier.c +0
-11@@ -8010,28 +8010,15 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,return err; skip_type_check: -if (arg_type_is_release (arg_type)) { -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 ; - } -if (meta->release_regno) { -verifier_bug (env,"more than one release argument" ); -return -EFAULT ; - } - meta->release_regno = regno;
Quoted 8 lines
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 8017
Quoted 5 lines
kernel/bpf/verifier.c +5
-0+if (arg_type_is_release (arg_type) && !arg_type_is_dynptr (arg_type) && + !reg->ref_obj_id && !bpf_register_is_null (reg)) { +verbose (env,"release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n" , +func_id_name (meta->func_id),reg_arg_name (env, argno)); +return -EINVAL ;Nit: a similar check is added in
check_kfunc_args(),
can these be wrapped in some utility function?
Make sense.
Quoted 47 lines
Quoted 16 lines
kernel/bpf/verifier.c +1
-8} -if (reg->ref_obj_id &&base_type (arg_type) !=ARG_KPTR_XCHG_DEST ) { -if (meta->release_regno && meta->ref_obj.cnt) { -verbose (env,"more than one arg with ref_obj_id %s %u %u" , -reg_arg_name (env, argno), reg->ref_obj_id, - meta->ref_obj.ref_obj_id); -return -EACCES ; - } +if (reg->ref_obj_id)update_ref_obj (&meta->ref_obj, reg); - }switch (base_type (arg_type)) {case ARG_CONST_MAP_PTR :[...]
Quoted 28 lines
kernel/bpf/verifier.c +1
-16@@ -9825,7 +9883,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insnmemset (&meta,0 ,sizeof (meta)); meta.pkt_access = fn->pkt_access; - err =check_func_proto (fn); + err =check_func_proto (fn, &meta);if (err) {verifier_bug (env,"incorrect func proto %s#%d" ,func_id_name (func_id), func_id);return err;@@ -9870,37 +9928,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn }if (meta.release_regno) { - err = -EINVAL ; -if (arg_type_is_dynptr (fn->arg_type[meta.release_regno -BPF_REG_1 ])) { - err =unmark_stack_slots_dynptr (env, ®s[meta.release_regno]); - }else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj.ref_obj_id) { -u32 ref_obj_id = meta.ref_obj.ref_obj_id; -bool in_rcu =in_rcu_cs (env); -struct bpf_func_state *state; -struct bpf_reg_state *reg; - - err =release_reference_nomark (env->cur_state, ref_obj_id); -if (!err) { - bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ - if (reg->ref_obj_id == ref_obj_id) { - if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { - reg->ref_obj_id = 0;
Quoted 8 lines
kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 9891
Quoted 4 lines
kernel/bpf/verifier.c +0
-4- reg->type &= ~MEM_ALLOC ; - reg->type |=MEM_RCU ; - }else { -mark_reg_invalid (env, reg);Note:
release_reg()does not have this 'else' path, but it seem to be not a problem,
assuming thatMEM_ALLOC|MEM_PERCPUregisters are generated only from some othercmp_xchgcall. Is that the case?
AFAIK, percpu allocated objects (i.e., MEM_ALLOC | MEM_PERCPU registers) only come from bpf_kptr_xchg() and bpf_percpu_obj_new(). We don't have a mechanism to derive registers from percpu allocated objects such that we need to mark_reg_invalid when calling bpf_kptr_xchg().
If there is such case in the future, maybe we can do the following in release_reg() then
if (convert_rcu)
err = ref_convert_alloc_rcu_protected(env, reg->ref_obj_id);
if (release_dynptr)
err = unmark_stack_slots_dynptr(env, reg);
else if (reg->ref_obj_id)
err = release_reference(env, reg->ref_obj_id);
else if (bpf_register_is_null(reg))
err = 0;Quoted 53 lines
Quoted 21 lines
kernel/bpf/verifier.c +5
-12- } - } - })); - } - }else if (meta.ref_obj.ref_obj_id) { - err =release_reference (env, meta.ref_obj.ref_obj_id); - }else if (bpf_register_is_null (®s[meta.release_regno])) { -/* meta.ref_obj.ref_obj_id can only be 0 if register that is meant to be -* released is NULL, which must be > R0. -*/ - err =0 ; - } +struct bpf_reg_state *reg = ®s[meta.release_regno]; +bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) &&in_rcu_cs (env) && + (reg->type &MEM_ALLOC ) && (reg->type &MEM_PERCPU ); + + err =release_reg (env, reg, convert_rcu, !!meta.dynptr.ref_obj_id);if (err)return err; }[...]
Quoted 27 lines
kernel/bpf/verifier.c +8
-10@@ -11609,18 +11640,16 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_return -EACCES ; } -if (reg->ref_obj_id) { -if (is_kfunc_release (meta) && meta->ref_obj.cnt) { -verbose (env,"more than one arg with ref_obj_id %s %u %u" , -reg_arg_name (env, argno), reg->ref_obj_id, - meta->ref_obj.ref_obj_id); -return -EFAULT ; - } -update_ref_obj (&meta->ref_obj, reg); -if (is_kfunc_release (meta)) - meta->release_regno = regno; +if (regno == meta->release_regno && !is_kfunc_arg_dynptr (meta->btf, &args[i]) && + !reg->ref_obj_id && !bpf_register_is_null (reg)) { +verbose (env,"release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n" , + func_name,reg_arg_name (env, argno)); +return -EINVAL ; } +if (reg->ref_obj_id) +update_ref_obj (&meta->ref_obj, reg); + ref_t =btf_type_skip_modifiers (btf, t->type, &ref_id); ref_tname =btf_name_by_offset (btf, ref_t->name_off);[...]
Re: [PATCH bpf-next v4 08/12] bpf: Unify release handling for helpers and kfuncs
On Tue, 2026-05-12 at 23:22 +0200, Amery Hung wrote:
[...]
Quoted 37 lines
Quoted 19 lines
Quoted 19 lines
kernel/bpf/verifier.c +0
-15@@ -9870,37 +9928,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn }if (meta.release_regno) { - err = -EINVAL ; -if (arg_type_is_dynptr (fn->arg_type[meta.release_regno -BPF_REG_1 ])) { - err =unmark_stack_slots_dynptr (env, ®s[meta.release_regno]); - }else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj.ref_obj_id) { -u32 ref_obj_id = meta.ref_obj.ref_obj_id; -bool in_rcu =in_rcu_cs (env); -struct bpf_func_state *state; -struct bpf_reg_state *reg; - - err =release_reference_nomark (env->cur_state, ref_obj_id); -if (!err) { - bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ - if (reg->ref_obj_id == ref_obj_id) { - if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { - reg->ref_obj_id = 0;Quoted 8 lines
kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 9891
Quoted 4 lines
kernel/bpf/verifier.c +0
-4- reg->type &= ~MEM_ALLOC ; - reg->type |=MEM_RCU ; - }else { -mark_reg_invalid (env, reg);Note:
release_reg()does not have this 'else' path, but it seem to be not a problem,
assuming thatMEM_ALLOC|MEM_PERCPUregisters are generated only from some othercmp_xchgcall. Is that the case?AFAIK, percpu allocated objects (i.e.,
MEM_ALLOC|MEM_PERCPUregisters) only come frombpf_kptr_xchg()andbpf_percpu_obj_new(). We don't have a mechanism to derive registers from percpu allocated objects such that we need tomark_reg_invalidwhen callingbpf_kptr_xchg().If there is such case in the future, maybe we can do the following in
release_reg()then
Quoted 9 lines
if (convert_rcu)
err = ref_convert_alloc_rcu_protected(env, reg->ref_obj_id);
if (release_dynptr)
err = unmark_stack_slots_dynptr(env, reg);
else if (reg->ref_obj_id)
err = release_reference(env, reg->ref_obj_id);
else if (bpf_register_is_null(reg))
err = 0;Thank you for explaining, in such case I think the code is good as it is.
[...]
PATCH v4 9/12 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("Leaking reference id={{[0-9]+}} alloc_insn={{[0-9]+}}. Release it first.") __log_level(2)int dynptr_pruning_overwrite (struct __sk_buff *ctx)
Signature · 1 line
2.52.0
PATCH v4 10/12 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.52.0
PATCH v4 11/12 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.52.0
PATCH v4 12/12 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.52.0