Coverage Report

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