Bug Summary

File:tools/lld/ELF/InputFiles.cpp
Warning:line 894, 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

Press '?' to see keyboard shortcuts

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