]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Strings.cpp
Import zstandard 1.3.1
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Strings.cpp
1 //===- Strings.cpp -------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "Strings.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/Demangle/Demangle.h"
17 #include <algorithm>
18 #include <cstring>
19
20 using namespace llvm;
21 using namespace lld;
22 using namespace lld::elf;
23
24 StringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {
25   for (StringRef S : Pat) {
26     Expected<GlobPattern> Pat = GlobPattern::create(S);
27     if (!Pat)
28       error(toString(Pat.takeError()));
29     else
30       Patterns.push_back(*Pat);
31   }
32 }
33
34 bool StringMatcher::match(StringRef S) const {
35   for (const GlobPattern &Pat : Patterns)
36     if (Pat.match(S))
37       return true;
38   return false;
39 }
40
41 // Converts a hex string (e.g. "deadbeef") to a vector.
42 std::vector<uint8_t> elf::parseHex(StringRef S) {
43   std::vector<uint8_t> Hex;
44   while (!S.empty()) {
45     StringRef B = S.substr(0, 2);
46     S = S.substr(2);
47     uint8_t H;
48     if (!to_integer(B, H, 16)) {
49       error("not a hexadecimal value: " + B);
50       return {};
51     }
52     Hex.push_back(H);
53   }
54   return Hex;
55 }
56
57 static bool isAlpha(char C) {
58   return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
59 }
60
61 static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
62
63 // Returns true if S is valid as a C language identifier.
64 bool elf::isValidCIdentifier(StringRef S) {
65   return !S.empty() && isAlpha(S[0]) &&
66          std::all_of(S.begin() + 1, S.end(), isAlnum);
67 }
68
69 // Returns the demangled C++ symbol name for Name.
70 Optional<std::string> elf::demangle(StringRef Name) {
71   // itaniumDemangle can be used to demangle strings other than symbol
72   // names which do not necessarily start with "_Z". Name can be
73   // either a C or C++ symbol. Don't call itaniumDemangle if the name
74   // does not look like a C++ symbol name to avoid getting unexpected
75   // result for a C symbol that happens to match a mangled type name.
76   if (!Name.startswith("_Z"))
77     return None;
78
79   char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);
80   if (!Buf)
81     return None;
82   std::string S(Buf);
83   free(Buf);
84   return S;
85 }