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