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/ADT/StringExtras.h"
13#include "llvm/Support/FileSystem.h"
14#include "llvm/Support/GlobPattern.h"
15#include <algorithm>
16#include <mutex>
17#include <vector>
18
19using namespace llvm;
20using namespace lld;
21
22SingleStringMatcher::SingleStringMatcher(StringRef Pattern) {
23 if (Pattern.size() > 2 && Pattern.starts_with(Prefix: "\"") &&
24 Pattern.ends_with(Suffix: "\"")) {
25 ExactMatch = true;
26 ExactPattern = Pattern.substr(Start: 1, N: Pattern.size() - 2);
27 } else {
28 Expected<GlobPattern> Glob = GlobPattern::create(Pat: Pattern);
29 if (!Glob) {
30 error(msg: toString(E: Glob.takeError()) + ": " + Pattern);
31 return;
32 }
33 ExactMatch = false;
34 GlobPatternMatcher = *Glob;
35 }
36}
37
38bool SingleStringMatcher::match(StringRef s) const {
39 return ExactMatch ? (ExactPattern == s) : GlobPatternMatcher.match(S: s);
40}
41
42bool StringMatcher::match(StringRef s) const {
43 for (const SingleStringMatcher &pat : patterns)
44 if (pat.match(s))
45 return true;
46 return false;
47}
48
49// Converts a hex string (e.g. "deadbeef") to a vector.
50SmallVector<uint8_t, 0> lld::parseHex(StringRef s) {
51 SmallVector<uint8_t, 0> hex;
52 while (!s.empty()) {
53 StringRef b = s.substr(Start: 0, N: 2);
54 s = s.substr(Start: 2);
55 uint8_t h;
56 if (!to_integer(S: b, Num&: h, Base: 16)) {
57 error(msg: "not a hexadecimal value: " + b);
58 return {};
59 }
60 hex.push_back(Elt: h);
61 }
62 return hex;
63}
64
65// Returns true if S is valid as a C language identifier.
66bool lld::isValidCIdentifier(StringRef s) {
67 return !s.empty() && !isDigit(C: s[0]) &&
68 llvm::all_of(Range&: s, P: [](char c) { return isAlnum(C: c) || c == '_'; });
69}
70
71// Write the contents of the a buffer to a file
72void lld::saveBuffer(StringRef buffer, const Twine &path) {
73 std::error_code ec;
74 raw_fd_ostream os(path.str(), ec, sys::fs::OpenFlags::OF_None);
75 if (ec)
76 error(msg: "cannot create " + path + ": " + ec.message());
77 os << buffer;
78}
79

source code of lld/Common/Strings.cpp