libelf: Fix possible memory leak in elf_getdata_rawchunk

Message ID 20231108125952.960361-2-mark@klomp.org
State Committed
Headers
Series libelf: Fix possible memory leak in elf_getdata_rawchunk |

Commit Message

Mark Wielaard Nov. 8, 2023, 12:59 p.m. UTC
  If the rawchunk is not properly aligned we'll create a new buffer
that is correctly aligned and put the data in that new buffer with
memcpy or the conversion function. In such cases the rawchunk leaks
because the new buffer is put into the Elf_Data_Chunk.

	* libelf/elf_getdata_rawchunk.c (elf_getdata_rawchunk):
	Call free on the rawchunk if new buffer was allocated.

Signed-off-by: Mark Wielaard <mark@klomp.org>
---
 libelf/elf_getdata_rawchunk.c | 5 +++++
 1 file changed, 5 insertions(+)
  

Comments

Mark Wielaard Nov. 14, 2023, 2:58 p.m. UTC | #1
Hi,

On Wed, 2023-11-08 at 13:59 +0100, Mark Wielaard wrote:
> If the rawchunk is not properly aligned we'll create a new buffer
> that is correctly aligned and put the data in that new buffer with
> memcpy or the conversion function. In such cases the rawchunk leaks
> because the new buffer is put into the Elf_Data_Chunk.
> 
> 	* libelf/elf_getdata_rawchunk.c (elf_getdata_rawchunk):
> 	Call free on the rawchunk if new buffer was allocated.

Pushed to main.

Cheers,

Mark
  

Patch

diff --git a/libelf/elf_getdata_rawchunk.c b/libelf/elf_getdata_rawchunk.c
index 05ff329c..1751878d 100644
--- a/libelf/elf_getdata_rawchunk.c
+++ b/libelf/elf_getdata_rawchunk.c
@@ -175,6 +175,8 @@  elf_getdata_rawchunk (Elf *elf, int64_t offset, size_t size, Elf_Type type)
 
 	  /* The copy will be appropriately aligned for direct access.  */
 	  memcpy (buffer, rawchunk, size);
+
+	  free (rawchunk);
 	}
     }
   else
@@ -191,6 +193,9 @@  elf_getdata_rawchunk (Elf *elf, int64_t offset, size_t size, Elf_Type type)
 
       /* Call the conversion function.  */
       (*__elf_xfctstom[elf->class - 1][type])(buffer, rawchunk, size, 0);
+
+      if (!flags)
+	free (rawchunk);
     }
 
   /* Allocate the dummy container to point at this buffer.  */