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 // Returns the demangled C++ symbol name for Name.
23 Optional<std::string> lld::demangleItanium(StringRef Name) {
24 // itaniumDemangle can be used to demangle strings other than symbol
25 // names which do not necessarily start with "_Z". Name can be
26 // either a C or C++ symbol. Don't call itaniumDemangle if the name
27 // does not look like a C++ symbol name to avoid getting unexpected
28 // result for a C symbol that happens to match a mangled type name.
29 if (!Name.startswith("_Z"))
32 char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
40 Optional<std::string> lld::demangleMSVC(StringRef Name) {
42 if (Name.consume_front("__imp_"))
43 Prefix = "__declspec(dllimport) ";
45 // Demangle only C++ names.
46 if (!Name.startswith("?"))
49 char *Buf = microsoftDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
57 StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {
58 for (StringRef S : Pat) {
59 Expected<GlobPattern> Pat = GlobPattern::create(S);
61 error(toString(Pat.takeError()));
63 Patterns.push_back(*Pat);
67 bool StringMatcher::match(StringRef S) const {
68 for (const GlobPattern &Pat : Patterns)
74 // Converts a hex string (e.g. "deadbeef") to a vector.
75 std::vector<uint8_t> lld::parseHex(StringRef S) {
76 std::vector<uint8_t> Hex;
78 StringRef B = S.substr(0, 2);
81 if (!to_integer(B, H, 16)) {
82 error("not a hexadecimal value: " + B);
90 // Returns true if S is valid as a C language identifier.
91 bool lld::isValidCIdentifier(StringRef S) {
92 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
93 std::all_of(S.begin() + 1, S.end(),
94 [](char C) { return C == '_' || isAlnum(C); });
97 // Write the contents of the a buffer to a file
98 void lld::saveBuffer(StringRef Buffer, const Twine &Path) {
100 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
102 error("cannot create " + Path + ": " + EC.message());