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#include <atomic>
23
24namespace llvm {
25struct DILineInfo;
26class TarWriter;
27namespace lto {
28class InputFile;
29}
30} // namespace llvm
31
32namespace lld {
33class DWARFCache;
34
35namespace elf {
36class InputSection;
37class Symbol;
38
39// Returns "<internal>", "foo.a(bar.o)" or "baz.o".
40std::string toStr(Ctx &, const InputFile *f);
41const ELFSyncStream &operator<<(const ELFSyncStream &, const InputFile *);
42
43// Opens a given file.
44std::optional<MemoryBufferRef> readFile(Ctx &, StringRef path);
45
46// Add symbols in File to the symbol table.
47void parseFile(Ctx &, InputFile *file);
48void parseFiles(Ctx &, const SmallVector<std::unique_ptr<InputFile>, 0> &);
49
50// The root class of input files.
51class InputFile {
52public:
53 Ctx &ctx;
54
55protected:
56 std::unique_ptr<Symbol *[]> symbols;
57 size_t numSymbols = 0;
58 SmallVector<InputSectionBase *, 0> sections;
59
60public:
61 enum Kind : uint8_t {
62 ObjKind,
63 SharedKind,
64 BitcodeKind,
65 BinaryKind,
66 InternalKind,
67 };
68
69 InputFile(Ctx &, Kind k, MemoryBufferRef m);
70 virtual ~InputFile();
71 Kind kind() const { return fileKind; }
72
73 bool isElf() const {
74 Kind k = kind();
75 return k == ObjKind || k == SharedKind;
76 }
77 bool isInternal() const { return kind() == InternalKind; }
78
79 StringRef getName() const { return mb.getBufferIdentifier(); }
80 MemoryBufferRef mb;
81
82 // Returns sections. It is a runtime error to call this function
83 // on files that don't have the notion of sections.
84 ArrayRef<InputSectionBase *> getSections() const {
85 assert(fileKind == ObjKind || fileKind == BinaryKind);
86 return sections;
87 }
88 void cacheDecodedCrel(size_t i, InputSectionBase *s) { sections[i] = s; }
89
90 // Returns object file symbols. It is a runtime error to call this
91 // function on files of other types.
92 ArrayRef<Symbol *> getSymbols() const {
93 assert(fileKind == BinaryKind || fileKind == ObjKind ||
94 fileKind == BitcodeKind);
95 return {symbols.get(), numSymbols};
96 }
97
98 MutableArrayRef<Symbol *> getMutableSymbols() {
99 assert(fileKind == BinaryKind || fileKind == ObjKind ||
100 fileKind == BitcodeKind);
101 return {symbols.get(), numSymbols};
102 }
103
104 Symbol &getSymbol(uint32_t symbolIndex) const {
105 assert(fileKind == ObjKind);
106 if (symbolIndex >= numSymbols)
107 Fatal(ctx) << this << ": invalid symbol index";
108 return *this->symbols[symbolIndex];
109 }
110
111 template <typename RelT> Symbol &getRelocTargetSym(const RelT &rel) const {
112 uint32_t symIndex = rel.getSymbol(ctx.arg.isMips64EL);
113 return getSymbol(symbolIndex: symIndex);
114 }
115
116 // Get filename to use for linker script processing.
117 StringRef getNameForScript() const;
118
119 // .got2 in the current file. This is used by PPC32 -fPIC/-fPIE to compute
120 // offsets in PLT call stubs.
121 InputSection *ppc32Got2 = nullptr;
122
123 // Index of MIPS GOT built for this file.
124 uint32_t mipsGotIndex = -1;
125
126 // groupId is used for --warn-backrefs which is an optional error
127 // checking feature. All files within the same --{start,end}-group or
128 // --{start,end}-lib get the same group ID. Otherwise, each file gets a new
129 // group ID. For more info, see checkDependency() in SymbolTable.cpp.
130 uint32_t groupId = 0;
131
132 // If this is an architecture-specific file, the following members
133 // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
134 uint16_t emachine = llvm::ELF::EM_NONE;
135 const Kind fileKind;
136 ELFKind ekind = ELFNoneKind;
137 uint8_t osabi = 0;
138 uint8_t abiVersion = 0;
139
140 // True if this is a relocatable object file/bitcode file in an ar archive
141 // or between --start-lib and --end-lib.
142 bool lazy = false;
143
144 // True if this is an argument for --just-symbols. Usually false.
145 bool justSymbols = false;
146
147 // On PPC64 we need to keep track of which files contain small code model
148 // relocations that access the .toc section. To minimize the chance of a
149 // relocation overflow, files that do contain said relocations should have
150 // their .toc sections sorted closer to the .got section than files that do
151 // not contain any small code model relocations. Thats because the toc-pointer
152 // is defined to point at .got + 0x8000 and the instructions used with small
153 // code model relocations support immediates in the range [-0x8000, 0x7FFC],
154 // making the addressable range relative to the toc pointer
155 // [.got, .got + 0xFFFC].
156 bool ppc64SmallCodeModelTocRelocs = false;
157
158public:
159 // If not empty, this stores the name of the archive containing this file.
160 // We use this string for creating error messages.
161 SmallString<0> archiveName;
162 // Cache for toStr(Ctx &, const InputFile *). Only toStr should use this
163 // member.
164 mutable SmallString<0> toStringCache;
165
166private:
167 // Cache for getNameForScript().
168 mutable SmallString<0> nameForScriptCache;
169};
170
171class ELFFileBase : public InputFile {
172public:
173 ELFFileBase(Ctx &ctx, Kind k, ELFKind ekind, MemoryBufferRef m);
174 ~ELFFileBase();
175 static bool classof(const InputFile *f) { return f->isElf(); }
176
177 void init();
178 template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const {
179 return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer()));
180 }
181
182 StringRef getStringTable() const { return stringTable; }
183
184 ArrayRef<Symbol *> getLocalSymbols() {
185 if (numSymbols == 0)
186 return {};
187 return llvm::ArrayRef(symbols.get() + 1, firstGlobal - 1);
188 }
189 ArrayRef<Symbol *> getGlobalSymbols() {
190 return llvm::ArrayRef(symbols.get() + firstGlobal,
191 numSymbols - firstGlobal);
192 }
193 MutableArrayRef<Symbol *> getMutableGlobalSymbols() {
194 return llvm::MutableArrayRef(symbols.get() + firstGlobal,
195 numSymbols - firstGlobal);
196 }
197
198 template <typename ELFT> typename ELFT::ShdrRange getELFShdrs() const {
199 return typename ELFT::ShdrRange(
200 reinterpret_cast<const typename ELFT::Shdr *>(elfShdrs), numELFShdrs);
201 }
202 template <typename ELFT> typename ELFT::SymRange getELFSyms() const {
203 return typename ELFT::SymRange(
204 reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numSymbols);
205 }
206 template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const {
207 return getELFSyms<ELFT>().slice(firstGlobal);
208 }
209
210 // Get cached DWARF information.
211 DWARFCache *getDwarf();
212
213protected:
214 // Initializes this class's member variables.
215 template <typename ELFT> void init(InputFile::Kind k);
216
217 StringRef stringTable;
218 const void *elfShdrs = nullptr;
219 const void *elfSyms = nullptr;
220 uint32_t numELFShdrs = 0;
221 uint32_t firstGlobal = 0;
222
223 // Below are ObjFile specific members.
224
225 // Debugging information to retrieve source file and line for error
226 // reporting. Linker may find reasonable number of errors in a
227 // single object file, so we cache debugging information in order to
228 // parse it only once for each object file we link.
229 llvm::once_flag initDwarf;
230 std::unique_ptr<DWARFCache> dwarf;
231
232public:
233 // Name of source file obtained from STT_FILE, if present.
234 StringRef sourceFile;
235 uint32_t andFeatures = 0;
236 bool hasCommonSyms = false;
237 std::optional<AArch64PauthAbiCoreInfo> aarch64PauthAbiCoreInfo;
238};
239
240// .o file.
241template <class ELFT> class ObjFile : public ELFFileBase {
242 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
243
244public:
245 static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
246
247 llvm::object::ELFFile<ELFT> getObj() const {
248 return this->ELFFileBase::getObj<ELFT>();
249 }
250
251 ObjFile(Ctx &ctx, ELFKind ekind, MemoryBufferRef m, StringRef archiveName)
252 : ELFFileBase(ctx, ObjKind, ekind, m) {
253 this->archiveName = archiveName;
254 }
255
256 void parse(bool ignoreComdats = false);
257 void parseLazy();
258
259 // Intern global symbol names on a worker thread and then set `interned`.
260 void internSymbols();
261 std::atomic<bool> interned = false;
262
263 StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
264 const Elf_Shdr &sec);
265
266 uint32_t getSectionIndex(const Elf_Sym &sym) const;
267
268
269 // Pointer to this input file's .llvm_addrsig section, if it has one.
270 const Elf_Shdr *addrsigSec = nullptr;
271
272 // Embedded unoptimized dynamic debug input section.
273 std::unique_ptr<InputSection> dynDbgSec;
274
275 // SHT_LLVM_CALL_GRAPH_PROFILE section index.
276 uint32_t cgProfileSectionIndex = 0;
277
278 // MIPS GP0 value defined by this file. This value represents the gp value
279 // used to create the relocatable object and required to support
280 // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations.
281 uint32_t mipsGp0 = 0;
282
283 // True if the file defines functions compiled with
284 // -fsplit-stack. Usually false.
285 bool splitStack = false;
286
287 // True if the file defines functions compiled with -fsplit-stack,
288 // but had one or more functions with the no_split_stack attribute.
289 bool someNoSplitStack = false;
290
291 void initDwarf();
292
293 void initSectionsAndLocalSyms();
294 void postParse();
295 void importCmseSymbols();
296
297private:
298 void initializeSections(const llvm::object::ELFFile<ELFT> &obj);
299 Symbol *insertGlobal(size_t i);
300 void initializeSymbols(const llvm::object::ELFFile<ELFT> &obj);
301 void initDynDbgSymbols();
302 void initializeJustSymbols();
303
304 InputSectionBase *getRelocTarget(uint32_t idx, uint32_t info);
305 InputSectionBase *createInputSection(uint32_t idx, const Elf_Shdr &sec,
306 StringRef name);
307
308 bool shouldMerge(const Elf_Shdr &sec, StringRef name);
309
310 // Each ELF symbol contains a section index which the symbol belongs to.
311 // However, because the number of bits dedicated for that is limited, a
312 // symbol can directly point to a section only when the section index is
313 // equal to or smaller than 65280.
314 //
315 // If an object file contains more than 65280 sections, the file must
316 // contain .symtab_shndx section. The section contains an array of
317 // 32-bit integers whose size is the same as the number of symbols.
318 // Nth symbol's section index is in the Nth entry of .symtab_shndx.
319 //
320 // The following variable contains the contents of .symtab_shndx.
321 // If the section does not exist (which is common), the array is empty.
322 ArrayRef<Elf_Word> shndxTable;
323
324 // Section indices of kept SHT_GROUP sections, recorded by parse() in
325 // ascending order, to be used by the parallel initializeSections().
326 SmallVector<uint32_t, 0> keptGroups;
327};
328
329class BitcodeFile : public InputFile {
330public:
331 BitcodeFile(Ctx &, 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.
342class SharedFile : public ELFFileBase {
343public:
344 SharedFile(Ctx &, MemoryBufferRef m, StringRef defaultSoName);
345
346 // This is actually a vector of Elf_Verdef pointers.
347 SmallVector<const void *, 0> verdefs;
348
349 // Parallel to verdefs. If a version definition is referenced by a relocatable
350 // file, the entry records the assigned Vernaux index in the output file and
351 // whether all references are weak.
352 struct VerneedInfo {
353 uint16_t id = 0;
354 // True if all references to this version are weak. Used to set
355 // VER_FLG_WEAK.
356 bool weak = true;
357 };
358 SmallVector<VerneedInfo, 0> verneedInfo;
359
360 SmallVector<StringRef, 0> dtNeeded;
361 StringRef soName;
362
363 static bool classof(const InputFile *f) { return f->kind() == SharedKind; }
364
365 template <typename ELFT> void parse();
366
367 // Used for --as-needed
368 std::atomic<bool> isNeeded;
369
370 // Non-weak undefined symbols which are not yet resolved when the SO is
371 // parsed. Only filled for `--no-allow-shlib-undefined`.
372 SmallVector<Symbol *, 0> requiredSymbols;
373
374private:
375 template <typename ELFT>
376 std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj,
377 const typename ELFT::Shdr *sec);
378 template <typename ELFT>
379 void parseGnuAndFeatures(const llvm::object::ELFFile<ELFT> &obj);
380};
381
382class BinaryFile : public InputFile {
383public:
384 explicit BinaryFile(Ctx &ctx, MemoryBufferRef m)
385 : InputFile(ctx, BinaryKind, m) {}
386 static bool classof(const InputFile *f) { return f->kind() == BinaryKind; }
387 void parse();
388};
389
390InputFile *createInternalFile(Ctx &, StringRef name);
391std::unique_ptr<ELFFileBase> createObjFile(Ctx &, MemoryBufferRef mb,
392 StringRef archiveName = "",
393 bool lazy = false);
394
395std::string replaceThinLTOSuffix(Ctx &, StringRef path);
396
397// Name of embedded unoptimized dynamic debug input/output section.
398constexpr StringRef dynDbgSecName = ".debug_llvm_dyndbg";
399} // namespace elf
400} // namespace lld
401
402#endif
403