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