Add regression coverage for bpf_refcount_acquire() on graph-node-derived
pointers.

The rejected case passes a popped list node pointer directly to
bpf_refcount_acquire(), which must fail because the pointer carries a
non-zero fixed offset.

Signed-off-by: Yiyang Chen <[email protected]>
---
 .../bpf/progs/refcounted_kptr_fail.c          | 34 +++++++++++++++++++
 1 file changed, 34 insertions(+)

diff --git a/tools/testing/selftests/bpf/progs/refcounted_kptr_fail.c 
b/tools/testing/selftests/bpf/progs/refcounted_kptr_fail.c
index 7247a20c0..024ef2aae 100644
--- a/tools/testing/selftests/bpf/progs/refcounted_kptr_fail.c
+++ b/tools/testing/selftests/bpf/progs/refcounted_kptr_fail.c
@@ -13,12 +13,20 @@ struct node_acquire {
        struct bpf_refcount refcount;
 };
 
+struct node_refcounted {
+       long key;
+       struct bpf_list_node list;
+       struct bpf_refcount refcount;
+};
+
 extern void bpf_rcu_read_lock(void) __ksym;
 extern void bpf_rcu_read_unlock(void) __ksym;
 
 #define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
 private(A) struct bpf_spin_lock glock;
 private(A) struct bpf_rb_root groot __contains(node_acquire, node);
+private(B) struct bpf_spin_lock lock;
+private(B) struct bpf_list_head head __contains(node_refcounted, list);
 
 static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
 {
@@ -93,6 +101,32 @@ long rbtree_refcounted_node_ref_escapes_owning_input(void 
*ctx)
        return 0;
 }
 
+SEC("?tc")
+__failure __msg("dereference of modified ptr_ ptr R1")
+long refcount_acquire_list_node_offset(void *ctx)
+{
+       struct node_refcounted *node, *base, *ref;
+       struct bpf_list_node *list_node;
+
+       node = bpf_obj_new(typeof(*node));
+       if (!node)
+               return 1;
+
+       bpf_spin_lock(&lock);
+       bpf_list_push_front(&head, &node->list);
+       list_node = bpf_list_pop_front(&head);
+       bpf_spin_unlock(&lock);
+       if (!list_node)
+               return 2;
+
+       base = container_of(list_node, struct node_refcounted, list);
+       ref = bpf_refcount_acquire(list_node);
+       if (ref)
+               bpf_obj_drop(ref);
+       bpf_obj_drop(base);
+       return 0;
+}
+
 SEC("?fentry.s/" SYS_PREFIX "sys_getpgid")
 __failure __msg("function calls are not allowed while holding a lock")
 int BPF_PROG(rbtree_fail_sleepable_lock_across_rcu,
-- 
2.34.1


Reply via email to