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_ELF_INPUT_FILES_H
10 #define LLD_ELF_INPUT_FILES_H
11
12 #include "Config.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "lld/Common/LLVM.h"
15 #include "lld/Common/Reproduce.h"
16 #include "llvm/ADT/CachedHashString.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ELF.h"
22 #include "llvm/Object/IRObjectFile.h"
23 #include "llvm/Support/Threading.h"
24 #include <map>
25
26 namespace llvm {
27 struct DILineInfo;
28 class TarWriter;
29 namespace lto {
30 class InputFile;
31 }
32 } // namespace llvm
33
34 namespace lld {
35 class DWARFCache;
36
37 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
38 std::string toString(const elf::InputFile *f);
39
40 namespace elf {
41
42 using llvm::object::Archive;
43
44 class Symbol;
45
46 // If -reproduce option is given, all input files are written
47 // to this tar archive.
48 extern std::unique_ptr<llvm::TarWriter> tar;
49
50 // Opens a given file.
51 llvm::Optional<MemoryBufferRef> readFile(StringRef path);
52
53 // Add symbols in File to the symbol table.
54 void parseFile(InputFile *file);
55
56 // The root class of input files.
57 class InputFile {
58 public:
59 enum Kind {
60 ObjKind,
61 SharedKind,
62 LazyObjKind,
63 ArchiveKind,
64 BitcodeKind,
65 BinaryKind,
66 };
67
kind()68 Kind kind() const { return fileKind; }
69
isElf()70 bool isElf() const {
71 Kind k = kind();
72 return k == ObjKind || k == SharedKind;
73 }
74
getName()75 StringRef getName() const { return mb.getBufferIdentifier(); }
76 MemoryBufferRef mb;
77
78 // Returns sections. It is a runtime error to call this function
79 // on files that don't have the notion of sections.
getSections()80 ArrayRef<InputSectionBase *> getSections() const {
81 assert(fileKind == ObjKind || fileKind == BinaryKind);
82 return sections;
83 }
84
85 // Returns object file symbols. It is a runtime error to call this
86 // function on files of other types.
getSymbols()87 ArrayRef<Symbol *> getSymbols() { return getMutableSymbols(); }
88
getMutableSymbols()89 MutableArrayRef<Symbol *> getMutableSymbols() {
90 assert(fileKind == BinaryKind || fileKind == ObjKind ||
91 fileKind == BitcodeKind);
92 return symbols;
93 }
94
95 // Filename of .a which contained this file. If this file was
96 // not in an archive file, it is the empty string. We use this
97 // string for creating error messages.
98 std::string archiveName;
99
100 // If this is an architecture-specific file, the following members
101 // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
102 ELFKind ekind = ELFNoneKind;
103 uint16_t emachine = llvm::ELF::EM_NONE;
104 uint64_t eflags = 0;
105 uint8_t osabi = 0;
106 uint8_t abiVersion = 0;
107
108 // Cache for toString(). Only toString() should use this member.
109 mutable std::string toStringCache;
110
111 std::string getSrcMsg(const Symbol &sym, const InputSectionBase &sec,
112 uint64_t offset);
113
114 // True if this is an argument for --just-symbols. Usually false.
115 bool justSymbols = false;
116
117 // outSecOff of .got2 in the current file. This is used by PPC32 -fPIC/-fPIE
118 // to compute offsets in PLT call stubs.
119 uint32_t ppc32Got2OutSecOff = 0;
120
121 // On PPC64 we need to keep track of which files contain small code model
122 // relocations that access the .toc section. To minimize the chance of a
123 // relocation overflow, files that do contain said relocations should have
124 // their .toc sections sorted closer to the .got section than files that do
125 // not contain any small code model relocations. Thats because the toc-pointer
126 // is defined to point at .got + 0x8000 and the instructions used with small
127 // code model relocations support immediates in the range [-0x8000, 0x7FFC],
128 // making the addressable range relative to the toc pointer
129 // [.got, .got + 0xFFFC].
130 bool ppc64SmallCodeModelTocRelocs = false;
131
132 // groupId is used for --warn-backrefs which is an optional error
133 // checking feature. All files within the same --{start,end}-group or
134 // --{start,end}-lib get the same group ID. Otherwise, each file gets a new
135 // group ID. For more info, see checkDependency() in SymbolTable.cpp.
136 uint32_t groupId;
137 static bool isInGroup;
138 static uint32_t nextGroupId;
139
140 // Index of MIPS GOT built for this file.
141 llvm::Optional<size_t> mipsGotIndex;
142
143 std::vector<Symbol *> symbols;
144
145 protected:
146 InputFile(Kind k, MemoryBufferRef m);
147 std::vector<InputSectionBase *> sections;
148
149 private:
150 const Kind fileKind;
151 };
152
153 class ELFFileBase : public InputFile {
154 public:
155 ELFFileBase(Kind k, MemoryBufferRef m);
classof(const InputFile * f)156 static bool classof(const InputFile *f) { return f->isElf(); }
157
getObj()158 template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const {
159 return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer()));
160 }
161
getStringTable()162 StringRef getStringTable() const { return stringTable; }
163
getELFSyms()164 template <typename ELFT> typename ELFT::SymRange getELFSyms() const {
165 return typename ELFT::SymRange(
166 reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numELFSyms);
167 }
getGlobalELFSyms()168 template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const {
169 return getELFSyms<ELFT>().slice(firstGlobal);
170 }
171
172 protected:
173 // Initializes this class's member variables.
174 template <typename ELFT> void init();
175
176 const void *elfSyms = nullptr;
177 size_t numELFSyms = 0;
178 uint32_t firstGlobal = 0;
179 StringRef stringTable;
180 };
181
182 // .o file.
183 template <class ELFT> class ObjFile : public ELFFileBase {
184 using Elf_Rel = typename ELFT::Rel;
185 using Elf_Rela = typename ELFT::Rela;
186 using Elf_Sym = typename ELFT::Sym;
187 using Elf_Shdr = typename ELFT::Shdr;
188 using Elf_Word = typename ELFT::Word;
189 using Elf_CGProfile = typename ELFT::CGProfile;
190
191 public:
classof(const InputFile * f)192 static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
193
getObj()194 llvm::object::ELFFile<ELFT> getObj() const {
195 return this->ELFFileBase::getObj<ELFT>();
196 }
197
198 ArrayRef<Symbol *> getLocalSymbols();
199 ArrayRef<Symbol *> getGlobalSymbols();
200
ObjFile(MemoryBufferRef m,StringRef archiveName)201 ObjFile(MemoryBufferRef m, StringRef archiveName) : ELFFileBase(ObjKind, m) {
202 this->archiveName = std::string(archiveName);
203 }
204
205 void parse(bool ignoreComdats = false);
206
207 StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
208 const Elf_Shdr &sec);
209
getSymbol(uint32_t symbolIndex)210 Symbol &getSymbol(uint32_t symbolIndex) const {
211 if (symbolIndex >= this->symbols.size())
212 fatal(toString(this) + ": invalid symbol index");
213 return *this->symbols[symbolIndex];
214 }
215
216 uint32_t getSectionIndex(const Elf_Sym &sym) const;
217
getRelocTargetSym(const RelT & rel)218 template <typename RelT> Symbol &getRelocTargetSym(const RelT &rel) const {
219 uint32_t symIndex = rel.getSymbol(config->isMips64EL);
220 return getSymbol(symIndex);
221 }
222
223 llvm::Optional<llvm::DILineInfo> getDILineInfo(const InputSectionBase *, uint64_t);
224 llvm::Optional<std::pair<std::string, unsigned>> getVariableLoc(StringRef name);
225
226 // MIPS GP0 value defined by this file. This value represents the gp value
227 // used to create the relocatable object and required to support
228 // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations.
229 uint32_t mipsGp0 = 0;
230
231 uint32_t andFeatures = 0;
232
233 // Name of source file obtained from STT_FILE symbol value,
234 // or empty string if there is no such symbol in object file
235 // symbol table.
236 StringRef sourceFile;
237
238 // True if the file defines functions compiled with
239 // -fsplit-stack. Usually false.
240 bool splitStack = false;
241
242 // True if the file defines functions compiled with -fsplit-stack,
243 // but had one or more functions with the no_split_stack attribute.
244 bool someNoSplitStack = false;
245
246 // Pointer to this input file's .llvm_addrsig section, if it has one.
247 const Elf_Shdr *addrsigSec = nullptr;
248
249 // SHT_LLVM_CALL_GRAPH_PROFILE table
250 ArrayRef<Elf_CGProfile> cgProfile;
251
252 // Get cached DWARF information.
253 DWARFCache *getDwarf();
254
255 private:
256 void initializeSections(bool ignoreComdats);
257 void initializeSymbols();
258 void initializeJustSymbols();
259
260 InputSectionBase *getRelocTarget(const Elf_Shdr &sec);
261 InputSectionBase *createInputSection(const Elf_Shdr &sec);
262 StringRef getSectionName(const Elf_Shdr &sec);
263
264 bool shouldMerge(const Elf_Shdr &sec, StringRef name);
265
266 // Each ELF symbol contains a section index which the symbol belongs to.
267 // However, because the number of bits dedicated for that is limited, a
268 // symbol can directly point to a section only when the section index is
269 // equal to or smaller than 65280.
270 //
271 // If an object file contains more than 65280 sections, the file must
272 // contain .symtab_shndx section. The section contains an array of
273 // 32-bit integers whose size is the same as the number of symbols.
274 // Nth symbol's section index is in the Nth entry of .symtab_shndx.
275 //
276 // The following variable contains the contents of .symtab_shndx.
277 // If the section does not exist (which is common), the array is empty.
278 ArrayRef<Elf_Word> shndxTable;
279
280 // .shstrtab contents.
281 StringRef sectionStringTable;
282
283 // Debugging information to retrieve source file and line for error
284 // reporting. Linker may find reasonable number of errors in a
285 // single object file, so we cache debugging information in order to
286 // parse it only once for each object file we link.
287 std::unique_ptr<DWARFCache> dwarf;
288 llvm::once_flag initDwarf;
289 };
290
291 // LazyObjFile is analogous to ArchiveFile in the sense that
292 // the file contains lazy symbols. The difference is that
293 // LazyObjFile wraps a single file instead of multiple files.
294 //
295 // This class is used for --start-lib and --end-lib options which
296 // instruct the linker to link object files between them with the
297 // archive file semantics.
298 class LazyObjFile : public InputFile {
299 public:
LazyObjFile(MemoryBufferRef m,StringRef archiveName,uint64_t offsetInArchive)300 LazyObjFile(MemoryBufferRef m, StringRef archiveName,
301 uint64_t offsetInArchive)
302 : InputFile(LazyObjKind, m), offsetInArchive(offsetInArchive) {
303 this->archiveName = std::string(archiveName);
304 }
305
classof(const InputFile * f)306 static bool classof(const InputFile *f) { return f->kind() == LazyObjKind; }
307
308 template <class ELFT> void parse();
309 void fetch();
310
311 bool fetched = false;
312
313 private:
314 uint64_t offsetInArchive;
315 };
316
317 // An ArchiveFile object represents a .a file.
318 class ArchiveFile : public InputFile {
319 public:
320 explicit ArchiveFile(std::unique_ptr<Archive> &&file);
classof(const InputFile * f)321 static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; }
322 void parse();
323
324 // Pulls out an object file that contains a definition for Sym and
325 // returns it. If the same file was instantiated before, this
326 // function does nothing (so we don't instantiate the same file
327 // more than once.)
328 void fetch(const Archive::Symbol &sym);
329
330 size_t getMemberCount() const;
getFetchedMemberCount()331 size_t getFetchedMemberCount() const { return seen.size(); }
332
333 bool parsed = false;
334
335 private:
336 std::unique_ptr<Archive> file;
337 llvm::DenseSet<uint64_t> seen;
338 };
339
340 class BitcodeFile : public InputFile {
341 public:
342 BitcodeFile(MemoryBufferRef m, StringRef archiveName,
343 uint64_t offsetInArchive);
classof(const InputFile * f)344 static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
345 template <class ELFT> void parse();
346 std::unique_ptr<llvm::lto::InputFile> obj;
347 };
348
349 // .so file.
350 class SharedFile : public ELFFileBase {
351 public:
SharedFile(MemoryBufferRef m,StringRef defaultSoName)352 SharedFile(MemoryBufferRef m, StringRef defaultSoName)
353 : ELFFileBase(SharedKind, m), soName(std::string(defaultSoName)),
354 isNeeded(!config->asNeeded) {}
355 uint64_t cheriFlags = 0;
356
357 // This is actually a vector of Elf_Verdef pointers.
358 std::vector<const void *> verdefs;
359
360 // If the output file needs Elf_Verneed data structures for this file, this is
361 // a vector of Elf_Vernaux version identifiers that map onto the entries in
362 // Verdefs, otherwise it is empty.
363 std::vector<unsigned> vernauxs;
364
365 static unsigned vernauxNum;
366
367 std::vector<StringRef> dtNeeded;
368 std::string soName;
369
classof(const InputFile * f)370 static bool classof(const InputFile *f) { return f->kind() == SharedKind; }
371
372 template <typename ELFT> void parse();
373
374 // Used for --no-allow-shlib-undefined.
375 bool allNeededIsKnown;
376
377 // Used for --as-needed
378 bool isNeeded;
379
380 private:
381 template <typename ELFT>
382 std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj,
383 const typename ELFT::Shdr *sec);
384 };
385
386 class BinaryFile : public InputFile {
387 public:
BinaryFile(MemoryBufferRef m)388 explicit BinaryFile(MemoryBufferRef m) : InputFile(BinaryKind, m) {}
classof(const InputFile * f)389 static bool classof(const InputFile *f) { return f->kind() == BinaryKind; }
390 void parse();
391 };
392
393 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName = "",
394 uint64_t offsetInArchive = 0);
395
isBitcode(MemoryBufferRef mb)396 inline bool isBitcode(MemoryBufferRef mb) {
397 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
398 }
399
400 std::string replaceThinLTOSuffix(StringRef path);
401
402 extern std::vector<ArchiveFile *> archiveFiles;
403 extern std::vector<BinaryFile *> binaryFiles;
404 extern std::vector<BitcodeFile *> bitcodeFiles;
405 extern std::vector<LazyObjFile *> lazyObjFiles;
406 extern std::vector<InputFile *> objectFiles;
407 extern std::vector<SharedFile *> sharedFiles;
408
409 } // namespace elf
410 } // namespace lld
411
412 #endif
413