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 "lld/Common/ErrorHandler.h" 14 #include "lld/Common/LLVM.h" 15 #include "lld/Common/Reproduce.h" 16 #include "llvm/ADT/CachedHashString.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/IR/Comdat.h" 20 #include "llvm/Object/Archive.h" 21 #include "llvm/Object/ELF.h" 22 #include "llvm/Object/IRObjectFile.h" 23 #include "llvm/Support/Threading.h" 24 #include <map> 25 26 namespace llvm { 27 struct DILineInfo; 28 class TarWriter; 29 namespace lto { 30 class InputFile; 31 } 32 } // namespace llvm 33 34 namespace lld { 35 class DWARFCache; 36 37 // Returns "<internal>", "foo.a(bar.o)" or "baz.o". 38 std::string toString(const elf::InputFile *f); 39 40 namespace elf { 41 42 using llvm::object::Archive; 43 44 class Symbol; 45 46 // If --reproduce is specified, all input files are written to this tar archive. 47 extern std::unique_ptr<llvm::TarWriter> tar; 48 49 // Opens a given file. 50 llvm::Optional<MemoryBufferRef> readFile(StringRef path); 51 52 // Add symbols in File to the symbol table. 53 void parseFile(InputFile *file); 54 55 // The root class of input files. 56 class InputFile { 57 public: 58 enum Kind { 59 ObjKind, 60 SharedKind, 61 LazyObjKind, 62 ArchiveKind, 63 BitcodeKind, 64 BinaryKind, 65 }; 66 67 Kind kind() const { return fileKind; } 68 69 bool isElf() const { 70 Kind k = kind(); 71 return k == ObjKind || k == SharedKind; 72 } 73 74 StringRef getName() const { return mb.getBufferIdentifier(); } 75 MemoryBufferRef mb; 76 77 // Returns sections. It is a runtime error to call this function 78 // on files that don't have the notion of sections. 79 ArrayRef<InputSectionBase *> getSections() const { 80 assert(fileKind == ObjKind || fileKind == BinaryKind); 81 return sections; 82 } 83 84 // Returns object file symbols. It is a runtime error to call this 85 // function on files of other types. 86 ArrayRef<Symbol *> getSymbols() { return getMutableSymbols(); } 87 88 MutableArrayRef<Symbol *> getMutableSymbols() { 89 assert(fileKind == BinaryKind || fileKind == ObjKind || 90 fileKind == BitcodeKind); 91 return symbols; 92 } 93 94 // Get filename to use for linker script processing. 95 StringRef getNameForScript() const; 96 97 // If not empty, this stores the name of the archive containing this file. 98 // We use this string for creating error messages. 99 std::string archiveName; 100 101 // If this is an architecture-specific file, the following members 102 // have ELF type (i.e. ELF{32,64}{LE,BE}) and target machine type. 103 ELFKind ekind = ELFNoneKind; 104 uint16_t emachine = llvm::ELF::EM_NONE; 105 uint8_t osabi = 0; 106 uint8_t abiVersion = 0; 107 108 // Cache for toString(). Only toString() should use this member. 109 mutable std::string toStringCache; 110 111 std::string getSrcMsg(const Symbol &sym, InputSectionBase &sec, 112 uint64_t offset); 113 114 // True if this is an argument for --just-symbols. Usually false. 115 bool justSymbols = false; 116 117 // outSecOff of .got2 in the current file. This is used by PPC32 -fPIC/-fPIE 118 // to compute offsets in PLT call stubs. 119 uint32_t ppc32Got2OutSecOff = 0; 120 121 // On PPC64 we need to keep track of which files contain small code model 122 // relocations that access the .toc section. To minimize the chance of a 123 // relocation overflow, files that do contain said relocations should have 124 // their .toc sections sorted closer to the .got section than files that do 125 // not contain any small code model relocations. Thats because the toc-pointer 126 // is defined to point at .got + 0x8000 and the instructions used with small 127 // code model relocations support immediates in the range [-0x8000, 0x7FFC], 128 // making the addressable range relative to the toc pointer 129 // [.got, .got + 0xFFFC]. 130 bool ppc64SmallCodeModelTocRelocs = false; 131 132 // True if the file has TLSGD/TLSLD GOT relocations without R_PPC64_TLSGD or 133 // R_PPC64_TLSLD. Disable TLS relaxation to avoid bad code generation. 134 bool ppc64DisableTLSRelax = false; 135 136 // groupId is used for --warn-backrefs which is an optional error 137 // checking feature. All files within the same --{start,end}-group or 138 // --{start,end}-lib get the same group ID. Otherwise, each file gets a new 139 // group ID. For more info, see checkDependency() in SymbolTable.cpp. 140 uint32_t groupId; 141 static bool isInGroup; 142 static uint32_t nextGroupId; 143 144 // Index of MIPS GOT built for this file. 145 llvm::Optional<size_t> mipsGotIndex; 146 147 std::vector<Symbol *> symbols; 148 149 protected: 150 InputFile(Kind k, MemoryBufferRef m); 151 std::vector<InputSectionBase *> sections; 152 153 private: 154 const Kind fileKind; 155 156 // Cache for getNameForScript(). 157 mutable std::string nameForScriptCache; 158 }; 159 160 class ELFFileBase : public InputFile { 161 public: 162 ELFFileBase(Kind k, MemoryBufferRef m); 163 static bool classof(const InputFile *f) { return f->isElf(); } 164 165 template <typename ELFT> llvm::object::ELFFile<ELFT> getObj() const { 166 return check(llvm::object::ELFFile<ELFT>::create(mb.getBuffer())); 167 } 168 169 StringRef getStringTable() const { return stringTable; } 170 171 ArrayRef<Symbol *> getLocalSymbols() { 172 if (symbols.empty()) 173 return {}; 174 return llvm::makeArrayRef(symbols).slice(1, firstGlobal - 1); 175 } 176 ArrayRef<Symbol *> getGlobalSymbols() { 177 return llvm::makeArrayRef(symbols).slice(firstGlobal); 178 } 179 180 template <typename ELFT> typename ELFT::SymRange getELFSyms() const { 181 return typename ELFT::SymRange( 182 reinterpret_cast<const typename ELFT::Sym *>(elfSyms), numELFSyms); 183 } 184 template <typename ELFT> typename ELFT::SymRange getGlobalELFSyms() const { 185 return getELFSyms<ELFT>().slice(firstGlobal); 186 } 187 188 protected: 189 // Initializes this class's member variables. 190 template <typename ELFT> void init(); 191 192 const void *elfSyms = nullptr; 193 size_t numELFSyms = 0; 194 uint32_t firstGlobal = 0; 195 StringRef stringTable; 196 }; 197 198 // .o file. 199 template <class ELFT> class ObjFile : public ELFFileBase { 200 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 201 202 public: 203 static bool classof(const InputFile *f) { return f->kind() == ObjKind; } 204 205 llvm::object::ELFFile<ELFT> getObj() const { 206 return this->ELFFileBase::getObj<ELFT>(); 207 } 208 209 ObjFile(MemoryBufferRef m, StringRef archiveName) : ELFFileBase(ObjKind, m) { 210 this->archiveName = std::string(archiveName); 211 } 212 213 void parse(bool ignoreComdats = false); 214 215 StringRef getShtGroupSignature(ArrayRef<Elf_Shdr> sections, 216 const Elf_Shdr &sec); 217 218 Symbol &getSymbol(uint32_t symbolIndex) const { 219 if (symbolIndex >= this->symbols.size()) 220 fatal(toString(this) + ": invalid symbol index"); 221 return *this->symbols[symbolIndex]; 222 } 223 224 uint32_t getSectionIndex(const Elf_Sym &sym) const; 225 226 template <typename RelT> Symbol &getRelocTargetSym(const RelT &rel) const { 227 uint32_t symIndex = rel.getSymbol(config->isMips64EL); 228 return getSymbol(symIndex); 229 } 230 231 llvm::Optional<llvm::DILineInfo> getDILineInfo(InputSectionBase *, uint64_t); 232 llvm::Optional<std::pair<std::string, unsigned>> getVariableLoc(StringRef name); 233 234 // MIPS GP0 value defined by this file. This value represents the gp value 235 // used to create the relocatable object and required to support 236 // R_MIPS_GPREL16 / R_MIPS_GPREL32 relocations. 237 uint32_t mipsGp0 = 0; 238 239 uint32_t andFeatures = 0; 240 241 // Name of source file obtained from STT_FILE symbol value, 242 // or empty string if there is no such symbol in object file 243 // symbol table. 244 StringRef sourceFile; 245 246 // True if the file defines functions compiled with 247 // -fsplit-stack. Usually false. 248 bool splitStack = false; 249 250 // True if the file defines functions compiled with -fsplit-stack, 251 // but had one or more functions with the no_split_stack attribute. 252 bool someNoSplitStack = false; 253 254 // Pointer to this input file's .llvm_addrsig section, if it has one. 255 const Elf_Shdr *addrsigSec = nullptr; 256 257 // SHT_LLVM_CALL_GRAPH_PROFILE section index. 258 uint32_t cgProfileSectionIndex = 0; 259 260 // Get cached DWARF information. 261 DWARFCache *getDwarf(); 262 263 private: 264 void initializeSections(bool ignoreComdats); 265 void initializeSymbols(); 266 void initializeJustSymbols(); 267 268 InputSectionBase *getRelocTarget(uint32_t idx, StringRef name, 269 const Elf_Shdr &sec); 270 InputSectionBase *createInputSection(uint32_t idx, const Elf_Shdr &sec, 271 StringRef shstrtab); 272 273 bool shouldMerge(const Elf_Shdr &sec, StringRef name); 274 275 // Each ELF symbol contains a section index which the symbol belongs to. 276 // However, because the number of bits dedicated for that is limited, a 277 // symbol can directly point to a section only when the section index is 278 // equal to or smaller than 65280. 279 // 280 // If an object file contains more than 65280 sections, the file must 281 // contain .symtab_shndx section. The section contains an array of 282 // 32-bit integers whose size is the same as the number of symbols. 283 // Nth symbol's section index is in the Nth entry of .symtab_shndx. 284 // 285 // The following variable contains the contents of .symtab_shndx. 286 // If the section does not exist (which is common), the array is empty. 287 ArrayRef<Elf_Word> shndxTable; 288 289 // Debugging information to retrieve source file and line for error 290 // reporting. Linker may find reasonable number of errors in a 291 // single object file, so we cache debugging information in order to 292 // parse it only once for each object file we link. 293 std::unique_ptr<DWARFCache> dwarf; 294 llvm::once_flag initDwarf; 295 }; 296 297 // LazyObjFile is analogous to ArchiveFile in the sense that 298 // the file contains lazy symbols. The difference is that 299 // LazyObjFile wraps a single file instead of multiple files. 300 // 301 // This class is used for --start-lib and --end-lib options which 302 // instruct the linker to link object files between them with the 303 // archive file semantics. 304 class LazyObjFile : public InputFile { 305 public: 306 LazyObjFile(MemoryBufferRef m, StringRef archiveName, 307 uint64_t offsetInArchive) 308 : InputFile(LazyObjKind, m), offsetInArchive(offsetInArchive) { 309 this->archiveName = std::string(archiveName); 310 } 311 312 static bool classof(const InputFile *f) { return f->kind() == LazyObjKind; } 313 314 template <class ELFT> void parse(); 315 void extract(); 316 317 // Check if a non-common symbol should be extracted to override a common 318 // definition. 319 bool shouldExtractForCommon(const StringRef &name); 320 321 bool extracted = false; 322 323 private: 324 uint64_t offsetInArchive; 325 }; 326 327 // An ArchiveFile object represents a .a file. 328 class ArchiveFile : public InputFile { 329 public: 330 explicit ArchiveFile(std::unique_ptr<Archive> &&file); 331 static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; } 332 void parse(); 333 334 // Pulls out an object file that contains a definition for Sym and 335 // returns it. If the same file was instantiated before, this 336 // function does nothing (so we don't instantiate the same file 337 // more than once.) 338 void extract(const Archive::Symbol &sym); 339 340 // Check if a non-common symbol should be extracted to override a common 341 // definition. 342 bool shouldExtractForCommon(const Archive::Symbol &sym); 343 344 size_t getMemberCount() const; 345 size_t getExtractedMemberCount() const { return seen.size(); } 346 347 bool parsed = false; 348 349 private: 350 std::unique_ptr<Archive> file; 351 llvm::DenseSet<uint64_t> seen; 352 }; 353 354 class BitcodeFile : public InputFile { 355 public: 356 BitcodeFile(MemoryBufferRef m, StringRef archiveName, 357 uint64_t offsetInArchive); 358 static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; } 359 template <class ELFT> void parse(); 360 std::unique_ptr<llvm::lto::InputFile> obj; 361 }; 362 363 // .so file. 364 class SharedFile : public ELFFileBase { 365 public: 366 SharedFile(MemoryBufferRef m, StringRef defaultSoName) 367 : ELFFileBase(SharedKind, m), soName(defaultSoName), 368 isNeeded(!config->asNeeded) {} 369 370 // This is actually a vector of Elf_Verdef pointers. 371 std::vector<const void *> verdefs; 372 373 // If the output file needs Elf_Verneed data structures for this file, this is 374 // a vector of Elf_Vernaux version identifiers that map onto the entries in 375 // Verdefs, otherwise it is empty. 376 std::vector<unsigned> vernauxs; 377 378 static unsigned vernauxNum; 379 380 std::vector<StringRef> dtNeeded; 381 StringRef soName; 382 383 static bool classof(const InputFile *f) { return f->kind() == SharedKind; } 384 385 template <typename ELFT> void parse(); 386 387 // Used for --as-needed 388 bool isNeeded; 389 390 // Non-weak undefined symbols which are not yet resolved when the SO is 391 // parsed. Only filled for `--no-allow-shlib-undefined`. 392 std::vector<Symbol *> requiredSymbols; 393 394 private: 395 template <typename ELFT> 396 std::vector<uint32_t> parseVerneed(const llvm::object::ELFFile<ELFT> &obj, 397 const typename ELFT::Shdr *sec); 398 }; 399 400 class BinaryFile : public InputFile { 401 public: 402 explicit BinaryFile(MemoryBufferRef m) : InputFile(BinaryKind, m) {} 403 static bool classof(const InputFile *f) { return f->kind() == BinaryKind; } 404 void parse(); 405 }; 406 407 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName = "", 408 uint64_t offsetInArchive = 0); 409 410 inline bool isBitcode(MemoryBufferRef mb) { 411 return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode; 412 } 413 414 std::string replaceThinLTOSuffix(StringRef path); 415 416 extern std::vector<ArchiveFile *> archiveFiles; 417 extern std::vector<BinaryFile *> binaryFiles; 418 extern std::vector<BitcodeFile *> bitcodeFiles; 419 extern std::vector<LazyObjFile *> lazyObjFiles; 420 extern std::vector<InputFile *> objectFiles; 421 extern std::vector<SharedFile *> sharedFiles; 422 423 } // namespace elf 424 } // namespace lld 425 426 #endif 427