xref: /llvm-project-15.0.7/lld/ELF/InputFiles.h (revision cf838ebf)
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 is specified, all input files are written to this tar archive.
47 extern std::unique_ptr<llvm::TarWriter> tar;
48 
49 // Opens a given file.
50 llvm::Optional<MemoryBufferRef> readFile(StringRef path);
51 
52 // Add symbols in File to the symbol table.
53 void parseFile(InputFile *file);
54 
55 // The root class of input files.
56 class InputFile {
57 public:
58   enum Kind {
59     ObjKind,
60     SharedKind,
61     LazyObjKind,
62     ArchiveKind,
63     BitcodeKind,
64     BinaryKind,
65   };
66 
67   Kind kind() const { return fileKind; }
68 
69   bool isElf() const {
70     Kind k = kind();
71     return k == ObjKind || k == SharedKind;
72   }
73 
74   StringRef getName() const { return mb.getBufferIdentifier(); }
75   MemoryBufferRef mb;
76 
77   // Returns sections. It is a runtime error to call this function
78   // on files that don't have the notion of sections.
79   ArrayRef<InputSectionBase *> getSections() const {
80     assert(fileKind == ObjKind || fileKind == BinaryKind);
81     return sections;
82   }
83 
84   // Returns object file symbols. It is a runtime error to call this
85   // function on files of other types.
86   ArrayRef<Symbol *> getSymbols() { return getMutableSymbols(); }
87 
88   MutableArrayRef<Symbol *> getMutableSymbols() {
89     assert(fileKind == BinaryKind || fileKind == ObjKind ||
90            fileKind == BitcodeKind);
91     return symbols;
92   }
93 
94   // Get filename to use for linker script processing.
95   StringRef getNameForScript() const;
96 
97   // If not empty, this stores the name of the archive containing this file.
98   // We use this string for creating error messages.
99   std::string archiveName;
100 
101   // If this is an architecture-specific file, the following members
102   // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
103   ELFKind ekind = ELFNoneKind;
104   uint16_t emachine = llvm::ELF::EM_NONE;
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, 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   // True if the file has TLSGD/TLSLD GOT relocations without R_PPC64_TLSGD or
133   // R_PPC64_TLSLD. Disable TLS relaxation to avoid bad code generation.
134   bool ppc64DisableTLSRelax = false;
135 
136   // groupId is used for --warn-backrefs which is an optional error
137   // checking feature. All files within the same --{start,end}-group or
138   // --{start,end}-lib get the same group ID. Otherwise, each file gets a new
139   // group ID. For more info, see checkDependency() in SymbolTable.cpp.
140   uint32_t groupId;
141   static bool isInGroup;
142   static uint32_t nextGroupId;
143 
144   // Index of MIPS GOT built for this file.
145   llvm::Optional<size_t> mipsGotIndex;
146 
147   std::vector<Symbol *> symbols;
148 
149 protected:
150   InputFile(Kind k, MemoryBufferRef m);
151   std::vector<InputSectionBase *> sections;
152 
153 private:
154   const Kind fileKind;
155 
156   // Cache for getNameForScript().
157   mutable std::string nameForScriptCache;
158 };
159 
160 class ELFFileBase : public InputFile {
161 public:
162   ELFFileBase(Kind k, MemoryBufferRef m);
163   static bool classof(const InputFile *f) { return f->isElf(); }
164 
165   template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const {
166     return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer()));
167   }
168 
169   StringRef getStringTable() const { return stringTable; }
170 
171   template <typename ELFT> typename ELFT::SymRange getELFSyms() const {
172     return typename ELFT::SymRange(
173         reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numELFSyms);
174   }
175   template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const {
176     return getELFSyms<ELFT>().slice(firstGlobal);
177   }
178 
179 protected:
180   // Initializes this class's member variables.
181   template <typename ELFT> void init();
182 
183   const void *elfSyms = nullptr;
184   size_t numELFSyms = 0;
185   uint32_t firstGlobal = 0;
186   StringRef stringTable;
187 };
188 
189 // .o file.
190 template <class ELFT> class ObjFile : public ELFFileBase {
191   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
192 
193 public:
194   static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
195 
196   llvm::object::ELFFile<ELFT> getObj() const {
197     return this->ELFFileBase::getObj<ELFT>();
198   }
199 
200   ArrayRef<Symbol *> getLocalSymbols();
201   ArrayRef<Symbol *> getGlobalSymbols();
202 
203   ObjFile(MemoryBufferRef m, StringRef archiveName) : ELFFileBase(ObjKind, m) {
204     this->archiveName = std::string(archiveName);
205   }
206 
207   void parse(bool ignoreComdats = false);
208 
209   StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
210                                  const Elf_Shdr &sec);
211 
212   Symbol &getSymbol(uint32_t symbolIndex) const {
213     if (symbolIndex >= this->symbols.size())
214       fatal(toString(this) + ": invalid symbol index");
215     return *this->symbols[symbolIndex];
216   }
217 
218   uint32_t getSectionIndex(const Elf_Sym &sym) const;
219 
220   template <typename RelT> Symbol &getRelocTargetSym(const RelT &rel) const {
221     uint32_t symIndex = rel.getSymbol(config->isMips64EL);
222     return getSymbol(symIndex);
223   }
224 
225   llvm::Optional<llvm::DILineInfo> getDILineInfo(InputSectionBase *, uint64_t);
226   llvm::Optional<std::pair<std::string, unsigned>> getVariableLoc(StringRef name);
227 
228   // MIPS GP0 value defined by this file. This value represents the gp value
229   // used to create the relocatable object and required to support
230   // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations.
231   uint32_t mipsGp0 = 0;
232 
233   uint32_t andFeatures = 0;
234 
235   // Name of source file obtained from STT_FILE symbol value,
236   // or empty string if there is no such symbol in object file
237   // symbol table.
238   StringRef sourceFile;
239 
240   // True if the file defines functions compiled with
241   // -fsplit-stack. Usually false.
242   bool splitStack = false;
243 
244   // True if the file defines functions compiled with -fsplit-stack,
245   // but had one or more functions with the no_split_stack attribute.
246   bool someNoSplitStack = false;
247 
248   // Pointer to this input file's .llvm_addrsig section, if it has one.
249   const Elf_Shdr *addrsigSec = nullptr;
250 
251   // SHT_LLVM_CALL_GRAPH_PROFILE section index.
252   uint32_t cgProfileSectionIndex = 0;
253 
254   // Get cached DWARF information.
255   DWARFCache *getDwarf();
256 
257 private:
258   void initializeSections(bool ignoreComdats);
259   void initializeSymbols();
260   void initializeJustSymbols();
261 
262   InputSectionBase *getRelocTarget(const Elf_Shdr &sec);
263   InputSectionBase *createInputSection(uint32_t idx, const Elf_Shdr &sec,
264                                        StringRef shstrtab);
265 
266   bool shouldMerge(const Elf_Shdr &sec, StringRef name);
267 
268   // Each ELF symbol contains a section index which the symbol belongs to.
269   // However, because the number of bits dedicated for that is limited, a
270   // symbol can directly point to a section only when the section index is
271   // equal to or smaller than 65280.
272   //
273   // If an object file contains more than 65280 sections, the file must
274   // contain .symtab_shndx section. The section contains an array of
275   // 32-bit integers whose size is the same as the number of symbols.
276   // Nth symbol's section index is in the Nth entry of .symtab_shndx.
277   //
278   // The following variable contains the contents of .symtab_shndx.
279   // If the section does not exist (which is common), the array is empty.
280   ArrayRef<Elf_Word> shndxTable;
281 
282   // Debugging information to retrieve source file and line for error
283   // reporting. Linker may find reasonable number of errors in a
284   // single object file, so we cache debugging information in order to
285   // parse it only once for each object file we link.
286   std::unique_ptr<DWARFCache> dwarf;
287   llvm::once_flag initDwarf;
288 };
289 
290 // LazyObjFile is analogous to ArchiveFile in the sense that
291 // the file contains lazy symbols. The difference is that
292 // LazyObjFile wraps a single file instead of multiple files.
293 //
294 // This class is used for --start-lib and --end-lib options which
295 // instruct the linker to link object files between them with the
296 // archive file semantics.
297 class LazyObjFile : public InputFile {
298 public:
299   LazyObjFile(MemoryBufferRef m, StringRef archiveName,
300               uint64_t offsetInArchive)
301       : InputFile(LazyObjKind, m), offsetInArchive(offsetInArchive) {
302     this->archiveName = std::string(archiveName);
303   }
304 
305   static bool classof(const InputFile *f) { return f->kind() == LazyObjKind; }
306 
307   template <class ELFT> void parse();
308   void fetch();
309 
310   // Check if a non-common symbol should be fetched to override a common
311   // definition.
312   bool shouldFetchForCommon(const StringRef &name);
313 
314   bool fetched = false;
315 
316 private:
317   uint64_t offsetInArchive;
318 };
319 
320 // An ArchiveFile object represents a .a file.
321 class ArchiveFile : public InputFile {
322 public:
323   explicit ArchiveFile(std::unique_ptr<Archive> &&file);
324   static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; }
325   void parse();
326 
327   // Pulls out an object file that contains a definition for Sym and
328   // returns it. If the same file was instantiated before, this
329   // function does nothing (so we don't instantiate the same file
330   // more than once.)
331   void fetch(const Archive::Symbol &sym);
332 
333   // Check if a non-common symbol should be fetched to override a common
334   // definition.
335   bool shouldFetchForCommon(const Archive::Symbol &sym);
336 
337   size_t getMemberCount() const;
338   size_t getFetchedMemberCount() const { return seen.size(); }
339 
340   bool parsed = false;
341 
342 private:
343   std::unique_ptr<Archive> file;
344   llvm::DenseSet<uint64_t> seen;
345 };
346 
347 class BitcodeFile : public InputFile {
348 public:
349   BitcodeFile(MemoryBufferRef m, StringRef archiveName,
350               uint64_t offsetInArchive);
351   static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
352   template <class ELFT> void parse();
353   std::unique_ptr<llvm::lto::InputFile> obj;
354 };
355 
356 // .so file.
357 class SharedFile : public ELFFileBase {
358 public:
359   SharedFile(MemoryBufferRef m, StringRef defaultSoName)
360       : ELFFileBase(SharedKind, m), soName(defaultSoName),
361         isNeeded(!config->asNeeded) {}
362 
363   // This is actually a vector of Elf_Verdef pointers.
364   std::vector<const void *> verdefs;
365 
366   // If the output file needs Elf_Verneed data structures for this file, this is
367   // a vector of Elf_Vernaux version identifiers that map onto the entries in
368   // Verdefs, otherwise it is empty.
369   std::vector<unsigned> vernauxs;
370 
371   static unsigned vernauxNum;
372 
373   std::vector<StringRef> dtNeeded;
374   StringRef soName;
375 
376   static bool classof(const InputFile *f) { return f->kind() == SharedKind; }
377 
378   template <typename ELFT> void parse();
379 
380   // Used for --as-needed
381   bool isNeeded;
382 
383   // Non-weak undefined symbols which are not yet resolved when the SO is
384   // parsed. Only filled for `--no-allow-shlib-undefined`.
385   std::vector<Symbol *> requiredSymbols;
386 
387 private:
388   template <typename ELFT>
389   std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj,
390                                      const typename ELFT::Shdr *sec);
391 };
392 
393 class BinaryFile : public InputFile {
394 public:
395   explicit BinaryFile(MemoryBufferRef m) : InputFile(BinaryKind, m) {}
396   static bool classof(const InputFile *f) { return f->kind() == BinaryKind; }
397   void parse();
398 };
399 
400 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName = "",
401                             uint64_t offsetInArchive = 0);
402 
403 inline bool isBitcode(MemoryBufferRef mb) {
404   return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
405 }
406 
407 std::string replaceThinLTOSuffix(StringRef path);
408 
409 extern std::vector<ArchiveFile *> archiveFiles;
410 extern std::vector<BinaryFile *> binaryFiles;
411 extern std::vector<BitcodeFile *> bitcodeFiles;
412 extern std::vector<LazyObjFile *> lazyObjFiles;
413 extern std::vector<InputFile *> objectFiles;
414 extern std::vector<SharedFile *> sharedFiles;
415 
416 } // namespace elf
417 } // namespace lld
418 
419 #endif
420