Skip to content

Conversation

@aemerson
Copy link
Contributor

This was caught by Apple's Probabilistic Guard Malloc which detected
that OldF's memory is freed inside mergeTwoFunctions(), and then
back in insert() the now dangling pointer is dereferenced again.

rdar://163874208

This was caught by Apple's Probabilistic Guard Malloc which detected
that OldF's memory is freed inside mergeTwoFunctions(), and then
back in insert() the now dangling pointer is dereferenced again.

rdar://163874208
@llvmbot
Copy link
Member

llvmbot commented Dec 20, 2025

@llvm/pr-subscribers-llvm-transforms

Author: Amara Emerson (aemerson)

Changes

This was caught by Apple's Probabilistic Guard Malloc which detected
that OldF's memory is freed inside mergeTwoFunctions(), and then
back in insert() the now dangling pointer is dereferenced again.

rdar://163874208


Full diff: https://github.com/llvm/llvm-project/pull/173126.diff

1 Files Affected:

  • (modified) llvm/lib/Transforms/IPO/MergeFunctions.cpp (+7-3)
diff --git a/llvm/lib/Transforms/IPO/MergeFunctions.cpp b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
index f5525deb0172f..0faa36a495acc 100644
--- a/llvm/lib/Transforms/IPO/MergeFunctions.cpp
+++ b/llvm/lib/Transforms/IPO/MergeFunctions.cpp
@@ -1027,12 +1027,16 @@ bool MergeFunctions::insert(Function *NewFunction) {
     assert(OldF.getFunc() != F && "Must have swapped the functions.");
   }
 
-  LLVM_DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
+  // Capture the Function pointer before mergeTwoFunctions, which may invalidate
+  // OldF by erasing it from FnTree via removeUsers().
+  Function *OldFunc = OldF.getFunc();
+
+  LLVM_DEBUG(dbgs() << "  " << OldFunc->getName()
                     << " == " << NewFunction->getName() << '\n');
 
   Function *DeleteF = NewFunction;
-  mergeTwoFunctions(OldF.getFunc(), DeleteF);
-  this->DelToNewMap.insert({DeleteF, OldF.getFunc()});
+  mergeTwoFunctions(OldFunc, DeleteF);
+  this->DelToNewMap.insert({DeleteF, OldFunc});
   return true;
 }
 

@aemerson aemerson requested review from fhahn and nikic December 20, 2025 01:15
Copy link
Contributor

@boomanaiden154 boomanaiden154 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

Cool to see hardening features catching issues like this.

@aemerson
Copy link
Contributor Author

LGTM.

Cool to see hardening features catching issues like this.

Thanks, and agreed!

@aemerson aemerson merged commit 3eee451 into main Dec 21, 2025
12 checks passed
@aemerson aemerson deleted the users/amara/mergefunctions-use-after-free branch December 21, 2025 07:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants