[llvm] 36af4c8 - [SelectionDAG] Fix use-after-free introduced in D130881

Markus Böck via llvm-commits llvm-commits at lists.llvm.org
Mon Oct 3 06:11:10 PDT 2022


Author: Markus Böck
Date: 2022-10-03T15:09:14+02:00
New Revision: 36af4c8418c1250faadeb8437bf13e460d606521

URL: https://github.com/llvm/llvm-project/commit/36af4c8418c1250faadeb8437bf13e460d606521
DIFF: https://github.com/llvm/llvm-project/commit/36af4c8418c1250faadeb8437bf13e460d606521.diff

LOG: [SelectionDAG] Fix use-after-free introduced in D130881

The code introduced in https://reviews.llvm.org/D130881 has a bug as it may cause a use-after-free error that can be caught by ASAN.
The bug essentially boils down to iterator invalidation of `DenseMap`. The expression `SDEI[To] = I->second;` may cause `SDEI` to grow if `To` is inserted for the very first time. When that happens, all existing iterators to the map are invalidated as their backing storage has been freed. Accessing `I->second` is then invalid and attempts to access freed memory (as `I` is an iterator of `SDEI`).

This patch fixes that quite simply by first making a copy of `I->second`, and then moving into the possibly newly inserted KV of the ` DenseMap`.

No test attached as I am not sure it is practible to test.

Differential revision: https://reviews.llvm.org/D135019

Added: 
    

Modified: 
    llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
index 2da384077013..3c2a1166bb63 100644
--- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
@@ -12029,7 +12029,11 @@ void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) {
   auto I = SDEI.find(From);
   if (I == SDEI.end())
     return;
-  SDEI[To] = I->second;
+
+  // Use of operator[] on the DenseMap may cause an insertion, which invalidates
+  // the iterator, hence the need to make a copy to prevent a use-after-free.
+  NodeExtraInfo Copy = I->second;
+  SDEI[To] = std::move(Copy);
 }
 
 #ifndef NDEBUG


        


More information about the llvm-commits mailing list