]> git.ipfire.org Git - thirdparty/elfutils.git/commitdiff
libdw/libdw_findcu.c: Fix TOCTOU race condition in __libdw_findcu
authorAaron Merey <amerey@redhat.com>
Thu, 27 Mar 2025 03:35:47 +0000 (23:35 -0400)
committerAaron Merey <amerey@redhat.com>
Thu, 27 Mar 2025 04:02:58 +0000 (00:02 -0400)
Ensure that dwarf_lock is held before accessing next_tu_offset and
next_cu_offset.

This fixes a TOCTOU bug in __libdw_findcu that causes NULL to be
incorrectly returned.

Signed-off-by: Aaron Merey <amerey@redhat.com>
libdw/libdw_findcu.c

index 8805af9b37b03582848a2eafb4ce2aa0ed8182c8..0e4dcc3792466cad9ef99e3eda83cb07f48a9abd 100644 (file)
@@ -240,6 +240,8 @@ struct Dwarf_CU *
 internal_function
 __libdw_findcu (Dwarf *dbg, Dwarf_Off start, bool v4_debug_types)
 {
+  mutex_lock (dbg->dwarf_lock);
+
   search_tree *tree = v4_debug_types ? &dbg->tu_tree : &dbg->cu_tree;
   Dwarf_Off *next_offset
     = v4_debug_types ? &dbg->next_tu_offset : &dbg->next_cu_offset;
@@ -249,9 +251,10 @@ __libdw_findcu (Dwarf *dbg, Dwarf_Off start, bool v4_debug_types)
   struct Dwarf_CU **found = eu_tfind (&fake, tree, findcu_cb);
   struct Dwarf_CU *result = NULL;
   if (found != NULL)
-    return *found;
-
-  mutex_lock (dbg->dwarf_lock);
+    {
+      mutex_unlock (dbg->dwarf_lock);
+      return *found;
+    }
 
   if (start < *next_offset)
     __libdw_seterrno (DWARF_E_INVALID_DWARF);