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