1 //===- InputFiles.h ---------------------------------------------*- 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 #ifndef LLD_MACHO_INPUT_FILES_H
10 #define LLD_MACHO_INPUT_FILES_H
11 
12 #include "MachOStructs.h"
13 #include "Target.h"
14 
15 #include "lld/Common/LLVM.h"
16 #include "lld/Common/Memory.h"
17 #include "llvm/ADT/CachedHashString.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/BinaryFormat/MachO.h"
21 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
22 #include "llvm/Object/Archive.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/TextAPI/TextAPIReader.h"
25 
26 #include <vector>
27 
28 namespace llvm {
29 namespace lto {
30 class InputFile;
31 } // namespace lto
32 namespace MachO {
33 class InterfaceFile;
34 } // namespace MachO
35 class TarWriter;
36 } // namespace llvm
37 
38 namespace lld {
39 namespace macho {
40 
41 struct PlatformInfo;
42 class ConcatInputSection;
43 class Symbol;
44 struct Reloc;
45 enum class RefState : uint8_t;
46 
47 // If --reproduce option is given, all input files are written
48 // to this tar archive.
49 extern std::unique_ptr<llvm::TarWriter> tar;
50 
51 // If .subsections_via_symbols is set, each InputSection will be split along
52 // symbol boundaries. The field offset represents the offset of the subsection
53 // from the start of the original pre-split InputSection.
54 struct SubsectionEntry {
55   uint64_t offset;
56   InputSection *isec;
57 };
58 using SubsectionMap = std::vector<SubsectionEntry>;
59 
60 class InputFile {
61 public:
62   enum Kind {
63     ObjKind,
64     OpaqueKind,
65     DylibKind,
66     ArchiveKind,
67     BitcodeKind,
68   };
69 
70   virtual ~InputFile() = default;
71   Kind kind() const { return fileKind; }
72   StringRef getName() const { return name; }
73   static void resetIdCount() { idCount = 0; }
74 
75   MemoryBufferRef mb;
76 
77   std::vector<Symbol *> symbols;
78   std::vector<SubsectionMap> subsections;
79   // Provides an easy way to sort InputFiles deterministically.
80   const int id;
81 
82   // If not empty, this stores the name of the archive containing this file.
83   // We use this string for creating error messages.
84   std::string archiveName;
85 
86 protected:
87   InputFile(Kind kind, MemoryBufferRef mb)
88       : mb(mb), id(idCount++), fileKind(kind), name(mb.getBufferIdentifier()) {}
89 
90   InputFile(Kind, const llvm::MachO::InterfaceFile &);
91 
92 private:
93   const Kind fileKind;
94   const StringRef name;
95 
96   static int idCount;
97 };
98 
99 // .o file
100 class ObjFile final : public InputFile {
101 public:
102   ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName);
103   static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
104 
105   llvm::DWARFUnit *compileUnit = nullptr;
106   const uint32_t modTime;
107   std::vector<ConcatInputSection *> debugSections;
108   ArrayRef<llvm::MachO::data_in_code_entry> dataInCodeEntries;
109 
110 private:
111   template <class LP> void parse();
112   template <class Section> void parseSections(ArrayRef<Section>);
113   template <class LP>
114   void parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
115                     ArrayRef<typename LP::nlist> nList, const char *strtab,
116                     bool subsectionsViaSymbols);
117   template <class NList>
118   Symbol *parseNonSectionSymbol(const NList &sym, StringRef name);
119   template <class Section>
120   void parseRelocations(ArrayRef<Section> sectionHeaders, const Section &,
121                         SubsectionMap &);
122   void parseDebugInfo();
123   void parseDataInCode();
124   void registerCompactUnwind();
125 };
126 
127 // command-line -sectcreate file
128 class OpaqueFile final : public InputFile {
129 public:
130   OpaqueFile(MemoryBufferRef mb, StringRef segName, StringRef sectName);
131   static bool classof(const InputFile *f) { return f->kind() == OpaqueKind; }
132 };
133 
134 // .dylib or .tbd file
135 class DylibFile final : public InputFile {
136 public:
137   // Mach-O dylibs can re-export other dylibs as sub-libraries, meaning that the
138   // symbols in those sub-libraries will be available under the umbrella
139   // library's namespace. Those sub-libraries can also have their own
140   // re-exports. When loading a re-exported dylib, `umbrella` should be set to
141   // the root dylib to ensure symbols in the child library are correctly bound
142   // to the root. On the other hand, if a dylib is being directly loaded
143   // (through an -lfoo flag), then `umbrella` should be a nullptr.
144   explicit DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
145                      bool isBundleLoader = false);
146   explicit DylibFile(const llvm::MachO::InterfaceFile &interface,
147                      DylibFile *umbrella = nullptr,
148                      bool isBundleLoader = false);
149 
150   void parseLoadCommands(MemoryBufferRef mb);
151   void parseReexports(const llvm::MachO::InterfaceFile &interface);
152 
153   static bool classof(const InputFile *f) { return f->kind() == DylibKind; }
154 
155   StringRef installName;
156   DylibFile *exportingFile = nullptr;
157   DylibFile *umbrella;
158   SmallVector<StringRef, 2> rpaths;
159   uint32_t compatibilityVersion = 0;
160   uint32_t currentVersion = 0;
161   int64_t ordinal = 0; // Ordinal numbering starts from 1, so 0 is a sentinel
162   RefState refState;
163   bool reexport = false;
164   bool forceNeeded = false;
165   bool forceWeakImport = false;
166   bool deadStrippable = false;
167   bool explicitlyLinked = false;
168 
169   unsigned numReferencedSymbols = 0;
170 
171   bool isReferenced() const { return numReferencedSymbols > 0; }
172 
173   // An executable can be used as a bundle loader that will load the output
174   // file being linked, and that contains symbols referenced, but not
175   // implemented in the bundle. When used like this, it is very similar
176   // to a Dylib, so we re-used the same class to represent it.
177   bool isBundleLoader;
178 
179 private:
180   bool handleLDSymbol(StringRef originalName);
181   void handleLDPreviousSymbol(StringRef name, StringRef originalName);
182   void handleLDInstallNameSymbol(StringRef name, StringRef originalName);
183   void checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const;
184 };
185 
186 // .a file
187 class ArchiveFile final : public InputFile {
188 public:
189   explicit ArchiveFile(std::unique_ptr<llvm::object::Archive> &&file);
190   void addLazySymbols();
191   void fetch(const llvm::object::Archive::Symbol &);
192   // LLD normally doesn't use Error for error-handling, but the underlying
193   // Archive library does, so this is the cleanest way to wrap it.
194   Error fetch(const llvm::object::Archive::Child &, StringRef reason);
195   const llvm::object::Archive &getArchive() const { return *file; };
196   static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; }
197 
198 private:
199   std::unique_ptr<llvm::object::Archive> file;
200   // Keep track of children fetched from the archive by tracking
201   // which address offsets have been fetched already.
202   llvm::DenseSet<uint64_t> seen;
203 };
204 
205 class BitcodeFile final : public InputFile {
206 public:
207   explicit BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
208                        uint64_t offsetInArchive);
209   static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
210 
211   std::unique_ptr<llvm::lto::InputFile> obj;
212 };
213 
214 extern llvm::SetVector<InputFile *> inputFiles;
215 extern llvm::DenseMap<llvm::CachedHashStringRef, MemoryBufferRef> cachedReads;
216 
217 llvm::Optional<MemoryBufferRef> readFile(StringRef path);
218 
219 namespace detail {
220 
221 template <class CommandType, class... Types>
222 std::vector<const CommandType *>
223 findCommands(const void *anyHdr, size_t maxCommands, Types... types) {
224   std::vector<const CommandType *> cmds;
225   std::initializer_list<uint32_t> typesList{types...};
226   const auto *hdr = reinterpret_cast<const llvm::MachO::mach_header *>(anyHdr);
227   const uint8_t *p =
228       reinterpret_cast<const uint8_t *>(hdr) + target->headerSize;
229   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
230     auto *cmd = reinterpret_cast<const CommandType *>(p);
231     if (llvm::is_contained(typesList, cmd->cmd)) {
232       cmds.push_back(cmd);
233       if (cmds.size() == maxCommands)
234         return cmds;
235     }
236     p += cmd->cmdsize;
237   }
238   return cmds;
239 }
240 
241 } // namespace detail
242 
243 // anyHdr should be a pointer to either mach_header or mach_header_64
244 template <class CommandType = llvm::MachO::load_command, class... Types>
245 const CommandType *findCommand(const void *anyHdr, Types... types) {
246   std::vector<const CommandType *> cmds =
247       detail::findCommands<CommandType>(anyHdr, 1, types...);
248   return cmds.size() ? cmds[0] : nullptr;
249 }
250 
251 template <class CommandType = llvm::MachO::load_command, class... Types>
252 std::vector<const CommandType *> findCommands(const void *anyHdr,
253                                               Types... types) {
254   return detail::findCommands<CommandType>(anyHdr, 0, types...);
255 }
256 
257 } // namespace macho
258 
259 std::string toString(const macho::InputFile *file);
260 } // namespace lld
261 
262 #endif
263