548bcb
commit c0669ae1a629e16b536bf11cdd0865e0dbcf4bee
548bcb
Author: Szabolcs Nagy <szabolcs.nagy@arm.com>
548bcb
Date:   Wed Dec 30 21:52:38 2020 +0000
548bcb
548bcb
    elf: Refactor _dl_update_slotinfo to avoid use after free
548bcb
    
548bcb
    map is not valid to access here because it can be freed by a concurrent
548bcb
    dlclose: during tls access (via __tls_get_addr) _dl_update_slotinfo is
548bcb
    called without holding dlopen locks. So don't check the modid of map.
548bcb
    
548bcb
    The map == 0 and map != 0 code paths can be shared (avoiding the dtv
548bcb
    resize in case of map == 0 is just an optimization: larger dtv than
548bcb
    necessary would be fine too).
548bcb
    
548bcb
    Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
548bcb
548bcb
diff --git a/elf/dl-tls.c b/elf/dl-tls.c
548bcb
index 9375650a3ab5247d..15ed01d795a8627a 100644
548bcb
--- a/elf/dl-tls.c
548bcb
+++ b/elf/dl-tls.c
548bcb
@@ -743,6 +743,8 @@ _dl_update_slotinfo (unsigned long int req_modid)
548bcb
 	{
548bcb
 	  for (size_t cnt = total == 0 ? 1 : 0; cnt < listp->len; ++cnt)
548bcb
 	    {
548bcb
+	      size_t modid = total + cnt;
548bcb
+
548bcb
 	      size_t gen = listp->slotinfo[cnt].gen;
548bcb
 
548bcb
 	      if (gen > new_gen)
548bcb
@@ -758,25 +760,12 @@ _dl_update_slotinfo (unsigned long int req_modid)
548bcb
 
548bcb
 	      /* If there is no map this means the entry is empty.  */
548bcb
 	      struct link_map *map = listp->slotinfo[cnt].map;
548bcb
-	      if (map == NULL)
548bcb
-		{
548bcb
-		  if (dtv[-1].counter >= total + cnt)
548bcb
-		    {
548bcb
-		      /* If this modid was used at some point the memory
548bcb
-			 might still be allocated.  */
548bcb
-		      free (dtv[total + cnt].pointer.to_free);
548bcb
-		      dtv[total + cnt].pointer.val = TLS_DTV_UNALLOCATED;
548bcb
-		      dtv[total + cnt].pointer.to_free = NULL;
548bcb
-		    }
548bcb
-
548bcb
-		  continue;
548bcb
-		}
548bcb
-
548bcb
 	      /* Check whether the current dtv array is large enough.  */
548bcb
-	      size_t modid = map->l_tls_modid;
548bcb
-	      assert (total + cnt == modid);
548bcb
 	      if (dtv[-1].counter < modid)
548bcb
 		{
548bcb
+		  if (map == NULL)
548bcb
+		    continue;
548bcb
+
548bcb
 		  /* Resize the dtv.  */
548bcb
 		  dtv = _dl_resize_dtv (dtv);
548bcb