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

Markus Böck via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sat Oct 1 13:41:36 PDT 2022


zero9178 created this revision.
zero9178 added reviewers: melver, vitalybuka, dvyukov, eugenis, pcc, MaskRay.
Herald added subscribers: StephenFan, ecnelises, hiraditya.
Herald added a project: All.
zero9178 requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

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.
----------------------------------------------------------

Downstream ASAN failure for reference:
https://github.com/zero9178/Pylir/actions/runs/3165945057/jobs/5155328897

As can nicely be seen in the stacktrace, the memor is freed by `operator[]` and the accessed by `operator=` afterwards


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135019

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


Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
===================================================================
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
@@ -12024,7 +12024,11 @@
   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


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D135019.464515.patch
Type: text/x-patch
Size: 590 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221001/f77fc125/attachment.bin>


More information about the llvm-commits mailing list