2be09a
commit cf8c6a634c0a04a9f5d198ef05310f85f7338839
2be09a
Author: Florian Weimer <fweimer@redhat.com>
2be09a
Date:   Fri Nov 5 17:01:24 2021 +0100
2be09a
2be09a
    elf: Earlier missing dynamic segment check in _dl_map_object_from_fd
2be09a
    
2be09a
    Separated debuginfo files have PT_DYNAMIC with p_filesz == 0.  We
2be09a
    need to check for that before the _dl_map_segments call because
2be09a
    that could attempt to write to mappings that extend beyond the end
2be09a
    of the file, resulting in SIGBUS.
2be09a
    
2be09a
    Reviewed-by: H.J. Lu <hjl.tools@gmail.com>
2be09a
    (cherry picked from commit ea32ec354c65ddad11b82ca9d057010df13a9cea)
2be09a
2be09a
diff --git a/elf/dl-load.c b/elf/dl-load.c
2be09a
index 4445c28ef3fb4a7e..0976977fbdf21902 100644
2be09a
--- a/elf/dl-load.c
2be09a
+++ b/elf/dl-load.c
2be09a
@@ -1130,6 +1130,7 @@ _dl_map_object_from_fd (const char *name, const char *origname, int fd,
2be09a
     struct loadcmd loadcmds[l->l_phnum];
2be09a
     size_t nloadcmds = 0;
2be09a
     bool has_holes = false;
2be09a
+    bool empty_dynamic = false;
2be09a
 
2be09a
     /* The struct is initialized to zero so this is not necessary:
2be09a
     l->l_ld = 0;
2be09a
@@ -1142,7 +1143,9 @@ _dl_map_object_from_fd (const char *name, const char *origname, int fd,
2be09a
 	     segments are mapped in.  We record the addresses it says
2be09a
 	     verbatim, and later correct for the run-time load address.  */
2be09a
 	case PT_DYNAMIC:
2be09a
-	  if (ph->p_filesz)
2be09a
+	  if (ph->p_filesz == 0)
2be09a
+	    empty_dynamic = true; /* Usually separate debuginfo.  */
2be09a
+	  else
2be09a
 	    {
2be09a
 	      /* Debuginfo only files from "objcopy --only-keep-debug"
2be09a
 		 contain a PT_DYNAMIC segment with p_filesz == 0.  Skip
2be09a
@@ -1265,6 +1268,13 @@ _dl_map_object_from_fd (const char *name, const char *origname, int fd,
2be09a
 	goto lose;
2be09a
       }
2be09a
 
2be09a
+    /* This check recognizes most separate debuginfo files.  */
2be09a
+    if (__glibc_unlikely ((l->l_ld == 0 && type == ET_DYN) || empty_dynamic))
2be09a
+      {
2be09a
+	errstring = N_("object file has no dynamic section");
2be09a
+	goto lose;
2be09a
+      }
2be09a
+
2be09a
     /* Length of the sections to be loaded.  */
2be09a
     maplength = loadcmds[nloadcmds - 1].allocend - loadcmds[0].mapstart;
2be09a
 
2be09a
@@ -1282,15 +1292,7 @@ _dl_map_object_from_fd (const char *name, const char *origname, int fd,
2be09a
       }
2be09a
   }
2be09a
 
2be09a
-  if (l->l_ld == 0)
2be09a
-    {
2be09a
-      if (__glibc_unlikely (type == ET_DYN))
2be09a
-	{
2be09a
-	  errstring = N_("object file has no dynamic section");
2be09a
-	  goto lose;
2be09a
-	}
2be09a
-    }
2be09a
-  else
2be09a
+  if (l->l_ld != 0)
2be09a
     l->l_ld = (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr);
2be09a
 
2be09a
   elf_get_dynamic_info (l);