LLVM 20.0.0git
Utils.cpp
Go to the documentation of this file.
1//===- Utils.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// Implements utility functions for TextAPI Darwin operations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/TextAPI/Utils.h"
16
17using namespace llvm;
18using namespace llvm::MachO;
19
21 const Twine &Extension) {
22 StringRef P(Path.begin(), Path.size());
23 auto ParentPath = sys::path::parent_path(P);
24 auto Filename = sys::path::filename(P);
25
26 if (!ParentPath.ends_with(Filename.str() + ".framework")) {
27 sys::path::replace_extension(Path, Extension);
28 return;
29 }
30 // Framework dylibs do not have a file extension, in those cases the new
31 // extension is appended. e.g. given Path: "Foo.framework/Foo" and Extension:
32 // "tbd", the result is "Foo.framework/Foo.tbd".
33 SmallString<8> Storage;
34 StringRef Ext = Extension.toStringRef(Storage);
35
36 // Append '.' if needed.
37 if (!Ext.empty() && Ext[0] != '.')
38 Path.push_back('.');
39
40 // Append extension.
41 Path.append(Ext.begin(), Ext.end());
42}
43
44std::error_code llvm::MachO::shouldSkipSymLink(const Twine &Path,
45 bool &Result) {
46 Result = false;
48 auto P = Path.toNullTerminatedStringRef(Storage);
50 auto EC = sys::fs::status(P.data(), Stat1);
51 if (EC == std::errc::too_many_symbolic_link_levels) {
52 Result = true;
53 return {};
54 }
55
56 if (EC)
57 return EC;
58
60 while (!Parent.empty()) {
62 if (auto ec = sys::fs::status(Parent, Stat2))
63 return ec;
64
65 if (sys::fs::equivalent(Stat1, Stat2)) {
66 Result = true;
67 return {};
68 }
69
70 Parent = sys::path::parent_path(Parent);
71 }
72 return {};
73}
74
75std::error_code
77 SmallVectorImpl<char> &RelativePath) {
79 SmallString<PATH_MAX> Dst = To;
80 if (auto EC = sys::fs::make_absolute(Src))
81 return EC;
82
83 if (auto EC = sys::fs::make_absolute(Dst))
84 return EC;
85
88 auto IT1 = sys::path::begin(Src), IT2 = sys::path::begin(Dst),
89 IE1 = sys::path::end(Src), IE2 = sys::path::end(Dst);
90 // Ignore the common part.
91 for (; IT1 != IE1 && IT2 != IE2; ++IT1, ++IT2) {
92 if (*IT1 != *IT2)
93 break;
94 }
95
96 for (; IT1 != IE1; ++IT1)
97 sys::path::append(Result, "../");
98
99 for (; IT2 != IE2; ++IT2)
100 sys::path::append(Result, *IT2);
101
102 if (Result.empty())
103 Result = ".";
104
105 RelativePath.swap(Result);
106
107 return {};
108}
109
110bool llvm::MachO::isPrivateLibrary(StringRef Path, bool IsSymLink) {
111 // Remove the iOSSupport and DriverKit prefix to identify public locations.
112 Path.consume_front(MACCATALYST_PREFIX_PATH);
113 Path.consume_front(DRIVERKIT_PREFIX_PATH);
114 // Also /Library/Apple prefix for ROSP.
115 Path.consume_front("/Library/Apple");
116
117 if (Path.starts_with("/usr/local/lib"))
118 return true;
119
120 if (Path.starts_with("/System/Library/PrivateFrameworks"))
121 return true;
122
123 // Everything in /usr/lib/swift (including sub-directories) are considered
124 // public.
125 if (Path.consume_front("/usr/lib/swift/"))
126 return false;
127
128 // Only libraries directly in /usr/lib are public. All other libraries in
129 // sub-directories are private.
130 if (Path.consume_front("/usr/lib/"))
131 return Path.contains('/');
132
133 // "/System/Library/Frameworks/" is a public location.
134 if (Path.starts_with("/System/Library/Frameworks/")) {
135 StringRef Name, Rest;
136 std::tie(Name, Rest) =
137 Path.drop_front(sizeof("/System/Library/Frameworks")).split('.');
138
139 // Allow symlinks to top-level frameworks.
140 if (IsSymLink && Rest == "framework")
141 return false;
142
143 // Only top level framework are public.
144 // /System/Library/Frameworks/Foo.framework/Foo ==> true
145 // /System/Library/Frameworks/Foo.framework/Versions/A/Foo ==> true
146 // /System/Library/Frameworks/Foo.framework/Resources/libBar.dylib ==> false
147 // /System/Library/Frameworks/Foo.framework/Frameworks/Bar.framework/Bar
148 // ==> false
149 // /System/Library/Frameworks/Foo.framework/Frameworks/Xfoo.framework/XFoo
150 // ==> false
151 return !(Rest.starts_with("framework/") &&
152 (Rest.ends_with(Name) || Rest.ends_with((Name + ".tbd").str()) ||
153 (IsSymLink && Rest.ends_with("Current"))));
154 }
155 return false;
156}
157
158static StringLiteral RegexMetachars = "()^$|+.[]\\{}";
159
161 SmallString<128> RegexString("^");
162 unsigned NumWildcards = 0;
163 for (unsigned i = 0; i < Glob.size(); ++i) {
164 char C = Glob[i];
165 switch (C) {
166 case '?':
167 RegexString += '.';
168 break;
169 case '*': {
170 const char *PrevChar = i > 0 ? Glob.data() + i - 1 : nullptr;
171 NumWildcards = 1;
172 ++i;
173 while (i < Glob.size() && Glob[i] == '*') {
174 ++NumWildcards;
175 ++i;
176 }
177 const char *NextChar = i < Glob.size() ? Glob.data() + i : nullptr;
178
179 if ((NumWildcards > 1) && (PrevChar == nullptr || *PrevChar == '/') &&
180 (NextChar == nullptr || *NextChar == '/')) {
181 RegexString += "(([^/]*(/|$))*)";
182 } else
183 RegexString += "([^/]*)";
184 break;
185 }
186 default:
188 RegexString.push_back('\\');
189 RegexString.push_back(C);
190 }
191 }
192 RegexString.push_back('$');
193 if (NumWildcards == 0)
194 return make_error<StringError>("not a glob", inconvertibleErrorCode());
195
196 llvm::Regex Rule = Regex(RegexString);
197 std::string Error;
198 if (!Rule.isValid(Error))
199 return make_error<StringError>(Error, inconvertibleErrorCode());
200
201 return std::move(Rule);
202}
203
205llvm::MachO::parseAliasList(std::unique_ptr<llvm::MemoryBuffer> &Buffer) {
207 AliasMap Aliases;
208 Buffer->getBuffer().split(Lines, "\n", /*MaxSplit=*/-1,
209 /*KeepEmpty=*/false);
210 for (const StringRef Line : Lines) {
211 StringRef L = Line.trim();
212 if (L.empty())
213 continue;
214 // Skip comments.
215 if (L.starts_with("#"))
216 continue;
217 StringRef Symbol, Remain, Alias;
218 // Base symbol is separated by whitespace.
219 std::tie(Symbol, Remain) = getToken(L);
220 // The Alias symbol ends before a comment or EOL.
221 std::tie(Alias, Remain) = getToken(Remain, "#");
222 Alias = Alias.trim();
223 if (Alias.empty())
224 return make_error<TextAPIError>(
225 TextAPIError(TextAPIErrorCode::InvalidInputFormat,
226 ("missing alias for: " + Symbol).str()));
227 SimpleSymbol AliasSym = parseSymbol(Alias);
229 Aliases[{AliasSym.Name.str(), AliasSym.Kind}] = {BaseSym.Name.str(),
230 BaseSym.Kind};
231 }
232
233 return Aliases;
234}
235
237 PlatformType Platform) {
238 PathSeq Result;
239 for (const auto &[Path, CurrP] : Paths) {
240 if (!CurrP.has_value() || CurrP.value() == Platform)
241 Result.push_back(Path);
242 }
243 return Result;
244}
BlockVerifier::State From
std::string Name
#define P(N)
This file contains some functions that are useful when dealing with strings.
Define TAPI specific error codes.
static StringLiteral RegexMetachars
Definition: Utils.cpp:158
#define DRIVERKIT_PREFIX_PATH
Definition: Utils.h:30
#define MACCATALYST_PREFIX_PATH
Definition: Utils.h:29
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, if any.
Definition: Regex.cpp:69
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void swap(SmallVectorImpl &RHS)
Definition: SmallVector.h:981
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:838
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:250
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:409
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
Definition: StringRef.h:800
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:262
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:225
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
std::map< AliasEntry, AliasEntry > AliasMap
Definition: Utils.h:84
std::error_code make_relative(StringRef From, StringRef To, SmallVectorImpl< char > &RelativePath)
Turn absolute symlink into relative.
Definition: Utils.cpp:76
PlatformType
Definition: MachO.h:500
void replace_extension(SmallVectorImpl< char > &Path, const Twine &Extension)
Replace extension considering frameworks.
Definition: Utils.cpp:20
std::vector< PathToPlatform > PathToPlatformSeq
Definition: Utils.h:36
bool isPrivateLibrary(StringRef Path, bool IsSymLink=false)
Determine if library is private by parsing file path.
Definition: Utils.cpp:110
std::vector< std::string > PathSeq
Definition: Utils.h:34
llvm::Expected< llvm::Regex > createRegexFromGlob(llvm::StringRef Glob)
Create a regex rule from provided glob string.
Definition: Utils.cpp:160
SimpleSymbol parseSymbol(StringRef SymName)
Get symbol classification by parsing the name of a symbol.
Definition: Symbol.cpp:75
PathSeq getPathsForPlatform(const PathToPlatformSeq &Paths, PlatformType Platform)
Pickup active paths for a given platform.
Definition: Utils.cpp:236
std::error_code shouldSkipSymLink(const Twine &Path, bool &Result)
Determine whether to skip over symlink due to either too many symlink levels or is cyclic.
Definition: Utils.cpp:44
Expected< AliasMap > parseAliasList(std::unique_ptr< llvm::MemoryBuffer > &Buffer)
Parse input list and capture symbols and their alias.
Definition: Utils.cpp:205
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:907
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:227
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:481
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:236
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:468
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Lightweight struct for passing around symbol information.
Definition: Symbol.h:178