[PATCH 1/5] bpf: Improve exception handling in bpf_struct_ops_link_create()

From: Markus Elfring
Date: Sat Dec 30 2023 - 15:06:56 EST


From: Markus Elfring <elfring@xxxxxxxxxxxxxxxxxxxxx>
Date: Sat, 30 Dec 2023 18:50:45 +0100

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

* Thus use another label.

* Reorder function calls at the end.

* Delete an initialisation (for the variable “link”)
which became unnecessary with this refactoring.

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

diff --git a/kernel/bpf/bpf_struct_ops.c b/kernel/bpf/bpf_struct_ops.c
index 02068bd0e4d9..b49ea460d616 100644
--- a/kernel/bpf/bpf_struct_ops.c
+++ b/kernel/bpf/bpf_struct_ops.c
@@ -888,7 +888,7 @@ static const struct bpf_link_ops bpf_struct_ops_map_lops = {

int bpf_struct_ops_link_create(union bpf_attr *attr)
{
- struct bpf_struct_ops_link *link = NULL;
+ struct bpf_struct_ops_link *link;
struct bpf_link_primer link_primer;
struct bpf_struct_ops_map *st_map;
struct bpf_map *map;
@@ -902,13 +902,13 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)

if (!bpf_struct_ops_valid_to_reg(map)) {
err = -EINVAL;
- goto err_out;
+ goto put_map;
}

link = kzalloc(sizeof(*link), GFP_USER);
if (!link) {
err = -ENOMEM;
- goto err_out;
+ goto put_map;
}
bpf_link_init(&link->link, BPF_LINK_TYPE_STRUCT_OPS, &bpf_struct_ops_map_lops, NULL);

@@ -927,7 +927,8 @@ int bpf_struct_ops_link_create(union bpf_attr *attr)
return bpf_link_settle(&link_primer);

err_out:
- bpf_map_put(map);
kfree(link);
+put_map:
+ bpf_map_put(map);
return err;
}
--
2.43.0