binutils: avoid leaking section header pointers
Fixes a memory leak in readelf when processing thin archives by allocating section header pointers only when needed.
This patch addresses a memory leak in the readelf utility that occurs when dumping thin archives. The ElfXX(_get_section_headers) function was allocating memory for section headers on every non-probe call, overwriting previous allocations and causing a leak. The fix ensures that filedata->orig_section_headers is only allocated if it is currently NULL, resolving the leak and passing an ASan-enabled test case.
- proposer
Fixes a memory leak in readelf by allocating section header pointers only when they are NULL.
“ElfXX(_get_section_headers) allocates filedata->orig_section_headers on every non-probe call, so when it runs more than once for the same Filedata the earlier allocation is overwritten and lost.”
In Details
This PR fixes a memory leak in readelf related to thin archives. The ElfXX(_get_section_headers) function in binutils/readelf-nn.c incorrectly reallocates filedata->orig_section_headers even if it already holds a valid pointer, leading to a leak. The fix ensures this allocation only happens once when filedata->orig_section_headers is NULL.
- readelf
- A utility that displays information about ELF files, including section headers, symbols, and relocation entries.
- thin archive
- A type of archive file that contains only symbol table information and references to external object files, rather than the full object code.
- ELF
- Executable and Linkable Format, a common standard for object file formats on Unix-like systems.
- ASan
- AddressSanitizer, a fast memory error detector for C/C++ that finds issues like use-after-free and memory leaks.
- xcalloc
- A memory allocation function that initializes allocated memory to zero.