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