Coverage Report

Created: 2018-06-18 20:01

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