[PATCH 3/5] bpf: Improve exception handling in bpf_core_apply()

From: Markus Elfring
Date: Sat Dec 30 2023 - 15:10:53 EST


From: Markus Elfring <elfring@xxxxxxxxxxxxxxxxxxxxx>
Date: Sat, 30 Dec 2023 19:28:25 +0100

The kfree() function was called in two cases by
the bpf_core_apply() function during error handling
even if the passed data structure member contained a null pointer.
This issue was detected by using the Coccinelle software.

* Thus use another label.

* Reorder function calls at the end.

Signed-off-by: Markus Elfring <elfring@xxxxxxxxxxxxxxxxxxxxx>
---
kernel/bpf/btf.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 51e8b4bee0c8..e8391025d408 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -8322,13 +8322,13 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
bpf_log(ctx->log, "target candidate search failed for %d\n",
relo->type_id);
err = PTR_ERR(cc);
- goto out;
+ goto unlock_mutex;
}
if (cc->cnt) {
cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
if (!cands.cands) {
err = -ENOMEM;
- goto out;
+ goto unlock_mutex;
}
}
for (i = 0; i < cc->cnt; i++) {
@@ -8355,13 +8355,15 @@ int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
&targ_res);

out:
- kfree(specs);
if (need_cands) {
kfree(cands.cands);
+unlock_mutex:
mutex_unlock(&cand_cache_mutex);
if (ctx->log->level & BPF_LOG_LEVEL2)
print_cand_cache(ctx->log);
}
+
+ kfree(specs);
return err;
}

--
2.43.0