[PATCH] riscv: module: Use scope-based resource management for scratch buf

Florian Schmaus posted 1 patch 1 week, 6 days ago
arch/riscv/kernel/module-sections.c | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
[PATCH] riscv: module: Use scope-based resource management for scratch buf
Posted by Florian Schmaus 1 week, 6 days ago
The scratch buffer in module_frob_arch_sections() is currently managed
manually, requiring explicit calls to kvfree().

Convert it to use scope-based resource management via the
__free(kvfree) attribute. This automatically guarantees that the
buffer is freed when it goes out of scope, preventing potential memory
leaks. Most notably, it simplifies the kvrealloc() error path by
removing the need to manually free the original buffer before
returning -ENOMEM.

Signed-off-by: Florian Schmaus <florian.schmaus@codasip.com>
---
 arch/riscv/kernel/module-sections.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/arch/riscv/kernel/module-sections.c b/arch/riscv/kernel/module-sections.c
index b3b11b7f7ed9..ed3be8be377e 100644
--- a/arch/riscv/kernel/module-sections.c
+++ b/arch/riscv/kernel/module-sections.c
@@ -116,7 +116,7 @@ int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
 	size_t num_scratch_relas = 0;
 	unsigned int num_plts = 0;
 	unsigned int num_gots = 0;
-	Elf_Rela *scratch = NULL;
+	Elf_Rela *scratch __free(kvfree) = NULL;
 	Elf_Rela *new_scratch;
 	size_t scratch_size = 0;
 	int i;
@@ -168,10 +168,9 @@ int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
 		if (scratch_size_needed > scratch_size) {
 			scratch_size = scratch_size_needed;
 			new_scratch = kvrealloc(scratch, scratch_size, GFP_KERNEL);
-			if (!new_scratch) {
-				kvfree(scratch);
+			if (!new_scratch)
 				return -ENOMEM;
-			}
+
 			scratch = new_scratch;
 		}
 
@@ -184,7 +183,6 @@ int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
 		/* sort the accumulated PLT/GOT relocations so duplicates are adjacent */
 		sort(scratch, num_scratch_relas, sizeof(*scratch), cmp_rela, NULL);
 		count_max_entries(scratch, num_scratch_relas, &num_plts, &num_gots);
-		kvfree(scratch);
 	}
 
 	mod->arch.plt.shdr->sh_type = SHT_NOBITS;
-- 
2.53.0