mm/damon/tests/sysfs-kunit: handle alloc failures on damon_sysfs_test_add_targets()
authorSeongJae Park <sj@kernel.org>
Sat, 1 Nov 2025 18:20:14 +0000 (11:20 -0700)
committerAndrew Morton <akpm@linux-foundation.org>
Mon, 17 Nov 2025 01:28:35 +0000 (17:28 -0800)
damon_sysfs_test_add_targets() is assuming all dynamic memory allocation
in it will succeed.  Those are indeed likely in the real use cases since
those allocations are too small to fail, but theoretically those could
fail.  In the case, inappropriate memory access can happen.  Fix it by
appropriately cleanup pre-allocated memory and skip the execution of the
remaining tests in the failure cases.

Link: https://lkml.kernel.org/r/20251101182021.74868-21-sj@kernel.org
Fixes: b8ee5575f763 ("mm/damon/sysfs-test: add a unit test for damon_sysfs_set_targets()")
Signed-off-by: SeongJae Park <sj@kernel.org>
Cc: Brendan Higgins <brendan.higgins@linux.dev>
Cc: David Gow <davidgow@google.com>
Cc: Kefeng Wang <wangkefeng.wang@huawei.com>
Cc: <stable@vger.kernel.org> [6.7+]
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
mm/damon/tests/sysfs-kunit.h

index 7b5c7b3..ce72184 100644 (file)
@@ -45,16 +45,41 @@ static void damon_sysfs_test_add_targets(struct kunit *test)
        struct damon_ctx *ctx;
 
        sysfs_targets = damon_sysfs_targets_alloc();
+       if (!sysfs_targets)
+               kunit_skip(test, "sysfs_targets alloc fail");
        sysfs_targets->nr = 1;
        sysfs_targets->targets_arr = kmalloc_array(1,
                        sizeof(*sysfs_targets->targets_arr), GFP_KERNEL);
+       if (!sysfs_targets->targets_arr) {
+               kfree(sysfs_targets);
+               kunit_skip(test, "targets_arr alloc fail");
+       }
 
        sysfs_target = damon_sysfs_target_alloc();
+       if (!sysfs_target) {
+               kfree(sysfs_targets->targets_arr);
+               kfree(sysfs_targets);
+               kunit_skip(test, "sysfs_target alloc fail");
+       }
        sysfs_target->pid = __damon_sysfs_test_get_any_pid(12, 100);
        sysfs_target->regions = damon_sysfs_regions_alloc();
+       if (!sysfs_target->regions) {
+               kfree(sysfs_targets->targets_arr);
+               kfree(sysfs_targets);
+               kfree(sysfs_target);
+               kunit_skip(test, "sysfs_regions alloc fail");
+       }
+
        sysfs_targets->targets_arr[0] = sysfs_target;
 
        ctx = damon_new_ctx();
+       if (!ctx) {
+               kfree(sysfs_targets->targets_arr);
+               kfree(sysfs_targets);
+               kfree(sysfs_target);
+               kfree(sysfs_target->regions);
+               kunit_skip(test, "ctx alloc fail");
+       }
 
        damon_sysfs_add_targets(ctx, sysfs_targets);
        KUNIT_EXPECT_EQ(test, 1u, nr_damon_targets(ctx));