Bug Summary

File:tools/lld/ELF/InputFiles.cpp
Warning:line 884, 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~svn324331/build-llvm/tools/lld/ELF -I /build/llvm-toolchain-snapshot-7~svn324331/tools/lld/ELF -I /build/llvm-toolchain-snapshot-7~svn324331/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn324331/build-llvm/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn324331/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn324331/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~svn324331/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-02-06-191459-19498-1 -x c++ /build/llvm-toolchain-snapshot-7~svn324331/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~svn324331/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~svn324331/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 Symbols.reserve(File->getNumberOfSymbols());
711 for (const Archive::Symbol &Sym : File->symbols())
712 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
713}
714
715// Returns a buffer pointing to a member file containing a given symbol.
716std::pair<MemoryBufferRef, uint64_t>
717ArchiveFile::getMember(const Archive::Symbol *Sym) {
718 Archive::Child C =
719 CHECK(Sym->getMember(), toString(this) +check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
720 ": could not get the member for symbol " +check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
721 Sym->getName())check2(Sym->getMember(), [&] { return toString(toString
(this) + ": could not get the member for symbol " + Sym->getName
()); })
;
722
723 if (!Seen.insert(C.getChildOffset()).second)
724 return {MemoryBufferRef(), 0};
725
726 MemoryBufferRef Ret =
727 CHECK(C.getMemoryBufferRef(),check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
728 toString(this) +check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
729 ": 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()); })
730 Sym->getName())check2(C.getMemoryBufferRef(), [&] { return toString(toString
(this) + ": could not get the buffer for the member defining symbol "
+ Sym->getName()); })
;
731
732 if (C.getParent()->isThin() && Tar)
733 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)check2(C.getFullName(), [&] { return toString(this); })), Ret.getBuffer());
734 if (C.getParent()->isThin())
735 return {Ret, 0};
736 return {Ret, C.getChildOffset()};
737}
738
739template <class ELFT>
740SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
741 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
742 IsNeeded(!Config->AsNeeded) {}
743
744// Partially parse the shared object file so that we can call
745// getSoName on this object.
746template <class ELFT> void SharedFile<ELFT>::parseSoName() {
747 const Elf_Shdr *DynamicSec = nullptr;
748 const ELFFile<ELFT> Obj = this->getObj();
749 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this)check2(Obj.sections(), [&] { return toString(this); });
750
751 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
752 for (const Elf_Shdr &Sec : Sections) {
753 switch (Sec.sh_type) {
754 default:
755 continue;
756 case SHT_DYNSYM:
757 this->initSymtab(Sections, &Sec);
758 break;
759 case SHT_DYNAMIC:
760 DynamicSec = &Sec;
761 break;
762 case SHT_SYMTAB_SHNDX:
763 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this)check2(Obj.getSHNDXTable(Sec, Sections), [&] { return toString
(this); })
;
764 break;
765 case SHT_GNU_versym:
766 this->VersymSec = &Sec;
767 break;
768 case SHT_GNU_verdef:
769 this->VerdefSec = &Sec;
770 break;
771 }
772 }
773
774 if (this->VersymSec && this->ELFSyms.empty())
775 error("SHT_GNU_versym should be associated with symbol table");
776
777 // Search for a DT_SONAME tag to initialize this->SoName.
778 if (!DynamicSec)
779 return;
780 ArrayRef<Elf_Dyn> Arr =
781 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this)check2(Obj.template getSectionContentsAsArray<Elf_Dyn>(
DynamicSec), [&] { return toString(this); })
;
782 for (const Elf_Dyn &Dyn : Arr) {
783 if (Dyn.d_tag == DT_SONAME) {
784 uint64_t Val = Dyn.getVal();
785 if (Val >= this->StringTable.size())
786 fatal(toString(this) + ": invalid DT_SONAME entry");
787 SoName = this->StringTable.data() + Val;
788 return;
789 }
790 }
791}
792
793// Parse the version definitions in the object file if present. Returns a vector
794// whose nth element contains a pointer to the Elf_Verdef for version identifier
795// n. Version identifiers that are not definitions map to nullptr. The array
796// always has at least length 1.
797template <class ELFT>
798std::vector<const typename ELFT::Verdef *>
799SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
800 std::vector<const Elf_Verdef *> Verdefs(1);
801 // We only need to process symbol versions for this DSO if it has both a
802 // versym and a verdef section, which indicates that the DSO contains symbol
803 // version definitions.
804 if (!VersymSec || !VerdefSec)
805 return Verdefs;
806
807 // The location of the first global versym entry.
808 const char *Base = this->MB.getBuffer().data();
809 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
810 this->FirstNonLocal;
811
812 // We cannot determine the largest verdef identifier without inspecting
813 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
814 // sequentially starting from 1, so we predict that the largest identifier
815 // will be VerdefCount.
816 unsigned VerdefCount = VerdefSec->sh_info;
817 Verdefs.resize(VerdefCount + 1);
818
819 // Build the Verdefs array by following the chain of Elf_Verdef objects
820 // from the start of the .gnu.version_d section.
821 const char *Verdef = Base + VerdefSec->sh_offset;
822 for (unsigned I = 0; I != VerdefCount; ++I) {
823 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
824 Verdef += CurVerdef->vd_next;
825 unsigned VerdefIndex = CurVerdef->vd_ndx;
826 if (Verdefs.size() <= VerdefIndex)
827 Verdefs.resize(VerdefIndex + 1);
828 Verdefs[VerdefIndex] = CurVerdef;
829 }
830
831 return Verdefs;
832}
833
834// Fully parse the shared object file. This must be called after parseSoName().
835template <class ELFT> void SharedFile<ELFT>::parseRest() {
836 // Create mapping from version identifiers to Elf_Verdef entries.
837 const Elf_Versym *Versym = nullptr;
838 Verdefs = parseVerdefs(Versym);
839
840 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this)check2(this->getObj().sections(), [&] { return toString
(this); })
;
841
842 // Add symbols to the symbol table.
843 Elf_Sym_Range Syms = this->getGlobalELFSyms();
844 for (const Elf_Sym &Sym : Syms) {
1
Assuming '__begin' is not equal to '__end'
845 unsigned VersymIndex = VER_NDX_GLOBAL;
846 if (Versym) {
2
Assuming 'Versym' is null
3
Taking false branch
14
Taking false branch
25
Taking false branch
847 VersymIndex = Versym->vs_index;
848 ++Versym;
849 }
850 bool Hidden = VersymIndex & VERSYM_HIDDEN;
851 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
852
853 StringRef Name = CHECK(Sym.getName(this->StringTable), this)check2(Sym.getName(this->StringTable), [&] { return toString
(this); })
;
854 if (Sym.isUndefined()) {
4
Taking false branch
15
Taking false branch
26
Taking false branch
855 Undefs.push_back(Name);
856 continue;
857 }
858
859 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
860 warn("found local symbol '" + Name +
861 "' in global part of symbol table in file " + toString(this));
862 continue;
863 }
864
865 const Elf_Verdef *Ver = nullptr;
866 if (VersymIndex != VER_NDX_GLOBAL) {
7
Taking false branch
18
Taking false branch
29
Taking false branch
867 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
868 error("corrupt input file: version definition index " +
869 Twine(VersymIndex) + " for symbol " + Name +
870 " is out of bounds\n>>> defined in " + toString(this));
871 continue;
872 }
873 Ver = Verdefs[VersymIndex];
874 } else {
875 VersymIndex = 0;
876 }
877
878 // We do not usually care about alignments of data in shared object
879 // files because the loader takes care of it. However, if we promote a
880 // DSO symbol to point to .bss due to copy relocation, we need to keep
881 // the original alignment requirements. We infer it here.
882 uint64_t Alignment = 1;
883 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
884 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'
885 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
10
Assuming the condition is false
21
Assuming the condition is false
886 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
887 Alignment = std::min(Alignment, SecAlign);
888 }
889 if (Alignment > UINT32_MAX(4294967295U))
11
Taking false branch
22
Taking false branch
890 error(toString(this) + ": alignment too large: " + Name);
891
892 if (!Hidden)
12
Taking true branch
23
Taking true branch
893 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
894
895 // Also add the symbol with the versioned name to handle undefined symbols
896 // with explicit versions.
897 if (Ver) {
13
Taking false branch
24
Taking false branch
898 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
899 Name = Saver.save(Name + "@" + VerName);
900 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
901 }
902 }
903}
904
905static ELFKind getBitcodeELFKind(const Triple &T) {
906 if (T.isLittleEndian())
907 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
908 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
909}
910
911static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
912 switch (T.getArch()) {
913 case Triple::aarch64:
914 return EM_AARCH64;
915 case Triple::arm:
916 case Triple::thumb:
917 return EM_ARM;
918 case Triple::avr:
919 return EM_AVR;
920 case Triple::mips:
921 case Triple::mipsel:
922 case Triple::mips64:
923 case Triple::mips64el:
924 return EM_MIPS;
925 case Triple::ppc:
926 return EM_PPC;
927 case Triple::ppc64:
928 return EM_PPC64;
929 case Triple::x86:
930 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
931 case Triple::x86_64:
932 return EM_X86_64;
933 default:
934 fatal(Path + ": could not infer e_machine from bitcode target triple " +
935 T.str());
936 }
937}
938
939BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
940 uint64_t OffsetInArchive)
941 : InputFile(BitcodeKind, MB) {
942 this->ArchiveName = ArchiveName;
943
944 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
945 // (the fully resolved path of the archive) + member name + offset of the
946 // member in the archive.
947 // ThinLTO uses the MemoryBufferRef identifier to access its internal
948 // data structures and if two archives define two members with the same name,
949 // this causes a collision which result in only one of the objects being
950 // taken into consideration at LTO time (which very likely causes undefined
951 // symbols later in the link stage).
952 MemoryBufferRef MBRef(MB.getBuffer(),
953 Saver.save(ArchiveName + MB.getBufferIdentifier() +
954 utostr(OffsetInArchive)));
955 Obj = CHECK(lto::InputFile::create(MBRef), this)check2(lto::InputFile::create(MBRef), [&] { return toString
(this); })
;
956
957 Triple T(Obj->getTargetTriple());
958 EKind = getBitcodeELFKind(T);
959 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
960}
961
962static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
963 switch (GvVisibility) {
964 case GlobalValue::DefaultVisibility:
965 return STV_DEFAULT;
966 case GlobalValue::HiddenVisibility:
967 return STV_HIDDEN;
968 case GlobalValue::ProtectedVisibility:
969 return STV_PROTECTED;
970 }
971 llvm_unreachable("unknown visibility")::llvm::llvm_unreachable_internal("unknown visibility", "/build/llvm-toolchain-snapshot-7~svn324331/tools/lld/ELF/InputFiles.cpp"
, 971)
;
972}
973
974template <class ELFT>
975static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
976 const lto::InputFile::Symbol &ObjSym,
977 BitcodeFile &F) {
978 StringRef NameRef = Saver.save(ObjSym.getName());
979 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
980
981 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
982 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
983 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
984
985 int C = ObjSym.getComdatIndex();
986 if (C != -1 && !KeptComdats[C])
987 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
988 CanOmitFromDynSym, &F);
989
990 if (ObjSym.isUndefined())
991 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
992 CanOmitFromDynSym, &F);
993
994 if (ObjSym.isCommon())
995 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
996 ObjSym.getCommonAlignment(), Binding, Visibility,
997 STT_OBJECT, F);
998
999 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1000 CanOmitFromDynSym, F);
1001}
1002
1003template <class ELFT>
1004void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1005 std::vector<bool> KeptComdats;
1006 for (StringRef S : Obj->getComdatTable())
1007 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1008
1009 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1010 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1011}
1012
1013static ELFKind getELFKind(MemoryBufferRef MB) {
1014 unsigned char Size;
1015 unsigned char Endian;
1016 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1017
1018 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1019 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1020 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1021 fatal(MB.getBufferIdentifier() + ": invalid file class");
1022
1023 size_t BufSize = MB.getBuffer().size();
1024 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1025 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1026 fatal(MB.getBufferIdentifier() + ": file is too short");
1027
1028 if (Size == ELFCLASS32)
1029 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1030 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1031}
1032
1033void BinaryFile::parse() {
1034 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1035 auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1036 8, Data, ".data");
1037 Sections.push_back(Section);
1038
1039 // For each input file foo that is embedded to a result as a binary
1040 // blob, we define _binary_foo_{start,end,size} symbols, so that
1041 // user programs can access blobs by name. Non-alphanumeric
1042 // characters in a filename are replaced with underscore.
1043 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1044 for (size_t I = 0; I < S.size(); ++I)
1045 if (!isAlnum(S[I]))
1046 S[I] = '_';
1047
1048 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1049 STB_GLOBAL, Section, nullptr);
1050 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1051 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1052 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1053 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1054}
1055
1056static bool isBitcode(MemoryBufferRef MB) {
1057 using namespace sys::fs;
1058 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1059}
1060
1061InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1062 uint64_t OffsetInArchive) {
1063 if (isBitcode(MB))
1064 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1065
1066 switch (getELFKind(MB)) {
1067 case ELF32LEKind:
1068 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1069 case ELF32BEKind:
1070 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1071 case ELF64LEKind:
1072 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1073 case ELF64BEKind:
1074 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1075 default:
1076 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-7~svn324331/tools/lld/ELF/InputFiles.cpp"
, 1076)
;
1077 }
1078}
1079
1080InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1081 switch (getELFKind(MB)) {
1082 case ELF32LEKind:
1083 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1084 case ELF32BEKind:
1085 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1086 case ELF64LEKind:
1087 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1088 case ELF64BEKind:
1089 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1090 default:
1091 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-7~svn324331/tools/lld/ELF/InputFiles.cpp"
, 1091)
;
1092 }
1093}
1094
1095MemoryBufferRef LazyObjFile::getBuffer() {
1096 if (Seen)
1097 return MemoryBufferRef();
1098 Seen = true;
1099 return MB;
1100}
1101
1102InputFile *LazyObjFile::fetch() {
1103 MemoryBufferRef MBRef = getBuffer();
1104 if (MBRef.getBuffer().empty())
1105 return nullptr;
1106 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1107}
1108
1109template <class ELFT> void LazyObjFile::parse() {
1110 for (StringRef Sym : getSymbolNames())
1111 Symtab->addLazyObject<ELFT>(Sym, *this);
1112}
1113
1114template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1115 typedef typename ELFT::Shdr Elf_Shdr;
1116 typedef typename ELFT::Sym Elf_Sym;
1117 typedef typename ELFT::SymRange Elf_Sym_Range;
1118
1119 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1120 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this)check2(Obj.sections(), [&] { return toString(this); });
1121 for (const Elf_Shdr &Sec : Sections) {
1122 if (Sec.sh_type != SHT_SYMTAB)
1123 continue;
1124
1125 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this)check2(Obj.symbols(&Sec), [&] { return toString(this)
; })
;
1126 uint32_t FirstNonLocal = Sec.sh_info;
1127 StringRef StringTable =
1128 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this)check2(Obj.getStringTableForSymtab(Sec, Sections), [&] { return
toString(this); })
;
1129 std::vector<StringRef> V;
1130
1131 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1132 if (Sym.st_shndx != SHN_UNDEF)
1133 V.push_back(CHECK(Sym.getName(StringTable), this)check2(Sym.getName(StringTable), [&] { return toString(this
); })
);
1134 return V;
1135 }
1136 return {};
1137}
1138
1139std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1140 std::unique_ptr<lto::InputFile> Obj =
1141 CHECK(lto::InputFile::create(this->MB), this)check2(lto::InputFile::create(this->MB), [&] { return toString
(this); })
;
1142 std::vector<StringRef> V;
1143 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1144 if (!Sym.isUndefined())
1145 V.push_back(Saver.save(Sym.getName()));
1146 return V;
1147}
1148
1149// Returns a vector of globally-visible defined symbol names.
1150std::vector<StringRef> LazyObjFile::getSymbolNames() {
1151 if (isBitcode(this->MB))
1152 return getBitcodeSymbols();
1153
1154 switch (getELFKind(this->MB)) {
1155 case ELF32LEKind:
1156 return getElfSymbols<ELF32LE>();
1157 case ELF32BEKind:
1158 return getElfSymbols<ELF32BE>();
1159 case ELF64LEKind:
1160 return getElfSymbols<ELF64LE>();
1161 case ELF64BEKind:
1162 return getElfSymbols<ELF64BE>();
1163 default:
1164 llvm_unreachable("getELFKind")::llvm::llvm_unreachable_internal("getELFKind", "/build/llvm-toolchain-snapshot-7~svn324331/tools/lld/ELF/InputFiles.cpp"
, 1164)
;
1165 }
1166}
1167
1168template void ArchiveFile::parse<ELF32LE>();
1169template void ArchiveFile::parse<ELF32BE>();
1170template void ArchiveFile::parse<ELF64LE>();
1171template void ArchiveFile::parse<ELF64BE>();
1172
1173template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1174template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1175template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1176template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1177
1178template void LazyObjFile::parse<ELF32LE>();
1179template void LazyObjFile::parse<ELF32BE>();
1180template void LazyObjFile::parse<ELF64LE>();
1181template void LazyObjFile::parse<ELF64BE>();
1182
1183template class elf::ELFFileBase<ELF32LE>;
1184template class elf::ELFFileBase<ELF32BE>;
1185template class elf::ELFFileBase<ELF64LE>;
1186template class elf::ELFFileBase<ELF64BE>;
1187
1188template class elf::ObjFile<ELF32LE>;
1189template class elf::ObjFile<ELF32BE>;
1190template class elf::ObjFile<ELF64LE>;
1191template class elf::ObjFile<ELF64BE>;
1192
1193template class elf::SharedFile<ELF32LE>;
1194template class elf::SharedFile<ELF32BE>;
1195template class elf::SharedFile<ELF64LE>;
1196template class elf::SharedFile<ELF64BE>;