1 //===- llvm/TextAPI/InterfaceFile.h - TAPI Interface File -------*- C++ -*-===//
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 // A generic and abstract interface representation for linkable objects. This
10 // could be an MachO executable, bundle, dylib, or text-based stub file.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_TEXTAPI_INTERFACEFILE_H
15 #define LLVM_TEXTAPI_INTERFACEFILE_H
16
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/iterator.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/TextAPI/ArchitectureSet.h"
23 #include "llvm/TextAPI/FileTypes.h"
24 #include "llvm/TextAPI/PackedVersion.h"
25 #include "llvm/TextAPI/Platform.h"
26 #include "llvm/TextAPI/RecordsSlice.h"
27 #include "llvm/TextAPI/Symbol.h"
28 #include "llvm/TextAPI/SymbolSet.h"
29 #include "llvm/TextAPI/Target.h"
30
31 namespace llvm {
32 namespace MachO {
33
34 /// Defines a list of Objective-C constraints.
35 enum class ObjCConstraintType : unsigned {
36 /// No constraint.
37 None = 0,
38
39 /// Retain/Release.
40 Retain_Release = 1,
41
42 /// Retain/Release for Simulator.
43 Retain_Release_For_Simulator = 2,
44
45 /// Retain/Release or Garbage Collection.
46 Retain_Release_Or_GC = 3,
47
48 /// Garbage Collection.
49 GC = 4,
50 };
51
52 /// Reference to an interface file.
53 class InterfaceFileRef {
54 public:
55 InterfaceFileRef() = default;
56
InterfaceFileRef(StringRef InstallName)57 InterfaceFileRef(StringRef InstallName) : InstallName(InstallName) {}
58
InterfaceFileRef(StringRef InstallName,const TargetList Targets)59 InterfaceFileRef(StringRef InstallName, const TargetList Targets)
60 : InstallName(InstallName), Targets(std::move(Targets)) {}
61
getInstallName()62 StringRef getInstallName() const { return InstallName; };
63
64 LLVM_ABI void addTarget(const Target &Target);
addTargets(RangeT && Targets)65 template <typename RangeT> void addTargets(RangeT &&Targets) {
66 for (const auto &Target : Targets)
67 addTarget(Target(Target));
68 }
69
hasTarget(Target & Targ)70 bool hasTarget(Target &Targ) const {
71 return llvm::is_contained(Targets, Targ);
72 }
73
74 using const_target_iterator = TargetList::const_iterator;
75 using const_target_range = llvm::iterator_range<const_target_iterator>;
targets()76 const_target_range targets() const { return {Targets}; }
77
getArchitectures()78 ArchitectureSet getArchitectures() const {
79 return mapToArchitectureSet(Targets);
80 }
81
getPlatforms()82 PlatformSet getPlatforms() const { return mapToPlatformSet(Targets); }
83
84 bool operator==(const InterfaceFileRef &O) const {
85 return std::tie(InstallName, Targets) == std::tie(O.InstallName, O.Targets);
86 }
87
88 bool operator!=(const InterfaceFileRef &O) const {
89 return std::tie(InstallName, Targets) != std::tie(O.InstallName, O.Targets);
90 }
91
92 bool operator<(const InterfaceFileRef &O) const {
93 return std::tie(InstallName, Targets) < std::tie(O.InstallName, O.Targets);
94 }
95
96 private:
97 std::string InstallName;
98 TargetList Targets;
99 };
100
101 } // end namespace MachO.
102
103 namespace MachO {
104
105 /// Defines the interface file.
106 class InterfaceFile {
107 public:
InterfaceFile(std::unique_ptr<SymbolSet> && InputSymbols)108 InterfaceFile(std::unique_ptr<SymbolSet> &&InputSymbols)
109 : SymbolsSet(std::move(InputSymbols)) {}
110
InterfaceFile()111 InterfaceFile() : SymbolsSet(std::make_unique<SymbolSet>()){};
112 /// Set the path from which this file was generated (if applicable).
113 ///
114 /// \param Path_ The path to the source file.
setPath(StringRef Path_)115 void setPath(StringRef Path_) { Path = std::string(Path_); }
116
117 /// Get the path from which this file was generated (if applicable).
118 ///
119 /// \return The path to the source file or empty.
getPath()120 StringRef getPath() const { return Path; }
121
122 /// Set the file type.
123 ///
124 /// This is used by the YAML writer to identify the specification it should
125 /// use for writing the file.
126 ///
127 /// \param Kind The file type.
setFileType(FileType Kind)128 void setFileType(FileType Kind) { FileKind = Kind; }
129
130 /// Get the file type.
131 ///
132 /// \return The file type.
getFileType()133 FileType getFileType() const { return FileKind; }
134
135 /// Get the architectures.
136 ///
137 /// \return The applicable architectures.
getArchitectures()138 ArchitectureSet getArchitectures() const {
139 return mapToArchitectureSet(Targets);
140 }
141
142 /// Get the platforms.
143 ///
144 /// \return The applicable platforms.
getPlatforms()145 PlatformSet getPlatforms() const { return mapToPlatformSet(Targets); }
146
147 /// Set and add target.
148 ///
149 /// \param Target the target to add into.
150 LLVM_ABI void addTarget(const Target &Target);
151
152 /// Determine if target triple slice exists in file.
153 ///
154 /// \param Targ the value to find.
hasTarget(const Target & Targ)155 bool hasTarget(const Target &Targ) const {
156 return llvm::is_contained(Targets, Targ);
157 }
158
159 /// Set and add targets.
160 ///
161 /// Add the subset of llvm::triples that is supported by Tapi
162 ///
163 /// \param Targets the collection of targets.
addTargets(RangeT && Targets)164 template <typename RangeT> void addTargets(RangeT &&Targets) {
165 for (const auto &Target_ : Targets)
166 addTarget(Target(Target_));
167 }
168
169 using const_target_iterator = TargetList::const_iterator;
170 using const_target_range = llvm::iterator_range<const_target_iterator>;
targets()171 const_target_range targets() const { return {Targets}; }
172
173 using const_filtered_target_iterator =
174 llvm::filter_iterator<const_target_iterator,
175 std::function<bool(const Target &)>>;
176 using const_filtered_target_range =
177 llvm::iterator_range<const_filtered_target_iterator>;
178 LLVM_ABI const_filtered_target_range targets(ArchitectureSet Archs) const;
179
180 /// Set the install name of the library.
setInstallName(StringRef InstallName_)181 void setInstallName(StringRef InstallName_) {
182 InstallName = std::string(InstallName_);
183 }
184
185 /// Get the install name of the library.
getInstallName()186 StringRef getInstallName() const { return InstallName; }
187
188 /// Set the current version of the library.
setCurrentVersion(PackedVersion Version)189 void setCurrentVersion(PackedVersion Version) { CurrentVersion = Version; }
190
191 /// Get the current version of the library.
getCurrentVersion()192 PackedVersion getCurrentVersion() const { return CurrentVersion; }
193
194 /// Set the compatibility version of the library.
setCompatibilityVersion(PackedVersion Version)195 void setCompatibilityVersion(PackedVersion Version) {
196 CompatibilityVersion = Version;
197 }
198
199 /// Get the compatibility version of the library.
getCompatibilityVersion()200 PackedVersion getCompatibilityVersion() const { return CompatibilityVersion; }
201
202 /// Set the Swift ABI version of the library.
setSwiftABIVersion(uint8_t Version)203 void setSwiftABIVersion(uint8_t Version) { SwiftABIVersion = Version; }
204
205 /// Get the Swift ABI version of the library.
getSwiftABIVersion()206 uint8_t getSwiftABIVersion() const { return SwiftABIVersion; }
207
208 /// Specify if the library uses two-level namespace (or flat namespace).
209 void setTwoLevelNamespace(bool V = true) { IsTwoLevelNamespace = V; }
210
211 /// Check if the library uses two-level namespace.
isTwoLevelNamespace()212 bool isTwoLevelNamespace() const { return IsTwoLevelNamespace; }
213
214 /// Specify if the library is an OS library but not shared cache eligible.
215 void setOSLibNotForSharedCache(bool V = true) {
216 IsOSLibNotForSharedCache = V;
217 }
218
219 /// Check if the library is an OS library that is not shared cache eligible.
isOSLibNotForSharedCache()220 bool isOSLibNotForSharedCache() const { return IsOSLibNotForSharedCache; }
221
222 /// Specify if the library is application extension safe (or not).
223 void setApplicationExtensionSafe(bool V = true) { IsAppExtensionSafe = V; }
224
225 /// Check if the library is application extension safe.
isApplicationExtensionSafe()226 bool isApplicationExtensionSafe() const { return IsAppExtensionSafe; }
227
228 /// Check if the library has simulator support.
hasSimulatorSupport()229 bool hasSimulatorSupport() const { return HasSimSupport; }
230
231 /// Specify if the library has simulator support.
232 void setSimulatorSupport(bool V = true) { HasSimSupport = V; }
233
234 /// Set the Objective-C constraint.
setObjCConstraint(ObjCConstraintType Constraint)235 void setObjCConstraint(ObjCConstraintType Constraint) {
236 ObjcConstraint = Constraint;
237 }
238
239 /// Get the Objective-C constraint.
getObjCConstraint()240 ObjCConstraintType getObjCConstraint() const { return ObjcConstraint; }
241
242 /// Set the parent umbrella frameworks.
243 /// \param Target_ The target applicable to Parent
244 /// \param Parent The name of Parent
245 LLVM_ABI void addParentUmbrella(const Target &Target_, StringRef Parent);
246
247 /// Get the list of Parent Umbrella frameworks.
248 ///
249 /// \return Returns a list of target information and install name of parent
250 /// umbrellas.
umbrellas()251 const std::vector<std::pair<Target, std::string>> &umbrellas() const {
252 return ParentUmbrellas;
253 }
254
255 /// Add an allowable client.
256 ///
257 /// Mach-O Dynamic libraries have the concept of allowable clients that are
258 /// checked during static link time. The name of the application or library
259 /// that is being generated needs to match one of the allowable clients or the
260 /// linker refuses to link this library.
261 ///
262 /// \param InstallName The name of the client that is allowed to link this
263 /// library.
264 /// \param Target The target triple for which this applies.
265 LLVM_ABI void addAllowableClient(StringRef InstallName, const Target &Target);
266
267 /// Get the list of allowable clients.
268 ///
269 /// \return Returns a list of allowable clients.
allowableClients()270 const std::vector<InterfaceFileRef> &allowableClients() const {
271 return AllowableClients;
272 }
273
274 /// Add a re-exported library.
275 ///
276 /// \param InstallName The name of the library to re-export.
277 /// \param Target The target triple for which this applies.
278 LLVM_ABI void addReexportedLibrary(StringRef InstallName,
279 const Target &Target);
280
281 /// Get the list of re-exported libraries.
282 ///
283 /// \return Returns a list of re-exported libraries.
reexportedLibraries()284 const std::vector<InterfaceFileRef> &reexportedLibraries() const {
285 return ReexportedLibraries;
286 }
287
288 /// Add a library for inlining to top level library.
289 ///
290 ///\param Document The library to inline with top level library.
291 LLVM_ABI void addDocument(std::shared_ptr<InterfaceFile> &&Document);
292
293 /// Returns the pointer to parent document if exists or nullptr otherwise.
getParent()294 InterfaceFile *getParent() const { return Parent; }
295
296 /// Get the list of inlined libraries.
297 ///
298 /// \return Returns a list of the inlined frameworks.
documents()299 const std::vector<std::shared_ptr<InterfaceFile>> &documents() const {
300 return Documents;
301 }
302
303 /// Set the runpath search paths.
304 /// \param RPath The name of runpath.
305 /// \param InputTarget The target applicable to runpath search path.
306 LLVM_ABI void addRPath(StringRef RPath, const Target &InputTarget);
307
308 /// Get the list of runpath search paths.
309 ///
310 /// \return Returns a list of the rpaths per target.
rpaths()311 const std::vector<std::pair<Target, std::string>> &rpaths() const {
312 return RPaths;
313 }
314
315 /// Get symbol if exists in file.
316 ///
317 /// \param Kind The kind of global symbol to record.
318 /// \param Name The name of the symbol.
319 /// \param ObjCIF The ObjCInterface symbol type, if applicable.
320 std::optional<const Symbol *>
321 getSymbol(EncodeKind Kind, StringRef Name,
322 ObjCIFSymbolKind ObjCIF = ObjCIFSymbolKind::None) const {
323 if (auto *Sym = SymbolsSet->findSymbol(Kind, Name, ObjCIF))
324 return Sym;
325 return std::nullopt;
326 }
327
328 /// Add a symbol to the symbols list or extend an existing one.
329 template <typename RangeT, typename ElT = std::remove_reference_t<
330 decltype(*std::begin(std::declval<RangeT>()))>>
331 void addSymbol(EncodeKind Kind, StringRef Name, RangeT &&Targets,
332 SymbolFlags Flags = SymbolFlags::None) {
333 SymbolsSet->addGlobal(Kind, Name, Flags, Targets);
334 }
335
336 /// Add Symbol with multiple targets.
337 ///
338 /// \param Kind The kind of global symbol to record.
339 /// \param Name The name of the symbol.
340 /// \param Targets The list of targets the symbol is defined in.
341 /// \param Flags The properties the symbol holds.
342 void addSymbol(EncodeKind Kind, StringRef Name, TargetList &&Targets,
343 SymbolFlags Flags = SymbolFlags::None) {
344 SymbolsSet->addGlobal(Kind, Name, Flags, Targets);
345 }
346
347 /// Add Symbol with single target.
348 ///
349 /// \param Kind The kind of global symbol to record.
350 /// \param Name The name of the symbol.
351 /// \param Target The target the symbol is defined in.
352 /// \param Flags The properties the symbol holds.
353 void addSymbol(EncodeKind Kind, StringRef Name, Target &Target,
354 SymbolFlags Flags = SymbolFlags::None) {
355 SymbolsSet->addGlobal(Kind, Name, Flags, Target);
356 }
357
358 /// Get size of symbol set.
359 /// \return The number of symbols the file holds.
symbolsCount()360 size_t symbolsCount() const { return SymbolsSet->size(); }
361
362 using const_symbol_range = SymbolSet::const_symbol_range;
363 using const_filtered_symbol_range = SymbolSet::const_filtered_symbol_range;
364
symbols()365 const_symbol_range symbols() const { return SymbolsSet->symbols(); };
exports()366 const_filtered_symbol_range exports() const { return SymbolsSet->exports(); };
reexports()367 const_filtered_symbol_range reexports() const {
368 return SymbolsSet->reexports();
369 };
undefineds()370 const_filtered_symbol_range undefineds() const {
371 return SymbolsSet->undefineds();
372 };
373
374 /// Extract architecture slice from Interface.
375 ///
376 /// \param Arch architecture to extract from.
377 /// \return New InterfaceFile with extracted architecture slice.
378 LLVM_ABI llvm::Expected<std::unique_ptr<InterfaceFile>>
379 extract(Architecture Arch) const;
380
381 /// Remove architecture slice from Interface.
382 ///
383 /// \param Arch architecture to remove.
384 /// \return New Interface File with removed architecture slice.
385 LLVM_ABI llvm::Expected<std::unique_ptr<InterfaceFile>>
386 remove(Architecture Arch) const;
387
388 /// Merge Interfaces for the same library. The following library attributes
389 /// must match.
390 /// * Install name, Current & Compatibility version,
391 /// * Two-level namespace enablement, and App extension enablement.
392 ///
393 /// \param O The Interface to merge.
394 /// \return New Interface File that was merged.
395 LLVM_ABI llvm::Expected<std::unique_ptr<InterfaceFile>>
396 merge(const InterfaceFile *O) const;
397
398 /// Inline reexported library into Interface.
399 ///
400 /// \param Library Interface of reexported library.
401 /// \param Overwrite Whether to overwrite preexisting inlined library.
402 LLVM_ABI void inlineLibrary(std::shared_ptr<InterfaceFile> Library,
403 bool Overwrite = false);
404
405 /// Set InterfaceFile properties from pre-gathered binary attributes,
406 /// if they are not set already.
407 ///
408 /// \param BA Attributes typically represented in load commands.
409 /// \param Targ MachO Target slice to add attributes to.
410 LLVM_ABI void setFromBinaryAttrs(const RecordsSlice::BinaryAttrs &BA,
411 const Target &Targ);
412
413 /// The equality is determined by attributes that impact linking
414 /// compatibilities. Path, & FileKind are irrelevant since these by
415 /// itself should not impact linking.
416 /// This is an expensive operation.
417 LLVM_ABI bool operator==(const InterfaceFile &O) const;
418
419 bool operator!=(const InterfaceFile &O) const { return !(*this == O); }
420
421 private:
422 llvm::BumpPtrAllocator Allocator;
copyString(StringRef String)423 StringRef copyString(StringRef String) {
424 if (String.empty())
425 return {};
426
427 void *Ptr = Allocator.Allocate(String.size(), 1);
428 memcpy(Ptr, String.data(), String.size());
429 return StringRef(reinterpret_cast<const char *>(Ptr), String.size());
430 }
431
432 TargetList Targets;
433 std::string Path;
434 FileType FileKind{FileType::Invalid};
435 std::string InstallName;
436 PackedVersion CurrentVersion;
437 PackedVersion CompatibilityVersion;
438 uint8_t SwiftABIVersion{0};
439 bool IsTwoLevelNamespace{false};
440 bool IsOSLibNotForSharedCache{false};
441 bool IsAppExtensionSafe{false};
442 bool HasSimSupport{false};
443 ObjCConstraintType ObjcConstraint = ObjCConstraintType::None;
444 std::vector<std::pair<Target, std::string>> ParentUmbrellas;
445 std::vector<InterfaceFileRef> AllowableClients;
446 std::vector<InterfaceFileRef> ReexportedLibraries;
447 std::vector<std::shared_ptr<InterfaceFile>> Documents;
448 std::vector<std::pair<Target, std::string>> RPaths;
449 std::unique_ptr<SymbolSet> SymbolsSet;
450 InterfaceFile *Parent = nullptr;
451 };
452
453 // Keep containers that hold InterfaceFileRefs in sorted order and uniqued.
454 template <typename C>
addEntry(C & Container,StringRef InstallName)455 typename C::iterator addEntry(C &Container, StringRef InstallName) {
456 auto I = partition_point(Container, [=](const InterfaceFileRef &O) {
457 return O.getInstallName() < InstallName;
458 });
459 if (I != Container.end() && I->getInstallName() == InstallName)
460 return I;
461
462 return Container.emplace(I, InstallName);
463 }
464
465 } // end namespace MachO.
466 } // end namespace llvm.
467
468 #endif // LLVM_TEXTAPI_INTERFACEFILE_H
469