Skip to content

Commit 235a1eb

Browse files
GoodLuck612robherring
authored andcommitted
of: unittest: Fix memory leak in unittest_data_add()
In unittest_data_add(), if of_resolve_phandles() fails, the allocated unittest_data is not freed, leading to a memory leak. Fix this by using scope-based cleanup helper __free(kfree) for automatic resource cleanup. This ensures unittest_data is automatically freed when it goes out of scope in error paths. For the success path, use retain_and_null_ptr() to transfer ownership of the memory to the device tree and prevent double freeing. Fixes: 2eb46da ("of/selftest: Use the resolver to fixup phandles") Suggested-by: Rob Herring <robh@kernel.org> Co-developed-by: Jianhao Xu <jianhao.xu@seu.edu.cn> Signed-off-by: Jianhao Xu <jianhao.xu@seu.edu.cn> Signed-off-by: Zilin Guan <zilin@seu.edu.cn> Link: https://patch.msgid.link/20251231114915.234638-1-zilin@seu.edu.cn Signed-off-by: Rob Herring (Arm) <robh@kernel.org>
1 parent 4f4f6b4 commit 235a1eb

1 file changed

Lines changed: 3 additions & 5 deletions

File tree

drivers/of/unittest.c

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1985,7 +1985,6 @@ static void attach_node_and_children(struct device_node *np)
19851985
*/
19861986
static int __init unittest_data_add(void)
19871987
{
1988-
void *unittest_data;
19891988
void *unittest_data_align;
19901989
struct device_node *unittest_data_node = NULL, *np;
19911990
/*
@@ -2004,7 +2003,7 @@ static int __init unittest_data_add(void)
20042003
}
20052004

20062005
/* creating copy */
2007-
unittest_data = kmalloc(size + FDT_ALIGN_SIZE, GFP_KERNEL);
2006+
void *unittest_data __free(kfree) = kmalloc(size + FDT_ALIGN_SIZE, GFP_KERNEL);
20082007
if (!unittest_data)
20092008
return -ENOMEM;
20102009

@@ -2014,12 +2013,10 @@ static int __init unittest_data_add(void)
20142013
ret = of_fdt_unflatten_tree(unittest_data_align, NULL, &unittest_data_node);
20152014
if (!ret) {
20162015
pr_warn("%s: unflatten testcases tree failed\n", __func__);
2017-
kfree(unittest_data);
20182016
return -ENODATA;
20192017
}
20202018
if (!unittest_data_node) {
20212019
pr_warn("%s: testcases tree is empty\n", __func__);
2022-
kfree(unittest_data);
20232020
return -ENODATA;
20242021
}
20252022

@@ -2038,7 +2035,6 @@ static int __init unittest_data_add(void)
20382035
/* attach the sub-tree to live tree */
20392036
if (!of_root) {
20402037
pr_warn("%s: no live tree to attach sub-tree\n", __func__);
2041-
kfree(unittest_data);
20422038
rc = -ENODEV;
20432039
goto unlock;
20442040
}
@@ -2059,6 +2055,8 @@ static int __init unittest_data_add(void)
20592055
EXPECT_END(KERN_INFO,
20602056
"Duplicate name in testcase-data, renamed to \"duplicate-name#1\"");
20612057

2058+
retain_and_null_ptr(unittest_data);
2059+
20622060
unlock:
20632061
of_overlay_mutex_unlock();
20642062

0 commit comments

Comments
 (0)