Skip to content

Commit ba3744f

Browse files
committed
[Reflection] Fix premature deallocation of string memory in buildContextDescriptor.
This function demangles a std::string, but the demangler can create interior pointers into the string being demangled. Solve this by copying the string into the Demangler first. readMangledName does the same thing. Consolidate the string copying code into a method on NodeFactory, then make both functions use it. rdar://102275748
1 parent aff7c14 commit ba3744f

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

include/swift/Demangling/Demangler.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,16 @@ class NodeFactory {
210210
Capacity += Growth;
211211
}
212212

213+
/// Copy a std::string to memory managed by the NodeFactory, returning a
214+
/// StringRef pointing to the copied string data.
215+
StringRef copyString(const std::string &str) {
216+
size_t stringSize = str.size() + 1; // + 1 for terminating NUL.
217+
218+
char *copiedString = Allocate<char>(stringSize);
219+
memcpy(copiedString, str.data(), stringSize);
220+
return {copiedString, str.size()};
221+
}
222+
213223
/// Creates a node of kind \p K.
214224
NodePointer createNode(Node::Kind K);
215225

include/swift/Remote/MetadataReader.h

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -515,11 +515,9 @@ class MetadataReader {
515515
const std::string &mangledName,
516516
MangledNameKind kind,
517517
Demangler &dem) {
518-
size_t stringSize = mangledName.size() + 1; // + 1 for terminating NUL.
519-
520-
char *copiedString = dem.Allocate<char>(stringSize);
521-
memcpy(copiedString, mangledName.data(), stringSize);
522-
return demangle(RemoteRef<char>(remoteAddress, copiedString), kind, dem);
518+
StringRef mangledNameCopy = dem.copyString(mangledName);
519+
return demangle(RemoteRef<char>(remoteAddress, mangledNameCopy.data()),
520+
kind, dem);
523521
}
524522

525523
/// Given a demangle tree, attempt to turn it into a type.
@@ -1495,7 +1493,12 @@ class MetadataReader {
14951493

14961494
return demangledSymbol;
14971495
}
1498-
1496+
1497+
Demangle::NodePointer buildContextManglingForSymbol(const std::string &symbol,
1498+
Demangler &dem) {
1499+
return buildContextManglingForSymbol(dem.copyString(symbol), dem);
1500+
}
1501+
14991502
/// Given a read context descriptor, attempt to build a demangling tree
15001503
/// for it.
15011504
Demangle::NodePointer

0 commit comments

Comments
 (0)