Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

bpf: Silence Coverity warning for find_kfunc_desc_btf

The helper function returns a pointer that in the failure case encodes
an error in the struct btf pointer. The current code lead to Coverity
warning about the use of the invalid pointer:

*** CID 1507963: Memory - illegal accesses (USE_AFTER_FREE)
/kernel/bpf/verifier.c: 1788 in find_kfunc_desc_btf()
1782 return ERR_PTR(-EINVAL);
1783 }
1784
1785 kfunc_btf = __find_kfunc_desc_btf(env, offset, btf_modp);
1786 if (IS_ERR_OR_NULL(kfunc_btf)) {
1787 verbose(env, "cannot find module BTF for func_id %u\n", func_id);
>>> CID 1507963: Memory - illegal accesses (USE_AFTER_FREE)
>>> Using freed pointer "kfunc_btf".
1788 return kfunc_btf ?: ERR_PTR(-ENOENT);
1789 }
1790 return kfunc_btf;
1791 }
1792 return btf_vmlinux ?: ERR_PTR(-ENOENT);
1793 }

Daniel suggested the use of ERR_CAST so that the intended use is clear
to Coverity, but on closer look it seems that we never return NULL from
the helper. Andrii noted that since __find_kfunc_desc_btf already logs
errors for all cases except btf_get_by_fd, it is much easier to add
logging for that and remove the IS_ERR check altogether, returning
directly from it.

Suggested-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Link: https://lore.kernel.org/bpf/20211009040900.803436-1-memxor@gmail.com

authored by

Kumar Kartikeya Dwivedi and committed by
Andrii Nakryiko
588cd7ef 32fa0efa

+4 -9
+4 -9
kernel/bpf/verifier.c
··· 1727 1727 return ERR_PTR(-EFAULT); 1728 1728 1729 1729 btf = btf_get_by_fd(btf_fd); 1730 - if (IS_ERR(btf)) 1730 + if (IS_ERR(btf)) { 1731 + verbose(env, "invalid module BTF fd specified\n"); 1731 1732 return btf; 1733 + } 1732 1734 1733 1735 if (!btf_is_module(btf)) { 1734 1736 verbose(env, "BTF fd for kfunc is not a module BTF\n"); ··· 1773 1771 u32 func_id, s16 offset, 1774 1772 struct module **btf_modp) 1775 1773 { 1776 - struct btf *kfunc_btf; 1777 - 1778 1774 if (offset) { 1779 1775 if (offset < 0) { 1780 1776 /* In the future, this can be allowed to increase limit ··· 1782 1782 return ERR_PTR(-EINVAL); 1783 1783 } 1784 1784 1785 - kfunc_btf = __find_kfunc_desc_btf(env, offset, btf_modp); 1786 - if (IS_ERR_OR_NULL(kfunc_btf)) { 1787 - verbose(env, "cannot find module BTF for func_id %u\n", func_id); 1788 - return kfunc_btf ?: ERR_PTR(-ENOENT); 1789 - } 1790 - return kfunc_btf; 1785 + return __find_kfunc_desc_btf(env, offset, btf_modp); 1791 1786 } 1792 1787 return btf_vmlinux ?: ERR_PTR(-ENOENT); 1793 1788 }