1 //===- Strings.cpp -------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lld/Common/Strings.h"
11 #include "lld/Common/ErrorHandler.h"
12 #include "lld/Common/LLVM.h"
13 #include "llvm/Demangle/Demangle.h"
14 #include "llvm/Support/GlobPattern.h"
22 // DbgHelp.h must be included after Windows.h.
24 #pragma comment(lib, "dbghelp.lib")
30 // Returns the demangled C++ symbol name for Name.
31 Optional<std::string> lld::demangleItanium(StringRef Name) {
32 // itaniumDemangle can be used to demangle strings other than symbol
33 // names which do not necessarily start with "_Z". Name can be
34 // either a C or C++ symbol. Don't call itaniumDemangle if the name
35 // does not look like a C++ symbol name to avoid getting unexpected
36 // result for a C symbol that happens to match a mangled type name.
37 if (!Name.startswith("_Z"))
40 char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
48 Optional<std::string> lld::demangleMSVC(StringRef S) {
50 // UnDecorateSymbolName is not thread-safe, so we need a mutex.
52 std::lock_guard<std::mutex> Lock(Mu);
55 if (S.startswith("?"))
56 if (size_t Len = UnDecorateSymbolName(S.str().c_str(), Buf, sizeof(Buf), 0))
57 return std::string(Buf, Len);
62 StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {
63 for (StringRef S : Pat) {
64 Expected<GlobPattern> Pat = GlobPattern::create(S);
66 error(toString(Pat.takeError()));
68 Patterns.push_back(*Pat);
72 bool StringMatcher::match(StringRef S) const {
73 for (const GlobPattern &Pat : Patterns)
79 // Converts a hex string (e.g. "deadbeef") to a vector.
80 std::vector<uint8_t> lld::parseHex(StringRef S) {
81 std::vector<uint8_t> Hex;
83 StringRef B = S.substr(0, 2);
86 if (!to_integer(B, H, 16)) {
87 error("not a hexadecimal value: " + B);
95 // Returns true if S is valid as a C language identifier.
96 bool lld::isValidCIdentifier(StringRef S) {
97 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
98 std::all_of(S.begin() + 1, S.end(),
99 [](char C) { return C == '_' || isAlnum(C); });
102 // Write the contents of the a buffer to a file
103 void lld::saveBuffer(StringRef Buffer, const Twine &Path) {
105 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
107 error("cannot create " + Path + ": " + EC.message());