Re: [PATCH v2] kernel/module: Fix mem leak in module_add_modinfo_attrs

From: Jessica Yu
Date: Mon Jun 03 2019 - 06:51:08 EST


+++ YueHaibing [30/05/19 21:43 +0800]:
In module_add_modinfo_attrs if sysfs_create_file
fails, we forget to free allocated modinfo_attrs
and roll back the sysfs files.

Fixes: 03e88ae1b13d ("[PATCH] fix module sysfs files reference counting")
Signed-off-by: YueHaibing <yuehaibing@xxxxxxxxxx>
---
v2: free from '--i' instead of 'i--'
---
kernel/module.c | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/kernel/module.c b/kernel/module.c
index 6e6712b..78e21a7 100644
--- a/kernel/module.c
+++ b/kernel/module.c
@@ -1723,15 +1723,29 @@ static int module_add_modinfo_attrs(struct module *mod)
return -ENOMEM;

temp_attr = mod->modinfo_attrs;
- for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
+ for (i = 0; (attr = modinfo_attrs[i]); i++) {
if (!attr->test || attr->test(mod)) {
memcpy(temp_attr, attr, sizeof(*temp_attr));
sysfs_attr_init(&temp_attr->attr);
error = sysfs_create_file(&mod->mkobj.kobj,
&temp_attr->attr);
+ if (error)
+ goto error_out;
++temp_attr;
}
}
+
+ return 0;
+
+error_out:
+ for (; (attr = &mod->modinfo_attrs[i]) && i >= 0; --i) {

The increment step is executed after the body of the loop, so this is
still starting at i instead of i - 1. I think we need:

for (--i; (attr = &mod->modinfo_attrs[i]) && i >= 0; i--)

Thanks,

Jessica

+ if (!attr->attr.name)
+ break;
+ sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
+ if (attr->free)
+ attr->free(mod);
+ }
+ kfree(mod->modinfo_attrs);
return error;
}

--
2.7.4