1 //===- Strings.cpp -------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lld/Common/Strings.h"
10 #include "lld/Common/ErrorHandler.h"
11 #include "lld/Common/LLVM.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/GlobPattern.h"
14 #include <algorithm>
15 #include <mutex>
16 #include <vector>
17 
18 using namespace llvm;
19 using namespace lld;
20 
21 SingleStringMatcher::SingleStringMatcher(StringRef Pattern) {
22   if (Pattern.size() > 2 && Pattern.startswith("\"") &&
23       Pattern.endswith("\"")) {
24     ExactMatch = true;
25     ExactPattern = Pattern.substr(1, Pattern.size() - 2);
26   } else {
27     Expected<GlobPattern> Glob = GlobPattern::create(Pattern);
28     if (!Glob) {
29       error(toString(Glob.takeError()));
30       return;
31     }
32     ExactMatch = false;
33     GlobPatternMatcher = *Glob;
34   }
35 }
36 
37 bool SingleStringMatcher::match(StringRef s) const {
38   return ExactMatch ? (ExactPattern == s) : GlobPatternMatcher.match(s);
39 }
40 
41 bool StringMatcher::match(StringRef s) const {
42   for (const SingleStringMatcher &pat : patterns)
43     if (pat.match(s))
44       return true;
45   return false;
46 }
47 
48 // Converts a hex string (e.g. "deadbeef") to a vector.
49 std::vector<uint8_t> lld::parseHex(StringRef s) {
50   std::vector<uint8_t> hex;
51   while (!s.empty()) {
52     StringRef b = s.substr(0, 2);
53     s = s.substr(2);
54     uint8_t h;
55     if (!to_integer(b, h, 16)) {
56       error("not a hexadecimal value: " + b);
57       return {};
58     }
59     hex.push_back(h);
60   }
61   return hex;
62 }
63 
64 // Returns true if S is valid as a C language identifier.
65 bool lld::isValidCIdentifier(StringRef s) {
66   return !s.empty() && !isDigit(s[0]) &&
67          llvm::all_of(s, [](char c) { return isAlnum(c) || c == '_'; });
68 }
69 
70 // Write the contents of the a buffer to a file
71 void lld::saveBuffer(StringRef buffer, const Twine &path) {
72   std::error_code ec;
73   raw_fd_ostream os(path.str(), ec, sys::fs::OpenFlags::OF_None);
74   if (ec)
75     error("cannot create " + path + ": " + ec.message());
76   os << buffer;
77 }
78