150
|
1 //===- InputFiles.cpp -----------------------------------------------------===//
|
|
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 #include "InputFiles.h"
|
|
10 #include "Driver.h"
|
|
11 #include "InputSection.h"
|
|
12 #include "LinkerScript.h"
|
|
13 #include "SymbolTable.h"
|
|
14 #include "Symbols.h"
|
|
15 #include "SyntheticSections.h"
|
|
16 #include "lld/Common/DWARF.h"
|
|
17 #include "lld/Common/ErrorHandler.h"
|
|
18 #include "lld/Common/Memory.h"
|
|
19 #include "llvm/ADT/STLExtras.h"
|
|
20 #include "llvm/CodeGen/Analysis.h"
|
|
21 #include "llvm/IR/LLVMContext.h"
|
|
22 #include "llvm/IR/Module.h"
|
|
23 #include "llvm/LTO/LTO.h"
|
|
24 #include "llvm/MC/StringTableBuilder.h"
|
|
25 #include "llvm/Object/ELFObjectFile.h"
|
|
26 #include "llvm/Support/ARMAttributeParser.h"
|
|
27 #include "llvm/Support/ARMBuildAttributes.h"
|
|
28 #include "llvm/Support/Endian.h"
|
|
29 #include "llvm/Support/Path.h"
|
|
30 #include "llvm/Support/TarWriter.h"
|
|
31 #include "llvm/Support/raw_ostream.h"
|
|
32
|
|
33 using namespace llvm;
|
|
34 using namespace llvm::ELF;
|
|
35 using namespace llvm::object;
|
|
36 using namespace llvm::sys;
|
|
37 using namespace llvm::sys::fs;
|
|
38 using namespace llvm::support::endian;
|
173
|
39 using namespace lld;
|
|
40 using namespace lld::elf;
|
150
|
41
|
173
|
42 bool InputFile::isInGroup;
|
|
43 uint32_t InputFile::nextGroupId;
|
|
44
|
|
45 std::vector<ArchiveFile *> elf::archiveFiles;
|
|
46 std::vector<BinaryFile *> elf::binaryFiles;
|
|
47 std::vector<BitcodeFile *> elf::bitcodeFiles;
|
|
48 std::vector<LazyObjFile *> elf::lazyObjFiles;
|
|
49 std::vector<InputFile *> elf::objectFiles;
|
|
50 std::vector<SharedFile *> elf::sharedFiles;
|
|
51
|
|
52 std::unique_ptr<TarWriter> elf::tar;
|
|
53
|
150
|
54 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
|
173
|
55 std::string lld::toString(const InputFile *f) {
|
150
|
56 if (!f)
|
|
57 return "<internal>";
|
|
58
|
|
59 if (f->toStringCache.empty()) {
|
|
60 if (f->archiveName.empty())
|
|
61 f->toStringCache = std::string(f->getName());
|
|
62 else
|
|
63 f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
|
|
64 }
|
|
65 return f->toStringCache;
|
|
66 }
|
|
67
|
|
68 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
|
|
69 unsigned char size;
|
|
70 unsigned char endian;
|
|
71 std::tie(size, endian) = getElfArchType(mb.getBuffer());
|
|
72
|
|
73 auto report = [&](StringRef msg) {
|
|
74 StringRef filename = mb.getBufferIdentifier();
|
|
75 if (archiveName.empty())
|
|
76 fatal(filename + ": " + msg);
|
|
77 else
|
|
78 fatal(archiveName + "(" + filename + "): " + msg);
|
|
79 };
|
|
80
|
|
81 if (!mb.getBuffer().startswith(ElfMagic))
|
|
82 report("not an ELF file");
|
|
83 if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
|
|
84 report("corrupted ELF file: invalid data encoding");
|
|
85 if (size != ELFCLASS32 && size != ELFCLASS64)
|
|
86 report("corrupted ELF file: invalid file class");
|
|
87
|
|
88 size_t bufSize = mb.getBuffer().size();
|
|
89 if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
|
|
90 (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
|
|
91 report("corrupted ELF file: file is too short");
|
|
92
|
|
93 if (size == ELFCLASS32)
|
|
94 return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
|
|
95 return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
|
|
96 }
|
|
97
|
|
98 InputFile::InputFile(Kind k, MemoryBufferRef m)
|
|
99 : mb(m), groupId(nextGroupId), fileKind(k) {
|
|
100 // All files within the same --{start,end}-group get the same group ID.
|
|
101 // Otherwise, a new file will get a new group ID.
|
|
102 if (!isInGroup)
|
|
103 ++nextGroupId;
|
|
104 }
|
|
105
|
173
|
106 Optional<MemoryBufferRef> elf::readFile(StringRef path) {
|
150
|
107 // The --chroot option changes our virtual root directory.
|
|
108 // This is useful when you are dealing with files created by --reproduce.
|
|
109 if (!config->chroot.empty() && path.startswith("/"))
|
|
110 path = saver.save(config->chroot + path);
|
|
111
|
|
112 log(path);
|
|
113
|
|
114 auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
|
|
115 if (auto ec = mbOrErr.getError()) {
|
|
116 error("cannot open " + path + ": " + ec.message());
|
|
117 return None;
|
|
118 }
|
|
119
|
|
120 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
|
|
121 MemoryBufferRef mbref = mb->getMemBufferRef();
|
|
122 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
|
|
123
|
|
124 if (tar)
|
|
125 tar->append(relativeToRoot(path), mbref.getBuffer());
|
|
126 return mbref;
|
|
127 }
|
|
128
|
|
129 // All input object files must be for the same architecture
|
|
130 // (e.g. it does not make sense to link x86 object files with
|
|
131 // MIPS object files.) This function checks for that error.
|
|
132 static bool isCompatible(InputFile *file) {
|
|
133 if (!file->isElf() && !isa<BitcodeFile>(file))
|
|
134 return true;
|
|
135
|
|
136 if (file->ekind == config->ekind && file->emachine == config->emachine) {
|
|
137 if (config->emachine != EM_MIPS)
|
|
138 return true;
|
|
139 if (isMipsN32Abi(file) == config->mipsN32Abi)
|
|
140 return true;
|
|
141 }
|
|
142
|
173
|
143 StringRef target =
|
|
144 !config->bfdname.empty() ? config->bfdname : config->emulation;
|
|
145 if (!target.empty()) {
|
|
146 error(toString(file) + " is incompatible with " + target);
|
150
|
147 return false;
|
|
148 }
|
|
149
|
|
150 InputFile *existing;
|
|
151 if (!objectFiles.empty())
|
|
152 existing = objectFiles[0];
|
|
153 else if (!sharedFiles.empty())
|
|
154 existing = sharedFiles[0];
|
173
|
155 else if (!bitcodeFiles.empty())
|
|
156 existing = bitcodeFiles[0];
|
150
|
157 else
|
173
|
158 llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to "
|
|
159 "determine target emulation");
|
150
|
160
|
|
161 error(toString(file) + " is incompatible with " + toString(existing));
|
|
162 return false;
|
|
163 }
|
|
164
|
|
165 template <class ELFT> static void doParseFile(InputFile *file) {
|
|
166 if (!isCompatible(file))
|
|
167 return;
|
|
168
|
|
169 // Binary file
|
|
170 if (auto *f = dyn_cast<BinaryFile>(file)) {
|
|
171 binaryFiles.push_back(f);
|
|
172 f->parse();
|
|
173 return;
|
|
174 }
|
|
175
|
|
176 // .a file
|
|
177 if (auto *f = dyn_cast<ArchiveFile>(file)) {
|
173
|
178 archiveFiles.push_back(f);
|
150
|
179 f->parse();
|
|
180 return;
|
|
181 }
|
|
182
|
|
183 // Lazy object file
|
|
184 if (auto *f = dyn_cast<LazyObjFile>(file)) {
|
|
185 lazyObjFiles.push_back(f);
|
|
186 f->parse<ELFT>();
|
|
187 return;
|
|
188 }
|
|
189
|
|
190 if (config->trace)
|
|
191 message(toString(file));
|
|
192
|
|
193 // .so file
|
|
194 if (auto *f = dyn_cast<SharedFile>(file)) {
|
|
195 f->parse<ELFT>();
|
|
196 return;
|
|
197 }
|
|
198
|
|
199 // LLVM bitcode file
|
|
200 if (auto *f = dyn_cast<BitcodeFile>(file)) {
|
|
201 bitcodeFiles.push_back(f);
|
|
202 f->parse<ELFT>();
|
|
203 return;
|
|
204 }
|
|
205
|
|
206 // Regular object file
|
|
207 objectFiles.push_back(file);
|
|
208 cast<ObjFile<ELFT>>(file)->parse();
|
|
209 }
|
|
210
|
|
211 // Add symbols in File to the symbol table.
|
173
|
212 void elf::parseFile(InputFile *file) {
|
150
|
213 switch (config->ekind) {
|
|
214 case ELF32LEKind:
|
|
215 doParseFile<ELF32LE>(file);
|
|
216 return;
|
|
217 case ELF32BEKind:
|
|
218 doParseFile<ELF32BE>(file);
|
|
219 return;
|
|
220 case ELF64LEKind:
|
|
221 doParseFile<ELF64LE>(file);
|
|
222 return;
|
|
223 case ELF64BEKind:
|
|
224 doParseFile<ELF64BE>(file);
|
|
225 return;
|
|
226 default:
|
|
227 llvm_unreachable("unknown ELFT");
|
|
228 }
|
|
229 }
|
|
230
|
|
231 // Concatenates arguments to construct a string representing an error location.
|
|
232 static std::string createFileLineMsg(StringRef path, unsigned line) {
|
|
233 std::string filename = std::string(path::filename(path));
|
|
234 std::string lineno = ":" + std::to_string(line);
|
|
235 if (filename == path)
|
|
236 return filename + lineno;
|
|
237 return filename + lineno + " (" + path.str() + lineno + ")";
|
|
238 }
|
|
239
|
|
240 template <class ELFT>
|
|
241 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
|
|
242 InputSectionBase &sec, uint64_t offset) {
|
|
243 // In DWARF, functions and variables are stored to different places.
|
|
244 // First, lookup a function for a given offset.
|
|
245 if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
|
|
246 return createFileLineMsg(info->FileName, info->Line);
|
|
247
|
|
248 // If it failed, lookup again as a variable.
|
|
249 if (Optional<std::pair<std::string, unsigned>> fileLine =
|
|
250 file.getVariableLoc(sym.getName()))
|
|
251 return createFileLineMsg(fileLine->first, fileLine->second);
|
|
252
|
|
253 // File.sourceFile contains STT_FILE symbol, and that is a last resort.
|
|
254 return std::string(file.sourceFile);
|
|
255 }
|
|
256
|
|
257 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
|
|
258 uint64_t offset) {
|
|
259 if (kind() != ObjKind)
|
|
260 return "";
|
|
261 switch (config->ekind) {
|
|
262 default:
|
|
263 llvm_unreachable("Invalid kind");
|
|
264 case ELF32LEKind:
|
|
265 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
|
|
266 case ELF32BEKind:
|
|
267 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
|
|
268 case ELF64LEKind:
|
|
269 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
|
|
270 case ELF64BEKind:
|
|
271 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
|
|
272 }
|
|
273 }
|
|
274
|
173
|
275 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
|
|
276 llvm::call_once(initDwarf, [this]() {
|
|
277 dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
|
|
278 std::make_unique<LLDDwarfObj<ELFT>>(this), "",
|
|
279 [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
|
|
280 [&](Error warning) {
|
|
281 warn(getName() + ": " + toString(std::move(warning)));
|
|
282 }));
|
|
283 });
|
|
284
|
|
285 return dwarf.get();
|
150
|
286 }
|
|
287
|
|
288 // Returns the pair of file name and line number describing location of data
|
|
289 // object (variable, array, etc) definition.
|
|
290 template <class ELFT>
|
|
291 Optional<std::pair<std::string, unsigned>>
|
|
292 ObjFile<ELFT>::getVariableLoc(StringRef name) {
|
173
|
293 return getDwarf()->getVariableLoc(name);
|
150
|
294 }
|
|
295
|
|
296 // Returns source line information for a given offset
|
|
297 // using DWARF debug info.
|
|
298 template <class ELFT>
|
|
299 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
|
|
300 uint64_t offset) {
|
|
301 // Detect SectionIndex for specified section.
|
|
302 uint64_t sectionIndex = object::SectionedAddress::UndefSection;
|
|
303 ArrayRef<InputSectionBase *> sections = s->file->getSections();
|
|
304 for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
|
|
305 if (s == sections[curIndex]) {
|
|
306 sectionIndex = curIndex;
|
|
307 break;
|
|
308 }
|
|
309 }
|
|
310
|
173
|
311 return getDwarf()->getDILineInfo(offset, sectionIndex);
|
150
|
312 }
|
|
313
|
|
314 ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
|
|
315 ekind = getELFKind(mb, "");
|
|
316
|
|
317 switch (ekind) {
|
|
318 case ELF32LEKind:
|
|
319 init<ELF32LE>();
|
|
320 break;
|
|
321 case ELF32BEKind:
|
|
322 init<ELF32BE>();
|
|
323 break;
|
|
324 case ELF64LEKind:
|
|
325 init<ELF64LE>();
|
|
326 break;
|
|
327 case ELF64BEKind:
|
|
328 init<ELF64BE>();
|
|
329 break;
|
|
330 default:
|
|
331 llvm_unreachable("getELFKind");
|
|
332 }
|
|
333 }
|
|
334
|
|
335 template <typename Elf_Shdr>
|
|
336 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
|
|
337 for (const Elf_Shdr &sec : sections)
|
|
338 if (sec.sh_type == type)
|
|
339 return &sec;
|
|
340 return nullptr;
|
|
341 }
|
|
342
|
|
343 template <class ELFT> void ELFFileBase::init() {
|
|
344 using Elf_Shdr = typename ELFT::Shdr;
|
|
345 using Elf_Sym = typename ELFT::Sym;
|
|
346
|
|
347 // Initialize trivial attributes.
|
|
348 const ELFFile<ELFT> &obj = getObj<ELFT>();
|
|
349 emachine = obj.getHeader()->e_machine;
|
|
350 osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
|
|
351 abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
|
|
352
|
|
353 ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
|
|
354
|
|
355 // Find a symbol table.
|
|
356 bool isDSO =
|
|
357 (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
|
|
358 const Elf_Shdr *symtabSec =
|
|
359 findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
|
|
360
|
|
361 if (!symtabSec)
|
|
362 return;
|
|
363
|
|
364 // Initialize members corresponding to a symbol table.
|
|
365 firstGlobal = symtabSec->sh_info;
|
|
366
|
|
367 ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
|
|
368 if (firstGlobal == 0 || firstGlobal > eSyms.size())
|
|
369 fatal(toString(this) + ": invalid sh_info in symbol table");
|
|
370
|
|
371 elfSyms = reinterpret_cast<const void *>(eSyms.data());
|
|
372 numELFSyms = eSyms.size();
|
|
373 stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
|
|
374 }
|
|
375
|
|
376 template <class ELFT>
|
|
377 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
|
|
378 return CHECK(
|
|
379 this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
|
|
380 this);
|
|
381 }
|
|
382
|
|
383 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
|
|
384 if (this->symbols.empty())
|
|
385 return {};
|
|
386 return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
|
|
387 }
|
|
388
|
|
389 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
|
|
390 return makeArrayRef(this->symbols).slice(this->firstGlobal);
|
|
391 }
|
|
392
|
|
393 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
|
|
394 // Read a section table. justSymbols is usually false.
|
|
395 if (this->justSymbols)
|
|
396 initializeJustSymbols();
|
|
397 else
|
|
398 initializeSections(ignoreComdats);
|
|
399
|
|
400 // Read a symbol table.
|
|
401 initializeSymbols();
|
|
402 }
|
|
403
|
|
404 // Sections with SHT_GROUP and comdat bits define comdat section groups.
|
|
405 // They are identified and deduplicated by group name. This function
|
|
406 // returns a group name.
|
|
407 template <class ELFT>
|
|
408 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
|
|
409 const Elf_Shdr &sec) {
|
|
410 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
|
|
411 if (sec.sh_info >= symbols.size())
|
|
412 fatal(toString(this) + ": invalid symbol index");
|
|
413 const typename ELFT::Sym &sym = symbols[sec.sh_info];
|
|
414 StringRef signature = CHECK(sym.getName(this->stringTable), this);
|
|
415
|
|
416 // As a special case, if a symbol is a section symbol and has no name,
|
|
417 // we use a section name as a signature.
|
|
418 //
|
|
419 // Such SHT_GROUP sections are invalid from the perspective of the ELF
|
|
420 // standard, but GNU gold 1.14 (the newest version as of July 2017) or
|
|
421 // older produce such sections as outputs for the -r option, so we need
|
|
422 // a bug-compatibility.
|
|
423 if (signature.empty() && sym.getType() == STT_SECTION)
|
|
424 return getSectionName(sec);
|
|
425 return signature;
|
|
426 }
|
|
427
|
|
428 template <class ELFT>
|
|
429 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
|
173
|
430 if (!(sec.sh_flags & SHF_MERGE))
|
|
431 return false;
|
|
432
|
150
|
433 // On a regular link we don't merge sections if -O0 (default is -O1). This
|
|
434 // sometimes makes the linker significantly faster, although the output will
|
|
435 // be bigger.
|
|
436 //
|
|
437 // Doing the same for -r would create a problem as it would combine sections
|
|
438 // with different sh_entsize. One option would be to just copy every SHF_MERGE
|
|
439 // section as is to the output. While this would produce a valid ELF file with
|
|
440 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
|
|
441 // they see two .debug_str. We could have separate logic for combining
|
|
442 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
|
|
443 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
|
|
444 // logic for -r.
|
|
445 if (config->optimize == 0 && !config->relocatable)
|
|
446 return false;
|
|
447
|
|
448 // A mergeable section with size 0 is useless because they don't have
|
|
449 // any data to merge. A mergeable string section with size 0 can be
|
|
450 // argued as invalid because it doesn't end with a null character.
|
|
451 // We'll avoid a mess by handling them as if they were non-mergeable.
|
|
452 if (sec.sh_size == 0)
|
|
453 return false;
|
|
454
|
|
455 // Check for sh_entsize. The ELF spec is not clear about the zero
|
|
456 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
|
|
457 // the section does not hold a table of fixed-size entries". We know
|
|
458 // that Rust 1.13 produces a string mergeable section with a zero
|
|
459 // sh_entsize. Here we just accept it rather than being picky about it.
|
|
460 uint64_t entSize = sec.sh_entsize;
|
|
461 if (entSize == 0)
|
|
462 return false;
|
|
463 if (sec.sh_size % entSize)
|
|
464 fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
|
|
465 Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
|
|
466 Twine(entSize) + ")");
|
|
467
|
173
|
468 if (sec.sh_flags & SHF_WRITE)
|
150
|
469 fatal(toString(this) + ":(" + name +
|
|
470 "): writable SHF_MERGE section is not supported");
|
|
471
|
|
472 return true;
|
|
473 }
|
|
474
|
|
475 // This is for --just-symbols.
|
|
476 //
|
|
477 // --just-symbols is a very minor feature that allows you to link your
|
|
478 // output against other existing program, so that if you load both your
|
|
479 // program and the other program into memory, your output can refer the
|
|
480 // other program's symbols.
|
|
481 //
|
|
482 // When the option is given, we link "just symbols". The section table is
|
|
483 // initialized with null pointers.
|
|
484 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
|
|
485 ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
|
|
486 this->sections.resize(sections.size());
|
|
487 }
|
|
488
|
|
489 // An ELF object file may contain a `.deplibs` section. If it exists, the
|
|
490 // section contains a list of library specifiers such as `m` for libm. This
|
|
491 // function resolves a given name by finding the first matching library checking
|
|
492 // the various ways that a library can be specified to LLD. This ELF extension
|
|
493 // is a form of autolinking and is called `dependent libraries`. It is currently
|
|
494 // unique to LLVM and lld.
|
|
495 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
|
|
496 if (!config->dependentLibraries)
|
|
497 return;
|
|
498 if (fs::exists(specifier))
|
|
499 driver->addFile(specifier, /*withLOption=*/false);
|
|
500 else if (Optional<std::string> s = findFromSearchPaths(specifier))
|
|
501 driver->addFile(*s, /*withLOption=*/true);
|
|
502 else if (Optional<std::string> s = searchLibraryBaseName(specifier))
|
|
503 driver->addFile(*s, /*withLOption=*/true);
|
|
504 else
|
|
505 error(toString(f) +
|
|
506 ": unable to find library from dependent library specifier: " +
|
|
507 specifier);
|
|
508 }
|
|
509
|
|
510 // Record the membership of a section group so that in the garbage collection
|
|
511 // pass, section group members are kept or discarded as a unit.
|
|
512 template <class ELFT>
|
|
513 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
|
|
514 ArrayRef<typename ELFT::Word> entries) {
|
|
515 bool hasAlloc = false;
|
|
516 for (uint32_t index : entries.slice(1)) {
|
|
517 if (index >= sections.size())
|
|
518 return;
|
|
519 if (InputSectionBase *s = sections[index])
|
|
520 if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
|
|
521 hasAlloc = true;
|
|
522 }
|
|
523
|
|
524 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
|
|
525 // collection. See the comment in markLive(). This rule retains .debug_types
|
|
526 // and .rela.debug_types.
|
|
527 if (!hasAlloc)
|
|
528 return;
|
|
529
|
|
530 // Connect the members in a circular doubly-linked list via
|
|
531 // nextInSectionGroup.
|
|
532 InputSectionBase *head;
|
|
533 InputSectionBase *prev = nullptr;
|
|
534 for (uint32_t index : entries.slice(1)) {
|
|
535 InputSectionBase *s = sections[index];
|
|
536 if (!s || s == &InputSection::discarded)
|
|
537 continue;
|
|
538 if (prev)
|
|
539 prev->nextInSectionGroup = s;
|
|
540 else
|
|
541 head = s;
|
|
542 prev = s;
|
|
543 }
|
|
544 if (prev)
|
|
545 prev->nextInSectionGroup = head;
|
|
546 }
|
|
547
|
|
548 template <class ELFT>
|
|
549 void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
|
|
550 const ELFFile<ELFT> &obj = this->getObj();
|
|
551
|
|
552 ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
|
|
553 uint64_t size = objSections.size();
|
|
554 this->sections.resize(size);
|
|
555 this->sectionStringTable =
|
|
556 CHECK(obj.getSectionStringTable(objSections), this);
|
|
557
|
|
558 std::vector<ArrayRef<Elf_Word>> selectedGroups;
|
|
559
|
|
560 for (size_t i = 0, e = objSections.size(); i < e; ++i) {
|
|
561 if (this->sections[i] == &InputSection::discarded)
|
|
562 continue;
|
|
563 const Elf_Shdr &sec = objSections[i];
|
|
564
|
|
565 if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
|
|
566 cgProfile =
|
|
567 check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
|
|
568
|
|
569 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
|
|
570 // if -r is given, we'll let the final link discard such sections.
|
|
571 // This is compatible with GNU.
|
|
572 if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
|
|
573 if (sec.sh_type == SHT_LLVM_ADDRSIG) {
|
|
574 // We ignore the address-significance table if we know that the object
|
|
575 // file was created by objcopy or ld -r. This is because these tools
|
|
576 // will reorder the symbols in the symbol table, invalidating the data
|
|
577 // in the address-significance table, which refers to symbols by index.
|
|
578 if (sec.sh_link != 0)
|
|
579 this->addrsigSec = &sec;
|
|
580 else if (config->icf == ICFLevel::Safe)
|
|
581 warn(toString(this) + ": --icf=safe is incompatible with object "
|
|
582 "files created using objcopy or ld -r");
|
|
583 }
|
|
584 this->sections[i] = &InputSection::discarded;
|
|
585 continue;
|
|
586 }
|
|
587
|
|
588 switch (sec.sh_type) {
|
|
589 case SHT_GROUP: {
|
|
590 // De-duplicate section groups by their signatures.
|
|
591 StringRef signature = getShtGroupSignature(objSections, sec);
|
|
592 this->sections[i] = &InputSection::discarded;
|
|
593
|
|
594
|
|
595 ArrayRef<Elf_Word> entries =
|
|
596 CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
|
|
597 if (entries.empty())
|
|
598 fatal(toString(this) + ": empty SHT_GROUP");
|
|
599
|
|
600 // The first word of a SHT_GROUP section contains flags. Currently,
|
|
601 // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
|
|
602 // An group with the empty flag doesn't define anything; such sections
|
|
603 // are just skipped.
|
|
604 if (entries[0] == 0)
|
|
605 continue;
|
|
606
|
|
607 if (entries[0] != GRP_COMDAT)
|
|
608 fatal(toString(this) + ": unsupported SHT_GROUP format");
|
|
609
|
|
610 bool isNew =
|
|
611 ignoreComdats ||
|
|
612 symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
|
|
613 .second;
|
|
614 if (isNew) {
|
|
615 if (config->relocatable)
|
|
616 this->sections[i] = createInputSection(sec);
|
|
617 selectedGroups.push_back(entries);
|
|
618 continue;
|
|
619 }
|
|
620
|
|
621 // Otherwise, discard group members.
|
|
622 for (uint32_t secIndex : entries.slice(1)) {
|
|
623 if (secIndex >= size)
|
|
624 fatal(toString(this) +
|
|
625 ": invalid section index in group: " + Twine(secIndex));
|
|
626 this->sections[secIndex] = &InputSection::discarded;
|
|
627 }
|
|
628 break;
|
|
629 }
|
|
630 case SHT_SYMTAB_SHNDX:
|
|
631 shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
|
|
632 break;
|
|
633 case SHT_SYMTAB:
|
|
634 case SHT_STRTAB:
|
|
635 case SHT_NULL:
|
|
636 break;
|
|
637 default:
|
|
638 this->sections[i] = createInputSection(sec);
|
|
639 }
|
|
640 }
|
|
641
|
|
642 // This block handles SHF_LINK_ORDER.
|
|
643 for (size_t i = 0, e = objSections.size(); i < e; ++i) {
|
|
644 if (this->sections[i] == &InputSection::discarded)
|
|
645 continue;
|
|
646 const Elf_Shdr &sec = objSections[i];
|
|
647 if (!(sec.sh_flags & SHF_LINK_ORDER))
|
|
648 continue;
|
|
649
|
|
650 // .ARM.exidx sections have a reverse dependency on the InputSection they
|
|
651 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
|
|
652 InputSectionBase *linkSec = nullptr;
|
|
653 if (sec.sh_link < this->sections.size())
|
|
654 linkSec = this->sections[sec.sh_link];
|
|
655 if (!linkSec)
|
|
656 fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
|
|
657
|
|
658 InputSection *isec = cast<InputSection>(this->sections[i]);
|
|
659 linkSec->dependentSections.push_back(isec);
|
|
660 if (!isa<InputSection>(linkSec))
|
|
661 error("a section " + isec->name +
|
|
662 " with SHF_LINK_ORDER should not refer a non-regular section: " +
|
|
663 toString(linkSec));
|
|
664 }
|
|
665
|
|
666 for (ArrayRef<Elf_Word> entries : selectedGroups)
|
|
667 handleSectionGroup<ELFT>(this->sections, entries);
|
|
668 }
|
|
669
|
|
670 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
|
|
671 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
|
|
672 // the input objects have been compiled.
|
|
673 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
|
|
674 const InputFile *f) {
|
173
|
675 Optional<unsigned> attr =
|
|
676 attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
|
|
677 if (!attr.hasValue())
|
150
|
678 // If an ABI tag isn't present then it is implicitly given the value of 0
|
|
679 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
|
|
680 // including some in glibc that don't use FP args (and should have value 3)
|
|
681 // don't have the attribute so we do not consider an implicit value of 0
|
|
682 // as a clash.
|
|
683 return;
|
|
684
|
173
|
685 unsigned vfpArgs = attr.getValue();
|
150
|
686 ARMVFPArgKind arg;
|
|
687 switch (vfpArgs) {
|
|
688 case ARMBuildAttrs::BaseAAPCS:
|
|
689 arg = ARMVFPArgKind::Base;
|
|
690 break;
|
|
691 case ARMBuildAttrs::HardFPAAPCS:
|
|
692 arg = ARMVFPArgKind::VFP;
|
|
693 break;
|
|
694 case ARMBuildAttrs::ToolChainFPPCS:
|
|
695 // Tool chain specific convention that conforms to neither AAPCS variant.
|
|
696 arg = ARMVFPArgKind::ToolChain;
|
|
697 break;
|
|
698 case ARMBuildAttrs::CompatibleFPAAPCS:
|
|
699 // Object compatible with all conventions.
|
|
700 return;
|
|
701 default:
|
|
702 error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
|
|
703 return;
|
|
704 }
|
|
705 // Follow ld.bfd and error if there is a mix of calling conventions.
|
|
706 if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
|
|
707 error(toString(f) + ": incompatible Tag_ABI_VFP_args");
|
|
708 else
|
|
709 config->armVFPArgs = arg;
|
|
710 }
|
|
711
|
|
712 // The ARM support in lld makes some use of instructions that are not available
|
|
713 // on all ARM architectures. Namely:
|
|
714 // - Use of BLX instruction for interworking between ARM and Thumb state.
|
|
715 // - Use of the extended Thumb branch encoding in relocation.
|
|
716 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
|
|
717 // The ARM Attributes section contains information about the architecture chosen
|
|
718 // at compile time. We follow the convention that if at least one input object
|
|
719 // is compiled with an architecture that supports these features then lld is
|
|
720 // permitted to use them.
|
|
721 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
|
173
|
722 Optional<unsigned> attr =
|
|
723 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
|
|
724 if (!attr.hasValue())
|
150
|
725 return;
|
173
|
726 auto arch = attr.getValue();
|
150
|
727 switch (arch) {
|
|
728 case ARMBuildAttrs::Pre_v4:
|
|
729 case ARMBuildAttrs::v4:
|
|
730 case ARMBuildAttrs::v4T:
|
|
731 // Architectures prior to v5 do not support BLX instruction
|
|
732 break;
|
|
733 case ARMBuildAttrs::v5T:
|
|
734 case ARMBuildAttrs::v5TE:
|
|
735 case ARMBuildAttrs::v5TEJ:
|
|
736 case ARMBuildAttrs::v6:
|
|
737 case ARMBuildAttrs::v6KZ:
|
|
738 case ARMBuildAttrs::v6K:
|
|
739 config->armHasBlx = true;
|
|
740 // Architectures used in pre-Cortex processors do not support
|
|
741 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
|
|
742 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
|
|
743 break;
|
|
744 default:
|
|
745 // All other Architectures have BLX and extended branch encoding
|
|
746 config->armHasBlx = true;
|
|
747 config->armJ1J2BranchEncoding = true;
|
|
748 if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
|
|
749 // All Architectures used in Cortex processors with the exception
|
|
750 // of v6-M and v6S-M have the MOVT and MOVW instructions.
|
|
751 config->armHasMovtMovw = true;
|
|
752 break;
|
|
753 }
|
|
754 }
|
|
755
|
|
756 // If a source file is compiled with x86 hardware-assisted call flow control
|
|
757 // enabled, the generated object file contains feature flags indicating that
|
|
758 // fact. This function reads the feature flags and returns it.
|
|
759 //
|
|
760 // Essentially we want to read a single 32-bit value in this function, but this
|
|
761 // function is rather complicated because the value is buried deep inside a
|
|
762 // .note.gnu.property section.
|
|
763 //
|
|
764 // The section consists of one or more NOTE records. Each NOTE record consists
|
|
765 // of zero or more type-length-value fields. We want to find a field of a
|
|
766 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
|
|
767 // the ABI is unnecessarily complicated.
|
|
768 template <class ELFT>
|
|
769 static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
|
|
770 using Elf_Nhdr = typename ELFT::Nhdr;
|
|
771 using Elf_Note = typename ELFT::Note;
|
|
772
|
|
773 uint32_t featuresSet = 0;
|
|
774 while (!data.empty()) {
|
|
775 // Read one NOTE record.
|
|
776 if (data.size() < sizeof(Elf_Nhdr))
|
|
777 fatal(toString(obj) + ": .note.gnu.property: section too short");
|
|
778
|
|
779 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
|
|
780 if (data.size() < nhdr->getSize())
|
|
781 fatal(toString(obj) + ": .note.gnu.property: section too short");
|
|
782
|
|
783 Elf_Note note(*nhdr);
|
|
784 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
|
|
785 data = data.slice(nhdr->getSize());
|
|
786 continue;
|
|
787 }
|
|
788
|
|
789 uint32_t featureAndType = config->emachine == EM_AARCH64
|
|
790 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
|
|
791 : GNU_PROPERTY_X86_FEATURE_1_AND;
|
|
792
|
|
793 // Read a body of a NOTE record, which consists of type-length-value fields.
|
|
794 ArrayRef<uint8_t> desc = note.getDesc();
|
|
795 while (!desc.empty()) {
|
|
796 if (desc.size() < 8)
|
|
797 fatal(toString(obj) + ": .note.gnu.property: section too short");
|
|
798
|
|
799 uint32_t type = read32le(desc.data());
|
|
800 uint32_t size = read32le(desc.data() + 4);
|
|
801
|
|
802 if (type == featureAndType) {
|
|
803 // We found a FEATURE_1_AND field. There may be more than one of these
|
|
804 // in a .note.gnu.property section, for a relocatable object we
|
|
805 // accumulate the bits set.
|
|
806 featuresSet |= read32le(desc.data() + 8);
|
|
807 }
|
|
808
|
|
809 // On 64-bit, a payload may be followed by a 4-byte padding to make its
|
|
810 // size a multiple of 8.
|
|
811 if (ELFT::Is64Bits)
|
|
812 size = alignTo(size, 8);
|
|
813
|
|
814 desc = desc.slice(size + 8); // +8 for Type and Size
|
|
815 }
|
|
816
|
|
817 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
|
|
818 data = data.slice(nhdr->getSize());
|
|
819 }
|
|
820
|
|
821 return featuresSet;
|
|
822 }
|
|
823
|
|
824 template <class ELFT>
|
|
825 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
|
|
826 uint32_t idx = sec.sh_info;
|
|
827 if (idx >= this->sections.size())
|
|
828 fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
|
|
829 InputSectionBase *target = this->sections[idx];
|
|
830
|
|
831 // Strictly speaking, a relocation section must be included in the
|
|
832 // group of the section it relocates. However, LLVM 3.3 and earlier
|
|
833 // would fail to do so, so we gracefully handle that case.
|
|
834 if (target == &InputSection::discarded)
|
|
835 return nullptr;
|
|
836
|
|
837 if (!target)
|
|
838 fatal(toString(this) + ": unsupported relocation reference");
|
|
839 return target;
|
|
840 }
|
|
841
|
|
842 // Create a regular InputSection class that has the same contents
|
|
843 // as a given section.
|
|
844 static InputSection *toRegularSection(MergeInputSection *sec) {
|
|
845 return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
|
|
846 sec->data(), sec->name);
|
|
847 }
|
|
848
|
|
849 template <class ELFT>
|
|
850 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
|
|
851 StringRef name = getSectionName(sec);
|
|
852
|
|
853 switch (sec.sh_type) {
|
|
854 case SHT_ARM_ATTRIBUTES: {
|
|
855 if (config->emachine != EM_ARM)
|
|
856 break;
|
|
857 ARMAttributeParser attributes;
|
|
858 ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
|
173
|
859 if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
|
|
860 ? support::little
|
|
861 : support::big)) {
|
|
862 auto *isec = make<InputSection>(*this, sec, name);
|
|
863 warn(toString(isec) + ": " + llvm::toString(std::move(e)));
|
|
864 break;
|
|
865 }
|
150
|
866 updateSupportedARMFeatures(attributes);
|
|
867 updateARMVFPArgs(attributes, this);
|
|
868
|
|
869 // FIXME: Retain the first attribute section we see. The eglibc ARM
|
|
870 // dynamic loaders require the presence of an attribute section for dlopen
|
|
871 // to work. In a full implementation we would merge all attribute sections.
|
|
872 if (in.armAttributes == nullptr) {
|
|
873 in.armAttributes = make<InputSection>(*this, sec, name);
|
|
874 return in.armAttributes;
|
|
875 }
|
|
876 return &InputSection::discarded;
|
|
877 }
|
|
878 case SHT_LLVM_DEPENDENT_LIBRARIES: {
|
|
879 if (config->relocatable)
|
|
880 break;
|
|
881 ArrayRef<char> data =
|
|
882 CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
|
|
883 if (!data.empty() && data.back() != '\0') {
|
|
884 error(toString(this) +
|
|
885 ": corrupted dependent libraries section (unterminated string): " +
|
|
886 name);
|
|
887 return &InputSection::discarded;
|
|
888 }
|
|
889 for (const char *d = data.begin(), *e = data.end(); d < e;) {
|
|
890 StringRef s(d);
|
|
891 addDependentLibrary(s, this);
|
|
892 d += s.size() + 1;
|
|
893 }
|
|
894 return &InputSection::discarded;
|
|
895 }
|
|
896 case SHT_RELA:
|
|
897 case SHT_REL: {
|
|
898 // Find a relocation target section and associate this section with that.
|
|
899 // Target may have been discarded if it is in a different section group
|
|
900 // and the group is discarded, even though it's a violation of the
|
|
901 // spec. We handle that situation gracefully by discarding dangling
|
|
902 // relocation sections.
|
|
903 InputSectionBase *target = getRelocTarget(sec);
|
|
904 if (!target)
|
|
905 return nullptr;
|
|
906
|
|
907 // ELF spec allows mergeable sections with relocations, but they are
|
|
908 // rare, and it is in practice hard to merge such sections by contents,
|
|
909 // because applying relocations at end of linking changes section
|
|
910 // contents. So, we simply handle such sections as non-mergeable ones.
|
|
911 // Degrading like this is acceptable because section merging is optional.
|
|
912 if (auto *ms = dyn_cast<MergeInputSection>(target)) {
|
|
913 target = toRegularSection(ms);
|
|
914 this->sections[sec.sh_info] = target;
|
|
915 }
|
|
916
|
|
917 // This section contains relocation information.
|
|
918 // If -r is given, we do not interpret or apply relocation
|
|
919 // but just copy relocation sections to output.
|
|
920 if (config->relocatable) {
|
|
921 InputSection *relocSec = make<InputSection>(*this, sec, name);
|
|
922 // We want to add a dependency to target, similar like we do for
|
|
923 // -emit-relocs below. This is useful for the case when linker script
|
|
924 // contains the "/DISCARD/". It is perhaps uncommon to use a script with
|
|
925 // -r, but we faced it in the Linux kernel and have to handle such case
|
|
926 // and not to crash.
|
|
927 target->dependentSections.push_back(relocSec);
|
|
928 return relocSec;
|
|
929 }
|
|
930
|
|
931 if (target->firstRelocation)
|
|
932 fatal(toString(this) +
|
|
933 ": multiple relocation sections to one section are not supported");
|
|
934
|
|
935 if (sec.sh_type == SHT_RELA) {
|
|
936 ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
|
|
937 target->firstRelocation = rels.begin();
|
|
938 target->numRelocations = rels.size();
|
|
939 target->areRelocsRela = true;
|
|
940 } else {
|
|
941 ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
|
|
942 target->firstRelocation = rels.begin();
|
|
943 target->numRelocations = rels.size();
|
|
944 target->areRelocsRela = false;
|
|
945 }
|
|
946 assert(isUInt<31>(target->numRelocations));
|
|
947
|
|
948 // Relocation sections processed by the linker are usually removed
|
|
949 // from the output, so returning `nullptr` for the normal case.
|
|
950 // However, if -emit-relocs is given, we need to leave them in the output.
|
|
951 // (Some post link analysis tools need this information.)
|
|
952 if (config->emitRelocs) {
|
|
953 InputSection *relocSec = make<InputSection>(*this, sec, name);
|
|
954 // We will not emit relocation section if target was discarded.
|
|
955 target->dependentSections.push_back(relocSec);
|
|
956 return relocSec;
|
|
957 }
|
|
958 return nullptr;
|
|
959 }
|
|
960 }
|
|
961
|
|
962 // The GNU linker uses .note.GNU-stack section as a marker indicating
|
|
963 // that the code in the object file does not expect that the stack is
|
|
964 // executable (in terms of NX bit). If all input files have the marker,
|
|
965 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
|
|
966 // make the stack non-executable. Most object files have this section as
|
|
967 // of 2017.
|
|
968 //
|
|
969 // But making the stack non-executable is a norm today for security
|
|
970 // reasons. Failure to do so may result in a serious security issue.
|
|
971 // Therefore, we make LLD always add PT_GNU_STACK unless it is
|
|
972 // explicitly told to do otherwise (by -z execstack). Because the stack
|
|
973 // executable-ness is controlled solely by command line options,
|
|
974 // .note.GNU-stack sections are simply ignored.
|
|
975 if (name == ".note.GNU-stack")
|
|
976 return &InputSection::discarded;
|
|
977
|
|
978 // Object files that use processor features such as Intel Control-Flow
|
|
979 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
|
|
980 // .note.gnu.property section containing a bitfield of feature bits like the
|
|
981 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
|
|
982 //
|
|
983 // Since we merge bitmaps from multiple object files to create a new
|
|
984 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
|
|
985 // file's .note.gnu.property section.
|
|
986 if (name == ".note.gnu.property") {
|
|
987 ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
|
|
988 this->andFeatures = readAndFeatures(this, contents);
|
|
989 return &InputSection::discarded;
|
|
990 }
|
|
991
|
|
992 // Split stacks is a feature to support a discontiguous stack,
|
|
993 // commonly used in the programming language Go. For the details,
|
|
994 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
|
|
995 // for split stack will include a .note.GNU-split-stack section.
|
|
996 if (name == ".note.GNU-split-stack") {
|
|
997 if (config->relocatable) {
|
|
998 error("cannot mix split-stack and non-split-stack in a relocatable link");
|
|
999 return &InputSection::discarded;
|
|
1000 }
|
|
1001 this->splitStack = true;
|
|
1002 return &InputSection::discarded;
|
|
1003 }
|
|
1004
|
|
1005 // An object file cmpiled for split stack, but where some of the
|
|
1006 // functions were compiled with the no_split_stack_attribute will
|
|
1007 // include a .note.GNU-no-split-stack section.
|
|
1008 if (name == ".note.GNU-no-split-stack") {
|
|
1009 this->someNoSplitStack = true;
|
|
1010 return &InputSection::discarded;
|
|
1011 }
|
|
1012
|
|
1013 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
|
|
1014 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
|
|
1015 // sections. Drop those sections to avoid duplicate symbol errors.
|
|
1016 // FIXME: This is glibc PR20543, we should remove this hack once that has been
|
|
1017 // fixed for a while.
|
|
1018 if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
|
|
1019 name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
|
|
1020 return &InputSection::discarded;
|
|
1021
|
|
1022 // If we are creating a new .build-id section, strip existing .build-id
|
|
1023 // sections so that the output won't have more than one .build-id.
|
|
1024 // This is not usually a problem because input object files normally don't
|
|
1025 // have .build-id sections, but you can create such files by
|
|
1026 // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
|
|
1027 if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
|
|
1028 return &InputSection::discarded;
|
|
1029
|
|
1030 // The linker merges EH (exception handling) frames and creates a
|
|
1031 // .eh_frame_hdr section for runtime. So we handle them with a special
|
|
1032 // class. For relocatable outputs, they are just passed through.
|
|
1033 if (name == ".eh_frame" && !config->relocatable)
|
|
1034 return make<EhInputSection>(*this, sec, name);
|
|
1035
|
|
1036 if (shouldMerge(sec, name))
|
|
1037 return make<MergeInputSection>(*this, sec, name);
|
|
1038 return make<InputSection>(*this, sec, name);
|
|
1039 }
|
|
1040
|
|
1041 template <class ELFT>
|
|
1042 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
|
|
1043 return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
|
|
1044 }
|
|
1045
|
|
1046 // Initialize this->Symbols. this->Symbols is a parallel array as
|
|
1047 // its corresponding ELF symbol table.
|
|
1048 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
|
|
1049 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
|
|
1050 this->symbols.resize(eSyms.size());
|
|
1051
|
|
1052 // Our symbol table may have already been partially initialized
|
|
1053 // because of LazyObjFile.
|
|
1054 for (size_t i = 0, end = eSyms.size(); i != end; ++i)
|
|
1055 if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
|
|
1056 this->symbols[i] =
|
|
1057 symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
|
|
1058
|
|
1059 // Fill this->Symbols. A symbol is either local or global.
|
|
1060 for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
|
|
1061 const Elf_Sym &eSym = eSyms[i];
|
|
1062
|
|
1063 // Read symbol attributes.
|
|
1064 uint32_t secIdx = getSectionIndex(eSym);
|
|
1065 if (secIdx >= this->sections.size())
|
|
1066 fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
|
|
1067
|
|
1068 InputSectionBase *sec = this->sections[secIdx];
|
|
1069 uint8_t binding = eSym.getBinding();
|
|
1070 uint8_t stOther = eSym.st_other;
|
|
1071 uint8_t type = eSym.getType();
|
|
1072 uint64_t value = eSym.st_value;
|
|
1073 uint64_t size = eSym.st_size;
|
|
1074 StringRefZ name = this->stringTable.data() + eSym.st_name;
|
|
1075
|
|
1076 // Handle local symbols. Local symbols are not added to the symbol
|
|
1077 // table because they are not visible from other object files. We
|
|
1078 // allocate symbol instances and add their pointers to Symbols.
|
|
1079 if (binding == STB_LOCAL) {
|
|
1080 if (eSym.getType() == STT_FILE)
|
|
1081 sourceFile = CHECK(eSym.getName(this->stringTable), this);
|
|
1082
|
|
1083 if (this->stringTable.size() <= eSym.st_name)
|
|
1084 fatal(toString(this) + ": invalid symbol name offset");
|
|
1085
|
|
1086 if (eSym.st_shndx == SHN_UNDEF)
|
|
1087 this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
|
|
1088 else if (sec == &InputSection::discarded)
|
|
1089 this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
|
|
1090 /*DiscardedSecIdx=*/secIdx);
|
|
1091 else
|
|
1092 this->symbols[i] =
|
|
1093 make<Defined>(this, name, binding, stOther, type, value, size, sec);
|
|
1094 continue;
|
|
1095 }
|
|
1096
|
|
1097 // Handle global undefined symbols.
|
|
1098 if (eSym.st_shndx == SHN_UNDEF) {
|
|
1099 this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
|
|
1100 this->symbols[i]->referenced = true;
|
|
1101 continue;
|
|
1102 }
|
|
1103
|
|
1104 // Handle global common symbols.
|
|
1105 if (eSym.st_shndx == SHN_COMMON) {
|
|
1106 if (value == 0 || value >= UINT32_MAX)
|
|
1107 fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
|
|
1108 "' has invalid alignment: " + Twine(value));
|
|
1109 this->symbols[i]->resolve(
|
|
1110 CommonSymbol{this, name, binding, stOther, type, value, size});
|
|
1111 continue;
|
|
1112 }
|
|
1113
|
|
1114 // If a defined symbol is in a discarded section, handle it as if it
|
|
1115 // were an undefined symbol. Such symbol doesn't comply with the
|
|
1116 // standard, but in practice, a .eh_frame often directly refer
|
|
1117 // COMDAT member sections, and if a comdat group is discarded, some
|
|
1118 // defined symbol in a .eh_frame becomes dangling symbols.
|
|
1119 if (sec == &InputSection::discarded) {
|
|
1120 this->symbols[i]->resolve(
|
|
1121 Undefined{this, name, binding, stOther, type, secIdx});
|
|
1122 continue;
|
|
1123 }
|
|
1124
|
|
1125 // Handle global defined symbols.
|
|
1126 if (binding == STB_GLOBAL || binding == STB_WEAK ||
|
|
1127 binding == STB_GNU_UNIQUE) {
|
|
1128 this->symbols[i]->resolve(
|
|
1129 Defined{this, name, binding, stOther, type, value, size, sec});
|
|
1130 continue;
|
|
1131 }
|
|
1132
|
|
1133 fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
|
|
1134 }
|
|
1135 }
|
|
1136
|
|
1137 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
|
|
1138 : InputFile(ArchiveKind, file->getMemoryBufferRef()),
|
|
1139 file(std::move(file)) {}
|
|
1140
|
|
1141 void ArchiveFile::parse() {
|
|
1142 for (const Archive::Symbol &sym : file->symbols())
|
|
1143 symtab->addSymbol(LazyArchive{*this, sym});
|
|
1144 }
|
|
1145
|
|
1146 // Returns a buffer pointing to a member file containing a given symbol.
|
|
1147 void ArchiveFile::fetch(const Archive::Symbol &sym) {
|
|
1148 Archive::Child c =
|
|
1149 CHECK(sym.getMember(), toString(this) +
|
|
1150 ": could not get the member for symbol " +
|
|
1151 toELFString(sym));
|
|
1152
|
|
1153 if (!seen.insert(c.getChildOffset()).second)
|
|
1154 return;
|
|
1155
|
|
1156 MemoryBufferRef mb =
|
|
1157 CHECK(c.getMemoryBufferRef(),
|
|
1158 toString(this) +
|
|
1159 ": could not get the buffer for the member defining symbol " +
|
|
1160 toELFString(sym));
|
|
1161
|
|
1162 if (tar && c.getParent()->isThin())
|
|
1163 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
|
|
1164
|
173
|
1165 InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
|
150
|
1166 file->groupId = groupId;
|
|
1167 parseFile(file);
|
|
1168 }
|
|
1169
|
173
|
1170 size_t ArchiveFile::getMemberCount() const {
|
|
1171 size_t count = 0;
|
|
1172 Error err = Error::success();
|
|
1173 for (const Archive::Child &c : file->children(err)) {
|
|
1174 (void)c;
|
|
1175 ++count;
|
|
1176 }
|
|
1177 // This function is used by --print-archive-stats=, where an error does not
|
|
1178 // really matter.
|
|
1179 consumeError(std::move(err));
|
|
1180 return count;
|
|
1181 }
|
|
1182
|
150
|
1183 unsigned SharedFile::vernauxNum;
|
|
1184
|
|
1185 // Parse the version definitions in the object file if present, and return a
|
|
1186 // vector whose nth element contains a pointer to the Elf_Verdef for version
|
|
1187 // identifier n. Version identifiers that are not definitions map to nullptr.
|
|
1188 template <typename ELFT>
|
|
1189 static std::vector<const void *> parseVerdefs(const uint8_t *base,
|
|
1190 const typename ELFT::Shdr *sec) {
|
|
1191 if (!sec)
|
|
1192 return {};
|
|
1193
|
|
1194 // We cannot determine the largest verdef identifier without inspecting
|
|
1195 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
|
|
1196 // sequentially starting from 1, so we predict that the largest identifier
|
|
1197 // will be verdefCount.
|
|
1198 unsigned verdefCount = sec->sh_info;
|
|
1199 std::vector<const void *> verdefs(verdefCount + 1);
|
|
1200
|
|
1201 // Build the Verdefs array by following the chain of Elf_Verdef objects
|
|
1202 // from the start of the .gnu.version_d section.
|
|
1203 const uint8_t *verdef = base + sec->sh_offset;
|
|
1204 for (unsigned i = 0; i != verdefCount; ++i) {
|
|
1205 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
|
|
1206 verdef += curVerdef->vd_next;
|
|
1207 unsigned verdefIndex = curVerdef->vd_ndx;
|
|
1208 verdefs.resize(verdefIndex + 1);
|
|
1209 verdefs[verdefIndex] = curVerdef;
|
|
1210 }
|
|
1211 return verdefs;
|
|
1212 }
|
|
1213
|
173
|
1214 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
|
|
1215 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
|
|
1216 // implement sophisticated error checking like in llvm-readobj because the value
|
|
1217 // of such diagnostics is low.
|
|
1218 template <typename ELFT>
|
|
1219 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
|
|
1220 const typename ELFT::Shdr *sec) {
|
|
1221 if (!sec)
|
|
1222 return {};
|
|
1223 std::vector<uint32_t> verneeds;
|
|
1224 ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(sec), this);
|
|
1225 const uint8_t *verneedBuf = data.begin();
|
|
1226 for (unsigned i = 0; i != sec->sh_info; ++i) {
|
|
1227 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end() ||
|
|
1228 uintptr_t(verneedBuf) % sizeof(uint32_t) != 0)
|
|
1229 fatal(toString(this) + " has an invalid Verneed");
|
|
1230 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
|
|
1231 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
|
|
1232 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
|
|
1233 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end() ||
|
|
1234 uintptr_t(vernauxBuf) % sizeof(uint32_t) != 0)
|
|
1235 fatal(toString(this) + " has an invalid Vernaux");
|
|
1236 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
|
|
1237 if (aux->vna_name >= this->stringTable.size())
|
|
1238 fatal(toString(this) + " has a Vernaux with an invalid vna_name");
|
|
1239 uint16_t version = aux->vna_other & VERSYM_VERSION;
|
|
1240 if (version >= verneeds.size())
|
|
1241 verneeds.resize(version + 1);
|
|
1242 verneeds[version] = aux->vna_name;
|
|
1243 vernauxBuf += aux->vna_next;
|
|
1244 }
|
|
1245 verneedBuf += vn->vn_next;
|
|
1246 }
|
|
1247 return verneeds;
|
|
1248 }
|
|
1249
|
150
|
1250 // We do not usually care about alignments of data in shared object
|
|
1251 // files because the loader takes care of it. However, if we promote a
|
|
1252 // DSO symbol to point to .bss due to copy relocation, we need to keep
|
|
1253 // the original alignment requirements. We infer it in this function.
|
|
1254 template <typename ELFT>
|
|
1255 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
|
|
1256 const typename ELFT::Sym &sym) {
|
|
1257 uint64_t ret = UINT64_MAX;
|
|
1258 if (sym.st_value)
|
|
1259 ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
|
|
1260 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
|
|
1261 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
|
|
1262 return (ret > UINT32_MAX) ? 0 : ret;
|
|
1263 }
|
|
1264
|
|
1265 // Fully parse the shared object file.
|
|
1266 //
|
|
1267 // This function parses symbol versions. If a DSO has version information,
|
|
1268 // the file has a ".gnu.version_d" section which contains symbol version
|
|
1269 // definitions. Each symbol is associated to one version through a table in
|
|
1270 // ".gnu.version" section. That table is a parallel array for the symbol
|
|
1271 // table, and each table entry contains an index in ".gnu.version_d".
|
|
1272 //
|
|
1273 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
|
|
1274 // VER_NDX_GLOBAL. There's no table entry for these special versions in
|
|
1275 // ".gnu.version_d".
|
|
1276 //
|
|
1277 // The file format for symbol versioning is perhaps a bit more complicated
|
|
1278 // than necessary, but you can easily understand the code if you wrap your
|
|
1279 // head around the data structure described above.
|
|
1280 template <class ELFT> void SharedFile::parse() {
|
|
1281 using Elf_Dyn = typename ELFT::Dyn;
|
|
1282 using Elf_Shdr = typename ELFT::Shdr;
|
|
1283 using Elf_Sym = typename ELFT::Sym;
|
|
1284 using Elf_Verdef = typename ELFT::Verdef;
|
|
1285 using Elf_Versym = typename ELFT::Versym;
|
|
1286
|
|
1287 ArrayRef<Elf_Dyn> dynamicTags;
|
|
1288 const ELFFile<ELFT> obj = this->getObj<ELFT>();
|
|
1289 ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
|
|
1290
|
|
1291 const Elf_Shdr *versymSec = nullptr;
|
|
1292 const Elf_Shdr *verdefSec = nullptr;
|
173
|
1293 const Elf_Shdr *verneedSec = nullptr;
|
150
|
1294
|
|
1295 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
|
|
1296 for (const Elf_Shdr &sec : sections) {
|
|
1297 switch (sec.sh_type) {
|
|
1298 default:
|
|
1299 continue;
|
|
1300 case SHT_DYNAMIC:
|
|
1301 dynamicTags =
|
|
1302 CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
|
|
1303 break;
|
|
1304 case SHT_GNU_versym:
|
|
1305 versymSec = &sec;
|
|
1306 break;
|
|
1307 case SHT_GNU_verdef:
|
|
1308 verdefSec = &sec;
|
|
1309 break;
|
173
|
1310 case SHT_GNU_verneed:
|
|
1311 verneedSec = &sec;
|
|
1312 break;
|
150
|
1313 }
|
|
1314 }
|
|
1315
|
|
1316 if (versymSec && numELFSyms == 0) {
|
|
1317 error("SHT_GNU_versym should be associated with symbol table");
|
|
1318 return;
|
|
1319 }
|
|
1320
|
|
1321 // Search for a DT_SONAME tag to initialize this->soName.
|
|
1322 for (const Elf_Dyn &dyn : dynamicTags) {
|
|
1323 if (dyn.d_tag == DT_NEEDED) {
|
|
1324 uint64_t val = dyn.getVal();
|
|
1325 if (val >= this->stringTable.size())
|
|
1326 fatal(toString(this) + ": invalid DT_NEEDED entry");
|
|
1327 dtNeeded.push_back(this->stringTable.data() + val);
|
|
1328 } else if (dyn.d_tag == DT_SONAME) {
|
|
1329 uint64_t val = dyn.getVal();
|
|
1330 if (val >= this->stringTable.size())
|
|
1331 fatal(toString(this) + ": invalid DT_SONAME entry");
|
|
1332 soName = this->stringTable.data() + val;
|
|
1333 }
|
|
1334 }
|
|
1335
|
|
1336 // DSOs are uniquified not by filename but by soname.
|
|
1337 DenseMap<StringRef, SharedFile *>::iterator it;
|
|
1338 bool wasInserted;
|
|
1339 std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
|
|
1340
|
|
1341 // If a DSO appears more than once on the command line with and without
|
|
1342 // --as-needed, --no-as-needed takes precedence over --as-needed because a
|
|
1343 // user can add an extra DSO with --no-as-needed to force it to be added to
|
|
1344 // the dependency list.
|
|
1345 it->second->isNeeded |= isNeeded;
|
|
1346 if (!wasInserted)
|
|
1347 return;
|
|
1348
|
|
1349 sharedFiles.push_back(this);
|
|
1350
|
|
1351 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
|
173
|
1352 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
|
150
|
1353
|
|
1354 // Parse ".gnu.version" section which is a parallel array for the symbol
|
|
1355 // table. If a given file doesn't have a ".gnu.version" section, we use
|
|
1356 // VER_NDX_GLOBAL.
|
|
1357 size_t size = numELFSyms - firstGlobal;
|
173
|
1358 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
|
150
|
1359 if (versymSec) {
|
|
1360 ArrayRef<Elf_Versym> versym =
|
|
1361 CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
|
|
1362 this)
|
|
1363 .slice(firstGlobal);
|
|
1364 for (size_t i = 0; i < size; ++i)
|
|
1365 versyms[i] = versym[i].vs_index;
|
|
1366 }
|
|
1367
|
|
1368 // System libraries can have a lot of symbols with versions. Using a
|
|
1369 // fixed buffer for computing the versions name (foo@ver) can save a
|
|
1370 // lot of allocations.
|
|
1371 SmallString<0> versionedNameBuffer;
|
|
1372
|
|
1373 // Add symbols to the symbol table.
|
|
1374 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
|
|
1375 for (size_t i = 0; i < syms.size(); ++i) {
|
|
1376 const Elf_Sym &sym = syms[i];
|
|
1377
|
|
1378 // ELF spec requires that all local symbols precede weak or global
|
|
1379 // symbols in each symbol table, and the index of first non-local symbol
|
|
1380 // is stored to sh_info. If a local symbol appears after some non-local
|
|
1381 // symbol, that's a violation of the spec.
|
|
1382 StringRef name = CHECK(sym.getName(this->stringTable), this);
|
|
1383 if (sym.getBinding() == STB_LOCAL) {
|
|
1384 warn("found local symbol '" + name +
|
|
1385 "' in global part of symbol table in file " + toString(this));
|
|
1386 continue;
|
|
1387 }
|
|
1388
|
173
|
1389 uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
|
150
|
1390 if (sym.isUndefined()) {
|
173
|
1391 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
|
|
1392 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
|
|
1393 if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
|
|
1394 if (idx >= verneeds.size()) {
|
|
1395 error("corrupt input file: version need index " + Twine(idx) +
|
|
1396 " for symbol " + name + " is out of bounds\n>>> defined in " +
|
|
1397 toString(this));
|
|
1398 continue;
|
|
1399 }
|
|
1400 StringRef verName = this->stringTable.data() + verneeds[idx];
|
|
1401 versionedNameBuffer.clear();
|
|
1402 name =
|
|
1403 saver.save((name + "@" + verName).toStringRef(versionedNameBuffer));
|
|
1404 }
|
150
|
1405 Symbol *s = symtab->addSymbol(
|
|
1406 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
|
|
1407 s->exportDynamic = true;
|
|
1408 continue;
|
|
1409 }
|
|
1410
|
|
1411 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
|
|
1412 // assigns VER_NDX_LOCAL to this section global symbol. Here is a
|
|
1413 // workaround for this bug.
|
|
1414 if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
|
|
1415 name == "_gp_disp")
|
|
1416 continue;
|
|
1417
|
|
1418 uint32_t alignment = getAlignment<ELFT>(sections, sym);
|
|
1419 if (!(versyms[i] & VERSYM_HIDDEN)) {
|
|
1420 symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
|
|
1421 sym.st_other, sym.getType(), sym.st_value,
|
|
1422 sym.st_size, alignment, idx});
|
|
1423 }
|
|
1424
|
|
1425 // Also add the symbol with the versioned name to handle undefined symbols
|
|
1426 // with explicit versions.
|
|
1427 if (idx == VER_NDX_GLOBAL)
|
|
1428 continue;
|
|
1429
|
|
1430 if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
|
|
1431 error("corrupt input file: version definition index " + Twine(idx) +
|
|
1432 " for symbol " + name + " is out of bounds\n>>> defined in " +
|
|
1433 toString(this));
|
|
1434 continue;
|
|
1435 }
|
|
1436
|
|
1437 StringRef verName =
|
|
1438 this->stringTable.data() +
|
|
1439 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
|
|
1440 versionedNameBuffer.clear();
|
|
1441 name = (name + "@" + verName).toStringRef(versionedNameBuffer);
|
|
1442 symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
|
|
1443 sym.st_other, sym.getType(), sym.st_value,
|
|
1444 sym.st_size, alignment, idx});
|
|
1445 }
|
|
1446 }
|
|
1447
|
|
1448 static ELFKind getBitcodeELFKind(const Triple &t) {
|
|
1449 if (t.isLittleEndian())
|
|
1450 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
|
|
1451 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
|
|
1452 }
|
|
1453
|
|
1454 static uint8_t getBitcodeMachineKind(StringRef path, const Triple &t) {
|
|
1455 switch (t.getArch()) {
|
|
1456 case Triple::aarch64:
|
|
1457 return EM_AARCH64;
|
|
1458 case Triple::amdgcn:
|
|
1459 case Triple::r600:
|
|
1460 return EM_AMDGPU;
|
|
1461 case Triple::arm:
|
|
1462 case Triple::thumb:
|
|
1463 return EM_ARM;
|
|
1464 case Triple::avr:
|
|
1465 return EM_AVR;
|
|
1466 case Triple::mips:
|
|
1467 case Triple::mipsel:
|
|
1468 case Triple::mips64:
|
|
1469 case Triple::mips64el:
|
|
1470 return EM_MIPS;
|
|
1471 case Triple::msp430:
|
|
1472 return EM_MSP430;
|
|
1473 case Triple::ppc:
|
|
1474 return EM_PPC;
|
|
1475 case Triple::ppc64:
|
|
1476 case Triple::ppc64le:
|
|
1477 return EM_PPC64;
|
|
1478 case Triple::riscv32:
|
|
1479 case Triple::riscv64:
|
|
1480 return EM_RISCV;
|
|
1481 case Triple::x86:
|
|
1482 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
|
|
1483 case Triple::x86_64:
|
|
1484 return EM_X86_64;
|
|
1485 default:
|
|
1486 error(path + ": could not infer e_machine from bitcode target triple " +
|
|
1487 t.str());
|
|
1488 return EM_NONE;
|
|
1489 }
|
|
1490 }
|
|
1491
|
|
1492 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
|
|
1493 uint64_t offsetInArchive)
|
|
1494 : InputFile(BitcodeKind, mb) {
|
|
1495 this->archiveName = std::string(archiveName);
|
|
1496
|
|
1497 std::string path = mb.getBufferIdentifier().str();
|
|
1498 if (config->thinLTOIndexOnly)
|
|
1499 path = replaceThinLTOSuffix(mb.getBufferIdentifier());
|
|
1500
|
|
1501 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
|
|
1502 // name. If two archives define two members with the same name, this
|
|
1503 // causes a collision which result in only one of the objects being taken
|
|
1504 // into consideration at LTO time (which very likely causes undefined
|
|
1505 // symbols later in the link stage). So we append file offset to make
|
|
1506 // filename unique.
|
173
|
1507 StringRef name =
|
|
1508 archiveName.empty()
|
|
1509 ? saver.save(path)
|
|
1510 : saver.save(archiveName + "(" + path::filename(path) + " at " +
|
|
1511 utostr(offsetInArchive) + ")");
|
150
|
1512 MemoryBufferRef mbref(mb.getBuffer(), name);
|
|
1513
|
|
1514 obj = CHECK(lto::InputFile::create(mbref), this);
|
|
1515
|
|
1516 Triple t(obj->getTargetTriple());
|
|
1517 ekind = getBitcodeELFKind(t);
|
|
1518 emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
|
|
1519 }
|
|
1520
|
|
1521 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
|
|
1522 switch (gvVisibility) {
|
|
1523 case GlobalValue::DefaultVisibility:
|
|
1524 return STV_DEFAULT;
|
|
1525 case GlobalValue::HiddenVisibility:
|
|
1526 return STV_HIDDEN;
|
|
1527 case GlobalValue::ProtectedVisibility:
|
|
1528 return STV_PROTECTED;
|
|
1529 }
|
|
1530 llvm_unreachable("unknown visibility");
|
|
1531 }
|
|
1532
|
|
1533 template <class ELFT>
|
|
1534 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
|
|
1535 const lto::InputFile::Symbol &objSym,
|
|
1536 BitcodeFile &f) {
|
|
1537 StringRef name = saver.save(objSym.getName());
|
|
1538 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
|
|
1539 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
|
|
1540 uint8_t visibility = mapVisibility(objSym.getVisibility());
|
|
1541 bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
|
|
1542
|
|
1543 int c = objSym.getComdatIndex();
|
|
1544 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
|
|
1545 Undefined newSym(&f, name, binding, visibility, type);
|
|
1546 if (canOmitFromDynSym)
|
|
1547 newSym.exportDynamic = false;
|
|
1548 Symbol *ret = symtab->addSymbol(newSym);
|
|
1549 ret->referenced = true;
|
|
1550 return ret;
|
|
1551 }
|
|
1552
|
|
1553 if (objSym.isCommon())
|
|
1554 return symtab->addSymbol(
|
|
1555 CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
|
|
1556 objSym.getCommonAlignment(), objSym.getCommonSize()});
|
|
1557
|
|
1558 Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
|
|
1559 if (canOmitFromDynSym)
|
|
1560 newSym.exportDynamic = false;
|
|
1561 return symtab->addSymbol(newSym);
|
|
1562 }
|
|
1563
|
|
1564 template <class ELFT> void BitcodeFile::parse() {
|
|
1565 std::vector<bool> keptComdats;
|
|
1566 for (StringRef s : obj->getComdatTable())
|
|
1567 keptComdats.push_back(
|
|
1568 symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
|
|
1569
|
|
1570 for (const lto::InputFile::Symbol &objSym : obj->symbols())
|
|
1571 symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
|
|
1572
|
|
1573 for (auto l : obj->getDependentLibraries())
|
|
1574 addDependentLibrary(l, this);
|
|
1575 }
|
|
1576
|
|
1577 void BinaryFile::parse() {
|
|
1578 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
|
|
1579 auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
|
|
1580 8, data, ".data");
|
|
1581 sections.push_back(section);
|
|
1582
|
|
1583 // For each input file foo that is embedded to a result as a binary
|
|
1584 // blob, we define _binary_foo_{start,end,size} symbols, so that
|
|
1585 // user programs can access blobs by name. Non-alphanumeric
|
|
1586 // characters in a filename are replaced with underscore.
|
|
1587 std::string s = "_binary_" + mb.getBufferIdentifier().str();
|
|
1588 for (size_t i = 0; i < s.size(); ++i)
|
|
1589 if (!isAlnum(s[i]))
|
|
1590 s[i] = '_';
|
|
1591
|
|
1592 symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
|
|
1593 STV_DEFAULT, STT_OBJECT, 0, 0, section});
|
|
1594 symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
|
|
1595 STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
|
|
1596 symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
|
|
1597 STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
|
|
1598 }
|
|
1599
|
173
|
1600 InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
|
|
1601 uint64_t offsetInArchive) {
|
150
|
1602 if (isBitcode(mb))
|
|
1603 return make<BitcodeFile>(mb, archiveName, offsetInArchive);
|
|
1604
|
|
1605 switch (getELFKind(mb, archiveName)) {
|
|
1606 case ELF32LEKind:
|
|
1607 return make<ObjFile<ELF32LE>>(mb, archiveName);
|
|
1608 case ELF32BEKind:
|
|
1609 return make<ObjFile<ELF32BE>>(mb, archiveName);
|
|
1610 case ELF64LEKind:
|
|
1611 return make<ObjFile<ELF64LE>>(mb, archiveName);
|
|
1612 case ELF64BEKind:
|
|
1613 return make<ObjFile<ELF64BE>>(mb, archiveName);
|
|
1614 default:
|
|
1615 llvm_unreachable("getELFKind");
|
|
1616 }
|
|
1617 }
|
|
1618
|
|
1619 void LazyObjFile::fetch() {
|
|
1620 if (mb.getBuffer().empty())
|
|
1621 return;
|
|
1622
|
|
1623 InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
|
|
1624 file->groupId = groupId;
|
|
1625
|
|
1626 mb = {};
|
|
1627
|
|
1628 // Copy symbol vector so that the new InputFile doesn't have to
|
|
1629 // insert the same defined symbols to the symbol table again.
|
|
1630 file->symbols = std::move(symbols);
|
|
1631
|
|
1632 parseFile(file);
|
|
1633 }
|
|
1634
|
|
1635 template <class ELFT> void LazyObjFile::parse() {
|
|
1636 using Elf_Sym = typename ELFT::Sym;
|
|
1637
|
|
1638 // A lazy object file wraps either a bitcode file or an ELF file.
|
|
1639 if (isBitcode(this->mb)) {
|
|
1640 std::unique_ptr<lto::InputFile> obj =
|
|
1641 CHECK(lto::InputFile::create(this->mb), this);
|
|
1642 for (const lto::InputFile::Symbol &sym : obj->symbols()) {
|
|
1643 if (sym.isUndefined())
|
|
1644 continue;
|
|
1645 symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
|
|
1646 }
|
|
1647 return;
|
|
1648 }
|
|
1649
|
|
1650 if (getELFKind(this->mb, archiveName) != config->ekind) {
|
|
1651 error("incompatible file: " + this->mb.getBufferIdentifier());
|
|
1652 return;
|
|
1653 }
|
|
1654
|
|
1655 // Find a symbol table.
|
|
1656 ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
|
|
1657 ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
|
|
1658
|
|
1659 for (const typename ELFT::Shdr &sec : sections) {
|
|
1660 if (sec.sh_type != SHT_SYMTAB)
|
|
1661 continue;
|
|
1662
|
|
1663 // A symbol table is found.
|
|
1664 ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
|
|
1665 uint32_t firstGlobal = sec.sh_info;
|
|
1666 StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
|
|
1667 this->symbols.resize(eSyms.size());
|
|
1668
|
|
1669 // Get existing symbols or insert placeholder symbols.
|
|
1670 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
|
|
1671 if (eSyms[i].st_shndx != SHN_UNDEF)
|
|
1672 this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
|
|
1673
|
|
1674 // Replace existing symbols with LazyObject symbols.
|
|
1675 //
|
|
1676 // resolve() may trigger this->fetch() if an existing symbol is an
|
|
1677 // undefined symbol. If that happens, this LazyObjFile has served
|
|
1678 // its purpose, and we can exit from the loop early.
|
|
1679 for (Symbol *sym : this->symbols) {
|
|
1680 if (!sym)
|
|
1681 continue;
|
|
1682 sym->resolve(LazyObject{*this, sym->getName()});
|
|
1683
|
|
1684 // MemoryBuffer is emptied if this file is instantiated as ObjFile.
|
|
1685 if (mb.getBuffer().empty())
|
|
1686 return;
|
|
1687 }
|
|
1688 return;
|
|
1689 }
|
|
1690 }
|
|
1691
|
173
|
1692 std::string elf::replaceThinLTOSuffix(StringRef path) {
|
150
|
1693 StringRef suffix = config->thinLTOObjectSuffixReplace.first;
|
|
1694 StringRef repl = config->thinLTOObjectSuffixReplace.second;
|
|
1695
|
|
1696 if (path.consume_back(suffix))
|
|
1697 return (path + repl).str();
|
|
1698 return std::string(path);
|
|
1699 }
|
|
1700
|
|
1701 template void BitcodeFile::parse<ELF32LE>();
|
|
1702 template void BitcodeFile::parse<ELF32BE>();
|
|
1703 template void BitcodeFile::parse<ELF64LE>();
|
|
1704 template void BitcodeFile::parse<ELF64BE>();
|
|
1705
|
|
1706 template void LazyObjFile::parse<ELF32LE>();
|
|
1707 template void LazyObjFile::parse<ELF32BE>();
|
|
1708 template void LazyObjFile::parse<ELF64LE>();
|
|
1709 template void LazyObjFile::parse<ELF64BE>();
|
|
1710
|
173
|
1711 template class elf::ObjFile<ELF32LE>;
|
|
1712 template class elf::ObjFile<ELF32BE>;
|
|
1713 template class elf::ObjFile<ELF64LE>;
|
|
1714 template class elf::ObjFile<ELF64BE>;
|
150
|
1715
|
|
1716 template void SharedFile::parse<ELF32LE>();
|
|
1717 template void SharedFile::parse<ELF32BE>();
|
|
1718 template void SharedFile::parse<ELF64LE>();
|
|
1719 template void SharedFile::parse<ELF64BE>();
|