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