Bug Summary

File:tools/lld/ELF/InputFiles.cpp
Warning:line 878, column 24
The result of the left shift is undefined due to shifting by '64', which is greater or equal to the width of type 'unsigned long long'

Annotated Source Code

[?] Use j/k keys for keyboard navigation

1//===- InputFiles.cpp -----------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "InputFiles.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/ErrorHandler.h"
17#include "lld/Common/Memory.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/CodeGen/Analysis.h"
20#include "llvm/DebugInfo/DWARF/DWARFContext.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/Path.h"
29#include "llvm/Support/TarWriter.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace llvm;
33using namespace llvm::ELF;
34using namespace llvm::object;
35using namespace llvm::sys;
36using namespace llvm::sys::fs;
37
38using namespace lld;
39using namespace lld::elf;
40
41std::vector<BinaryFile *> elf::BinaryFiles;
42std::vector<BitcodeFile *> elf::BitcodeFiles;
43std::vector<InputFile *> elf::ObjectFiles;
44std::vector<InputFile *> elf::SharedFiles;
45
46TarWriter *elf::Tar;
47
48InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
49
50Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
51 // The --chroot option changes our virtual root directory.
52 // This is useful when you are dealing with files created by --reproduce.
53 if (!Config->Chroot.empty() && Path.startswith("/"))
54 Path = Saver.save(Config->Chroot + Path);
55
56 log(Path);
57
58 auto MBOrErr = MemoryBuffer::getFile(Path);
59 if (auto EC = MBOrErr.getError()) {
60 error("cannot open " + Path + ": " + EC.message());
61 return None;
62 }
63
64 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
65 MemoryBufferRef MBRef = MB->getMemBufferRef();
66 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
67
68 if (Tar)
69 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
70 return MBRef;
71}
72
73// Concatenates arguments to construct a string representing an error location.
74static std::string createFileLineMsg(StringRef Path, unsigned Line) {
75 std::string Filename = path::filename(Path);
76 std::string Lineno = ":" + std::to_string(Line);
77 if (Filename == Path)
78 return Filename + Lineno;
79 return Filename + Lineno + " (" + Path.str() + Lineno + ")";
80}
81
82template <class ELFT>
83static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym,
84 InputSectionBase &Sec, uint64_t Offset) {
85 // In DWARF, functions and variables are stored to different places.
86 // First, lookup a function for a given offset.
87 if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset))
88 return createFileLineMsg(Info->FileName, Info->Line);
89
90 // If it failed, lookup again as a variable.
91 if (Optional<std::pair<std::string, unsigned>> FileLine =
92 File.getVariableLoc(Sym.getName()))
93 return createFileLineMsg(FileLine->first, FileLine->second);
94
95 // File.SourceFile contains STT_FILE symbol, and that is a last resort.
96 return File.SourceFile;
97}
98
99std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
100 uint64_t Offset) {
101 if (kind() != ObjKind)
102 return "";
103 switch (Config->EKind) {
104 default:
105 llvm_unreachable("Invalid kind")::llvm::llvm_unreachable_internal("Invalid kind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 105)
;
106 case ELF32LEKind:
107 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
108 case ELF32BEKind:
109 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
110 case ELF64LEKind:
111 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
112 case ELF64BEKind:
113 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
114 }
115}
116
117template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
118 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(this));
119 const DWARFObject &Obj = Dwarf.getDWARFObj();
120 DwarfLine.reset(new DWARFDebugLine);
121 DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE,
122 Config->Wordsize);
123
124 // The second parameter is offset in .debug_line section
125 // for compilation unit (CU) of interest. We have only one
126 // CU (object file), so offset is always 0.
127 // FIXME: Provide the associated DWARFUnit if there is one. DWARF v5
128 // needs it in order to find indirect strings.
129 const DWARFDebugLine::LineTable *LT =
130 DwarfLine->getOrParseLineTable(LineData, 0, nullptr);
131
132 // Return if there is no debug information about CU available.
133 if (!Dwarf.getNumCompileUnits())
134 return;
135
136 // Loop over variable records and insert them to VariableLoc.
137 DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0);
138 for (const auto &Entry : CU->dies()) {
139 DWARFDie Die(CU, &Entry);
140 // Skip all tags that are not variables.
141 if (Die.getTag() != dwarf::DW_TAG_variable)
142 continue;
143
144 // Skip if a local variable because we don't need them for generating error
145 // messages. In general, only non-local symbols can fail to be linked.
146 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
147 continue;
148
149 // Get the source filename index for the variable.
150 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
151 if (!LT->hasFileAtIndex(File))
152 continue;
153
154 // Get the line number on which the variable is declared.
155 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
156
157 // Get the name of the variable and add the collected information to
158 // VariableLoc. Usually Name is non-empty, but it can be empty if the input
159 // object file lacks some debug info.
160 StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), "");
161 if (!Name.empty())
162 VariableLoc.insert({Name, {File, Line}});
163 }
164}
165
166// Returns the pair of file name and line number describing location of data
167// object (variable, array, etc) definition.
168template <class ELFT>
169Optional<std::pair<std::string, unsigned>>
170ObjFile<ELFT>::getVariableLoc(StringRef Name) {
171 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
172
173 // There is always only one CU so it's offset is 0.
174 const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0);
175 if (!LT)
176 return None;
177
178 // Return if we have no debug information about data object.
179 auto It = VariableLoc.find(Name);
180 if (It == VariableLoc.end())
181 return None;
182
183 // Take file name string from line table.
184 std::string FileName;
185 if (!LT->getFileNameByIndex(
186 It->second.first /* File */, nullptr,
187 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
188 return None;
189
190 return std::make_pair(FileName, It->second.second /*Line*/);
191}
192
193// Returns source line information for a given offset
194// using DWARF debug info.
195template <class ELFT>
196Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
197 uint64_t Offset) {
198 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
199
200 // The offset to CU is 0.
201 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
202 if (!Tbl)
203 return None;
204
205 // Use fake address calcuated by adding section file offset and offset in
206 // section. See comments for ObjectInfo class.
207 DILineInfo Info;
208 Tbl->getFileLineInfoForAddress(
209 S->getOffsetInFile() + Offset, nullptr,
210 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
211 if (Info.Line == 0)
212 return None;
213 return Info;
214}
215
216// Returns source line information for a given offset
217// using DWARF debug info.
218template <class ELFT>
219std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
220 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
221 return Info->FileName + ":" + std::to_string(Info->Line);
222 return "";
223}
224
225// Returns "<internal>", "foo.a(bar.o)" or "baz.o".
226std::string lld::toString(const InputFile *F) {
227 if (!F)
228 return "<internal>";
229
230 if (F->ToStringCache.empty()) {
231 if (F->ArchiveName.empty())
232 F->ToStringCache = F->getName();
233 else
234 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
235 }
236 return F->ToStringCache;
237}
238
239template <class ELFT>
240ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
241 if (ELFT::TargetEndianness == support::little)
242 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
243 else
244 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
245
246 EMachine = getObj().getHeader()->e_machine;
247 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
248}
249
250template <class ELFT>
251typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
252 return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
253}
254
255template <class ELFT>
256uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
257 return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this)check2(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX
), [&] { return toString(this); })
;
258}
259
260template <class ELFT>
261void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
262 const Elf_Shdr *Symtab) {
263 FirstNonLocal = Symtab->sh_info;
264 ELFSyms = CHECK(getObj().symbols(Symtab), this)check2(getObj().symbols(Symtab), [&] { return toString(this
); })
;
265 if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
266 fatal(toString(this) + ": invalid sh_info in symbol table");
267
268 StringTable =
269 CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this)check2(getObj().getStringTableForSymtab(*Symtab, Sections), [
&] { return toString(this); })
;
270}
271
272template <class ELFT>
273ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
274 : ELFFileBase<ELFT>(Base::ObjKind, M) {
275 this->ArchiveName = ArchiveName;
276}
277
278template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
279 if (this->Symbols.empty())
280 return {};
281 return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
282}
283
284template <class ELFT>
285void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
286 // Read section and symbol tables.
287 initializeSections(ComdatGroups);
288 initializeSymbols();
289}
290
291// Sections with SHT_GROUP and comdat bits define comdat section groups.
292// They are identified and deduplicated by group name. This function
293// returns a group name.
294template <class ELFT>
295StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
296 const Elf_Shdr &Sec) {
297 // Group signatures are stored as symbol names in object files.
298 // sh_info contains a symbol index, so we fetch a symbol and read its name.
299 if (this->ELFSyms.empty())
300 this->initSymtab(
301 Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this)check2(object::getSection<ELFT>(Sections, Sec.sh_link),
[&] { return toString(this); })
);
302
303 const Elf_Sym *Sym =
304 CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this)check2(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info
), [&] { return toString(this); })
;
305 StringRef Signature = CHECK(Sym->getName(this->StringTable), this)check2(Sym->getName(this->StringTable), [&] { return
toString(this); })
;
306
307 // As a special case, if a symbol is a section symbol and has no name,
308 // we use a section name as a signature.
309 //
310 // Such SHT_GROUP sections are invalid from the perspective of the ELF
311 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
312 // older produce such sections as outputs for the -r option, so we need
313 // a bug-compatibility.
314 if (Signature.empty() && Sym->getType() == STT_SECTION)
315 return getSectionName(Sec);
316 return Signature;
317}
318
319template <class ELFT>
320ArrayRef<typename ObjFile<ELFT>::Elf_Word>
321ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
322 const ELFFile<ELFT> &Obj = this->getObj();
323 ArrayRef<Elf_Word> Entries =
324 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this)check2(Obj.template getSectionContentsAsArray<Elf_Word>
(&Sec), [&] { return toString(this); })
;
325 if (Entries.empty() || Entries[0] != GRP_COMDAT)
326 fatal(toString(this) + ": unsupported SHT_GROUP format");
327 return Entries.slice(1);
328}
329
330template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
331 // We don't merge sections if -O0 (default is -O1). This makes sometimes
332 // the linker significantly faster, although the output will be bigger.
333 if (Config->Optimize == 0)
334 return false;
335
336 // A mergeable section with size 0 is useless because they don't have
337 // any data to merge. A mergeable string section with size 0 can be
338 // argued as invalid because it doesn't end with a null character.
339 // We'll avoid a mess by handling them as if they were non-mergeable.
340 if (Sec.sh_size == 0)
341 return false;
342
343 // Check for sh_entsize. The ELF spec is not clear about the zero
344 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
345 // the section does not hold a table of fixed-size entries". We know
346 // that Rust 1.13 produces a string mergeable section with a zero
347 // sh_entsize. Here we just accept it rather than being picky about it.
348 uint64_t EntSize = Sec.sh_entsize;
349 if (EntSize == 0)
350 return false;
351 if (Sec.sh_size % EntSize)
352 fatal(toString(this) +
353 ": SHF_MERGE section size must be a multiple of sh_entsize");
354
355 uint64_t Flags = Sec.sh_flags;
356 if (!(Flags & SHF_MERGE))
357 return false;
358 if (Flags & SHF_WRITE)
359 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
360
361 return true;
362}
363
364template <class ELFT>
365void ObjFile<ELFT>::initializeSections(
366 DenseSet<CachedHashStringRef> &ComdatGroups) {
367 const ELFFile<ELFT> &Obj = this->getObj();
368
369 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this)check2(this->getObj().sections(), [&] { return toString
(this); })
;
370 uint64_t Size = ObjSections.size();
371 this->Sections.resize(Size);
372 this->SectionStringTable =
373 CHECK(Obj.getSectionStringTable(ObjSections), this)check2(Obj.getSectionStringTable(ObjSections), [&] { return
toString(this); })
;
374
375 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
376 if (this->Sections[I] == &InputSection::Discarded)
377 continue;
378 const Elf_Shdr &Sec = ObjSections[I];
379
380 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
381 // if -r is given, we'll let the final link discard such sections.
382 // This is compatible with GNU.
383 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
384 this->Sections[I] = &InputSection::Discarded;
385 continue;
386 }
387
388 switch (Sec.sh_type) {
389 case SHT_GROUP: {
390 // De-duplicate section groups by their signatures.
391 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
392 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
393 this->Sections[I] = &InputSection::Discarded;
394
395 // If it is a new section group, we want to keep group members.
396 // Group leader sections, which contain indices of group members, are
397 // discarded because they are useless beyond this point. The only
398 // exception is the -r option because in order to produce re-linkable
399 // object files, we want to pass through basically everything.
400 if (IsNew) {
401 if (Config->Relocatable)
402 this->Sections[I] = createInputSection(Sec);
403 continue;
404 }
405
406 // Otherwise, discard group members.
407 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
408 if (SecIndex >= Size)
409 fatal(toString(this) +
410 ": invalid section index in group: " + Twine(SecIndex));
411 this->Sections[SecIndex] = &InputSection::Discarded;
412 }
413 break;
414 }
415 case SHT_SYMTAB:
416 this->initSymtab(ObjSections, &Sec);
417 break;
418 case SHT_SYMTAB_SHNDX:
419 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this)check2(Obj.getSHNDXTable(Sec, ObjSections), [&] { return toString
(this); })
;
420 break;
421 case SHT_STRTAB:
422 case SHT_NULL:
423 break;
424 default:
425 this->Sections[I] = createInputSection(Sec);
426 }
427
428 // .ARM.exidx sections have a reverse dependency on the InputSection they
429 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
430 if (Sec.sh_flags & SHF_LINK_ORDER) {
431 if (Sec.sh_link >= this->Sections.size())
432 fatal(toString(this) +
433 ": invalid sh_link index: " + Twine(Sec.sh_link));
434 this->Sections[Sec.sh_link]->DependentSections.push_back(
435 cast<InputSection>(this->Sections[I]));
436 }
437 }
438}
439
440// The ARM support in lld makes some use of instructions that are not available
441// on all ARM architectures. Namely:
442// - Use of BLX instruction for interworking between ARM and Thumb state.
443// - Use of the extended Thumb branch encoding in relocation.
444// - Use of the MOVT/MOVW instructions in Thumb Thunks.
445// The ARM Attributes section contains information about the architecture chosen
446// at compile time. We follow the convention that if at least one input object
447// is compiled with an architecture that supports these features then lld is
448// permitted to use them.
449static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
450 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
451 return;
452 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
453 switch (Arch) {
454 case ARMBuildAttrs::Pre_v4:
455 case ARMBuildAttrs::v4:
456 case ARMBuildAttrs::v4T:
457 // Architectures prior to v5 do not support BLX instruction
458 break;
459 case ARMBuildAttrs::v5T:
460 case ARMBuildAttrs::v5TE:
461 case ARMBuildAttrs::v5TEJ:
462 case ARMBuildAttrs::v6:
463 case ARMBuildAttrs::v6KZ:
464 case ARMBuildAttrs::v6K:
465 Config->ARMHasBlx = true;
466 // Architectures used in pre-Cortex processors do not support
467 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
468 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
469 break;
470 default:
471 // All other Architectures have BLX and extended branch encoding
472 Config->ARMHasBlx = true;
473 Config->ARMJ1J2BranchEncoding = true;
474 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
475 // All Architectures used in Cortex processors with the exception
476 // of v6-M and v6S-M have the MOVT and MOVW instructions.
477 Config->ARMHasMovtMovw = true;
478 break;
479 }
480}
481
482template <class ELFT>
483InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
484 uint32_t Idx = Sec.sh_info;
485 if (Idx >= this->Sections.size())
486 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
487 InputSectionBase *Target = this->Sections[Idx];
488
489 // Strictly speaking, a relocation section must be included in the
490 // group of the section it relocates. However, LLVM 3.3 and earlier
491 // would fail to do so, so we gracefully handle that case.
492 if (Target == &InputSection::Discarded)
493 return nullptr;
494
495 if (!Target)
496 fatal(toString(this) + ": unsupported relocation reference");
497 return Target;
498}
499
500// Create a regular InputSection class that has the same contents
501// as a given section.
502static InputSection *toRegularSection(MergeInputSection *Sec) {
503 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
504 Sec->Data, Sec->Name);
505}
506
507template <class ELFT>
508InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
509 StringRef Name = getSectionName(Sec);
510
511 switch (Sec.sh_type) {
512 case SHT_ARM_ATTRIBUTES: {
513 if (Config->EMachine != EM_ARM)
514 break;
515 ARMAttributeParser Attributes;
516 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
517 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
518 updateSupportedARMFeatures(Attributes);
519 // FIXME: Retain the first attribute section we see. The eglibc ARM
520 // dynamic loaders require the presence of an attribute section for dlopen
521 // to work. In a full implementation we would merge all attribute sections.
522 if (InX::ARMAttributes == nullptr) {
523 InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
524 return InX::ARMAttributes;
525 }
526 return &InputSection::Discarded;
527 }
528 case SHT_RELA:
529 case SHT_REL: {
530 // Find the relocation target section and associate this
531 // section with it. Target can be discarded, for example
532 // if it is a duplicated member of SHT_GROUP section, we
533 // do not create or proccess relocatable sections then.
534 InputSectionBase *Target = getRelocTarget(Sec);
535 if (!Target)
536 return nullptr;
537
538 // This section contains relocation information.
539 // If -r is given, we do not interpret or apply relocation
540 // but just copy relocation sections to output.
541 if (Config->Relocatable)
542 return make<InputSection>(*this, Sec, Name);
543
544 if (Target->FirstRelocation)
545 fatal(toString(this) +
546 ": multiple relocation sections to one section are not supported");
547
548 // Mergeable sections with relocations are tricky because relocations
549 // need to be taken into account when comparing section contents for
550 // merging. It's not worth supporting such mergeable sections because
551 // they are rare and it'd complicates the internal design (we usually
552 // have to determine if two sections are mergeable early in the link
553 // process much before applying relocations). We simply handle mergeable
554 // sections with relocations as non-mergeable.
555 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
556 Target = toRegularSection(MS);
557 this->Sections[Sec.sh_info] = Target;
558 }
559
560 size_t NumRelocations;
561 if (Sec.sh_type == SHT_RELA) {
562 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this)check2(this->getObj().relas(&Sec), [&] { return toString
(this); })
;
563 Target->FirstRelocation = Rels.begin();
564 NumRelocations = Rels.size();
565 Target->AreRelocsRela = true;
566 } else {
567 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this)check2(this->getObj().rels(&Sec), [&] { return toString
(this); })
;
568 Target->FirstRelocation = Rels.begin();
569 NumRelocations = Rels.size();
570 Target->AreRelocsRela = false;
571 }
572 assert(isUInt<31>(NumRelocations))(static_cast <bool> (isUInt<31>(NumRelocations)) ?
void (0) : __assert_fail ("isUInt<31>(NumRelocations)"
, "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 572, __extension__ __PRETTY_FUNCTION__))
;
573 Target->NumRelocations = NumRelocations;
574
575 // Relocation sections processed by the linker are usually removed
576 // from the output, so returning `nullptr` for the normal case.
577 // However, if -emit-relocs is given, we need to leave them in the output.
578 // (Some post link analysis tools need this information.)
579 if (Config->EmitRelocs) {
580 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
581 // We will not emit relocation section if target was discarded.
582 Target->DependentSections.push_back(RelocSec);
583 return RelocSec;
584 }
585 return nullptr;
586 }
587 }
588
589 // The GNU linker uses .note.GNU-stack section as a marker indicating
590 // that the code in the object file does not expect that the stack is
591 // executable (in terms of NX bit). If all input files have the marker,
592 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
593 // make the stack non-executable. Most object files have this section as
594 // of 2017.
595 //
596 // But making the stack non-executable is a norm today for security
597 // reasons. Failure to do so may result in a serious security issue.
598 // Therefore, we make LLD always add PT_GNU_STACK unless it is
599 // explicitly told to do otherwise (by -z execstack). Because the stack
600 // executable-ness is controlled solely by command line options,
601 // .note.GNU-stack sections are simply ignored.
602 if (Name == ".note.GNU-stack")
603 return &InputSection::Discarded;
604
605 // Split stacks is a feature to support a discontiguous stack. At least
606 // as of 2017, it seems that the feature is not being used widely.
607 // Only GNU gold supports that. We don't. For the details about that,
608 // see https://gcc.gnu.org/wiki/SplitStacks
609 if (Name == ".note.GNU-split-stack") {
610 error(toString(this) +
611 ": object file compiled with -fsplit-stack is not supported");
612 return &InputSection::Discarded;
613 }
614
615 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
616 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
617 // sections. Drop those sections to avoid duplicate symbol errors.
618 // FIXME: This is glibc PR20543, we should remove this hack once that has been
619 // fixed for a while.
620 if (Name.startswith(".gnu.linkonce."))
621 return &InputSection::Discarded;
622
623 // The linker merges EH (exception handling) frames and creates a
624 // .eh_frame_hdr section for runtime. So we handle them with a special
625 // class. For relocatable outputs, they are just passed through.
626 if (Name == ".eh_frame" && !Config->Relocatable)
627 return make<EhInputSection>(*this, Sec, Name);
628
629 if (shouldMerge(Sec))
630 return make<MergeInputSection>(*this, Sec, Name);
631 return make<InputSection>(*this, Sec, Name);
632}
633
634template <class ELFT>
635StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
636 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this)check2(this->getObj().getSectionName(&Sec, SectionStringTable
), [&] { return toString(this); })
;
637}
638
639template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
640 this->Symbols.reserve(this->ELFSyms.size());
641 for (const Elf_Sym &Sym : this->ELFSyms)
642 this->Symbols.push_back(createSymbol(&Sym));
643}
644
645template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
646 int Binding = Sym->getBinding();
647
648 uint32_t SecIdx = this->getSectionIndex(*Sym);
649 if (SecIdx >= this->Sections.size())
650 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
651
652 InputSectionBase *Sec = this->Sections[SecIdx];
653 uint8_t StOther = Sym->st_other;
654 uint8_t Type = Sym->getType();
655 uint64_t Value = Sym->st_value;
656 uint64_t Size = Sym->st_size;
657
658 if (Binding == STB_LOCAL) {
659 if (Sym->getType() == STT_FILE)
660 SourceFile = CHECK(Sym->getName(this->StringTable), this)check2(Sym->getName(this->StringTable), [&] { return
toString(this); })
;
661
662 if (this->StringTable.size() <= Sym->st_name)
663 fatal(toString(this) + ": invalid symbol name offset");
664
665 StringRefZ Name = this->StringTable.data() + Sym->st_name;
666 if (Sym->st_shndx == SHN_UNDEF)
667 return make<Undefined>(this, Name, Binding, StOther, Type);
668
669 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
670 }
671
672 StringRef Name = CHECK(Sym->getName(this->StringTable), this)check2(Sym->getName(this->StringTable), [&] { return
toString(this); })
;
673
674 switch (Sym->st_shndx) {
675 case SHN_UNDEF:
676 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
677 /*CanOmitFromDynSym=*/false, this);
678 case SHN_COMMON:
679 if (Value == 0 || Value >= UINT32_MAX(4294967295U))
680 fatal(toString(this) + ": common symbol '" + Name +
681 "' has invalid alignment: " + Twine(Value));
682 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
683 }
684
685 switch (Binding) {
686 default:
687 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
688 case STB_GLOBAL:
689 case STB_WEAK:
690 case STB_GNU_UNIQUE:
691 if (Sec == &InputSection::Discarded)
692 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
693 /*CanOmitFromDynSym=*/false, this);
694 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
695 this);
696 }
697}
698
699ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
700 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
701 File(std::move(File)) {}
702
703template <class ELFT> void ArchiveFile::parse() {
704 Symbols.reserve(File->getNumberOfSymbols());
705 for (const Archive::Symbol &Sym : File->symbols())
706 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
707}
708
709// Returns a buffer pointing to a member file containing a given symbol.
710std::pair<MemoryBufferRef, uint64_t>
711ArchiveFile::getMember(const Archive::Symbol *Sym) {
712 Archive::Child C =
713 CHECK(Sym->getMember(), toString(this) +check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
714 ": could not get the member for symbol " +check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
715 Sym->getName())check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
;
716
717 if (!Seen.insert(C.getChildOffset()).second)
718 return {MemoryBufferRef(), 0};
719
720 MemoryBufferRef Ret =
721 CHECK(C.getMemoryBufferRef(),check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
722 toString(this) +check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
723 ": could not get the buffer for the member defining symbol " +check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
724 Sym->getName())check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
;
725
726 if (C.getParent()->isThin() && Tar)
727 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)check2(C.getFullName(), [&] { return toString(this); })), Ret.getBuffer());
728 if (C.getParent()->isThin())
729 return {Ret, 0};
730 return {Ret, C.getChildOffset()};
731}
732
733template <class ELFT>
734SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
735 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
736 IsNeeded(!Config->AsNeeded) {}
737
738// Partially parse the shared object file so that we can call
739// getSoName on this object.
740template <class ELFT> void SharedFile<ELFT>::parseSoName() {
741 const Elf_Shdr *DynamicSec = nullptr;
742 const ELFFile<ELFT> Obj = this->getObj();
743 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this)check2(Obj.sections(), [&] { return toString(this); });
744
745 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
746 for (const Elf_Shdr &Sec : Sections) {
747 switch (Sec.sh_type) {
748 default:
749 continue;
750 case SHT_DYNSYM:
751 this->initSymtab(Sections, &Sec);
752 break;
753 case SHT_DYNAMIC:
754 DynamicSec = &Sec;
755 break;
756 case SHT_SYMTAB_SHNDX:
757 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this)check2(Obj.getSHNDXTable(Sec, Sections), [&] { return toString
(this); })
;
758 break;
759 case SHT_GNU_versym:
760 this->VersymSec = &Sec;
761 break;
762 case SHT_GNU_verdef:
763 this->VerdefSec = &Sec;
764 break;
765 }
766 }
767
768 if (this->VersymSec && this->ELFSyms.empty())
769 error("SHT_GNU_versym should be associated with symbol table");
770
771 // Search for a DT_SONAME tag to initialize this->SoName.
772 if (!DynamicSec)
773 return;
774 ArrayRef<Elf_Dyn> Arr =
775 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this)check2(Obj.template getSectionContentsAsArray<Elf_Dyn>(
DynamicSec), [&] { return toString(this); })
;
776 for (const Elf_Dyn &Dyn : Arr) {
777 if (Dyn.d_tag == DT_SONAME) {
778 uint64_t Val = Dyn.getVal();
779 if (Val >= this->StringTable.size())
780 fatal(toString(this) + ": invalid DT_SONAME entry");
781 SoName = this->StringTable.data() + Val;
782 return;
783 }
784 }
785}
786
787// Parse the version definitions in the object file if present. Returns a vector
788// whose nth element contains a pointer to the Elf_Verdef for version identifier
789// n. Version identifiers that are not definitions map to nullptr. The array
790// always has at least length 1.
791template <class ELFT>
792std::vector<const typename ELFT::Verdef *>
793SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
794 std::vector<const Elf_Verdef *> Verdefs(1);
795 // We only need to process symbol versions for this DSO if it has both a
796 // versym and a verdef section, which indicates that the DSO contains symbol
797 // version definitions.
798 if (!VersymSec || !VerdefSec)
799 return Verdefs;
800
801 // The location of the first global versym entry.
802 const char *Base = this->MB.getBuffer().data();
803 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
804 this->FirstNonLocal;
805
806 // We cannot determine the largest verdef identifier without inspecting
807 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
808 // sequentially starting from 1, so we predict that the largest identifier
809 // will be VerdefCount.
810 unsigned VerdefCount = VerdefSec->sh_info;
811 Verdefs.resize(VerdefCount + 1);
812
813 // Build the Verdefs array by following the chain of Elf_Verdef objects
814 // from the start of the .gnu.version_d section.
815 const char *Verdef = Base + VerdefSec->sh_offset;
816 for (unsigned I = 0; I != VerdefCount; ++I) {
817 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
818 Verdef += CurVerdef->vd_next;
819 unsigned VerdefIndex = CurVerdef->vd_ndx;
820 if (Verdefs.size() <= VerdefIndex)
821 Verdefs.resize(VerdefIndex + 1);
822 Verdefs[VerdefIndex] = CurVerdef;
823 }
824
825 return Verdefs;
826}
827
828// Fully parse the shared object file. This must be called after parseSoName().
829template <class ELFT> void SharedFile<ELFT>::parseRest() {
830 // Create mapping from version identifiers to Elf_Verdef entries.
831 const Elf_Versym *Versym = nullptr;
832 Verdefs = parseVerdefs(Versym);
833
834 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this)check2(this->getObj().sections(), [&] { return toString
(this); })
;
835
836 // Add symbols to the symbol table.
837 Elf_Sym_Range Syms = this->getGlobalELFSyms();
838 for (const Elf_Sym &Sym : Syms) {
1
Assuming '__begin' is not equal to '__end'
839 unsigned VersymIndex = VER_NDX_GLOBAL;
840 if (Versym) {
2
Assuming 'Versym' is null
3
Taking false branch
14
Taking false branch
25
Taking false branch
841 VersymIndex = Versym->vs_index;
842 ++Versym;
843 }
844 bool Hidden = VersymIndex & VERSYM_HIDDEN;
845 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
846
847 StringRef Name = CHECK(Sym.getName(this->StringTable), this)check2(Sym.getName(this->StringTable), [&] { return toString
(this); })
;
848 if (Sym.isUndefined()) {
4
Taking false branch
15
Taking false branch
26
Taking false branch
849 Undefs.push_back(Name);
850 continue;
851 }
852
853 if (Sym.getBinding() == STB_LOCAL) {
5
Assuming the condition is false
6
Taking false branch
16
Assuming the condition is false
17
Taking false branch
27
Assuming the condition is false
28
Taking false branch
854 warn("found local symbol '" + Name +
855 "' in global part of symbol table in file " + toString(this));
856 continue;
857 }
858
859 const Elf_Verdef *Ver = nullptr;
860 if (VersymIndex != VER_NDX_GLOBAL) {
7
Taking false branch
18
Taking false branch
29
Taking false branch
861 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
862 error("corrupt input file: version definition index " +
863 Twine(VersymIndex) + " for symbol " + Name +
864 " is out of bounds\n>>> defined in " + toString(this));
865 continue;
866 }
867 Ver = Verdefs[VersymIndex];
868 } else {
869 VersymIndex = 0;
870 }
871
872 // We do not usually care about alignments of data in shared object
873 // files because the loader takes care of it. However, if we promote a
874 // DSO symbol to point to .bss due to copy relocation, we need to keep
875 // the original alignment requirements. We infer it here.
876 uint64_t Alignment = 1;
877 if (Sym.st_value)
8
Assuming the condition is false
9
Taking false branch
19
Assuming the condition is false
20
Taking false branch
30
Assuming the condition is true
31
Taking true branch
878 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
32
The result of the left shift is undefined due to shifting by '64', which is greater or equal to the width of type 'unsigned long long'
879 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
10
Assuming the condition is false
21
Assuming the condition is false
880 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
881 Alignment = std::min(Alignment, SecAlign);
882 }
883 if (Alignment > UINT32_MAX(4294967295U))
11
Taking false branch
22
Taking false branch
884 error(toString(this) + ": alignment too large: " + Name);
885
886 if (!Hidden)
12
Taking true branch
23
Taking true branch
887 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
888
889 // Also add the symbol with the versioned name to handle undefined symbols
890 // with explicit versions.
891 if (Ver) {
13
Taking false branch
24
Taking false branch
892 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
893 Name = Saver.save(Name + "@" + VerName);
894 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
895 }
896 }
897}
898
899static ELFKind getBitcodeELFKind(const Triple &T) {
900 if (T.isLittleEndian())
901 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
902 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
903}
904
905static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
906 switch (T.getArch()) {
907 case Triple::aarch64:
908 return EM_AARCH64;
909 case Triple::arm:
910 case Triple::thumb:
911 return EM_ARM;
912 case Triple::avr:
913 return EM_AVR;
914 case Triple::mips:
915 case Triple::mipsel:
916 case Triple::mips64:
917 case Triple::mips64el:
918 return EM_MIPS;
919 case Triple::ppc:
920 return EM_PPC;
921 case Triple::ppc64:
922 return EM_PPC64;
923 case Triple::x86:
924 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
925 case Triple::x86_64:
926 return EM_X86_64;
927 default:
928 fatal(Path + ": could not infer e_machine from bitcode target triple " +
929 T.str());
930 }
931}
932
933BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
934 uint64_t OffsetInArchive)
935 : InputFile(BitcodeKind, MB) {
936 this->ArchiveName = ArchiveName;
937
938 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
939 // (the fully resolved path of the archive) + member name + offset of the
940 // member in the archive.
941 // ThinLTO uses the MemoryBufferRef identifier to access its internal
942 // data structures and if two archives define two members with the same name,
943 // this causes a collision which result in only one of the objects being
944 // taken into consideration at LTO time (which very likely causes undefined
945 // symbols later in the link stage).
946 MemoryBufferRef MBRef(MB.getBuffer(),
947 Saver.save(ArchiveName + MB.getBufferIdentifier() +
948 utostr(OffsetInArchive)));
949 Obj = CHECK(lto::InputFile::create(MBRef), this)check2(lto::InputFile::create(MBRef), [&] { return toString
(this); })
;
950
951 Triple T(Obj->getTargetTriple());
952 EKind = getBitcodeELFKind(T);
953 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
954}
955
956static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
957 switch (GvVisibility) {
958 case GlobalValue::DefaultVisibility:
959 return STV_DEFAULT;
960 case GlobalValue::HiddenVisibility:
961 return STV_HIDDEN;
962 case GlobalValue::ProtectedVisibility:
963 return STV_PROTECTED;
964 }
965 llvm_unreachable("unknown visibility")::llvm::llvm_unreachable_internal("unknown visibility", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 965)
;
966}
967
968template <class ELFT>
969static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
970 const lto::InputFile::Symbol &ObjSym,
971 BitcodeFile &F) {
972 StringRef NameRef = Saver.save(ObjSym.getName());
973 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
974
975 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
976 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
977 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
978
979 int C = ObjSym.getComdatIndex();
980 if (C != -1 && !KeptComdats[C])
981 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
982 CanOmitFromDynSym, &F);
983
984 if (ObjSym.isUndefined())
985 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
986 CanOmitFromDynSym, &F);
987
988 if (ObjSym.isCommon())
989 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
990 ObjSym.getCommonAlignment(), Binding, Visibility,
991 STT_OBJECT, F);
992
993 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
994 CanOmitFromDynSym, F);
995}
996
997template <class ELFT>
998void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
999 std::vector<bool> KeptComdats;
1000 for (StringRef S : Obj->getComdatTable())
1001 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1002
1003 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1004 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1005}
1006
1007static ELFKind getELFKind(MemoryBufferRef MB) {
1008 unsigned char Size;
1009 unsigned char Endian;
1010 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1011
1012 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1013 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1014 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1015 fatal(MB.getBufferIdentifier() + ": invalid file class");
1016
1017 size_t BufSize = MB.getBuffer().size();
1018 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1019 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1020 fatal(MB.getBufferIdentifier() + ": file is too short");
1021
1022 if (Size == ELFCLASS32)
1023 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1024 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1025}
1026
1027void BinaryFile::parse() {
1028 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1029 auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1030 SHT_PROGBITS, 8, Data, ".data");
1031 Sections.push_back(Section);
1032
1033 // For each input file foo that is embedded to a result as a binary
1034 // blob, we define _binary_foo_{start,end,size} symbols, so that
1035 // user programs can access blobs by name. Non-alphanumeric
1036 // characters in a filename are replaced with underscore.
1037 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1038 for (size_t I = 0; I < S.size(); ++I)
1039 if (!isAlnum(S[I]))
1040 S[I] = '_';
1041
1042 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1043 STB_GLOBAL, Section, nullptr);
1044 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1045 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1046 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1047 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1048}
1049
1050static bool isBitcode(MemoryBufferRef MB) {
1051 using namespace sys::fs;
1052 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1053}
1054
1055InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1056 uint64_t OffsetInArchive) {
1057 if (isBitcode(MB))
1058 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1059
1060 switch (getELFKind(MB)) {
1061 case ELF32LEKind:
1062 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1063 case ELF32BEKind:
1064 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1065 case ELF64LEKind:
1066 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1067 case ELF64BEKind:
1068 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1069 default:
1070 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 1070)
;
1071 }
1072}
1073
1074InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1075 switch (getELFKind(MB)) {
1076 case ELF32LEKind:
1077 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1078 case ELF32BEKind:
1079 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1080 case ELF64LEKind:
1081 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1082 case ELF64BEKind:
1083 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1084 default:
1085 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 1085)
;
1086 }
1087}
1088
1089MemoryBufferRef LazyObjFile::getBuffer() {
1090 if (Seen)
1091 return MemoryBufferRef();
1092 Seen = true;
1093 return MB;
1094}
1095
1096InputFile *LazyObjFile::fetch() {
1097 MemoryBufferRef MBRef = getBuffer();
1098 if (MBRef.getBuffer().empty())
1099 return nullptr;
1100 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1101}
1102
1103template <class ELFT> void LazyObjFile::parse() {
1104 for (StringRef Sym : getSymbolNames())
1105 Symtab->addLazyObject<ELFT>(Sym, *this);
1106}
1107
1108template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1109 typedef typename ELFT::Shdr Elf_Shdr;
1110 typedef typename ELFT::Sym Elf_Sym;
1111 typedef typename ELFT::SymRange Elf_Sym_Range;
1112
1113 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1114 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this)check2(Obj.sections(), [&] { return toString(this); });
1115 for (const Elf_Shdr &Sec : Sections) {
1116 if (Sec.sh_type != SHT_SYMTAB)
1117 continue;
1118
1119 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this)check2(Obj.symbols(&Sec), [&] { return toString(this)
; })
;
1120 uint32_t FirstNonLocal = Sec.sh_info;
1121 StringRef StringTable =
1122 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this)check2(Obj.getStringTableForSymtab(Sec, Sections), [&] { return
toString(this); })
;
1123 std::vector<StringRef> V;
1124
1125 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1126 if (Sym.st_shndx != SHN_UNDEF)
1127 V.push_back(CHECK(Sym.getName(StringTable), this)check2(Sym.getName(StringTable), [&] { return toString(this
); })
);
1128 return V;
1129 }
1130 return {};
1131}
1132
1133std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1134 std::unique_ptr<lto::InputFile> Obj =
1135 CHECK(lto::InputFile::create(this->MB), this)check2(lto::InputFile::create(this->MB), [&] { return toString
(this); })
;
1136 std::vector<StringRef> V;
1137 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1138 if (!Sym.isUndefined())
1139 V.push_back(Saver.save(Sym.getName()));
1140 return V;
1141}
1142
1143// Returns a vector of globally-visible defined symbol names.
1144std::vector<StringRef> LazyObjFile::getSymbolNames() {
1145 if (isBitcode(this->MB))
1146 return getBitcodeSymbols();
1147
1148 switch (getELFKind(this->MB)) {
1149 case ELF32LEKind:
1150 return getElfSymbols<ELF32LE>();
1151 case ELF32BEKind:
1152 return getElfSymbols<ELF32BE>();
1153 case ELF64LEKind:
1154 return getElfSymbols<ELF64LE>();
1155 case ELF64BEKind:
1156 return getElfSymbols<ELF64BE>();
1157 default:
1158 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-6.0~svn321639/tools/lld/ELF/InputFiles.cpp"
, 1158)
;
1159 }
1160}
1161
1162template void ArchiveFile::parse<ELF32LE>();
1163template void ArchiveFile::parse<ELF32BE>();
1164template void ArchiveFile::parse<ELF64LE>();
1165template void ArchiveFile::parse<ELF64BE>();
1166
1167template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1168template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1169template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1170template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1171
1172template void LazyObjFile::parse<ELF32LE>();
1173template void LazyObjFile::parse<ELF32BE>();
1174template void LazyObjFile::parse<ELF64LE>();
1175template void LazyObjFile::parse<ELF64BE>();
1176
1177template class elf::ELFFileBase<ELF32LE>;
1178template class elf::ELFFileBase<ELF32BE>;
1179template class elf::ELFFileBase<ELF64LE>;
1180template class elf::ELFFileBase<ELF64BE>;
1181
1182template class elf::ObjFile<ELF32LE>;
1183template class elf::ObjFile<ELF32BE>;
1184template class elf::ObjFile<ELF64LE>;
1185template class elf::ObjFile<ELF64BE>;
1186
1187template class elf::SharedFile<ELF32LE>;
1188template class elf::SharedFile<ELF32BE>;
1189template class elf::SharedFile<ELF64LE>;
1190template class elf::SharedFile<ELF64BE>;