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 // Check if a non-common symbol should be extracted to override a common
119 // definition.
120 bool shouldExtractForCommon(StringRef name) const;
121
122 // .got2 in the current file. This is used by PPC32 -fPIC/-fPIE to compute
123 // offsets in PLT call stubs.
124 InputSection *ppc32Got2 = nullptr;
125
126 // Index of MIPS GOT built for this file.
127 uint32_t mipsGotIndex = -1;
128
129 // groupId is used for --warn-backrefs which is an optional error
130 // checking feature. All files within the same --{start,end}-group or
131 // --{start,end}-lib get the same group ID. Otherwise, each file gets a new
132 // group ID. For more info, see checkDependency() in SymbolTable.cpp.
133 uint32_t groupId;
134
135 // If this is an architecture-specific file, the following members
136 // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type.
137 uint16_t emachine = llvm::ELF::EM_NONE;
138 const Kind fileKind;
139 ELFKind ekind = ELFNoneKind;
140 uint8_t osabi = 0;
141 uint8_t abiVersion = 0;
142
143 // True if this is a relocatable object file/bitcode file in an ar archive
144 // or between --start-lib and --end-lib.
145 bool lazy = false;
146
147 // True if this is an argument for --just-symbols. Usually false.
148 bool justSymbols = false;
149
150 // On PPC64 we need to keep track of which files contain small code model
151 // relocations that access the .toc section. To minimize the chance of a
152 // relocation overflow, files that do contain said relocations should have
153 // their .toc sections sorted closer to the .got section than files that do
154 // not contain any small code model relocations. Thats because the toc-pointer
155 // is defined to point at .got + 0x8000 and the instructions used with small
156 // code model relocations support immediates in the range [-0x8000, 0x7FFC],
157 // making the addressable range relative to the toc pointer
158 // [.got, .got + 0xFFFC].
159 bool ppc64SmallCodeModelTocRelocs = false;
160
161public:
162 // If not empty, this stores the name of the archive containing this file.
163 // We use this string for creating error messages.
164 SmallString<0> archiveName;
165 // Cache for toStr(Ctx &, const InputFile *). Only toStr should use this
166 // member.
167 mutable SmallString<0> toStringCache;
168
169private:
170 // Cache for getNameForScript().
171 mutable SmallString<0> nameForScriptCache;
172};
173
174class ELFFileBase : public InputFile {
175public:
176 ELFFileBase(Ctx &ctx, Kind k, ELFKind ekind, MemoryBufferRef m);
177 ~ELFFileBase();
178 static bool classof(const InputFile *f) { return f->isElf(); }
179
180 void init();
181 template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const {
182 return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer()));
183 }
184
185 StringRef getStringTable() const { return stringTable; }
186
187 ArrayRef<Symbol *> getLocalSymbols() {
188 if (numSymbols == 0)
189 return {};
190 return llvm::ArrayRef(symbols.get() + 1, firstGlobal - 1);
191 }
192 ArrayRef<Symbol *> getGlobalSymbols() {
193 return llvm::ArrayRef(symbols.get() + firstGlobal,
194 numSymbols - firstGlobal);
195 }
196 MutableArrayRef<Symbol *> getMutableGlobalSymbols() {
197 return llvm::MutableArrayRef(symbols.get() + firstGlobal,
198 numSymbols - firstGlobal);
199 }
200
201 template <typename ELFT> typename ELFT::ShdrRange getELFShdrs() const {
202 return typename ELFT::ShdrRange(
203 reinterpret_cast<const typename ELFT::Shdr *>(elfShdrs), numELFShdrs);
204 }
205 template <typename ELFT> typename ELFT::SymRange getELFSyms() const {
206 return typename ELFT::SymRange(
207 reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numSymbols);
208 }
209 template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const {
210 return getELFSyms<ELFT>().slice(firstGlobal);
211 }
212
213 // Get cached DWARF information.
214 DWARFCache *getDwarf();
215
216protected:
217 // Initializes this class's member variables.
218 template <typename ELFT> void init(InputFile::Kind k);
219
220 StringRef stringTable;
221 const void *elfShdrs = nullptr;
222 const void *elfSyms = nullptr;
223 uint32_t numELFShdrs = 0;
224 uint32_t firstGlobal = 0;
225
226 // Below are ObjFile specific members.
227
228 // Debugging information to retrieve source file and line for error
229 // reporting. Linker may find reasonable number of errors in a
230 // single object file, so we cache debugging information in order to
231 // parse it only once for each object file we link.
232 llvm::once_flag initDwarf;
233 std::unique_ptr<DWARFCache> dwarf;
234
235public:
236 // Name of source file obtained from STT_FILE, if present.
237 StringRef sourceFile;
238 uint32_t andFeatures = 0;
239 bool hasCommonSyms = false;
240 std::optional<AArch64PauthAbiCoreInfo> aarch64PauthAbiCoreInfo;
241};
242
243// .o file.
244template <class ELFT> class ObjFile : public ELFFileBase {
245 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
246
247public:
248 static bool classof(const InputFile *f) { return f->kind() == ObjKind; }
249
250 llvm::object::ELFFile<ELFT> getObj() const {
251 return this->ELFFileBase::getObj<ELFT>();
252 }
253
254 ObjFile(Ctx &ctx, ELFKind ekind, MemoryBufferRef m, StringRef archiveName)
255 : ELFFileBase(ctx, ObjKind, ekind, m) {
256 this->archiveName = archiveName;
257 }
258
259 void parse(bool ignoreComdats = false);
260 void parseLazy();
261
262 StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
263 const Elf_Shdr &sec);
264
265 uint32_t getSectionIndex(const Elf_Sym &sym) const;
266
267
268 // Pointer to this input file's .llvm_addrsig section, if it has one.
269 const Elf_Shdr *addrsigSec = nullptr;
270
271 // SHT_LLVM_CALL_GRAPH_PROFILE section index.
272 uint32_t cgProfileSectionIndex = 0;
273
274 // MIPS GP0 value defined by this file. This value represents the gp value
275 // used to create the relocatable object and required to support
276 // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations.
277 uint32_t mipsGp0 = 0;
278
279 // True if the file defines functions compiled with
280 // -fsplit-stack. Usually false.
281 bool splitStack = false;
282
283 // True if the file defines functions compiled with -fsplit-stack,
284 // but had one or more functions with the no_split_stack attribute.
285 bool someNoSplitStack = false;
286
287 void initDwarf();
288
289 void initSectionsAndLocalSyms(bool ignoreComdats);
290 void postParse();
291 void importCmseSymbols();
292
293private:
294 void initializeSections(bool ignoreComdats,
295 const llvm::object::ELFFile<ELFT> &obj);
296 void initializeSymbols(const llvm::object::ELFFile<ELFT> &obj);
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
320class BitcodeFile : public InputFile {
321public:
322 BitcodeFile(Ctx &, 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.
333class SharedFile : public ELFFileBase {
334public:
335 SharedFile(Ctx &, MemoryBufferRef m, StringRef defaultSoName);
336
337 // This is actually a vector of Elf_Verdef pointers.
338 SmallVector<const void *, 0> verdefs;
339
340 // Parallel to verdefs. If a version definition is referenced by a relocatable
341 // file, the entry records the assigned Vernaux index in the output file and
342 // whether all references are weak.
343 struct VerneedInfo {
344 uint16_t id = 0;
345 // True if all references to this version are weak. Used to set
346 // VER_FLG_WEAK.
347 bool weak = true;
348 };
349 SmallVector<VerneedInfo, 0> verneedInfo;
350
351 SmallVector<StringRef, 0> dtNeeded;
352 StringRef soName;
353
354 static bool classof(const InputFile *f) { return f->kind() == SharedKind; }
355
356 template <typename ELFT> void parse();
357
358 // Used for --as-needed
359 bool isNeeded;
360
361 // Non-weak undefined symbols which are not yet resolved when the SO is
362 // parsed. Only filled for `--no-allow-shlib-undefined`.
363 SmallVector<Symbol *, 0> requiredSymbols;
364
365private:
366 template <typename ELFT>
367 std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj,
368 const typename ELFT::Shdr *sec);
369 template <typename ELFT>
370 void parseGnuAndFeatures(const llvm::object::ELFFile<ELFT> &obj);
371};
372
373class BinaryFile : public InputFile {
374public:
375 explicit BinaryFile(Ctx &ctx, MemoryBufferRef m)
376 : InputFile(ctx, BinaryKind, m) {}
377 static bool classof(const InputFile *f) { return f->kind() == BinaryKind; }
378 void parse();
379};
380
381InputFile *createInternalFile(Ctx &, StringRef name);
382std::unique_ptr<ELFFileBase> createObjFile(Ctx &, MemoryBufferRef mb,
383 StringRef archiveName = "",
384 bool lazy = false);
385
386std::string replaceThinLTOSuffix(Ctx &, StringRef path);
387
388} // namespace elf
389} // namespace lld
390
391#endif
392