[Bug,libdw/29434] Memory leak in `dwarf_getscopes`

Message ID bug-29434-10460-XruazjeeAF@http.sourceware.org/bugzilla/
State New
Headers
Series [Bug,libdw/29434] Memory leak in `dwarf_getscopes` |

Commit Message

mliska at suse dot cz Aug. 4, 2022, 3:13 p.m. UTC
  https://sourceware.org/bugzilla/show_bug.cgi?id=29434

--- Comment #3 from Mark Wielaard <mark at klomp dot org> ---
(In reply to Pablo Galindo Salgado from comment #2)
> > it could in theory also be zero
> 
> In this case, the result was 0 (I am working with Matt)

Interesting, I assumed it was on a failure path.
My proposed patch would have been:

     }
@@ -198,6 +198,8 @@ dwarf_getscopes (Dwarf_Die *cudie, Dwarf_Addr pc, Dwarf_Die
**scopes)

   if (result > 0)
     *scopes = a.scopes;
+  else if (result < 0)
+    free (a.scopes);

   return result;
 }

But if the result is zero I don't believe I fully understand yet how the leak
happens.
  

Patch

diff --git a/libdw/dwarf_getscopes.c b/libdw/dwarf_getscopes.c
index 5662eecf..676d62f3 100644
--- a/libdw/dwarf_getscopes.c
+++ b/libdw/dwarf_getscopes.c
@@ -100,7 +100,7 @@  origin_match (unsigned int depth, struct Dwarf_Die_Chain
*die, void *arg)
   Dwarf_Die *scopes = realloc (a->scopes, nscopes * sizeof scopes[0]);
   if (scopes == NULL)
     {
-      free (a->scopes);
+      /* a->scopes will be freed by dwarf_getscopes on error.  */
       __libdw_seterrno (DWARF_E_NOMEM);
       return -1;