xref: /llvm-project-15.0.7/lld/ELF/InputFiles.h (revision f4bf4227)
1 //===- InputFiles.h ---------------------------------------------*- C++ -*-===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef LLD_ELF_INPUT_FILES_H
11 #define LLD_ELF_INPUT_FILES_H
12 
13 #include "Config.h"
14 #include "InputSection.h"
15 #include "Symbols.h"
16 #include "lld/Common/ErrorHandler.h"
17 
18 #include "lld/Common/LLVM.h"
19 #include "lld/Common/Reproduce.h"
20 #include "llvm/ADT/CachedHashString.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/Object/Archive.h"
25 #include "llvm/Object/ELF.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Support/Threading.h"
28 
29 #include <map>
30 
31 namespace llvm {
32 class DWARFDebugLine;
33 class TarWriter;
34 struct DILineInfo;
35 namespace lto {
36 class InputFile;
37 }
38 } // namespace llvm
39 
40 namespace lld {
41 namespace elf {
42 class InputFile;
43 }
44 
45 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
46 std::string toString(const elf::InputFile *F);
47 
48 namespace elf {
49 
50 using llvm::object::Archive;
51 
52 class Lazy;
53 class Symbol;
54 
55 // If -reproduce option is given, all input files are written
56 // to this tar archive.
57 extern llvm::TarWriter *Tar;
58 
59 // Opens a given file.
60 llvm::Optional<MemoryBufferRef> readFile(StringRef Path);
61 
62 // The root class of input files.
63 class InputFile {
64 public:
65   enum Kind {
66     ObjKind,
67     SharedKind,
68     LazyObjKind,
69     ArchiveKind,
70     BitcodeKind,
71     BinaryKind,
72   };
73 
74   Kind kind() const { return FileKind; }
75 
76   StringRef getName() const { return MB.getBufferIdentifier(); }
77   MemoryBufferRef MB;
78 
79   // Returns sections. It is a runtime error to call this function
80   // on files that don't have the notion of sections.
81   ArrayRef<InputSectionBase *> getSections() const {
82     assert(FileKind == ObjKind || FileKind == BinaryKind);
83     return Sections;
84   }
85 
86   // Returns object file symbols. It is a runtime error to call this
87   // function on files of other types.
88   ArrayRef<Symbol *> getSymbols() {
89     assert(FileKind == ObjKind || FileKind == BitcodeKind ||
90            FileKind == ArchiveKind);
91     return Symbols;
92   }
93 
94   // Filename of .a which contained this file. If this file was
95   // not in an archive file, it is the empty string. We use this
96   // string for creating error messages.
97   StringRef ArchiveName;
98 
99   // If this is an architecture-specific file, the following members
100   // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
101   ELFKind EKind = ELFNoneKind;
102   uint16_t EMachine = llvm::ELF::EM_NONE;
103   uint8_t OSABI = 0;
104 
105   // Cache for toString(). Only toString() should use this member.
106   mutable std::string ToStringCache;
107 
108 protected:
109   InputFile(Kind K, MemoryBufferRef M);
110   std::vector<InputSectionBase *> Sections;
111   std::vector<Symbol *> Symbols;
112 
113 private:
114   const Kind FileKind;
115 };
116 
117 template <typename ELFT> class ELFFileBase : public InputFile {
118 public:
119   typedef typename ELFT::Shdr Elf_Shdr;
120   typedef typename ELFT::Sym Elf_Sym;
121   typedef typename ELFT::Word Elf_Word;
122   typedef typename ELFT::SymRange Elf_Sym_Range;
123 
124   ELFFileBase(Kind K, MemoryBufferRef M);
125   static bool classof(const InputFile *F) {
126     Kind K = F->kind();
127     return K == ObjKind || K == SharedKind;
128   }
129 
130   llvm::object::ELFFile<ELFT> getObj() const {
131     return check(llvm::object::ELFFile<ELFT>::create(MB.getBuffer()));
132   }
133 
134   StringRef getStringTable() const { return StringTable; }
135 
136   uint32_t getSectionIndex(const Elf_Sym &Sym) const;
137 
138   Elf_Sym_Range getGlobalELFSyms();
139   Elf_Sym_Range getELFSyms() const { return ELFSyms; }
140 
141 protected:
142   ArrayRef<Elf_Sym> ELFSyms;
143   uint32_t FirstNonLocal = 0;
144   ArrayRef<Elf_Word> SymtabSHNDX;
145   StringRef StringTable;
146   void initSymtab(ArrayRef<Elf_Shdr> Sections, const Elf_Shdr *Symtab);
147 };
148 
149 // .o file.
150 template <class ELFT> class ObjFile : public ELFFileBase<ELFT> {
151   typedef ELFFileBase<ELFT> Base;
152   typedef typename ELFT::Rel Elf_Rel;
153   typedef typename ELFT::Rela Elf_Rela;
154   typedef typename ELFT::Sym Elf_Sym;
155   typedef typename ELFT::Shdr Elf_Shdr;
156   typedef typename ELFT::Word Elf_Word;
157 
158   StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
159                                  const Elf_Shdr &Sec);
160   ArrayRef<Elf_Word> getShtGroupEntries(const Elf_Shdr &Sec);
161 
162 public:
163   static bool classof(const InputFile *F) { return F->kind() == Base::ObjKind; }
164 
165   ArrayRef<Symbol *> getLocalSymbols();
166 
167   ObjFile(MemoryBufferRef M, StringRef ArchiveName);
168   void parse(llvm::DenseSet<llvm::CachedHashStringRef> &ComdatGroups);
169 
170   InputSectionBase *getSection(uint32_t Index) const;
171 
172   Symbol &getSymbol(uint32_t SymbolIndex) const {
173     if (SymbolIndex >= this->Symbols.size())
174       fatal(toString(this) + ": invalid symbol index");
175     return *this->Symbols[SymbolIndex];
176   }
177 
178   template <typename RelT> Symbol &getRelocTargetSym(const RelT &Rel) const {
179     uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
180     return getSymbol(SymIndex);
181   }
182 
183   // Returns source line information for a given offset.
184   // If no information is available, returns "".
185   std::string getLineInfo(InputSectionBase *S, uint64_t Offset);
186   llvm::Optional<llvm::DILineInfo> getDILineInfo(InputSectionBase *, uint64_t);
187   llvm::Optional<std::pair<std::string, unsigned>> getVariableLoc(StringRef Name);
188 
189   // MIPS GP0 value defined by this file. This value represents the gp value
190   // used to create the relocatable object and required to support
191   // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations.
192   uint32_t MipsGp0 = 0;
193 
194   // Name of source file obtained from STT_FILE symbol value,
195   // or empty string if there is no such symbol in object file
196   // symbol table.
197   StringRef SourceFile;
198 
199 private:
200   void
201   initializeSections(llvm::DenseSet<llvm::CachedHashStringRef> &ComdatGroups);
202   void initializeSymbols();
203   void initializeDwarf();
204   InputSectionBase *getRelocTarget(const Elf_Shdr &Sec);
205   InputSectionBase *createInputSection(const Elf_Shdr &Sec);
206   StringRef getSectionName(const Elf_Shdr &Sec);
207 
208   bool shouldMerge(const Elf_Shdr &Sec);
209   Symbol *createSymbol(const Elf_Sym *Sym);
210 
211   // .shstrtab contents.
212   StringRef SectionStringTable;
213 
214   // Debugging information to retrieve source file and line for error
215   // reporting. Linker may find reasonable number of errors in a
216   // single object file, so we cache debugging information in order to
217   // parse it only once for each object file we link.
218   std::unique_ptr<llvm::DWARFDebugLine> DwarfLine;
219   llvm::DenseMap<StringRef, std::pair<unsigned, unsigned>> VariableLoc;
220   llvm::once_flag InitDwarfLine;
221 };
222 
223 // LazyObjFile is analogous to ArchiveFile in the sense that
224 // the file contains lazy symbols. The difference is that
225 // LazyObjFile wraps a single file instead of multiple files.
226 //
227 // This class is used for --start-lib and --end-lib options which
228 // instruct the linker to link object files between them with the
229 // archive file semantics.
230 class LazyObjFile : public InputFile {
231 public:
232   LazyObjFile(MemoryBufferRef M, StringRef ArchiveName,
233               uint64_t OffsetInArchive)
234       : InputFile(LazyObjKind, M), OffsetInArchive(OffsetInArchive) {
235     this->ArchiveName = ArchiveName;
236   }
237 
238   static bool classof(const InputFile *F) { return F->kind() == LazyObjKind; }
239 
240   template <class ELFT> void parse();
241   MemoryBufferRef getBuffer();
242   InputFile *fetch();
243 
244 private:
245   std::vector<StringRef> getSymbolNames();
246   template <class ELFT> std::vector<StringRef> getElfSymbols();
247   std::vector<StringRef> getBitcodeSymbols();
248 
249   bool Seen = false;
250   uint64_t OffsetInArchive;
251 };
252 
253 // An ArchiveFile object represents a .a file.
254 class ArchiveFile : public InputFile {
255 public:
256   explicit ArchiveFile(std::unique_ptr<Archive> &&File);
257   static bool classof(const InputFile *F) { return F->kind() == ArchiveKind; }
258   template <class ELFT> void parse();
259 
260   // Returns a memory buffer for a given symbol and the offset in the archive
261   // for the member. An empty memory buffer and an offset of zero
262   // is returned if we have already returned the same memory buffer.
263   // (So that we don't instantiate same members more than once.)
264   std::pair<MemoryBufferRef, uint64_t> getMember(const Archive::Symbol *Sym);
265 
266 private:
267   std::unique_ptr<Archive> File;
268   llvm::DenseSet<uint64_t> Seen;
269 };
270 
271 class BitcodeFile : public InputFile {
272 public:
273   BitcodeFile(MemoryBufferRef M, StringRef ArchiveName,
274               uint64_t OffsetInArchive);
275   static bool classof(const InputFile *F) { return F->kind() == BitcodeKind; }
276   template <class ELFT>
277   void parse(llvm::DenseSet<llvm::CachedHashStringRef> &ComdatGroups);
278   std::unique_ptr<llvm::lto::InputFile> Obj;
279 };
280 
281 // .so file.
282 template <class ELFT> class SharedFile : public ELFFileBase<ELFT> {
283   typedef ELFFileBase<ELFT> Base;
284   typedef typename ELFT::Dyn Elf_Dyn;
285   typedef typename ELFT::Shdr Elf_Shdr;
286   typedef typename ELFT::Sym Elf_Sym;
287   typedef typename ELFT::SymRange Elf_Sym_Range;
288   typedef typename ELFT::Verdef Elf_Verdef;
289   typedef typename ELFT::Versym Elf_Versym;
290 
291   std::vector<StringRef> Undefs;
292   const Elf_Shdr *VersymSec = nullptr;
293   const Elf_Shdr *VerdefSec = nullptr;
294 
295 public:
296   std::string SoName;
297 
298   llvm::ArrayRef<StringRef> getUndefinedSymbols() { return Undefs; }
299 
300   static bool classof(const InputFile *F) {
301     return F->kind() == Base::SharedKind;
302   }
303 
304   SharedFile(MemoryBufferRef M, StringRef DefaultSoName);
305 
306   void parseSoName();
307   void parseRest();
308   std::vector<const Elf_Verdef *> parseVerdefs(const Elf_Versym *&Versym);
309 
310   struct NeededVer {
311     // The string table offset of the version name in the output file.
312     size_t StrTab;
313 
314     // The version identifier for this version name.
315     uint16_t Index;
316   };
317 
318   // Mapping from Elf_Verdef data structures to information about Elf_Vernaux
319   // data structures in the output file.
320   std::map<const Elf_Verdef *, NeededVer> VerdefMap;
321 
322   // Used for --as-needed
323   bool AsNeeded = false;
324   bool IsUsed = false;
325   bool isNeeded() const { return !AsNeeded || IsUsed; }
326 };
327 
328 class BinaryFile : public InputFile {
329 public:
330   explicit BinaryFile(MemoryBufferRef M) : InputFile(BinaryKind, M) {}
331   static bool classof(const InputFile *F) { return F->kind() == BinaryKind; }
332   template <class ELFT> void parse();
333 };
334 
335 InputFile *createObjectFile(MemoryBufferRef MB, StringRef ArchiveName = "",
336                             uint64_t OffsetInArchive = 0);
337 InputFile *createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName);
338 
339 extern std::vector<BinaryFile *> BinaryFiles;
340 extern std::vector<BitcodeFile *> BitcodeFiles;
341 extern std::vector<InputFile *> ObjectFiles;
342 extern std::vector<InputFile *> SharedFiles;
343 
344 } // namespace elf
345 } // namespace lld
346 
347 #endif
348