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/DWARF.h"
16 #include "lld/Common/LLVM.h"
17 #include "lld/Common/Memory.h"
18 #include "llvm/ADT/CachedHashString.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/BinaryFormat/MachO.h"
22 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Threading.h"
26 #include "llvm/TextAPI/TextAPIReader.h"
27 
28 #include <vector>
29 
30 namespace llvm {
31 namespace lto {
32 class InputFile;
33 } // namespace lto
34 namespace MachO {
35 class InterfaceFile;
36 } // namespace MachO
37 class TarWriter;
38 } // namespace llvm
39 
40 namespace lld {
41 namespace macho {
42 
43 struct PlatformInfo;
44 class ConcatInputSection;
45 class Symbol;
46 class Defined;
47 struct Reloc;
48 enum class RefState : uint8_t;
49 
50 // If --reproduce option is given, all input files are written
51 // to this tar archive.
52 extern std::unique_ptr<llvm::TarWriter> tar;
53 
54 // If .subsections_via_symbols is set, each InputSection will be split along
55 // symbol boundaries. The field offset represents the offset of the subsection
56 // from the start of the original pre-split InputSection.
57 struct Subsection {
58   uint64_t offset = 0;
59   InputSection *isec = nullptr;
60 };
61 
62 using Subsections = std::vector<Subsection>;
63 class InputFile;
64 
65 class Section {
66 public:
67   InputFile *file;
68   StringRef segname;
69   StringRef name;
70   uint32_t flags;
71   uint64_t addr;
72   Subsections subsections;
73 
74   Section(InputFile *file, StringRef segname, StringRef name, uint32_t flags,
75           uint64_t addr)
76       : file(file), segname(segname), name(name), flags(flags), addr(addr) {}
77   // Ensure pointers to Sections are never invalidated.
78   Section(const Section &) = delete;
79   Section &operator=(const Section &) = delete;
80   Section(Section &&) = delete;
81   Section &operator=(Section &&) = delete;
82 
83 private:
84   // Whether we have already split this section into individual subsections.
85   // For sections that cannot be split (e.g. literal sections), this is always
86   // false.
87   bool doneSplitting = false;
88   friend class ObjFile;
89 };
90 
91 // Represents a call graph profile edge.
92 struct CallGraphEntry {
93   // The index of the caller in the symbol table.
94   uint32_t fromIndex;
95   // The index of the callee in the symbol table.
96   uint32_t toIndex;
97   // Number of calls from callee to caller in the profile.
98   uint64_t count;
99 
100   CallGraphEntry(uint32_t fromIndex, uint32_t toIndex, uint64_t count)
101       : fromIndex(fromIndex), toIndex(toIndex), count(count) {}
102 };
103 
104 class InputFile {
105 public:
106   enum Kind {
107     ObjKind,
108     OpaqueKind,
109     DylibKind,
110     ArchiveKind,
111     BitcodeKind,
112   };
113 
114   virtual ~InputFile() = default;
115   Kind kind() const { return fileKind; }
116   StringRef getName() const { return name; }
117   static void resetIdCount() { idCount = 0; }
118 
119   MemoryBufferRef mb;
120 
121   std::vector<Symbol *> symbols;
122   std::vector<Section *> sections;
123 
124   // If not empty, this stores the name of the archive containing this file.
125   // We use this string for creating error messages.
126   std::string archiveName;
127 
128   // Provides an easy way to sort InputFiles deterministically.
129   const int id;
130 
131   // True if this is a lazy ObjFile or BitcodeFile.
132   bool lazy = false;
133 
134 protected:
135   InputFile(Kind kind, MemoryBufferRef mb, bool lazy = false)
136       : mb(mb), id(idCount++), lazy(lazy), fileKind(kind),
137         name(mb.getBufferIdentifier()) {}
138 
139   InputFile(Kind, const llvm::MachO::InterfaceFile &);
140 
141 private:
142   const Kind fileKind;
143   const StringRef name;
144 
145   static int idCount;
146 };
147 
148 struct FDE {
149   uint32_t funcLength;
150   Symbol *personality;
151   InputSection *lsda;
152 };
153 
154 // .o file
155 class ObjFile final : public InputFile {
156 public:
157   ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
158           bool lazy = false);
159   ArrayRef<llvm::MachO::data_in_code_entry> getDataInCode() const;
160   template <class LP> void parse();
161 
162   static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
163 
164   std::string sourceFile() const;
165   // Parses line table information for diagnostics. compileUnit should be used
166   // for other purposes.
167   lld::DWARFCache *getDwarf();
168 
169   llvm::DWARFUnit *compileUnit = nullptr;
170   std::unique_ptr<lld::DWARFCache> dwarfCache;
171   Section *addrSigSection = nullptr;
172   const uint32_t modTime;
173   std::vector<ConcatInputSection *> debugSections;
174   std::vector<CallGraphEntry> callGraph;
175   llvm::DenseMap<ConcatInputSection *, FDE> fdes;
176 
177 private:
178   llvm::once_flag initDwarf;
179   template <class LP> void parseLazy();
180   template <class SectionHeader> void parseSections(ArrayRef<SectionHeader>);
181   template <class LP>
182   void parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
183                     ArrayRef<typename LP::nlist> nList, const char *strtab,
184                     bool subsectionsViaSymbols);
185   template <class NList>
186   Symbol *parseNonSectionSymbol(const NList &sym, StringRef name);
187   template <class SectionHeader>
188   void parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
189                         const SectionHeader &, Section &);
190   void parseDebugInfo();
191   void splitEhFrames(ArrayRef<uint8_t> dataArr, Section &ehFrameSection);
192   void registerCompactUnwind(Section &compactUnwindSection);
193   void registerEhFrames(Section &ehFrameSection);
194 };
195 
196 // command-line -sectcreate file
197 class OpaqueFile final : public InputFile {
198 public:
199   OpaqueFile(MemoryBufferRef mb, StringRef segName, StringRef sectName);
200   static bool classof(const InputFile *f) { return f->kind() == OpaqueKind; }
201 };
202 
203 // .dylib or .tbd file
204 class DylibFile final : public InputFile {
205 public:
206   // Mach-O dylibs can re-export other dylibs as sub-libraries, meaning that the
207   // symbols in those sub-libraries will be available under the umbrella
208   // library's namespace. Those sub-libraries can also have their own
209   // re-exports. When loading a re-exported dylib, `umbrella` should be set to
210   // the root dylib to ensure symbols in the child library are correctly bound
211   // to the root. On the other hand, if a dylib is being directly loaded
212   // (through an -lfoo flag), then `umbrella` should be a nullptr.
213   explicit DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
214                      bool isBundleLoader, bool explicitlyLinked);
215   explicit DylibFile(const llvm::MachO::InterfaceFile &interface,
216                      DylibFile *umbrella, bool isBundleLoader,
217                      bool explicitlyLinked);
218 
219   void parseLoadCommands(MemoryBufferRef mb);
220   void parseReexports(const llvm::MachO::InterfaceFile &interface);
221   bool isReferenced() const { return numReferencedSymbols > 0; }
222 
223   static bool classof(const InputFile *f) { return f->kind() == DylibKind; }
224 
225   StringRef installName;
226   DylibFile *exportingFile = nullptr;
227   DylibFile *umbrella;
228   SmallVector<StringRef, 2> rpaths;
229   uint32_t compatibilityVersion = 0;
230   uint32_t currentVersion = 0;
231   int64_t ordinal = 0; // Ordinal numbering starts from 1, so 0 is a sentinel
232   unsigned numReferencedSymbols = 0;
233   RefState refState;
234   bool reexport = false;
235   bool forceNeeded = false;
236   bool forceWeakImport = false;
237   bool deadStrippable = false;
238   bool explicitlyLinked = false;
239   // An executable can be used as a bundle loader that will load the output
240   // file being linked, and that contains symbols referenced, but not
241   // implemented in the bundle. When used like this, it is very similar
242   // to a dylib, so we've used the same class to represent it.
243   bool isBundleLoader;
244 
245 private:
246   bool handleLDSymbol(StringRef originalName);
247   void handleLDPreviousSymbol(StringRef name, StringRef originalName);
248   void handleLDInstallNameSymbol(StringRef name, StringRef originalName);
249   void handleLDHideSymbol(StringRef name, StringRef originalName);
250   void checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const;
251 
252   llvm::DenseSet<llvm::CachedHashStringRef> hiddenSymbols;
253 };
254 
255 // .a file
256 class ArchiveFile final : public InputFile {
257 public:
258   explicit ArchiveFile(std::unique_ptr<llvm::object::Archive> &&file);
259   void addLazySymbols();
260   void fetch(const llvm::object::Archive::Symbol &);
261   // LLD normally doesn't use Error for error-handling, but the underlying
262   // Archive library does, so this is the cleanest way to wrap it.
263   Error fetch(const llvm::object::Archive::Child &, StringRef reason);
264   const llvm::object::Archive &getArchive() const { return *file; };
265   static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; }
266 
267 private:
268   std::unique_ptr<llvm::object::Archive> file;
269   // Keep track of children fetched from the archive by tracking
270   // which address offsets have been fetched already.
271   llvm::DenseSet<uint64_t> seen;
272 };
273 
274 class BitcodeFile final : public InputFile {
275 public:
276   explicit BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
277                        uint64_t offsetInArchive, bool lazy = false);
278   static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
279   void parse();
280 
281   std::unique_ptr<llvm::lto::InputFile> obj;
282 
283 private:
284   void parseLazy();
285 };
286 
287 extern llvm::SetVector<InputFile *> inputFiles;
288 extern llvm::DenseMap<llvm::CachedHashStringRef, MemoryBufferRef> cachedReads;
289 
290 llvm::Optional<MemoryBufferRef> readFile(StringRef path);
291 
292 void extract(InputFile &file, StringRef reason);
293 
294 namespace detail {
295 
296 template <class CommandType, class... Types>
297 std::vector<const CommandType *>
298 findCommands(const void *anyHdr, size_t maxCommands, Types... types) {
299   std::vector<const CommandType *> cmds;
300   std::initializer_list<uint32_t> typesList{types...};
301   const auto *hdr = reinterpret_cast<const llvm::MachO::mach_header *>(anyHdr);
302   const uint8_t *p =
303       reinterpret_cast<const uint8_t *>(hdr) + target->headerSize;
304   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
305     auto *cmd = reinterpret_cast<const CommandType *>(p);
306     if (llvm::is_contained(typesList, cmd->cmd)) {
307       cmds.push_back(cmd);
308       if (cmds.size() == maxCommands)
309         return cmds;
310     }
311     p += cmd->cmdsize;
312   }
313   return cmds;
314 }
315 
316 } // namespace detail
317 
318 // anyHdr should be a pointer to either mach_header or mach_header_64
319 template <class CommandType = llvm::MachO::load_command, class... Types>
320 const CommandType *findCommand(const void *anyHdr, Types... types) {
321   std::vector<const CommandType *> cmds =
322       detail::findCommands<CommandType>(anyHdr, 1, types...);
323   return cmds.size() ? cmds[0] : nullptr;
324 }
325 
326 template <class CommandType = llvm::MachO::load_command, class... Types>
327 std::vector<const CommandType *> findCommands(const void *anyHdr,
328                                               Types... types) {
329   return detail::findCommands<CommandType>(anyHdr, 0, types...);
330 }
331 
332 } // namespace macho
333 
334 std::string toString(const macho::InputFile *file);
335 std::string toString(const macho::Section &);
336 } // namespace lld
337 
338 #endif
339