Skip to content

Commit a4af7bd

Browse files
committed
[SampleProfile] Fix UB in Demangler invocation.
Currently the backing buffer of a std::vector<char> is passed[1] to Demangler.getFunctionBaseName. However, deeply inside the call stack OutputBuffer::grow will call[2] std::realloc if it needs to grow the buffer, leading to UB. The demangler APIs specify[3] that "Buf and N behave like the second and third parameters to __cxa_demangle" and the docs for the latter say[4] that the output buffer must be allocated with malloc (but can also be NULL and will then be realloced accordingly). [1]: https://github.com/llvm/llvm-project/blob/d7e631c7cd6d9c13b9519991ec6becf08bc6b8aa/llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp#L744 [2]: https://github.com/llvm/llvm-project/blob/d7e631c7cd6d9c13b9519991ec6becf08bc6b8aa/llvm/include/llvm/Demangle/Utility.h#L50 [3]: https://github.com/llvm/llvm-project/blob/d7e631c7cd6d9c13b9519991ec6becf08bc6b8aa/llvm/include/llvm/Demangle/Demangle.h#L92-L93 [4]: https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html
1 parent a6f4a54 commit a4af7bd

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

llvm/lib/Transforms/IPO/SampleProfileMatcher.cpp

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -737,14 +737,13 @@ bool SampleProfileMatcher::functionMatchesProfileHelper(
737737
auto FunctionName = FName.str();
738738
if (Demangler.partialDemangle(FunctionName.c_str()))
739739
return std::string();
740-
constexpr size_t MaxBaseNameSize = 65536;
741-
std::vector<char> BaseNameBuf(MaxBaseNameSize, 0);
742-
size_t BaseNameSize = MaxBaseNameSize;
743-
char *BaseNamePtr =
744-
Demangler.getFunctionBaseName(BaseNameBuf.data(), &BaseNameSize);
745-
return (BaseNamePtr && BaseNameSize)
746-
? std::string(BaseNamePtr, BaseNameSize)
747-
: std::string();
740+
size_t BaseNameSize = 0;
741+
char *BaseNamePtr = Demangler.getFunctionBaseName(nullptr, &BaseNameSize);
742+
std::string Result = (BaseNamePtr && BaseNameSize)
743+
? std::string(BaseNamePtr, BaseNameSize)
744+
: std::string();
745+
free(BaseNamePtr);
746+
return Result;
748747
};
749748
auto IRBaseName = GetBaseName(IRFunc.getName());
750749
auto ProfBaseName = GetBaseName(ProfFunc.stringRef());

0 commit comments

Comments
 (0)