[PATCH bpf-next] selftests/bpf: Add malloc failure checks in bpf_iter

From: Yuran Pereira
Date: Tue Oct 24 2023 - 21:54:16 EST


Since some malloc calls in bpf_iter may at times fail,
this patch adds the appropriate fail checks, and ensures that
any previously allocated resource is appropriately destroyed
before returning the function.

This is patch 2 in the sequence should be applied after d1a88d37cecc
"selftests/bpf: Convert CHECK macros to ASSERT_* macros in bpf_iter"

Patch 1:
https://lore.kernel.org/lkml/DB3PR10MB683589A5F705C6CA5BE0D325E8DFA@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Signed-off-by: Yuran Pereira <yuran.pereira@xxxxxxxxxxx>
---
tools/testing/selftests/bpf/prog_tests/bpf_iter.c | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c
index 526ac4e741ee..c6cf42c64af3 100644
--- a/tools/testing/selftests/bpf/prog_tests/bpf_iter.c
+++ b/tools/testing/selftests/bpf/prog_tests/bpf_iter.c
@@ -700,7 +700,7 @@ static void test_overflow(bool test_e2big_overflow, bool ret1)
goto free_link;

buf = malloc(expected_read_len);
- if (!buf)
+ if (!ASSERT_OK_PTR(buf, "malloc"))
goto close_iter;

/* do read */
@@ -871,6 +871,10 @@ static void test_bpf_percpu_hash_map(void)

skel->rodata->num_cpus = bpf_num_possible_cpus();
val = malloc(8 * bpf_num_possible_cpus());
+ if (!ASSERT_OK_PTR(val, "malloc")) {
+ bpf_iter_bpf_percpu_hash_map__destroy(skel);
+ return;
+ }

err = bpf_iter_bpf_percpu_hash_map__load(skel);
if (!ASSERT_OK_PTR(skel, "bpf_iter_bpf_percpu_hash_map__load"))
@@ -1048,6 +1052,10 @@ static void test_bpf_percpu_array_map(void)

skel->rodata->num_cpus = bpf_num_possible_cpus();
val = malloc(8 * bpf_num_possible_cpus());
+ if (!ASSERT_OK_PTR(val, "malloc")) {
+ bpf_iter_bpf_percpu_array_map__destroy(skel);
+ return;
+ }

err = bpf_iter_bpf_percpu_array_map__load(skel);
if (!ASSERT_OK_PTR(skel, "bpf_iter_bpf_percpu_array_map__load"))
--
2.25.1