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