selftest/bpf: Fix memory leak in kprobe_multi_test
authorXu Kuohai <xukuohai@huawei.com>
Tue, 11 Oct 2022 12:01:06 +0000 (08:01 -0400)
committerAndrii Nakryiko <andrii@kernel.org>
Thu, 13 Oct 2022 17:53:24 +0000 (10:53 -0700)
The get_syms() function in kprobe_multi_test.c does not free the string
memory allocated by sscanf correctly. Fix it.

Fixes: 5b6c7e5c4434 ("selftests/bpf: Add attach bench test")
Signed-off-by: Xu Kuohai <xukuohai@huawei.com>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Acked-by: Jiri Olsa <jolsa@kernel.org>
Acked-by: Martin KaFai Lau <martin.lau@kernel.org>
Link: https://lore.kernel.org/bpf/20221011120108.782373-5-xukuohai@huaweicloud.com
tools/testing/selftests/bpf/prog_tests/kprobe_multi_test.c

index d457a55..287b3ac 100644 (file)
@@ -325,7 +325,7 @@ static bool symbol_equal(const void *key1, const void *key2, void *ctx __maybe_u
 static int get_syms(char ***symsp, size_t *cntp)
 {
        size_t cap = 0, cnt = 0, i;
-       char *name, **syms = NULL;
+       char *name = NULL, **syms = NULL;
        struct hashmap *map;
        char buf[256];
        FILE *f;
@@ -352,6 +352,8 @@ static int get_syms(char ***symsp, size_t *cntp)
                /* skip modules */
                if (strchr(buf, '['))
                        continue;
+
+               free(name);
                if (sscanf(buf, "%ms$*[^\n]\n", &name) != 1)
                        continue;
                /*
@@ -369,32 +371,32 @@ static int get_syms(char ***symsp, size_t *cntp)
                if (!strncmp(name, "__ftrace_invalid_address__",
                             sizeof("__ftrace_invalid_address__") - 1))
                        continue;
+
                err = hashmap__add(map, name, NULL);
-               if (err) {
-                       free(name);
-                       if (err == -EEXIST)
-                               continue;
+               if (err == -EEXIST)
+                       continue;
+               if (err)
                        goto error;
-               }
+
                err = libbpf_ensure_mem((void **) &syms, &cap,
                                        sizeof(*syms), cnt + 1);
-               if (err) {
-                       free(name);
+               if (err)
                        goto error;
-               }
-               syms[cnt] = name;
-               cnt++;
+
+               syms[cnt++] = name;
+               name = NULL;
        }
 
        *symsp = syms;
        *cntp = cnt;
 
 error:
+       free(name);
        fclose(f);
        hashmap__free(map);
        if (err) {
                for (i = 0; i < cnt; i++)
-                       free(syms[cnt]);
+                       free(syms[i]);
                free(syms);
        }
        return err;