• Dave Marchevsky's avatar
    bpf: Search for kptrs in prog BTF structs · 7a851ecb
    Dave Marchevsky authored
    Currently btf_parse_fields is used in two places to create struct
    btf_record's for structs: when looking at mapval type, and when looking
    at any struct in program BTF. The former looks for kptr fields while the
    latter does not. This patch modifies the btf_parse_fields call made when
    looking at prog BTF struct types to search for kptrs as well.
    
    Before this series there was no reason to search for kptrs in non-mapval
    types: a referenced kptr needs some owner to guarantee resource cleanup,
    and map values were the only owner that supported this. If a struct with
    a kptr field were to have some non-kptr-aware owner, the kptr field
    might not be properly cleaned up and result in resources leaking. Only
    searching for kptr fields in mapval was a simple way to avoid this
    problem.
    
    In practice, though, searching for BPF_KPTR when populating
    struct_meta_tab does not expose us to this risk, as struct_meta_tab is
    only accessed through btf_find_struct_meta helper, and that helper is
    only called in contexts where recognizing the kptr field is safe:
    
      * PTR_TO_BTF_ID reg w/ MEM_ALLOC flag
        * Such a reg is a local kptr and must be free'd via bpf_obj_drop,
          which will correctly handle kptr field
    
      * When handling specific kfuncs which either expect MEM_ALLOC input or
        return MEM_ALLOC output (obj_{new,drop}, percpu_obj_{new,drop},
        list+rbtree funcs, refcount_acquire)
         * Will correctly handle kptr field for same reasons as above
    
      * When looking at kptr pointee type
         * Called by functions which implement "correct kptr resource
           handling"
    
      * In btf_check_and_fixup_fields
         * Helper that ensures no ownership loops for lists and rbtrees,
           doesn't care about kptr field existence
    
    So we should be able to find BPF_KPTR fields in all prog BTF structs
    without leaking resources.
    
    Further patches in the series will build on this change to support
    kptr_xchg into non-mapval local kptr. Without this change there would be
    no kptr field found in such a type.
    Acked-by: default avatarMartin KaFai Lau <martin.lau@kernel.org>
    Acked-by: default avatarHou Tao <houtao1@huawei.com>
    Signed-off-by: default avatarDave Marchevsky <davemarchevsky@fb.com>
    Signed-off-by: default avatarAmery Hung <amery.hung@bytedance.com>
    Link: https://lore.kernel.org/r/20240813212424.2871455-3-amery.hung@bytedance.comSigned-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
    7a851ecb
btf.c 237 KB