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