Skip to content

Commit c42458f

Browse files
YuuoniyPaul Walmsley
authored andcommitted
riscv: Fix memory leak in module_frob_arch_sections()
The current code directly overwrites the scratch pointer with the return value of kvrealloc(). If kvrealloc() fails and returns NULL, the original buffer becomes unreachable, causing a memory leak. Fix this by using a temporary variable to store kvrealloc()'s return value and only update the scratch pointer on success. Found via static anlaysis and this is similar to commit 42378a9 ("bpf, verifier: Fix memory leak in array reallocation for stack state") Fixes: be17c0d ("riscv: module: Optimize PLT/GOT entry counting") Cc: stable@vger.kernel.org Signed-off-by: Miaoqian Lin <linmq006@gmail.com> Link: https://lore.kernel.org/r/20251026091912.39727-1-linmq006@gmail.com Signed-off-by: Paul Walmsley <pjw@kernel.org>
1 parent a74f038 commit c42458f

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

arch/riscv/kernel/module-sections.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
119119
unsigned int num_plts = 0;
120120
unsigned int num_gots = 0;
121121
Elf_Rela *scratch = NULL;
122+
Elf_Rela *new_scratch;
122123
size_t scratch_size = 0;
123124
int i;
124125

@@ -168,9 +169,12 @@ int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
168169
scratch_size_needed = (num_scratch_relas + num_relas) * sizeof(*scratch);
169170
if (scratch_size_needed > scratch_size) {
170171
scratch_size = scratch_size_needed;
171-
scratch = kvrealloc(scratch, scratch_size, GFP_KERNEL);
172-
if (!scratch)
172+
new_scratch = kvrealloc(scratch, scratch_size, GFP_KERNEL);
173+
if (!new_scratch) {
174+
kvfree(scratch);
173175
return -ENOMEM;
176+
}
177+
scratch = new_scratch;
174178
}
175179

176180
for (size_t j = 0; j < num_relas; j++)

0 commit comments

Comments
 (0)