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 "Symbols.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "lld/Common/LLVM.h"
16 #include "lld/Common/Reproduce.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/BinaryFormat/Magic.h"
19 #include "llvm/Object/ELF.h"
20 #include "llvm/Support/MemoryBufferRef.h"
21 #include "llvm/Support/Threading.h"
22 
23 namespace llvm {
24 struct DILineInfo;
25 class TarWriter;
26 namespace lto {
27 class InputFile;
28 }
29 } // namespace llvm
30 
31 namespace lld {
32 class DWARFCache;
33 
34 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
35 std::string toString(const elf::InputFile *f);
36 
37 namespace elf {
38 
39 class InputSection;
40 class Symbol;
41 
42 // If --reproduce is specified, all input files are written to this tar archive.
43 extern std::unique_ptr<llvm::TarWriter> tar;
44 
45 // Opens a given file.
46 std::optional<MemoryBufferRef> readFile(StringRef path);
47 
48 // Add symbols in File to the symbol table.
49 void parseFile(InputFile *file);
50 
51 // The root class of input files.
52 class InputFile {
53 protected:
54   std::unique_ptr<Symbol *[]> symbols;
55   uint32_t numSymbols = 0;
56   SmallVector<InputSectionBase *, 0> sections;
57 
58 public:
59   enum Kind : uint8_t {
60     ObjKind,
61     SharedKind,
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() const {
87     assert(fileKind == BinaryKind || fileKind == ObjKind ||
88            fileKind == BitcodeKind);
89     return {symbols.get(), numSymbols};
90   }
91 
92   // Get filename to use for linker script processing.
93   StringRef getNameForScript() const;
94 
95   // Check if a non-common symbol should be extracted to override a common
96   // definition.
97   bool shouldExtractForCommon(StringRef name);
98 
99   // .got2 in the current file. This is used by PPC32 -fPIC/-fPIE to compute
100   // offsets in PLT call stubs.
101   InputSection *ppc32Got2 = nullptr;
102 
103   // Index of MIPS GOT built for this file.
104   uint32_t mipsGotIndex = -1;
105 
106   // groupId is used for --warn-backrefs which is an optional error
107   // checking feature. All files within the same --{start,end}-group or
108   // --{start,end}-lib get the same group ID. Otherwise, each file gets a new
109   // group ID. For more info, see checkDependency() in SymbolTable.cpp.
110   uint32_t groupId;
111   static bool isInGroup;
112   static uint32_t nextGroupId;
113 
114   // If this is an architecture-specific file, the following members
115   // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
116   uint16_t emachine = llvm::ELF::EM_NONE;
117   const Kind fileKind;
118   ELFKind ekind = ELFNoneKind;
119   uint8_t osabi = 0;
120   uint8_t abiVersion = 0;
121 
122   // True if this is a relocatable object file/bitcode file between --start-lib
123   // and --end-lib.
124   bool lazy = false;
125 
126   // True if this is an argument for --just-symbols. Usually false.
127   bool justSymbols = false;
128 
129   std::string getSrcMsg(const Symbol &sym, InputSectionBase &sec,
130                         uint64_t offset);
131 
132   // On PPC64 we need to keep track of which files contain small code model
133   // relocations that access the .toc section. To minimize the chance of a
134   // relocation overflow, files that do contain said relocations should have
135   // their .toc sections sorted closer to the .got section than files that do
136   // not contain any small code model relocations. Thats because the toc-pointer
137   // is defined to point at .got + 0x8000 and the instructions used with small
138   // code model relocations support immediates in the range [-0x8000, 0x7FFC],
139   // making the addressable range relative to the toc pointer
140   // [.got, .got + 0xFFFC].
141   bool ppc64SmallCodeModelTocRelocs = false;
142 
143   // True if the file has TLSGD/TLSLD GOT relocations without R_PPC64_TLSGD or
144   // R_PPC64_TLSLD. Disable TLS relaxation to avoid bad code generation.
145   bool ppc64DisableTLSRelax = false;
146 
147 protected:
148   InputFile(Kind k, MemoryBufferRef m);
149 
150 public:
151   // If not empty, this stores the name of the archive containing this file.
152   // We use this string for creating error messages.
153   SmallString<0> archiveName;
154   // Cache for toString(). Only toString() should use this member.
155   mutable SmallString<0> toStringCache;
156 
157 private:
158   // Cache for getNameForScript().
159   mutable SmallString<0> nameForScriptCache;
160 };
161 
162 class ELFFileBase : public InputFile {
163 public:
164   ELFFileBase(Kind k, ELFKind ekind, MemoryBufferRef m);
165   static bool classof(const InputFile *f) { return f->isElf(); }
166 
167   void init();
168   template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const {
169     return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer()));
170   }
171 
172   StringRef getStringTable() const { return stringTable; }
173 
174   ArrayRef<Symbol *> getLocalSymbols() {
175     if (numSymbols == 0)
176       return {};
177     return llvm::ArrayRef(symbols.get() + 1, firstGlobal - 1);
178   }
179   ArrayRef<Symbol *> getGlobalSymbols() {
180     return llvm::ArrayRef(symbols.get() + firstGlobal,
181                           numSymbols - firstGlobal);
182   }
183   MutableArrayRef<Symbol *> getMutableGlobalSymbols() {
184     return llvm::MutableArrayRef(symbols.get() + firstGlobal,
185                                      numSymbols - firstGlobal);
186   }
187 
188   template <typename ELFT> typename ELFT::ShdrRange getELFShdrs() const {
189     return typename ELFT::ShdrRange(
190         reinterpret_cast<const typename ELFT::Shdr *>(elfShdrs), numELFShdrs);
191   }
192   template <typename ELFT> typename ELFT::SymRange getELFSyms() const {
193     return typename ELFT::SymRange(
194         reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numELFSyms);
195   }
196   template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const {
197     return getELFSyms<ELFT>().slice(firstGlobal);
198   }
199 
200 protected:
201   // Initializes this class's member variables.
202   template <typename ELFT> void init(InputFile::Kind k);
203 
204   StringRef stringTable;
205   const void *elfShdrs = nullptr;
206   const void *elfSyms = nullptr;
207   uint32_t numELFShdrs = 0;
208   uint32_t numELFSyms = 0;
209   uint32_t firstGlobal = 0;
210 
211 public:
212   uint32_t andFeatures = 0;
213   bool hasCommonSyms = false;
214 };
215 
216 // .o file.
217 template <class ELFT> class ObjFile : public ELFFileBase {
218   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
219 
220 public:
221   static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
222 
223   llvm::object::ELFFile<ELFT> getObj() const {
224     return this->ELFFileBase::getObj<ELFT>();
225   }
226 
227   ObjFile(ELFKind ekind, MemoryBufferRef m, StringRef archiveName)
228       : ELFFileBase(ObjKind, ekind, m) {
229     this->archiveName = archiveName;
230   }
231 
232   void parse(bool ignoreComdats = false);
233   void parseLazy();
234 
235   StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
236                                  const Elf_Shdr &sec);
237 
238   Symbol &getSymbol(uint32_t symbolIndex) const {
239     if (symbolIndex >= numSymbols)
240       fatal(toString(this) + ": invalid symbol index");
241     return *this->symbols[symbolIndex];
242   }
243 
244   uint32_t getSectionIndex(const Elf_Sym &sym) const;
245 
246   template <typename RelT> Symbol &getRelocTargetSym(const RelT &rel) const {
247     uint32_t symIndex = rel.getSymbol(config->isMips64EL);
248     return getSymbol(symIndex);
249   }
250 
251   std::optional<llvm::DILineInfo> getDILineInfo(InputSectionBase *, uint64_t);
252   std::optional<std::pair<std::string, unsigned>>
253   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   void initSectionsAndLocalSyms(bool ignoreComdats);
283   void postParse();
284 
285 private:
286   void initializeSections(bool ignoreComdats,
287                           const llvm::object::ELFFile<ELFT> &obj);
288   void initializeSymbols(const llvm::object::ELFFile<ELFT> &obj);
289   void initializeJustSymbols();
290 
291   InputSectionBase *getRelocTarget(uint32_t idx, const Elf_Shdr &sec,
292                                    uint32_t info);
293   InputSectionBase *createInputSection(uint32_t idx, const Elf_Shdr &sec,
294                                        StringRef name);
295 
296   bool shouldMerge(const Elf_Shdr &sec, StringRef name);
297 
298   // Each ELF symbol contains a section index which the symbol belongs to.
299   // However, because the number of bits dedicated for that is limited, a
300   // symbol can directly point to a section only when the section index is
301   // equal to or smaller than 65280.
302   //
303   // If an object file contains more than 65280 sections, the file must
304   // contain .symtab_shndx section. The section contains an array of
305   // 32-bit integers whose size is the same as the number of symbols.
306   // Nth symbol's section index is in the Nth entry of .symtab_shndx.
307   //
308   // The following variable contains the contents of .symtab_shndx.
309   // If the section does not exist (which is common), the array is empty.
310   ArrayRef<Elf_Word> shndxTable;
311 
312   // Debugging information to retrieve source file and line for error
313   // reporting. Linker may find reasonable number of errors in a
314   // single object file, so we cache debugging information in order to
315   // parse it only once for each object file we link.
316   std::unique_ptr<DWARFCache> dwarf;
317   llvm::once_flag initDwarf;
318 };
319 
320 class BitcodeFile : public InputFile {
321 public:
322   BitcodeFile(MemoryBufferRef m, StringRef archiveName,
323               uint64_t offsetInArchive, bool lazy);
324   static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
325   void parse();
326   void parseLazy();
327   void postParse();
328   std::unique_ptr<llvm::lto::InputFile> obj;
329   std::vector<bool> keptComdats;
330 };
331 
332 // .so file.
333 class SharedFile : public ELFFileBase {
334 public:
335   SharedFile(MemoryBufferRef m, StringRef defaultSoName);
336 
337   // This is actually a vector of Elf_Verdef pointers.
338   SmallVector<const void *, 0> verdefs;
339 
340   // If the output file needs Elf_Verneed data structures for this file, this is
341   // a vector of Elf_Vernaux version identifiers that map onto the entries in
342   // Verdefs, otherwise it is empty.
343   SmallVector<uint32_t, 0> vernauxs;
344 
345   static unsigned vernauxNum;
346 
347   SmallVector<StringRef, 0> dtNeeded;
348   StringRef soName;
349 
350   static bool classof(const InputFile *f) { return f->kind() == SharedKind; }
351 
352   template <typename ELFT> void parse();
353 
354   // Used for --as-needed
355   bool isNeeded;
356 
357   // Non-weak undefined symbols which are not yet resolved when the SO is
358   // parsed. Only filled for `--no-allow-shlib-undefined`.
359   SmallVector<Symbol *, 0> requiredSymbols;
360 
361 private:
362   template <typename ELFT>
363   std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj,
364                                      const typename ELFT::Shdr *sec);
365 };
366 
367 class BinaryFile : public InputFile {
368 public:
369   explicit BinaryFile(MemoryBufferRef m) : InputFile(BinaryKind, m) {}
370   static bool classof(const InputFile *f) { return f->kind() == BinaryKind; }
371   void parse();
372 };
373 
374 ELFFileBase *createObjFile(MemoryBufferRef mb, StringRef archiveName = "",
375                            bool lazy = false);
376 
377 std::string replaceThinLTOSuffix(StringRef path);
378 
379 } // namespace elf
380 } // namespace lld
381 
382 #endif
383