Movatterモバイル変換


[0]ホーム

URL:


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

Generated on Fri Jul 18 2025 16:45:37 for LLVM by doxygen 1.9.6
[8]ページ先頭

©2009-2025 Movatter.jp